@cortexkit/pi-magic-context 0.49.45 → 0.49.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -70,7 +70,7 @@ import {
70
70
  renderMessageByOrdinal2,
71
71
  renderVerboseRange2,
72
72
  renderItemByTag2
73
- } from "./index-6bedye3n.js";
73
+ } from "./index-nev91y6k.js";
74
74
  import {
75
75
  getLastIndexedOrdinal
76
76
  } from "./index-fzadydec.js";
@@ -609,6 +609,11 @@ function deriveWindowGeometry(providerID, modelID, catalogLimit, options = {}) {
609
609
  const requestedOutput = Math.min(output ?? OPENCODE_OUTPUT_CAP, OPENCODE_OUTPUT_CAP);
610
610
  usableHard = hardWindow - requestedOutput;
611
611
  }
612
+ let hardWithoutInputCap;
613
+ if (isFinitePositive(input) && input < usableHard) {
614
+ hardWithoutInputCap = Math.max(MIN_PLAUSIBLE_CONTEXT_LIMIT, Math.floor(usableHard));
615
+ usableHard = input;
616
+ }
612
617
  usableHard = Math.max(MIN_PLAUSIBLE_CONTEXT_LIMIT, Math.floor(usableHard));
613
618
  if (usableHard < usableSoft) {
614
619
  logGeometryClampOnce(`${providerID}/${modelID}|${usableSoft}|${usableHard}`, `usable hard limit clamped for ${providerID}/${modelID}: ${usableHard} → ${usableSoft} (window limit inversion)`, options.log);
@@ -625,7 +630,8 @@ function deriveWindowGeometry(providerID, modelID, catalogLimit, options = {}) {
625
630
  reserveSource,
626
631
  geometry,
627
632
  windowSource,
628
- absoluteWall: Math.floor(hardWindow)
633
+ absoluteWall: Math.floor(hardWindow),
634
+ ...hardWithoutInputCap !== undefined ? { hardWithoutInputCap } : {}
629
635
  }
630
636
  };
631
637
  }
@@ -647,11 +653,13 @@ function applyProvenInputFloor(geometry, provenInputTokens) {
647
653
  }
648
654
  const trustedAbsoluteWall = hasTrustedAbsoluteWall(geometry);
649
655
  const window = trustedAbsoluteWall ? geometry.derivation.window : Math.max(geometry.derivation.window, provenInputTokens);
656
+ const inputCapDisproved = geometry.derivation.hardWithoutInputCap !== undefined && provenInputTokens > geometry.usableHard;
657
+ const hardBeforeFloor = inputCapDisproved ? geometry.derivation.hardWithoutInputCap : geometry.usableHard;
650
658
  return {
651
659
  geometry: {
652
660
  ...geometry,
653
661
  usableSoft: provenInputTokens,
654
- usableHard: trustedAbsoluteWall ? geometry.usableHard : Math.max(geometry.usableHard, provenInputTokens),
662
+ usableHard: trustedAbsoluteWall ? hardBeforeFloor : Math.max(hardBeforeFloor, provenInputTokens),
655
663
  derivation: {
656
664
  ...geometry.derivation,
657
665
  window,
@@ -4784,15 +4792,115 @@ function resolveMuralWire(db, projectIdentity, modelKey, enabled, budgetTokens =
4784
4792
  };
4785
4793
  }
4786
4794
 
4787
- // ../plugin/src/features/magic-context/compaction-marker.ts
4795
+ // ../plugin/src/features/magic-context/request-tool-definitions.ts
4788
4796
  import { createHash as createHash4 } from "node:crypto";
4797
+ var sha = (value) => createHash4("sha256").update(JSON.stringify(value)).digest("hex");
4798
+ var v2SchemaDigests = new Map;
4799
+ function requestToolsFingerprint(tools, referencedNames) {
4800
+ let referenced;
4801
+ const included = [];
4802
+ for (const tool of tools) {
4803
+ if (tool.deferLoading === true) {
4804
+ referenced ??= referencedNames?.() ?? new Set;
4805
+ if (!referenced.has(tool.name))
4806
+ continue;
4807
+ }
4808
+ included.push(tool);
4809
+ }
4810
+ included.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
4811
+ return {
4812
+ names: sha(included.map((tool) => tool.name)),
4813
+ descriptions: sha(included.map((tool) => [tool.name, tool.description])),
4814
+ schemas: sha(included.map((tool) => tool.deferLoading === true ? [tool.name, tool.description, tool.schemaDigest, "defer_loading"] : [tool.name, tool.description, tool.schemaDigest]))
4815
+ };
4816
+ }
4817
+ function classifyRequestToolsChange(previous, current) {
4818
+ if (previous.names !== current.names)
4819
+ return "names";
4820
+ if (previous.descriptions !== current.descriptions)
4821
+ return "descriptions";
4822
+ if (previous.schemas !== current.schemas)
4823
+ return "schemas";
4824
+ return null;
4825
+ }
4826
+ function requestToolSchemaDigest(schema) {
4827
+ const pieces = [];
4828
+ writeCanonicalJson(toJsonValue(schema, ""), [], pieces);
4829
+ return createHash4("sha256").update(pieces.join("")).digest("hex");
4830
+ }
4831
+ function isJsonValue(value) {
4832
+ return value !== undefined && typeof value !== "function" && typeof value !== "symbol";
4833
+ }
4834
+ function toJsonValue(value, key) {
4835
+ if (typeof value !== "object" || value === null)
4836
+ return value;
4837
+ const toJSON = value.toJSON;
4838
+ const resolved = typeof toJSON === "function" ? toJSON.call(value, key) : value;
4839
+ if (resolved instanceof Number)
4840
+ return Number(resolved);
4841
+ if (resolved instanceof String)
4842
+ return String(resolved);
4843
+ if (resolved instanceof Boolean)
4844
+ return resolved.valueOf();
4845
+ return resolved;
4846
+ }
4847
+ function writeCanonicalJson(value, ancestors, out) {
4848
+ if (value === null || typeof value === "boolean" || typeof value === "string") {
4849
+ out.push(JSON.stringify(value));
4850
+ return;
4851
+ }
4852
+ if (typeof value === "number") {
4853
+ out.push(Number.isFinite(value) ? JSON.stringify(value) : "null");
4854
+ return;
4855
+ }
4856
+ if (typeof value === "bigint") {
4857
+ out.push(JSON.stringify(value.toString()));
4858
+ return;
4859
+ }
4860
+ if (typeof value !== "object") {
4861
+ out.push("null");
4862
+ return;
4863
+ }
4864
+ if (ancestors.includes(value)) {
4865
+ out.push('"[Circular]"');
4866
+ return;
4867
+ }
4868
+ ancestors.push(value);
4869
+ if (Array.isArray(value)) {
4870
+ out.push("[");
4871
+ for (let index = 0;index < value.length; index += 1) {
4872
+ if (index > 0)
4873
+ out.push(",");
4874
+ const item = toJsonValue(value[index], String(index));
4875
+ if (isJsonValue(item))
4876
+ writeCanonicalJson(item, ancestors, out);
4877
+ else
4878
+ out.push("null");
4879
+ }
4880
+ out.push("]");
4881
+ } else {
4882
+ const entries = Object.entries(value).map(([key, child]) => [key, toJsonValue(child, key)]).filter(([, child]) => isJsonValue(child)).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
4883
+ out.push("{");
4884
+ entries.forEach(([key, child], index) => {
4885
+ if (index > 0)
4886
+ out.push(",");
4887
+ out.push(JSON.stringify(key), ":");
4888
+ writeCanonicalJson(child, ancestors, out);
4889
+ });
4890
+ out.push("}");
4891
+ }
4892
+ ancestors.pop();
4893
+ }
4894
+
4895
+ // ../plugin/src/features/magic-context/compaction-marker.ts
4896
+ import { createHash as createHash5 } from "node:crypto";
4789
4897
  import { existsSync as existsSync6, statSync as statSync4 } from "node:fs";
4790
4898
  var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
4791
4899
  var ID_PREFIX_HEX_LENGTH = 12;
4792
4900
  var ID_SUFFIX_LENGTH = 14;
4793
4901
  var ID_PREFIX_MASK = (1n << BigInt(ID_PREFIX_HEX_LENGTH * 4)) - 1n;
4794
4902
  function deterministicBase62(seed, length) {
4795
- let value = BigInt(`0x${createHash4("sha256").update(seed).digest("hex")}`);
4903
+ let value = BigInt(`0x${createHash5("sha256").update(seed).digest("hex")}`);
4796
4904
  const chars = Array(length);
4797
4905
  for (let index = length - 1;index >= 0; index -= 1) {
4798
4906
  chars[index] = BASE62_CHARS[Number(value % 62n)];
@@ -6438,7 +6546,7 @@ async function wakePlaneStatus() {
6438
6546
  import { statSync as statSync5 } from "node:fs";
6439
6547
 
6440
6548
  // ../plugin/src/plugin/embedding-bootstrap-helpers.ts
6441
- import { createHash as createHash5 } from "node:crypto";
6549
+ import { createHash as createHash6 } from "node:crypto";
6442
6550
  var EMBEDDING_AFFECTING_KEYS = new Set([
6443
6551
  "embedding.api_key",
6444
6552
  "embedding.endpoint",
@@ -6486,7 +6594,7 @@ var EMBEDDING_WARNING_TERMS = [
6486
6594
  ];
6487
6595
  var loggedFailureSignatures = new Map;
6488
6596
  function sha256Prefix(value, length = 16) {
6489
- return createHash5("sha256").update(value).digest("hex").slice(0, length);
6597
+ return createHash6("sha256").update(value).digest("hex").slice(0, length);
6490
6598
  }
6491
6599
  function warningLooksEmbeddingRelated(message) {
6492
6600
  const lower = message.toLowerCase();
@@ -7610,9 +7718,9 @@ var FULL_PARAMETER_DESCRIPTIONS = {
7610
7718
  },
7611
7719
  ctx_memory: {
7612
7720
  action: "write | update | archive | merge | get",
7613
- content: "The memory text — one standalone fact (write, update, merge).",
7614
- category: "Kind of fact (required for write; on update/merge, pass the memory's current category to keep it).",
7615
- ids: "Memory ids from <project-memory>: one for update, one or more for archive, two or more for merge, 1–20 for get.",
7721
+ content: "The memory text — one standalone fact (write, update, merge). Archive and get take an empty string.",
7722
+ category: "Kind of fact: the new fact's kind for write; on update/merge, the memory's current category to keep it. Archive and get ignore it.",
7723
+ ids: "Memory ids from <project-memory>: one for update, one or more for archive, two or more for merge, 1–20 for get. Write takes an empty list.",
7616
7724
  reason: "Why it is being archived (optional)."
7617
7725
  },
7618
7726
  ctx_search: {
@@ -7645,9 +7753,9 @@ var LIGHT_PARAMETER_DESCRIPTIONS = {
7645
7753
  },
7646
7754
  ctx_memory: {
7647
7755
  action: "write | update | archive | merge | get",
7648
- content: "One standalone fact (write, update, merge).",
7649
- category: "Kind of fact (required for write; on update/merge pass the current category to keep it).",
7650
- ids: "Ids from <project-memory>: one for update, 1+ for archive, 2+ for merge, 1–20 for get.",
7756
+ content: "One standalone fact (write, update, merge). Archive and get: empty string.",
7757
+ category: "Kind of fact (write; on update/merge pass the current category to keep it). Archive and get ignore it.",
7758
+ ids: "Ids from <project-memory>: one for update, 1+ for archive, 2+ for merge, 1–20 for get. Write: empty list.",
7651
7759
  reason: "Why it is archived (optional)."
7652
7760
  },
7653
7761
  ctx_search: {
@@ -10702,4 +10810,4 @@ function registerMagicContextTools(pi, opts) {
10702
10810
  }
10703
10811
  }
10704
10812
 
10705
- export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, isCommitRetentionPaused, copyCommitRetentionRecovery, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, OPENCODE_OUTPUT_CAP, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, formatWindowSource, isSaneLimit, resolveOutputReserve, getSdkWindowGeometry, getSdkContextLimit, getSdkOutputLimit, getSdkInputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, resolvePiRealStableId, isPiContentFallbackId, isPiIndexFallbackId, piContentFallbackIds, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findRestartModelSeedFromBranch, iterateEntriesToRawMessageRange, iterateAsyncEntriesToRawMessageRange, convertEntriesToRawMessages, convertPiAssistantEntryById, convertEntriesToRawMessagePage, countPiRawMessages, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getSkippedDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, withCachedM0MemoryIds, readCachedM0MemoryIds, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, TEMPORAL_MARKER_REPLAY_PATTERN, temporalMarkerPrefix, renderUserProfileContent, clearInjectionCache, getVisibleMemoryIds, orderHistorianMemories, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, resetPrefixTrimFallbackState, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, neutralizeOmpMentions, restoreOmpMentions, resolvePiHarnessDetection, resolvePiHarnessKind, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
10813
+ export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, isCommitRetentionPaused, copyCommitRetentionRecovery, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, OPENCODE_OUTPUT_CAP, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, formatWindowSource, isSaneLimit, resolveOutputReserve, getSdkWindowGeometry, getSdkContextLimit, getSdkOutputLimit, getSdkInputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, resolvePiRealStableId, isPiContentFallbackId, isPiIndexFallbackId, piContentFallbackIds, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findRestartModelSeedFromBranch, iterateEntriesToRawMessageRange, iterateAsyncEntriesToRawMessageRange, convertEntriesToRawMessages, convertPiAssistantEntryById, convertEntriesToRawMessagePage, countPiRawMessages, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getSkippedDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, requestToolsFingerprint, classifyRequestToolsChange, requestToolSchemaDigest, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, withCachedM0MemoryIds, readCachedM0MemoryIds, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, TEMPORAL_MARKER_REPLAY_PATTERN, temporalMarkerPrefix, renderUserProfileContent, clearInjectionCache, getVisibleMemoryIds, orderHistorianMemories, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, resetPrefixTrimFallbackState, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, neutralizeOmpMentions, restoreOmpMentions, resolvePiHarnessDetection, resolvePiHarnessKind, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
@@ -68,7 +68,7 @@ import {
68
68
  import {
69
69
  gaDatabasePath2,
70
70
  V2StoreReader2
71
- } from "./index-ea37qn4x.js";
71
+ } from "./index-nvh6d3bz.js";
72
72
  import {
73
73
  deleteUnmappedMessageFtsRows2
74
74
  } from "./index-bbbp8zs1.js";
@@ -301,6 +301,50 @@ class V2StoreReader2 {
301
301
  }
302
302
  return statement;
303
303
  }
304
+ hasPartTable() {
305
+ this.connection.partTable ??= Boolean(this.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'session_part'").get());
306
+ return this.connection.partTable;
307
+ }
308
+ withParts(rows) {
309
+ const ids = rows.flatMap((row) => row.type === "assistant" ? [row.id] : []);
310
+ if (ids.length === 0 || !this.hasPartTable())
311
+ return rows;
312
+ const parts = new Map;
313
+ for (let offset = 0;offset < ids.length; offset += 500) {
314
+ const chunk = ids.slice(offset, offset + 500);
315
+ const partRows = this.prepare(`SELECT message_id, ordinal, data FROM session_part
316
+ WHERE message_id IN (${chunk.map(() => "?").join(", ")})
317
+ ORDER BY message_id ASC, ordinal ASC`).all(...chunk);
318
+ for (const part of partRows) {
319
+ let data;
320
+ try {
321
+ data = JSON.parse(part.data);
322
+ } catch {
323
+ throw new Error(`Invalid session_part data for ${part.message_id} at ordinal ${part.ordinal}`);
324
+ }
325
+ const list = parts.get(part.message_id);
326
+ if (list)
327
+ list.push(data);
328
+ else
329
+ parts.set(part.message_id, [data]);
330
+ }
331
+ }
332
+ if (parts.size === 0)
333
+ return rows;
334
+ return rows.map((row) => {
335
+ const content = parts.get(row.id);
336
+ if (!content)
337
+ return row;
338
+ const inline = row.data.content;
339
+ return {
340
+ ...row,
341
+ data: {
342
+ ...row.data,
343
+ content: Array.isArray(inline) ? [...content, ...inline] : content
344
+ }
345
+ };
346
+ });
347
+ }
304
348
  close() {
305
349
  if (this.closed)
306
350
  return;
@@ -330,9 +374,9 @@ class V2StoreReader2 {
330
374
  predicates.push("type = ?");
331
375
  parameters.push(options.type);
332
376
  }
333
- const rows = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
377
+ const rows = this.withParts(this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
334
378
  WHERE ${predicates.join(" AND ")}
335
- ORDER BY seq ASC LIMIT ?`).all(...parameters, limit).map(decode);
379
+ ORDER BY seq ASC LIMIT ?`).all(...parameters, limit).map(decode));
336
380
  return { rows, cursor: rows.at(-1)?.seq };
337
381
  });
338
382
  }
@@ -350,14 +394,14 @@ class V2StoreReader2 {
350
394
  if (after) {
351
395
  const anchor = this.prepare("SELECT seq FROM session_message WHERE session_id = ? AND id = ?").get(sessionID, after.id);
352
396
  if (anchor) {
353
- return this.prepare(`SELECT id, session_id, type, seq, time_created, data
397
+ return this.withParts(this.prepare(`SELECT id, session_id, type, seq, time_created, data
354
398
  FROM session_message WHERE session_id = ? AND seq > ?
355
- AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS}) ORDER BY seq ASC LIMIT ?`).all(sessionID, anchor.seq, ...RAW_MESSAGE_TYPES2, pageSize).map(decode);
399
+ AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS}) ORDER BY seq ASC LIMIT ?`).all(sessionID, anchor.seq, ...RAW_MESSAGE_TYPES2, pageSize).map(decode));
356
400
  }
357
401
  }
358
402
  const maximumSeq = Number.MAX_SAFE_INTEGER;
359
403
  const rows = this.prepare(V2_MESSAGE_PAGE_SQL).all(afterOrdinal, sessionID, ...RAW_MESSAGE_TYPES2, Math.max(0, afterOrdinal - 1), sessionID, sessionID, ...RAW_MESSAGE_TYPES2, finalWatermark - 1, maximumSeq, sessionID, ...RAW_MESSAGE_TYPES2, pageSize);
360
- return rows.map(decode);
404
+ return this.withParts(rows.map(decode));
361
405
  });
362
406
  }
363
407
  messageCount(sessionID) {
@@ -491,7 +535,7 @@ class V2StoreReader2 {
491
535
  const rawTypes = RAW_MESSAGE_TYPES2.map(() => "?").join(", ");
492
536
  const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
493
537
  WHERE session_id = ? AND id = ? AND type IN (${rawTypes}) LIMIT 1`).get(sessionID, id, ...RAW_MESSAGE_TYPES2);
494
- return row ? decode(row) : null;
538
+ return row ? this.withParts([decode(row)])[0] ?? null : null;
495
539
  });
496
540
  }
497
541
  messageTimeVersions(sessionID, ids, span) {
@@ -626,12 +670,20 @@ class V2StoreReader2 {
626
670
  spanRowStamps(sessionID, after, through) {
627
671
  if (!Number.isSafeInteger(after) || !Number.isSafeInteger(through))
628
672
  throw new Error("Invalid seq span");
629
- const rows = this.prepare(`SELECT seq, id, time_updated AS updated, length(CAST(data AS BLOB)) AS bytes
630
- FROM session_message WHERE session_id = ? AND seq > ? AND seq <= ?
631
- ORDER BY seq ASC`).all(sessionID, after, through);
673
+ const partJoin = this.hasPartTable() ? `LEFT JOIN (SELECT p.message_id AS message_id, COUNT(*) AS parts,
674
+ MAX(p.time_updated) AS partsUpdated,
675
+ SUM(length(CAST(p.data AS BLOB))) AS partsBytes
676
+ FROM session_message s JOIN session_part p ON p.message_id = s.id
677
+ WHERE s.session_id = ? AND s.seq > ? AND s.seq <= ?
678
+ GROUP BY p.message_id) g ON g.message_id = m.id` : "";
679
+ const rows = this.prepare(`SELECT m.seq AS seq, m.id AS id, m.time_updated AS updated,
680
+ length(CAST(m.data AS BLOB)) AS bytes${partJoin ? ", g.parts AS parts, g.partsUpdated AS partsUpdated, g.partsBytes AS partsBytes" : ""}
681
+ FROM session_message m ${partJoin}
682
+ WHERE m.session_id = ? AND m.seq > ? AND m.seq <= ?
683
+ ORDER BY m.seq ASC`).all(...partJoin ? [sessionID, after, through] : [], sessionID, after, through);
632
684
  const stamps = new Map;
633
685
  for (const row of rows)
634
- stamps.set(row.seq, `${row.id}\x00${row.updated ?? ""}\x00${row.bytes ?? ""}`);
686
+ stamps.set(row.seq, `${row.id}\x00${row.updated ?? ""}\x00${row.bytes ?? ""}${row.parts ? `\x00${row.parts}\x00${row.partsUpdated ?? ""}\x00${row.partsBytes ?? ""}` : ""}`);
635
687
  return stamps;
636
688
  }
637
689
  rawRowsThrough(sessionID, throughSeq, limit) {
@@ -641,9 +693,9 @@ class V2StoreReader2 {
641
693
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
642
694
  throw new Error("Invalid page limit");
643
695
  const rawTypes = RAW_MESSAGE_TYPES2.map(() => "?").join(", ");
644
- return this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
696
+ return this.withParts(this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
645
697
  WHERE session_id = ? AND type IN (${rawTypes}) AND seq <= ?
646
- ORDER BY seq DESC LIMIT ?`).all(sessionID, ...RAW_MESSAGE_TYPES2, throughSeq, limit).map(decode);
698
+ ORDER BY seq DESC LIMIT ?`).all(sessionID, ...RAW_MESSAGE_TYPES2, throughSeq, limit).map(decode));
647
699
  });
648
700
  }
649
701
  instructionRowsThrough(sessionID, throughSeq) {
@@ -734,7 +786,7 @@ class V2StoreReader2 {
734
786
  const rows = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
735
787
  WHERE session_id = ? AND type = 'assistant' AND seq > ?
736
788
  ORDER BY seq ASC`).all(sessionID, afterSeq);
737
- return rows.map((row) => decode(row));
789
+ return this.withParts(rows.map(decode));
738
790
  });
739
791
  }
740
792
  latestAssistant(sessionID) {
@@ -742,7 +794,7 @@ class V2StoreReader2 {
742
794
  const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
743
795
  WHERE session_id = ? AND type = 'assistant'
744
796
  ORDER BY seq DESC LIMIT 1`).get(sessionID);
745
- return row ? decode(row) : undefined;
797
+ return row ? this.withParts([decode(row)])[0] : undefined;
746
798
  });
747
799
  }
748
800
  latestIdle(sessionID) {
@@ -137,11 +137,11 @@ async function serveV2ArchiveReads2(port, openConnections) {
137
137
  { createV2RecoveryAttachments }
138
138
  ] = await Promise.all([
139
139
  import("./sqlite-v89bj0yy.js"),
140
- import("./store-reader-2m80zs5z.js"),
141
- import("./store-v60q7dje.js"),
140
+ import("./store-reader-mmfw2h48.js"),
141
+ import("./store-0hhs1db3.js"),
142
142
  import("./read-session-chunk-0ecmbegv.js"),
143
- import("./render-s6k2xqhj.js"),
144
- import("./search-archive-qza20zkm.js"),
143
+ import("./render-zcwm5nz3.js"),
144
+ import("./search-archive-9svkd0f6.js"),
145
145
  import("./expand-attachments-8sxeyj26.js")
146
146
  ]);
147
147
  const pool = new V2StoreReaderPool;
package/dist/index.js CHANGED
@@ -97,6 +97,9 @@ import {
97
97
  MEMORY_MURAL_BLOCK,
98
98
  buildMagicContextSection,
99
99
  resolveMuralWire,
100
+ requestToolsFingerprint,
101
+ classifyRequestToolsChange,
102
+ requestToolSchemaDigest,
100
103
  updateCompactionMarkerAfterPublication,
101
104
  COMPARTMENT_RENDER_EPOCH,
102
105
  MEMORY_RENDER_FORMAT_EPOCH,
@@ -150,7 +153,7 @@ import {
150
153
  registerTodoStateLifecycle,
151
154
  syncCtxMemoryToolEnabled,
152
155
  registerMagicContextTools
153
- } from "./index-k7gdgs11.js";
156
+ } from "./index-j9bhd718.js";
154
157
  import"./index-4knyh1kt.js";
155
158
  import {
156
159
  canonicalModelIdentity,
@@ -607,7 +610,7 @@ import {
607
610
  getSourceContents,
608
611
  recordSubagentInvocation,
609
612
  getLatestHistorianInvocationId
610
- } from "./index-6bedye3n.js";
613
+ } from "./index-nev91y6k.js";
611
614
  import {
612
615
  resolveOpenCodeDbPath,
613
616
  assertOpenCodeStoreGeneration,
@@ -626,7 +629,7 @@ import {
626
629
  import {
627
630
  RAW_SUMMARY_TEXT_MAX_CHARS2
628
631
  } from "./index-3g9fnq6y.js";
629
- import"./index-ea37qn4x.js";
632
+ import"./index-nvh6d3bz.js";
630
633
  import {
631
634
  formatSynapseLaneDescriptor
632
635
  } from "./index-gwvahsdz.js";
@@ -828,7 +831,7 @@ import {
828
831
  } from "./index-jaqdcqwz.js";
829
832
  import"./index-cq71g4dk.js";
830
833
  import"./index-1cvyaw9a.js";
831
- import"./index-nvgq29cw.js";
834
+ import"./index-tcm1gqcb.js";
832
835
  import"./index-v7m1nqwz.js";
833
836
  import {
834
837
  __toESM
@@ -3584,7 +3587,7 @@ function startHostStallProfilerSwitch() {
3584
3587
  // package.json
3585
3588
  var package_default = {
3586
3589
  name: "@cortexkit/pi-magic-context",
3587
- version: "0.49.45",
3590
+ version: "0.49.47",
3588
3591
  type: "module",
3589
3592
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3590
3593
  main: "dist/index.js",
@@ -25344,7 +25347,7 @@ function hasReclaimRide(signals) {
25344
25347
  return signals.hardFold || signals.force || signals.explicitFlush || signals.publishedHistory || signals.subagentExecute === true || signals.executeReclaim === true || signals.servedShapeRepair === true;
25345
25348
  }
25346
25349
  function prefixMutationPermitted(gate) {
25347
- return !gate.signedThinkingHold || gate.firstRender || gate.emergency;
25350
+ return !gate.signedThinkingHold || gate.firstRender || gate.hostCheckpointHead === true || gate.emergency;
25348
25351
  }
25349
25352
  function reclaimRidePermitted(signals, gate) {
25350
25353
  return prefixMutationPermitted(gate) && hasReclaimRide(signals);
@@ -27374,6 +27377,102 @@ function opencodeReasoningBudgetStatus(messages, budget, prefixBound, proseRatio
27374
27377
  };
27375
27378
  }
27376
27379
 
27380
+ // ../plugin/src/hooks/magic-context/recovery-fit.ts
27381
+ var RECOVERY_REFUSAL_NOTICE = "Magic Context is still summarizing older history so this conversation fits the model's context window. Send your message again to continue.";
27382
+ var RECOVERY_NO_HISTORY_REFUSAL_NOTICE = "This conversation no longer fits the model's context window, and Magic Context has no more older history it can summarize. Switch to a model with a larger context window to continue.";
27383
+ function recoveryLineTokens(windowTokens) {
27384
+ return Math.floor(windowTokens * BLOCK_UNTIL_DONE_PERCENTAGE / 100);
27385
+ }
27386
+ function recoveryAdmissionLimitTokens(windowTokens, historyRemains) {
27387
+ return historyRemains ? recoveryLineTokens(windowTokens) : Math.floor(windowTokens);
27388
+ }
27389
+ function recoveryRefusalNotice(historyRemains) {
27390
+ return historyRemains ? RECOVERY_REFUSAL_NOTICE : RECOVERY_NO_HISTORY_REFUSAL_NOTICE;
27391
+ }
27392
+
27393
+ // ../plugin/src/hooks/magic-context/request-tools-release.ts
27394
+ var NAMESPACE3 = "requestToolsRelease";
27395
+ var MAX_MODEL_RECORDS = 8;
27396
+ function parseEntry(value) {
27397
+ if (typeof value !== "object" || value === null)
27398
+ return null;
27399
+ const record = value;
27400
+ if (typeof record.modelKey !== "string" || typeof record.names !== "string" || typeof record.descriptions !== "string" || typeof record.schemas !== "string")
27401
+ return null;
27402
+ return {
27403
+ modelKey: record.modelKey,
27404
+ names: record.names,
27405
+ descriptions: record.descriptions,
27406
+ schemas: record.schemas
27407
+ };
27408
+ }
27409
+ function parseStored(value) {
27410
+ const models = value?.models;
27411
+ if (!Array.isArray(models))
27412
+ return [];
27413
+ const entries = [];
27414
+ for (const item of models) {
27415
+ const entry = parseEntry(item);
27416
+ if (entry)
27417
+ entries.push(entry);
27418
+ }
27419
+ return entries;
27420
+ }
27421
+ function sameEntry(left, right) {
27422
+ return left !== undefined && left.modelKey === right.modelKey && left.names === right.names && left.descriptions === right.descriptions && left.schemas === right.schemas;
27423
+ }
27424
+ function isLatest(entries, current) {
27425
+ return sameEntry(entries.at(-1), current);
27426
+ }
27427
+ function withLatest(entries, current) {
27428
+ const next = entries.filter((entry) => entry.modelKey !== current.modelKey);
27429
+ next.push(current);
27430
+ return next.slice(-MAX_MODEL_RECORDS);
27431
+ }
27432
+ function evaluateRequestToolsRelease(args) {
27433
+ const current = { modelKey: args.modelKey, ...args.fingerprint };
27434
+ let entries = [];
27435
+ let readable = true;
27436
+ try {
27437
+ entries = parseStored(readReplayEnvelope(args.db, args.sessionId, "read")[NAMESPACE3]);
27438
+ } catch (error) {
27439
+ readable = false;
27440
+ sessionLog2(args.sessionId, "request tools record unreadable:", error);
27441
+ }
27442
+ const stored = entries.find((entry) => entry.modelKey === current.modelKey);
27443
+ const change = stored ? classifyRequestToolsChange(stored, current) : null;
27444
+ if (change !== null) {
27445
+ sessionLog2(args.sessionId, `request tools changed (kind=${change === "schemas" ? "schema-only" : change}, model=${current.modelKey}, schemas ${stored?.schemas.slice(0, 12)}→${current.schemas.slice(0, 12)}): releasing signed thinking`);
27446
+ } else if (readable && !stored) {
27447
+ sessionLog2(args.sessionId, `request tools fingerprint adopted for model=${current.modelKey}${entries.length > 0 ? ` (records kept for ${entries.map((entry) => entry.modelKey).join(",")})` : ""}`);
27448
+ }
27449
+ return {
27450
+ change,
27451
+ commit: () => {
27452
+ if (!readable || isLatest(entries, current))
27453
+ return;
27454
+ try {
27455
+ let next = entries;
27456
+ const written = updateReplayDocument(args.db, args.sessionId, (doc) => {
27457
+ const latest = parseStored(doc[NAMESPACE3]);
27458
+ if (isLatest(latest, current))
27459
+ return false;
27460
+ next = withLatest(latest, current);
27461
+ doc.version = 2;
27462
+ doc[NAMESPACE3] = { models: next };
27463
+ return true;
27464
+ });
27465
+ if (written)
27466
+ entries = next;
27467
+ else
27468
+ sessionLog2(args.sessionId, "request tools record not written");
27469
+ } catch (error) {
27470
+ sessionLog2(args.sessionId, "request tools record write failed:", error);
27471
+ }
27472
+ }
27473
+ };
27474
+ }
27475
+
27377
27476
  // ../plugin/src/hooks/magic-context/signed-thinking-hold.ts
27378
27477
  var HEAVY_REASONING_TOKENS = 1500;
27379
27478
  var HEAVY_REASONING_WINDOW_STEPS = 15;
@@ -27854,7 +27953,7 @@ function resolveUnknownUsageFromWireEstimate(input) {
27854
27953
  const providerLimit = input.providerProvenLimitTokens;
27855
27954
  const canUseProviderMass = input.wireEstimateTrusted === false && typeof providerTokens === "number" && Number.isFinite(providerTokens) && providerTokens > 0 && typeof providerLimit === "number" && Number.isFinite(providerLimit) && providerLimit > 0;
27856
27955
  const tokens = canUseProviderMass ? Math.max(wireTokens, providerTokens) : wireTokens;
27857
- const limit = input.usableHardLimit;
27956
+ const limit = input.windowTokens;
27858
27957
  const estimatedPercentage = typeof limit === "number" && Number.isFinite(limit) && limit > 0 ? tokens / limit * 100 : input.usage.percentage;
27859
27958
  return {
27860
27959
  inputTokens: tokens,
@@ -30825,8 +30924,6 @@ ${chunkText}`,
30825
30924
  clearHistorianDrainFailure(db, sessionId);
30826
30925
  recordProtectedTailPublicationFloor(db, sessionId, lastNewEnd + 1);
30827
30926
  acknowledgePiHistoryRetirement(db, sessionId, lastNewEnd, (id) => provider.readMessages().find((message) => message.id === id)?.ordinal);
30828
- if (!isWrapupInProgress(db, sessionId))
30829
- clearEmergencyRecovery(db, sessionId);
30830
30927
  if (lastNewEndMessageId) {
30831
30928
  setPendingPiCompactionMarkerState(db, sessionId, {
30832
30929
  firstKeptEntryId,
@@ -41903,7 +42000,7 @@ function piRecoveryToolImageTokens(messages) {
41903
42000
  }
41904
42001
  return counts;
41905
42002
  }
41906
- function estimatePiOverflowRecoveryInputTokens(messages, envelope) {
42003
+ function estimatePiOverflowRecoveryInputTokens(messages, envelope, options = {}) {
41907
42004
  if (!envelope || !estimatePiOutgoingInputTokens([], envelope).trusted)
41908
42005
  return;
41909
42006
  const raw = tokenizePiMessages([...messages]);
@@ -41944,7 +42041,7 @@ function estimatePiOverflowRecoveryInputTokens(messages, envelope) {
41944
42041
  system: envelope.systemTokens,
41945
42042
  tools: envelope.toolDefinitionTokens + raw.toolCall,
41946
42043
  prose: raw.conversation
41947
- }, envelope.calibration ?? calibrationForModelKey(envelope.modelKey), true);
42044
+ }, envelope.calibration ?? calibrationForModelKey(envelope.modelKey), options.fitEnvelope ?? true);
41948
42045
  }
41949
42046
  function resolvePiOverflowRecoveryUsage(args) {
41950
42047
  if (!args.pricedPass || !args.providerOverflow || args.usage.inputTokens > 0)
@@ -41953,7 +42050,7 @@ function resolvePiOverflowRecoveryUsage(args) {
41953
42050
  usage: args.usage,
41954
42051
  pricedPass: args.pricedPass,
41955
42052
  wireEstimateTokens: estimatePiOverflowRecoveryInputTokens(args.messages, args.envelope),
41956
- usableHardLimit: args.usableHardLimit
42053
+ windowTokens: args.usableHardLimit
41957
42054
  });
41958
42055
  }
41959
42056
 
@@ -42272,6 +42369,167 @@ function resolvePiProvenInputFloor(args) {
42272
42369
  return observed;
42273
42370
  }
42274
42371
 
42372
+ // src/pi-request-tools.ts
42373
+ var schemaDigests = {
42374
+ omp: new WeakMap,
42375
+ anthropic: new WeakMap,
42376
+ "anthropic-strict": new WeakMap,
42377
+ raw: new WeakMap
42378
+ };
42379
+ function anthropicWireSchema(parameters, strict) {
42380
+ const schema = typeof parameters === "object" && parameters !== null ? parameters : {};
42381
+ const legacy = {
42382
+ type: "object",
42383
+ properties: schema.properties ?? {},
42384
+ required: schema.required ?? []
42385
+ };
42386
+ return strict ? { ...schema, ...legacy } : legacy;
42387
+ }
42388
+ function schemaDigest(tool, mode, wireSchema) {
42389
+ const key = tool.parameters;
42390
+ const cacheable = typeof key === "object" && key !== null || typeof key === "function";
42391
+ const cache = schemaDigests[mode];
42392
+ if (cacheable) {
42393
+ const cached = cache.get(key);
42394
+ if (cached !== undefined)
42395
+ return cached;
42396
+ }
42397
+ const digest = requestToolSchemaDigest(mode === "omp" && wireSchema ? wireSchema(tool) : mode === "anthropic" || mode === "anthropic-strict" ? anthropicWireSchema(tool.parameters, mode === "anthropic-strict") : tool.parameters);
42398
+ if (cacheable)
42399
+ cache.set(key, digest);
42400
+ return digest;
42401
+ }
42402
+ var CLAUDE_CODE_TOOL_NAMES = new Map([
42403
+ "Read",
42404
+ "Write",
42405
+ "Edit",
42406
+ "Bash",
42407
+ "Grep",
42408
+ "Glob",
42409
+ "AskUserQuestion",
42410
+ "EnterPlanMode",
42411
+ "ExitPlanMode",
42412
+ "KillShell",
42413
+ "NotebookEdit",
42414
+ "Skill",
42415
+ "Task",
42416
+ "TaskOutput",
42417
+ "TodoWrite",
42418
+ "WebFetch",
42419
+ "WebSearch"
42420
+ ].map((name) => [name.toLowerCase(), name]));
42421
+ var identityName = (name) => name;
42422
+ var claudeCodeName = (name) => CLAUDE_CODE_TOOL_NAMES.get(name.toLowerCase()) ?? name;
42423
+ function compatFlag(model, flag) {
42424
+ const value = model?.compat?.[flag];
42425
+ return typeof value === "boolean" ? value : undefined;
42426
+ }
42427
+ function supportsToolReferences(model) {
42428
+ const declared = compatFlag(model, "supportsToolReferences");
42429
+ if (declared !== undefined)
42430
+ return declared;
42431
+ if (model.provider !== "anthropic" || typeof model.id !== "string")
42432
+ return false;
42433
+ if (model.id.includes("haiku"))
42434
+ return false;
42435
+ const version = model.id.match(/^claude-(?:opus|sonnet|fable)-(\d+)(?:-(\d+))?(?:-|$)/);
42436
+ if (!version)
42437
+ return false;
42438
+ const major = Number(version[1]);
42439
+ const minor = version[2] && version[2].length < 8 ? Number(version[2]) : 0;
42440
+ return major > 4 || major === 4 && minor >= 5;
42441
+ }
42442
+ function deferredAndReferencedNames(messages, normalizeName) {
42443
+ const deferred = new Set;
42444
+ const referenced = new Set;
42445
+ for (const message of messages) {
42446
+ const { role, content, addedToolNames } = message ?? {};
42447
+ if (role === "assistant" && Array.isArray(content)) {
42448
+ for (const block of content) {
42449
+ const { type, name } = block ?? {};
42450
+ if (type === "toolCall" && typeof name === "string")
42451
+ referenced.add(normalizeName(name));
42452
+ }
42453
+ } else if (role === "toolResult" && Array.isArray(addedToolNames)) {
42454
+ for (const name of addedToolNames) {
42455
+ if (typeof name !== "string")
42456
+ continue;
42457
+ const normalized = normalizeName(name);
42458
+ if (!referenced.has(normalized))
42459
+ deferred.add(normalized);
42460
+ }
42461
+ }
42462
+ }
42463
+ for (const name of deferred)
42464
+ referenced.add(name);
42465
+ return { deferred, referenced };
42466
+ }
42467
+ function calledToolNames(messages) {
42468
+ const names = new Set;
42469
+ for (const message of messages) {
42470
+ const content = message?.content;
42471
+ if (!Array.isArray(content))
42472
+ continue;
42473
+ for (const part of content) {
42474
+ const { type, name } = part ?? {};
42475
+ if (typeof type === "string" && type.toLowerCase().includes("tool") && typeof name === "string")
42476
+ names.add(name);
42477
+ }
42478
+ }
42479
+ return names;
42480
+ }
42481
+ function readPiRequestToolsFingerprint(pi, wireSchema, messages, route = {}) {
42482
+ try {
42483
+ if (typeof pi.getAllTools !== "function" || typeof pi.getActiveTools !== "function")
42484
+ return;
42485
+ const all = pi.getAllTools();
42486
+ const active = pi.getActiveTools();
42487
+ if (!Array.isArray(all) || !Array.isArray(active))
42488
+ return;
42489
+ const registered = new Map;
42490
+ for (const tool of all) {
42491
+ if (!tool || typeof tool !== "object")
42492
+ return;
42493
+ const { name } = tool;
42494
+ if (typeof name !== "string")
42495
+ return;
42496
+ registered.set(name, tool);
42497
+ }
42498
+ const model = route.model;
42499
+ const anthropicWriter = route.host === "pi" && wireSchema === undefined && model?.api === "anthropic-messages";
42500
+ const mode = wireSchema ? "omp" : anthropicWriter ? compatFlag(model, "supportsStrictTools") === true ? "anthropic-strict" : "anthropic" : "raw";
42501
+ const normalizeName = anthropicWriter && route.oauth === true ? claudeCodeName : identityName;
42502
+ const sent = new Map;
42503
+ for (const name of active) {
42504
+ if (typeof name !== "string")
42505
+ return;
42506
+ const tool = registered.get(name);
42507
+ if (!tool)
42508
+ continue;
42509
+ sent.set(normalizeName(name), tool);
42510
+ }
42511
+ const split = anthropicWriter && model && supportsToolReferences(model) ? deferredAndReferencedNames(messages, normalizeName) : undefined;
42512
+ const anyImmediate = [...sent.keys()].some((name) => !split?.deferred.has(name));
42513
+ const tools = [];
42514
+ for (const [name, tool] of sent) {
42515
+ const description = typeof tool.description === "string" ? tool.description : "";
42516
+ tools.push({
42517
+ name,
42518
+ description,
42519
+ schemaDigest: schemaDigest({
42520
+ name: tool.name,
42521
+ description,
42522
+ parameters: tool.parameters
42523
+ }, mode, wireSchema),
42524
+ deferLoading: split ? anyImmediate && split.deferred.has(name) : tool.defer_loading === true || tool.deferLoading === true
42525
+ });
42526
+ }
42527
+ return requestToolsFingerprint(tools, () => split?.referenced ?? calledToolNames(messages));
42528
+ } catch {
42529
+ return;
42530
+ }
42531
+ }
42532
+
42275
42533
  // src/pi-tag-identity-repair.ts
42276
42534
  var PI_TAG_IDENTITY_REPAIR_REASON = "tag_identity_repair";
42277
42535
  var unreadableLedgerLogged = new Set;
@@ -42768,13 +43026,26 @@ function resolvePiBindingStripOrder(args) {
42768
43026
  if (hasThinkingPart(args.messages[index]))
42769
43027
  carriesThinking = true;
42770
43028
  }
42771
- const mayChangeOrder = onBranch && carriesThinking && args.bustPermittedAtStart;
42772
- if (mayChangeOrder && addMergedReasoningStrippedIds(args.db, args.sessionId, [
43029
+ if (onBranch && carriesThinking && args.bustPermittedAtStart && addMergedReasoningStrippedIds(args.db, args.sessionId, [
42773
43030
  THINKING_BINDING_STRIP_ORDER_END_MARKER
42774
43031
  ])) {
42775
43032
  return "end";
42776
43033
  }
42777
- return "start";
43034
+ return args.releasesAllThinking === true ? "end" : "start";
43035
+ }
43036
+ function recordPiBindingStripEndOrder(db, sessionId) {
43037
+ try {
43038
+ const ledger = getMergedReasoningStrippedIds(db, sessionId);
43039
+ if (ledger.has(THINKING_BINDING_STRIP_ORDER_END_MARKER))
43040
+ return true;
43041
+ if (frozenBindingEntryIds(db, sessionId).size === 0)
43042
+ return true;
43043
+ return addMergedReasoningStrippedIds(db, sessionId, [
43044
+ THINKING_BINDING_STRIP_ORDER_END_MARKER
43045
+ ]);
43046
+ } catch {
43047
+ return false;
43048
+ }
42778
43049
  }
42779
43050
  function shouldRunPiProactiveThinkingStrip(args) {
42780
43051
  return !args.compactionOff && args.bindingStripOrder === "end";
@@ -44368,6 +44639,7 @@ function logPiLkgRecovery(sessionId, message) {
44368
44639
  var PI_STABLE_ID_SCHEME = 1;
44369
44640
  var lastEmergencyNotificationAtMs = new Map;
44370
44641
  var EMERGENCY_NOTIFICATION_COOLDOWN_MS = 60000;
44642
+ var untrustedRecoveryCountLoggedSessions = new Set;
44371
44643
  var commitSeenLastPass = new Map;
44372
44644
  var historyRefreshSessions = new Set;
44373
44645
  var systemPromptRefreshSessions = new Set;
@@ -46224,12 +46496,34 @@ function registerPiContextHandler(pi, baseOptions) {
46224
46496
  const lkgInputIdByRef = new Map;
46225
46497
  for (const input of lkgPassSnapshot.inputs)
46226
46498
  lkgInputIdByRef.set(event.messages[input.messageIndex], input.id);
46499
+ const requestToolsRelease = isPrefixBoundThinkingModel(ctx.model?.provider, ctx.model?.id) ? (() => {
46500
+ const fingerprint = readPiRequestToolsFingerprint(pi, toolWireSchema, event.messages, {
46501
+ host: getHarness2() === "omp" ? "omp" : "pi",
46502
+ model: ctx.model,
46503
+ oauth: (() => {
46504
+ try {
46505
+ const registry = ctx.modelRegistry;
46506
+ return ctx.model && typeof registry?.isUsingOAuth === "function" ? registry.isUsingOAuth(ctx.model) === true : false;
46507
+ } catch {
46508
+ return false;
46509
+ }
46510
+ })()
46511
+ });
46512
+ return fingerprint ? evaluateRequestToolsRelease({
46513
+ db: options.db,
46514
+ sessionId,
46515
+ modelKey: `${ctx.model?.provider}/${ctx.model?.id}`,
46516
+ fingerprint
46517
+ }) : undefined;
46518
+ })() : undefined;
46519
+ const requestToolsChange = requestToolsRelease?.change ?? null;
46227
46520
  const bindingStripOrder = resolvePiBindingStripOrder({
46228
46521
  db: options.db,
46229
46522
  sessionId,
46230
46523
  messages: event.messages,
46231
46524
  entryIds: lkgEntryIds ?? [],
46232
- bustPermittedAtStart: hasPendingMaterialization(sessionId)
46525
+ bustPermittedAtStart: hasPendingMaterialization(sessionId),
46526
+ releasesAllThinking: requestToolsChange !== null
46233
46527
  });
46234
46528
  const startOfPassBindingRecovery = bindingStripOrder === "start" ? applyPiThinkingBindingRecovery({
46235
46529
  db: options.db,
@@ -46645,7 +46939,7 @@ function registerPiContextHandler(pi, baseOptions) {
46645
46939
  schedulerDeferReason,
46646
46940
  forceMaterialization: forceMaterialization || isEmergency,
46647
46941
  forceMaterializationPercentage,
46648
- signedThinkingHold: resolvePiSignedThinkingHold({
46942
+ signedThinkingHold: requestToolsChange === null && resolvePiSignedThinkingHold({
46649
46943
  sessionId,
46650
46944
  db: options.db,
46651
46945
  messages: event.messages,
@@ -46653,6 +46947,7 @@ function registerPiContextHandler(pi, baseOptions) {
46653
46947
  usagePercentage,
46654
46948
  executeThresholdPercentage: effectiveExecuteThresholdPercentage
46655
46949
  }),
46950
+ requestToolsChange,
46656
46951
  contextUsage: {
46657
46952
  percentage: usagePercentage,
46658
46953
  inputTokens: usageInputTokens
@@ -47283,6 +47578,26 @@ function registerPiContextHandler(pi, baseOptions) {
47283
47578
  if (getHarness2() === "pi" && classifyPiOutgoingFit(estimate, outgoingFitLimit) === "over-window-proof")
47284
47579
  throw new PiDegradedPassError("outgoing-over-window");
47285
47580
  }
47581
+ const recoveryWindow = windowGeometry?.usableHard;
47582
+ const recoveryLatch = !options.compactionOff && isEmergency && emergencyRecoveryArmed && typeof recoveryWindow === "number" && recoveryWindow > 0 ? getOverflowState(options.db, sessionId) : undefined;
47583
+ if (recoveryLatch?.needsEmergencyRecovery === true && recoveryLatch.emergencyRecoveryOrigin !== null && typeof recoveryWindow === "number") {
47584
+ const served = estimatePiOverflowRecoveryInputTokens(outputMessages, readPiLkgFitEnvelope(ctx, pi, resolvePiContextModelKey(ctx), sessionDecisionCalibration(options.db, sessionId), toolWireSchema), { fitEnvelope: false });
47585
+ const historyRemains = inFlightHistorian.has(sessionId);
47586
+ const limit = recoveryAdmissionLimitTokens(recoveryWindow, historyRemains);
47587
+ if (served !== undefined && served > limit) {
47588
+ sessionLog2(sessionId, historyRemains ? `transform: recovery request still over the window: about ${served} tokens against the 95% line ${limit} of ${recoveryWindow}; not sending it, recovery stays armed for the next turn` : `transform: recovery request still over the window: about ${served} tokens against the whole window ${limit}, with no older history left to summarize; not sending it`);
47589
+ throw contextRefusalError(recoveryRefusalNotice(historyRemains));
47590
+ }
47591
+ if (served === undefined) {
47592
+ if (!untrustedRecoveryCountLoggedSessions.has(sessionId)) {
47593
+ untrustedRecoveryCountLoggedSessions.add(sessionId);
47594
+ sessionLog2(sessionId, "transform: recovery request not counted: the fit envelope is untrusted (system prompt or tool definitions not measured yet), so only the byte-count check above applies");
47595
+ }
47596
+ } else {
47597
+ clearEmergencyRecovery(options.db, sessionId);
47598
+ sessionLog2(sessionId, `transform: recovery request admitted: about ${served} tokens, within ${limit} of ${recoveryWindow}; ${recoveryLatch.emergencyRecoveryOrigin} recovery ends`);
47599
+ }
47600
+ }
47286
47601
  publishFinalRequestAccounting();
47287
47602
  let serializedOutput;
47288
47603
  let numbersCommitted = false;
@@ -47368,7 +47683,11 @@ function registerPiContextHandler(pi, baseOptions) {
47368
47683
  }
47369
47684
  budget.assertOutcome();
47370
47685
  publishTransformDecision?.();
47371
- if (!budget.sideTurn && result.strictThinkingKept && !result.signedPrefixRewritten && !result.materialized)
47686
+ if (requestToolsChange === null || recordPiBindingStripEndOrder(options.db, sessionId))
47687
+ requestToolsRelease?.commit();
47688
+ else
47689
+ sessionLog2(sessionId, "request tools release not recorded: the end strip order could not be written");
47690
+ if (!budget.sideTurn && (result.strictThinkingKept && !result.signedPrefixRewritten || result.heldHeadReleasedForSystemChange === true) && !result.materialized)
47372
47691
  recordPiHeldSystemHead(sessionId, (ownsHistory) => deferPiDeliveredSystemRefresh(sessionId, ownsHistory));
47373
47692
  recordServedSystemHash();
47374
47693
  return { messages: outputMessages };
@@ -48111,7 +48430,7 @@ async function runCompactionOffPipeline(args) {
48111
48430
  muralEnabled: args.injection.muralEnabled === true,
48112
48431
  compactionOff: true
48113
48432
  };
48114
- const signedTurnHoldsHead = args.reasoningClearing?.prefixBound === true && hasActiveAnthropicThinkingTurn(args.messages, args.resolvedProviderID, args.resolvedModelID);
48433
+ const signedTurnHoldsHead = !args.requestToolsChange && args.reasoningClearing?.prefixBound === true && hasActiveAnthropicThinkingTurn(args.messages, args.resolvedProviderID, args.resolvedModelID);
48115
48434
  if (signedTurnHoldsHead)
48116
48435
  state.preparedPrefix = prepareCachedM0M1PiReplay(state, args.db, args.injectionPassSnapshot?.cachedRow);
48117
48436
  const servedBeforeFirstRender = signedTurnHoldsHead && !state.preparedPrefix ? args.readLastServedMessages?.() ?? null : undefined;
@@ -48128,7 +48447,7 @@ async function runCompactionOffPipeline(args) {
48128
48447
  sessionLog2(args.sessionId, "compaction-off fold changed the head: stripping signed thinking");
48129
48448
  }
48130
48449
  }
48131
- if (headChangedUnderSignedThinking)
48450
+ if (headChangedUnderSignedThinking || args.requestToolsChange)
48132
48451
  applyPiProactiveThinkingStrip({
48133
48452
  db: args.db,
48134
48453
  sessionId: args.sessionId,
@@ -48239,7 +48558,7 @@ async function runPipeline(args) {
48239
48558
  cacheBustingPass: isCacheBustingPass,
48240
48559
  stripActiveTurn: true,
48241
48560
  persistOnly: true,
48242
- requirePersistence: !!args.recoveryRebuildReason
48561
+ requirePersistence: !!args.recoveryRebuildReason || !!args.requestToolsChange
48243
48562
  });
48244
48563
  if (activeThinkingTurn && isCacheBustingPass && !result)
48245
48564
  throw new Error("Cannot persist signed thinking omission before prefix rewrite");
@@ -48249,6 +48568,8 @@ async function runPipeline(args) {
48249
48568
  };
48250
48569
  if (args.recoveryRebuildReason || args.forceSignedRebuildForFit && signedTurnOnPrefixBoundModel)
48251
48570
  stripForPrefixRewrite(isCacheBustingPass);
48571
+ if (args.requestToolsChange && !rewritingSignedPrefix)
48572
+ stripForPrefixRewrite();
48252
48573
  const stripUnheldSignedTurnOnBust = () => {
48253
48574
  if (isCacheBustingPass && signedTurnOnPrefixBoundModel && !protectedSignedPrefix && !rewritingSignedPrefix)
48254
48575
  stripForPrefixRewrite();
@@ -48426,6 +48747,12 @@ async function runPipeline(args) {
48426
48747
  const mismatch = foldDueDecision.mismatch ? ` mismatch=${JSON.stringify(foldDueDecision.mismatch)}` : "";
48427
48748
  sessionLog2(args.sessionId, `pi m[0] HARD fold decision: reason=${preFoldInjectionResult?.m0Reason ?? foldDueDecision.reason ?? "soft_refresh"}${mismatch} executed=${foldExecutedThisPass} bustsServedPrefix=${foldBustsServedPrefixThisPass}`);
48428
48749
  }
48750
+ let heldHeadReleasedForSystemChange = false;
48751
+ if (effectiveSystemChangedThisPass && protectedSignedPrefix) {
48752
+ sessionLog2(args.sessionId, "system prompt changed under a held signed turn: releasing signed thinking");
48753
+ heldHeadReleasedForSystemChange = !firstRenderBust && piM0State !== undefined;
48754
+ stripForPrefixRewrite();
48755
+ }
48429
48756
  const temporalCandidates = args.temporalAwareness ? collectPiTemporalCandidates(args.messages, args.entryIds ?? []) : new Map;
48430
48757
  for (const entry of readPiIdentityDecisions(args.db, args.sessionId) ?? []) {
48431
48758
  const decision = decodePiContentDecision(entry);
@@ -49437,12 +49764,14 @@ async function runPipeline(args) {
49437
49764
  stripPiLeadingTemporalMarker(message);
49438
49765
  }
49439
49766
  }
49440
- if (args.isCacheBusting && prefixMutationAllowed) {
49441
- historyRefreshSessions.delete(args.sessionId);
49442
- historyWasConsumedThisPass = true;
49443
- }
49444
- if (deferredHistoryRefresh && prefixMutationAllowed) {
49445
- historyWasConsumedThisPass = true;
49767
+ if (!heldHeadReleasedForSystemChange) {
49768
+ if (args.isCacheBusting && prefixMutationAllowed) {
49769
+ historyRefreshSessions.delete(args.sessionId);
49770
+ historyWasConsumedThisPass = true;
49771
+ }
49772
+ if (deferredHistoryRefresh && prefixMutationAllowed) {
49773
+ historyWasConsumedThisPass = true;
49774
+ }
49446
49775
  }
49447
49776
  logTransformTiming(args.sessionId, "prepareCompartmentInjection", tInjection);
49448
49777
  logTransformTiming(args.sessionId, "compartmentPhase", tInjection);
@@ -49690,6 +50019,7 @@ async function runPipeline(args) {
49690
50019
  prefixBustPermitted: isCacheBustingPass,
49691
50020
  prefixMutationAllowed,
49692
50021
  strictThinkingKept: protectedSignedPrefix,
50022
+ heldHeadReleasedForSystemChange,
49693
50023
  signedPrefixRewritten: rewritingSignedPrefix,
49694
50024
  prefixRebuildAlreadyPriced: firstRenderBust || !!args.recoveryRebuildReason && isCacheBustingPass,
49695
50025
  identityRebuilt: identityRebuild,
@@ -49951,6 +50281,7 @@ function clearContextHandlerSession(sessionId) {
49951
50281
  activeContextHandlerSessions.delete(sessionId);
49952
50282
  clearAutoSearchForPiSession(sessionId);
49953
50283
  lastEmergencyNotificationAtMs.delete(sessionId);
50284
+ untrustedRecoveryCountLoggedSessions.delete(sessionId);
49954
50285
  historyRefreshSessions.delete(sessionId);
49955
50286
  clearPendingMaterialization(pendingMaterializationSessions, sessionId);
49956
50287
  systemPromptRefreshSessions.delete(sessionId);
@@ -19,7 +19,7 @@ serveWorkerJobs(async (input, port) => {
19
19
  await main();
20
20
  async function main() {
21
21
  if (input.v2ArchiveReader) {
22
- const { serveV2ArchiveReads } = await import("./v2-archive-reader-2v7a879f.js");
22
+ const { serveV2ArchiveReads } = await import("./v2-archive-reader-ksmk6bfw.js");
23
23
  await serveV2ArchiveReads(port, openConnections);
24
24
  return;
25
25
  }
@@ -51,7 +51,7 @@ serveWorkerJobs(async (input, port) => {
51
51
  await runMessageFtsRowidMapBackfill(db);
52
52
  reply = { kind: "fts-rowid-backfill" };
53
53
  } else if (input.searchArchive) {
54
- const { renderSearchArchive } = await import("./search-archive-qza20zkm.js");
54
+ const { renderSearchArchive } = await import("./search-archive-9svkd0f6.js");
55
55
  const { readRawSessionMessageIdOrdinalsForRangeFromDb } = await import("./read-session-raw-nttnwy8p.js");
56
56
  const archive = input.searchArchive;
57
57
  let raw;
@@ -3,11 +3,11 @@ import {
3
3
  renderVerboseRange2,
4
4
  renderVerboseRangeForTool2,
5
5
  renderItemByTag2
6
- } from "./index-6bedye3n.js";
6
+ } from "./index-nev91y6k.js";
7
7
  import"./index-w26zvs1q.js";
8
8
  import"./index-fzadydec.js";
9
9
  import"./index-hgd00nas.js";
10
- import"./index-ea37qn4x.js";
10
+ import"./index-nvh6d3bz.js";
11
11
  import"./index-4sa1rx3h.js";
12
12
  import"./index-7esg5v2x.js";
13
13
  import"./index-zchc0df8.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  renderSearchArchive2
3
3
  } from "./index-v7m1nqwz.js";
4
- import"./index-nvgq29cw.js";
4
+ import"./index-tcm1gqcb.js";
5
5
  import"./index-1cvyaw9a.js";
6
6
  import"./index-7esg5v2x.js";
7
7
  import"./index-zchc0df8.js";
@@ -4,7 +4,7 @@ import"./index-n0zjvs3h.js";
4
4
  import"./index-2qtx0q6h.js";
5
5
  import {
6
6
  RAW_MESSAGE_TYPES2
7
- } from "./index-ea37qn4x.js";
7
+ } from "./index-nvh6d3bz.js";
8
8
  import {
9
9
  markHostUnservedRow
10
10
  } from "./index-by1bzjcd.js";
@@ -3,7 +3,7 @@ import {
3
3
  RAW_MESSAGE_TYPES2,
4
4
  V2StoreReaderPool2,
5
5
  V2StoreReader2
6
- } from "./index-ea37qn4x.js";
6
+ } from "./index-nvh6d3bz.js";
7
7
  import"./index-n0zjvs3h.js";
8
8
  import"./index-2qtx0q6h.js";
9
9
  export {
@@ -34,7 +34,7 @@ import {
34
34
  ensureProjectRegisteredFromPiDirectory,
35
35
  resolvePiHarnessKind,
36
36
  registerMagicContextTools
37
- } from "./index-k7gdgs11.js";
37
+ } from "./index-j9bhd718.js";
38
38
  import"./index-gzk7d940.js";
39
39
  import"./index-gwvahsdz.js";
40
40
  import"./index-4sa1rx3h.js";
@@ -45,14 +45,14 @@ import"./index-9p40dgkm.js";
45
45
  import"./index-mp0gh04g.js";
46
46
  import"./index-yhzhdp3m.js";
47
47
  import"./index-zwbgxt01.js";
48
- import"./index-6bedye3n.js";
48
+ import"./index-nev91y6k.js";
49
49
  import"./index-fzadydec.js";
50
50
  import"./index-zchc0df8.js";
51
51
  import"./index-6x556c2q.js";
52
- import"./index-ea37qn4x.js";
52
+ import"./index-nvh6d3bz.js";
53
53
  import"./index-w26zvs1q.js";
54
54
  import"./index-1cvyaw9a.js";
55
- import"./index-nvgq29cw.js";
55
+ import"./index-tcm1gqcb.js";
56
56
  import"./index-v7m1nqwz.js";
57
57
  import"./index-29nw7n1r.js";
58
58
  import"./index-qt711raa.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readV2ArchiveOffThread2,
3
3
  serveV2ArchiveReads2
4
- } from "./index-nvgq29cw.js";
4
+ } from "./index-tcm1gqcb.js";
5
5
  import"./index-8sqebjzk.js";
6
6
  import"./index-2qtx0q6h.js";
7
7
  import"./index-x2n261wp.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.49.45",
3
+ "version": "0.49.47",
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",