@retaw106/mmc-oc 2.4.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/dist/{context-c72brxe5.js → context-cfbjrr0n.js} +1636 -513
  2. package/dist/features/magic-context/compaction-marker.d.ts +34 -6
  3. package/dist/features/magic-context/compaction-marker.d.ts.map +1 -1
  4. package/dist/features/magic-context/message-index-async.d.ts +6 -2
  5. package/dist/features/magic-context/message-index-async.d.ts.map +1 -1
  6. package/dist/features/magic-context/message-index.d.ts +0 -26
  7. package/dist/features/magic-context/message-index.d.ts.map +1 -1
  8. package/dist/features/magic-context/search.d.ts +5 -1
  9. package/dist/features/magic-context/search.d.ts.map +1 -1
  10. package/dist/features/magic-context/session-decision-calibration.d.ts.map +1 -1
  11. package/dist/features/magic-context/session-retention.fixture.d.ts +4 -0
  12. package/dist/features/magic-context/session-retention.fixture.d.ts.map +1 -0
  13. package/dist/features/magic-context/storage-db.d.ts +2 -0
  14. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  15. package/dist/features/magic-context/storage-host-instruction-retention.d.ts +4 -0
  16. package/dist/features/magic-context/storage-host-instruction-retention.d.ts.map +1 -0
  17. package/dist/features/magic-context/storage-meta-persisted.d.ts +21 -1
  18. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  19. package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
  20. package/dist/features/magic-context/storage-meta-shared.d.ts +2 -2
  21. package/dist/features/magic-context/storage-meta-shared.d.ts.map +1 -1
  22. package/dist/features/magic-context/storage-native-replay.d.ts +2 -0
  23. package/dist/features/magic-context/storage-native-replay.d.ts.map +1 -1
  24. package/dist/features/magic-context/storage-session-tables.d.ts +5 -4
  25. package/dist/features/magic-context/storage-session-tables.d.ts.map +1 -1
  26. package/dist/features/magic-context/tool-definition-tokens.d.ts +113 -58
  27. package/dist/features/magic-context/tool-definition-tokens.d.ts.map +1 -1
  28. package/dist/features/magic-context/work-metrics.d.ts +5 -3
  29. package/dist/features/magic-context/work-metrics.d.ts.map +1 -1
  30. package/dist/hooks/magic-context/apply-operations.d.ts +32 -0
  31. package/dist/hooks/magic-context/apply-operations.d.ts.map +1 -1
  32. package/dist/hooks/magic-context/ask-answer-notice.d.ts +25 -0
  33. package/dist/hooks/magic-context/ask-answer-notice.d.ts.map +1 -0
  34. package/dist/hooks/magic-context/auto-search-hint.d.ts +3 -0
  35. package/dist/hooks/magic-context/auto-search-hint.d.ts.map +1 -1
  36. package/dist/hooks/magic-context/auto-search-runner.d.ts.map +1 -1
  37. package/dist/hooks/magic-context/channel2-delivery.d.ts.map +1 -1
  38. package/dist/hooks/magic-context/compaction-marker-manager.d.ts +5 -5
  39. package/dist/hooks/magic-context/compaction-marker-manager.d.ts.map +1 -1
  40. package/dist/hooks/magic-context/compaction-marker-publication.d.ts +14 -0
  41. package/dist/hooks/magic-context/compaction-marker-publication.d.ts.map +1 -0
  42. package/dist/hooks/magic-context/compaction-off-transition.d.ts.map +1 -1
  43. package/dist/hooks/magic-context/compartment-runner-historian.d.ts +2 -2
  44. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts +11 -0
  45. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  46. package/dist/hooks/magic-context/compartment-runner-validation.d.ts.map +1 -1
  47. package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
  48. package/dist/hooks/magic-context/diagnostic-log-state.d.ts +4 -0
  49. package/dist/hooks/magic-context/diagnostic-log-state.d.ts.map +1 -0
  50. package/dist/hooks/magic-context/emergency-drop.d.ts.map +1 -1
  51. package/dist/hooks/magic-context/file-token-coverage.d.ts +11 -0
  52. package/dist/hooks/magic-context/file-token-coverage.d.ts.map +1 -0
  53. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts +11 -3
  54. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
  55. package/dist/hooks/magic-context/historian-history-wait.d.ts +16 -0
  56. package/dist/hooks/magic-context/historian-history-wait.d.ts.map +1 -0
  57. package/dist/hooks/magic-context/history-boundary-repair.d.ts +1 -1
  58. package/dist/hooks/magic-context/history-boundary-repair.d.ts.map +1 -1
  59. package/dist/hooks/magic-context/hook-handlers.d.ts.map +1 -1
  60. package/dist/hooks/magic-context/host-served-rows.d.ts +10 -0
  61. package/dist/hooks/magic-context/host-served-rows.d.ts.map +1 -1
  62. package/dist/hooks/magic-context/inject-compartments.d.ts +1 -1
  63. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  64. package/dist/hooks/magic-context/lkg-measured-request.d.ts.map +1 -1
  65. package/dist/hooks/magic-context/lkg-recovery-fence.d.ts.map +1 -1
  66. package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts +3 -1
  67. package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts.map +1 -1
  68. package/dist/hooks/magic-context/lkg-replay-fit.d.ts.map +1 -1
  69. package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
  70. package/dist/hooks/magic-context/lkg-slot.d.ts +3 -1
  71. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  72. package/dist/hooks/magic-context/nudge-evaluation-log.d.ts +3 -0
  73. package/dist/hooks/magic-context/nudge-evaluation-log.d.ts.map +1 -0
  74. package/dist/hooks/magic-context/pass-outcome.d.ts +2 -0
  75. package/dist/hooks/magic-context/pass-outcome.d.ts.map +1 -1
  76. package/dist/hooks/magic-context/pending-drop-eligibility.d.ts.map +1 -1
  77. package/dist/hooks/magic-context/protected-tail-boundary.d.ts +2 -0
  78. package/dist/hooks/magic-context/protected-tail-boundary.d.ts.map +1 -1
  79. package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
  80. package/dist/hooks/magic-context/read-session-db.d.ts +8 -2
  81. package/dist/hooks/magic-context/read-session-db.d.ts.map +1 -1
  82. package/dist/hooks/magic-context/read-session-raw.d.ts +20 -0
  83. package/dist/hooks/magic-context/read-session-raw.d.ts.map +1 -1
  84. package/dist/hooks/magic-context/recomp-orchestrator.d.ts +3 -3
  85. package/dist/hooks/magic-context/recomp-orchestrator.d.ts.map +1 -1
  86. package/dist/hooks/magic-context/signed-thinking-fit-snapshot.d.ts +42 -0
  87. package/dist/hooks/magic-context/signed-thinking-fit-snapshot.d.ts.map +1 -0
  88. package/dist/hooks/magic-context/system-date-refresh.d.ts +3 -2
  89. package/dist/hooks/magic-context/system-date-refresh.d.ts.map +1 -1
  90. package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
  91. package/dist/hooks/magic-context/system-prompt-sticky-date.d.ts +4 -0
  92. package/dist/hooks/magic-context/system-prompt-sticky-date.d.ts.map +1 -0
  93. package/dist/hooks/magic-context/tag-content-primitives.d.ts +1 -1
  94. package/dist/hooks/magic-context/tag-content-primitives.d.ts.map +1 -1
  95. package/dist/hooks/magic-context/tag-messages.d.ts +17 -2
  96. package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
  97. package/dist/hooks/magic-context/text-complete.d.ts +1 -1
  98. package/dist/hooks/magic-context/text-complete.d.ts.map +1 -1
  99. package/dist/hooks/magic-context/tool-drop-target.d.ts +3 -2
  100. package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
  101. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +1 -0
  102. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  103. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +6 -0
  104. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  105. package/dist/hooks/magic-context/transform-stage-logger.d.ts +3 -0
  106. package/dist/hooks/magic-context/transform-stage-logger.d.ts.map +1 -1
  107. package/dist/hooks/magic-context/transform.d.ts +4 -2
  108. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  109. package/dist/{index-27ddyx39.js → index-1np16gxq.js} +1 -1
  110. package/dist/{index-ykq24x1n.js → index-8rmt6s4f.js} +78 -32
  111. package/dist/{index-dwh99z66.js → index-pte3cfs9.js} +194 -5
  112. package/dist/{index-r7s7d350.js → index-s3ebcy63.js} +1 -1
  113. package/dist/{index-48e9znrc.js → index-t0zx3tgz.js} +481 -109
  114. package/dist/{index-kahkxcqw.js → index-xk1dz6q9.js} +870 -315
  115. package/dist/index.js +2 -2
  116. package/dist/{message-time-backfill-j96x1sab.js → message-time-backfill-g9py24yt.js} +1 -1
  117. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  118. package/dist/plugin/subagent-tool-policy.d.ts +4 -0
  119. package/dist/plugin/subagent-tool-policy.d.ts.map +1 -1
  120. package/dist/{read-session-chunk-t8bg6wkz.js → read-session-chunk-2s8x6xps.js} +3 -3
  121. package/dist/{recomp-orchestrator-k760qy1n.js → recomp-orchestrator-51xyaexp.js} +6 -6
  122. package/dist/{send-session-notification-njjf3b4s.js → send-session-notification-vdppp5x6.js} +3 -3
  123. package/dist/shared/model-suggestion-retry.d.ts +2 -0
  124. package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
  125. package/dist/shared/rpc-discovery-cleanup.d.ts +3 -0
  126. package/dist/shared/rpc-discovery-cleanup.d.ts.map +1 -0
  127. package/dist/shared/rpc-server.d.ts +2 -0
  128. package/dist/shared/rpc-server.d.ts.map +1 -1
  129. package/dist/shared/search-text.d.ts +8 -0
  130. package/dist/shared/search-text.d.ts.map +1 -0
  131. package/dist/shared/sqlite.d.ts +6 -1
  132. package/dist/shared/sqlite.d.ts.map +1 -1
  133. package/dist/shared/storage-file-mutex.d.ts.map +1 -1
  134. package/dist/shared/system-directive.d.ts +2 -0
  135. package/dist/shared/system-directive.d.ts.map +1 -1
  136. package/dist/shared/tag-transcript.d.ts +2 -0
  137. package/dist/shared/tag-transcript.d.ts.map +1 -1
  138. package/dist/shared/transcript.d.ts +3 -1
  139. package/dist/shared/transcript.d.ts.map +1 -1
  140. package/dist/tools/ctx-memory/tools.d.ts.map +1 -1
  141. package/dist/tools/ctx-note/tools.d.ts.map +1 -1
  142. package/dist/tools/parameter-descriptions.d.ts +6 -6
  143. package/dist/tools/parameter-descriptions.d.ts.map +1 -1
  144. package/dist/v2/fold/native-replay.d.ts +11 -2
  145. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  146. package/dist/v2/fold/policy.d.ts.map +1 -1
  147. package/dist/v2/fold/restore.d.ts.map +1 -1
  148. package/dist/v2/hooks/context.d.ts +4 -0
  149. package/dist/v2/hooks/context.d.ts.map +1 -1
  150. package/dist/v2/hooks/generate.d.ts +36 -1
  151. package/dist/v2/hooks/generate.d.ts.map +1 -1
  152. package/dist/v2/hooks/lkg-system.d.ts +35 -4
  153. package/dist/v2/hooks/lkg-system.d.ts.map +1 -1
  154. package/dist/v2/hooks/payload.d.ts +10 -1
  155. package/dist/v2/hooks/payload.d.ts.map +1 -1
  156. package/dist/v2/hooks/store.d.ts +2 -0
  157. package/dist/v2/hooks/store.d.ts.map +1 -1
  158. package/dist/v2/hooks/types.d.ts +12 -0
  159. package/dist/v2/hooks/types.d.ts.map +1 -1
  160. package/dist/v2/message-times.d.ts +17 -0
  161. package/dist/v2/message-times.d.ts.map +1 -0
  162. package/dist/v2/server.js +4692 -2394
  163. package/dist/v2/store-reader.d.ts +21 -0
  164. package/dist/v2/store-reader.d.ts.map +1 -1
  165. package/dist/web/main.js +307 -12
  166. package/dist/{wrapup-orchestrator-b2gswatj.js → wrapup-orchestrator-g0mww1h4.js} +6 -6
  167. package/package.json +1 -1
  168. package/src/config/latch-permanence-guard.test.ts +4 -5
  169. package/src/shared/model-suggestion-retry.test.ts +52 -0
  170. package/src/shared/model-suggestion-retry.ts +8 -3
  171. package/src/shared/prompt-surface-a1-golden.md +6 -7
  172. package/src/shared/rpc-discovery-cleanup.test.ts +125 -0
  173. package/src/shared/rpc-discovery-cleanup.ts +57 -0
  174. package/src/shared/rpc-server.ts +36 -13
  175. package/src/shared/search-text.test.ts +30 -0
  176. package/src/shared/search-text.ts +62 -0
  177. package/src/shared/sqlite-transaction-mode-guard.test.ts +2 -0
  178. package/src/shared/sqlite-turn-deadline.test.ts +286 -0
  179. package/src/shared/sqlite.ts +237 -9
  180. package/src/shared/storage-file-mutex.test.ts +51 -2
  181. package/src/shared/storage-file-mutex.ts +11 -1
  182. package/src/shared/system-directive.test.ts +37 -0
  183. package/src/shared/system-directive.ts +19 -1
  184. package/src/shared/tag-transcript.ts +63 -8
  185. package/src/shared/transcript.ts +1 -1
  186. package/src/shared/write-transaction-attribution.test.ts +1 -6
  187. package/dist/features/magic-context/message-index-sweep.d.ts +0 -11
  188. package/dist/features/magic-context/message-index-sweep.d.ts.map +0 -1
@@ -7,7 +7,7 @@ import {
7
7
  } from "./index-x37vg474.js";
8
8
  import {
9
9
  getTagIdentityWriteGeneration
10
- } from "./index-dwh99z66.js";
10
+ } from "./index-pte3cfs9.js";
11
11
  import {
12
12
  getHarness,
13
13
  sessionLog
@@ -28,7 +28,7 @@ import {
28
28
  withReadOnlySessionDb,
29
29
  getRawSessionMessageCountFromDb,
30
30
  getMessageTimesFromOpenCodeDb
31
- } from "./index-ykq24x1n.js";
31
+ } from "./index-8rmt6s4f.js";
32
32
 
33
33
  // src/shared/protected-tools-policy.ts
34
34
  var DEFAULT_PROTECTED_TOOLS = {
@@ -102,7 +102,27 @@ function isSystemDirective(text) {
102
102
  return text.trimStart().startsWith(SYSTEM_DIRECTIVE_PREFIX);
103
103
  }
104
104
  function removeSystemReminders(text) {
105
- return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gi, "").trim();
105
+ return removeNestedBlocks(text, ["system-reminder"]).trim();
106
+ }
107
+ function removeNestedBlocks(text, names) {
108
+ const tags = new RegExp(`<(/?)(${names.join("|")})(?:\\s[^<>]*?)?\\s*(/?)>`, "gi");
109
+ const stack = [];
110
+ let end = 0;
111
+ let result = "";
112
+ for (const match of text.matchAll(tags)) {
113
+ if (stack.length === 0)
114
+ result += text.slice(end, match.index);
115
+ const name = match[2].toLowerCase();
116
+ if (match[1]) {
117
+ if (stack[stack.length - 1] === name)
118
+ stack.pop();
119
+ } else if (!match[3])
120
+ stack.push(name);
121
+ end = match.index + match[0].length;
122
+ }
123
+ if (stack.length === 0)
124
+ result += text.slice(end);
125
+ return result;
106
126
  }
107
127
 
108
128
  // src/hooks/magic-context/token-count-exact.ts
@@ -807,13 +827,16 @@ function stripDanglingTagNotationGlobally(value) {
807
827
  function stripTagSectionCharacters(value) {
808
828
  return value.replace(STRAY_SECTION_CHAR_REGEX, "");
809
829
  }
810
- function stripPersistedAssistantText(value) {
830
+ function stripPersistedAssistantText(value, acceptsEmpty = true) {
831
+ if (!acceptsEmpty && !value.includes("§") && !value.trim())
832
+ return value;
811
833
  let text = stripWellFormedLeadingTagPrefix(value);
812
834
  text = stripCompleteTagPairsGlobally(text);
813
835
  text = stripMalformedTagNotationGlobally(text);
814
836
  text = stripDanglingTagNotationGlobally(text);
815
837
  text = stripTagSectionCharacters(text);
816
- return text.trim();
838
+ const stripped = text.trim();
839
+ return !acceptsEmpty && value.trim().length > 0 && stripped.length === 0 ? value : stripped;
817
840
  }
818
841
  function byteSize(value) {
819
842
  return encoder.encode(value).length;
@@ -2832,9 +2855,11 @@ function planEmergencyDrop(input) {
2832
2855
  const workingSpan = Math.max(ceilingTokens - fixedFloor, 0);
2833
2856
  const target = fixedFloor + TARGET_FRACTION * workingSpan;
2834
2857
  const reclaimTokens = Math.round(currentTotalInputTokens - target);
2835
- const floorNote = fixedFloor > ceilingTokens ? `; fixed floor ≈${Math.round(fixedFloor)} already exceeds ceiling ${Math.round(ceilingTokens)}: tool drops cannot reach the target` : "";
2858
+ if (fixedFloor > ceilingTokens) {
2859
+ return noop(`fixed floor ≈${Math.round(fixedFloor)} already exceeds ceiling ${Math.round(ceilingTokens)}: tool drops cannot reach the target`);
2860
+ }
2836
2861
  if (reclaimTokens <= EMERGENCY_REARM_MIN_TOKENS) {
2837
- return noop(`reclaim<=min (${reclaimTokens} <= ${EMERGENCY_REARM_MIN_TOKENS})${floorNote}`);
2862
+ return noop(`reclaim<=min (${reclaimTokens} <= ${EMERGENCY_REARM_MIN_TOKENS})`);
2838
2863
  }
2839
2864
  const cutoff = input.protectedCutoff;
2840
2865
  const windowYields = absoluteEmergency;
@@ -2889,16 +2914,16 @@ function planEmergencyDrop(input) {
2889
2914
  }
2890
2915
  }
2891
2916
  if (selected.length === 0) {
2892
- return noop(`no-candidates${floorNote}`);
2917
+ return noop("no-candidates");
2893
2918
  }
2894
2919
  if (!input.passAlreadyPriced && reclaimed < EMERGENCY_MIN_ACHIEVABLE_RECLAIM_TOKENS) {
2895
- return noop(`achievable reclaim below minimum (${selected.length} tags, reclaim≈${Math.round(reclaimed)} < ${EMERGENCY_MIN_ACHIEVABLE_RECLAIM_TOKENS} against gap ${reclaimTokens})${floorNote}`);
2920
+ return noop(`achievable reclaim below minimum (${selected.length} tags, reclaim≈${Math.round(reclaimed)} < ${EMERGENCY_MIN_ACHIEVABLE_RECLAIM_TOKENS} against gap ${reclaimTokens})`);
2896
2921
  }
2897
2922
  return {
2898
2923
  shouldDrop: true,
2899
2924
  tagNumbers: selected,
2900
2925
  reclaimTokens,
2901
- reason: `tiered drop: ${selected.length} tags, reclaim≈${reclaimed}/${reclaimTokens} tokens (floor≈${fixedFloor}, ceiling=${Math.round(ceilingTokens)})${floorNote}`
2926
+ reason: `tiered drop: ${selected.length} tags, reclaim≈${reclaimed}/${reclaimTokens} tokens (floor≈${fixedFloor}, ceiling=${Math.round(ceilingTokens)})`
2902
2927
  };
2903
2928
  }
2904
2929
  function measureEmergencyTag(tag, target, calibration, skeleton) {
@@ -4665,6 +4690,70 @@ function expandToolPart(part, overrides, legacyPreview = false) {
4665
4690
  return renderToolTemplate(template, input, state?.output ?? state?.error, legacyPreview);
4666
4691
  }
4667
4692
 
4693
+ // src/hooks/magic-context/ask-answer-notice.ts
4694
+ var ANSWER_HEADER_PREFIX = /^Inbox [^\n]* notice from user via user_answer \(user_answer\)/;
4695
+ var ANSWER_TRAILER = /\n([\s\S]*?)\nThis ask is now closed; no dismiss is needed\. Continue accordingly\.$/;
4696
+ var ANSWER_ANSWER_LINE = /^The user answered your parked question (\S+)\.\nQuestion: ([^\n]+)\nAnswer: /;
4697
+ var ANSWER_QUESTION_LINE = /^Question: ([^\n]+)\nAnswer: /;
4698
+ var reminderEnvelopePattern = /<system-reminder>([\s\S]*?)<\/system-reminder>/gi;
4699
+ function reminderBodies(text) {
4700
+ reminderEnvelopePattern.lastIndex = 0;
4701
+ const bodies = [];
4702
+ for (const match of text.matchAll(reminderEnvelopePattern)) {
4703
+ const body = match[1];
4704
+ if (body !== undefined)
4705
+ bodies.push(body);
4706
+ }
4707
+ return bodies;
4708
+ }
4709
+ function parseAnswerBody(body) {
4710
+ const lines = body.replace(/\r\n/g, `
4711
+ `).replace(/^\n+|\n+$/g, "");
4712
+ if (!ANSWER_HEADER_PREFIX.test(lines))
4713
+ return null;
4714
+ if (lines.includes("The user dismissed this question"))
4715
+ return null;
4716
+ const framed = ANSWER_TRAILER.exec(lines);
4717
+ if (framed === null)
4718
+ return null;
4719
+ const content = framed[1] ?? "";
4720
+ const narrated = ANSWER_ANSWER_LINE.exec(content);
4721
+ if (narrated !== null) {
4722
+ const question = narrated[2] ?? "";
4723
+ const answer = content.slice(narrated[0].length);
4724
+ return closedAnswer(question, answer);
4725
+ }
4726
+ const bare = ANSWER_QUESTION_LINE.exec(content);
4727
+ if (bare !== null) {
4728
+ const question = bare[1] ?? "";
4729
+ const answer = content.slice(bare[0].length);
4730
+ return closedAnswer(question, answer);
4731
+ }
4732
+ return null;
4733
+ }
4734
+ function closedAnswer(question, answer) {
4735
+ if (question.trim().length === 0)
4736
+ return null;
4737
+ if (answer.trim().length === 0)
4738
+ return null;
4739
+ return { question, answer };
4740
+ }
4741
+ function extractAskAnswerNotices(text) {
4742
+ const notices = [];
4743
+ for (const body of reminderBodies(text)) {
4744
+ const notice = parseAnswerBody(body);
4745
+ if (notice !== null)
4746
+ notices.push(notice);
4747
+ }
4748
+ return notices;
4749
+ }
4750
+ function formatAskAnswerNotice(notice) {
4751
+ return `U (answered "${notice.question}"): ${notice.answer}`;
4752
+ }
4753
+ function askAnswerLines(text) {
4754
+ return extractAskAnswerNotices(text).map(formatAskAnswerNotice);
4755
+ }
4756
+
4668
4757
  // src/hooks/magic-context/host-served-rows.ts
4669
4758
  var HOST_UNSERVED_ROW = "hostUnservedRow";
4670
4759
  function markHostUnservedRow(target) {
@@ -4723,6 +4812,35 @@ function isHostRenderedSystemMessage(message) {
4723
4812
  const id = message.info.id;
4724
4813
  return (typeof id !== "string" || id.length === 0) && message.info.role === "system";
4725
4814
  }
4815
+ var COVERED_INSTRUCTION_ROW = "coveredInstructionRow";
4816
+ function markCoveredInstructionRow(target) {
4817
+ Object.defineProperty(target, COVERED_INSTRUCTION_ROW, {
4818
+ value: true,
4819
+ enumerable: false,
4820
+ configurable: true
4821
+ });
4822
+ return target;
4823
+ }
4824
+ function isCoveredInstructionRow(value) {
4825
+ return typeof value === "object" && value !== null && value[COVERED_INSTRUCTION_ROW] === true;
4826
+ }
4827
+ function takeCoveredInstructionRows(messages) {
4828
+ const taken = messages.filter((message) => isCoveredInstructionRow(message.info));
4829
+ if (taken.length > 0) {
4830
+ const kept = messages.filter((message) => !isCoveredInstructionRow(message.info));
4831
+ messages.splice(0, messages.length, ...kept);
4832
+ }
4833
+ return taken;
4834
+ }
4835
+ function cloneKeepingCoveredInstructionMarks(messages) {
4836
+ const copy = structuredClone(messages);
4837
+ messages.forEach((message, index) => {
4838
+ const copied = copy[index];
4839
+ if (copied && isCoveredInstructionRow(message.info))
4840
+ markCoveredInstructionRow(copied.info);
4841
+ });
4842
+ return copy;
4843
+ }
4726
4844
 
4727
4845
  // src/hooks/magic-context/read-session-true-raw-tokens.ts
4728
4846
  function completedToolArcCrossesBoundary(invOrdinal, resOrdinal, boundary) {
@@ -5355,11 +5473,6 @@ function isFilePart(part) {
5355
5473
  const p = part;
5356
5474
  return p.type === "file" && typeof p.url === "string";
5357
5475
  }
5358
- function buildFileSourceContent(parts) {
5359
- const content = parts.filter(isTextPart).map((part) => stripTagPrefix(part.text)).join(`
5360
- `).trim();
5361
- return content.length > 0 ? content : null;
5362
- }
5363
5476
 
5364
5477
  // src/shared/user-answer.ts
5365
5478
  function hasUserAnswerMetadata(value) {
@@ -5582,114 +5695,355 @@ function applyEditMarkerToInput(input) {
5582
5695
 
5583
5696
  // src/features/magic-context/tool-definition-tokens.ts
5584
5697
  import { createHash as createHash2 } from "node:crypto";
5585
- var measurements = new Map;
5586
- var fingerprints = new Map;
5698
+
5699
+ // src/shared/bounded-session-map.ts
5700
+ class BoundedSessionMap {
5701
+ maxEntries;
5702
+ store = new Map;
5703
+ constructor(maxEntries) {
5704
+ if (!Number.isFinite(maxEntries) || maxEntries < 1) {
5705
+ throw new Error(`BoundedSessionMap: maxEntries must be >= 1, got ${maxEntries}`);
5706
+ }
5707
+ this.maxEntries = maxEntries;
5708
+ }
5709
+ get(sessionId) {
5710
+ const value = this.store.get(sessionId);
5711
+ if (value === undefined)
5712
+ return;
5713
+ this.store.delete(sessionId);
5714
+ this.store.set(sessionId, value);
5715
+ return value;
5716
+ }
5717
+ peek(sessionId) {
5718
+ return this.store.get(sessionId);
5719
+ }
5720
+ has(sessionId) {
5721
+ return this.store.has(sessionId);
5722
+ }
5723
+ set(sessionId, value) {
5724
+ if (this.store.has(sessionId)) {
5725
+ this.store.delete(sessionId);
5726
+ } else if (this.store.size >= this.maxEntries) {
5727
+ const oldest = this.store.keys().next().value;
5728
+ if (oldest !== undefined)
5729
+ this.store.delete(oldest);
5730
+ }
5731
+ this.store.set(sessionId, value);
5732
+ }
5733
+ delete(sessionId) {
5734
+ return this.store.delete(sessionId);
5735
+ }
5736
+ clear() {
5737
+ this.store.clear();
5738
+ }
5739
+ get size() {
5740
+ return this.store.size;
5741
+ }
5742
+ }
5743
+
5744
+ // src/features/magic-context/tool-definition-tokens.ts
5745
+ var ACTIVITY_WINDOW_MS = 10 * 60000;
5746
+ var MAX_ACTIVITY_GAP_MS = 60000;
5747
+ var RETIRED_CACHE_LIMIT = 64;
5748
+ var WRITE_RETRY_MS = 5000;
5749
+ var WINDOWED_SINCE_KEY = "tool_definition_measurements:windowed_since";
5750
+ var routes = new Map;
5751
+ var sessionFlights = new BoundedSessionMap(1000);
5587
5752
  var persistenceDb = null;
5753
+ var windowedSince;
5754
+ var boundAt = 0;
5588
5755
  var cachedInsertStmt = null;
5756
+ var cachedDeleteStmt = null;
5757
+ function agentKey(agentName) {
5758
+ return agentName && agentName.length > 0 ? agentName : "default";
5759
+ }
5589
5760
  function keyFor(providerID, modelID, agentName) {
5590
- const agent = agentName && agentName.length > 0 ? agentName : "default";
5591
- return `${providerID}/${modelID}/${agent}`;
5761
+ return `${providerID}/${modelID}/${agentKey(agentName)}`;
5592
5762
  }
5593
5763
  function fingerprintFor(description, parameters) {
5594
5764
  return createHash2("sha256").update(description).update("\x00").update(stableStringify(parameters)).digest("hex");
5595
5765
  }
5596
- function getCurrentToolSetHash(providerID, modelID, agentName) {
5597
- if (!providerID || !modelID)
5598
- return "";
5599
- const toolIds = measurements.get(keyFor(providerID, modelID, agentName));
5600
- if (!toolIds || toolIds.size === 0)
5601
- return "";
5602
- return createHash2("sha256").update(Array.from(toolIds.keys()).sort().join("\x00")).digest("hex");
5766
+ function measure(description, parameters) {
5767
+ let paramsText = "";
5768
+ try {
5769
+ paramsText = parameters === undefined ? "" : JSON.stringify(parameters);
5770
+ } catch {
5771
+ paramsText = "";
5772
+ }
5773
+ return estimateTokens(description) + estimateTokens(paramsText);
5603
5774
  }
5604
- function getToolDefinitionMeasurementSignature(providerID, modelID, agentName) {
5775
+ function routeFor(providerID, modelID, agentName) {
5605
5776
  const key = keyFor(providerID, modelID, agentName);
5606
- const measured = measurements.get(key);
5607
- const observed = fingerprints.get(key);
5608
- if (!measured || !observed || [...measured.keys()].some((id) => !observed.has(id)))
5609
- return;
5610
- return createHash2("sha256").update(JSON.stringify([...measured.keys()].sort().map((id) => [id, observed.get(id)]))).digest("hex");
5777
+ let route = routes.get(key);
5778
+ if (!route) {
5779
+ route = {
5780
+ providerID,
5781
+ modelID,
5782
+ agentName: agentKey(agentName),
5783
+ tools: new Map,
5784
+ live: false,
5785
+ clock: 0,
5786
+ lastWallAt: Date.now(),
5787
+ oldestFireAt: Number.POSITIVE_INFINITY,
5788
+ retired: new Map,
5789
+ legacyRows: new Set
5790
+ };
5791
+ routes.set(key, route);
5792
+ }
5793
+ return { key, route };
5611
5794
  }
5612
- function setDatabase(db) {
5613
- persistenceDb = db;
5614
- cachedInsertStmt = null;
5795
+ function advanceClock(route) {
5796
+ const now = Date.now();
5797
+ const gap = Math.min(Math.max(now - route.lastWallAt, 0), MAX_ACTIVITY_GAP_MS);
5798
+ route.clock += gap;
5799
+ route.lastWallAt = Math.max(route.lastWallAt, now);
5800
+ return route.clock;
5615
5801
  }
5616
- function loadToolDefinitionMeasurements(db) {
5617
- let rows = [];
5802
+ function counts(route, slot) {
5803
+ if (!route.live)
5804
+ return true;
5805
+ if (slot.legacy)
5806
+ return false;
5807
+ return slot.lastFireAt >= route.clock - ACTIVITY_WINDOW_MS;
5808
+ }
5809
+ function currentTools(route) {
5810
+ return [...route.tools.entries()].filter(([, slot]) => counts(route, slot));
5811
+ }
5812
+ function summarize(entries, live) {
5813
+ let total = 0;
5814
+ for (const [, slot] of entries)
5815
+ total += slot.tokens;
5816
+ const ids = entries.map(([id]) => id).sort();
5817
+ const fingerprints = new Map(entries.map(([id, slot]) => [
5818
+ id,
5819
+ slot.fingerprint ?? (live ? `stored:${slot.tokens}` : undefined)
5820
+ ]));
5821
+ const complete = ids.every((id) => fingerprints.get(id) !== undefined);
5822
+ return {
5823
+ total,
5824
+ signature: complete ? createHash2("sha256").update(JSON.stringify(ids.map((id) => [id, fingerprints.get(id)]))).digest("hex") : undefined,
5825
+ hash: ids.length === 0 ? "" : createHash2("sha256").update(ids.join("\x00")).digest("hex")
5826
+ };
5827
+ }
5828
+ function resolve2(providerID, modelID, agentName, sessionId) {
5829
+ if (!providerID || !modelID)
5830
+ return;
5831
+ const key = keyFor(providerID, modelID, agentName);
5832
+ if (sessionId) {
5833
+ const flight = sessionFlights.peek(sessionId);
5834
+ if (flight?.key === key && flight.exact)
5835
+ return flight.exact;
5836
+ }
5837
+ const route = routes.get(key);
5838
+ if (!route)
5839
+ return;
5840
+ const entries = currentTools(route);
5841
+ if (!route.live && entries.length === 0)
5842
+ return;
5843
+ return summarize(entries, route.live);
5844
+ }
5845
+ function readWindowedSince(db) {
5618
5846
  try {
5619
- rows = db.prepare("SELECT provider_id, model_id, agent_name, tool_id, token_count FROM tool_definition_measurements").all();
5847
+ const row = db.prepare("SELECT value FROM schema_migrations_meta WHERE key = ?").get(WINDOWED_SINCE_KEY);
5848
+ if (!row)
5849
+ return;
5850
+ const value = Number(row.value);
5851
+ return Number.isFinite(value) ? value : undefined;
5620
5852
  } catch {
5621
5853
  return;
5622
5854
  }
5623
- for (const row of rows) {
5624
- const key = keyFor(row.provider_id, row.model_id, row.agent_name);
5625
- let inner = measurements.get(key);
5626
- if (!inner) {
5627
- inner = new Map;
5628
- measurements.set(key, inner);
5629
- }
5630
- inner.set(row.tool_id, row.token_count);
5631
- }
5632
5855
  }
5633
- function recordToolDefinition(providerID, modelID, agentName, toolID, description, parameters) {
5634
- if (!providerID || !modelID || !toolID)
5635
- return;
5636
- const key = keyFor(providerID, modelID, agentName);
5637
- const fp = fingerprintFor(description ?? "", parameters);
5638
- let innerFp = fingerprints.get(key);
5639
- if (innerFp && innerFp.get(toolID) === fp)
5856
+ function markWindowed() {
5857
+ if (windowedSince !== undefined || !persistenceDb)
5640
5858
  return;
5641
- let paramsText = "";
5642
5859
  try {
5643
- paramsText = parameters === undefined ? "" : JSON.stringify(parameters);
5860
+ persistenceDb.prepare("INSERT OR IGNORE INTO schema_migrations_meta (key, value) VALUES (?, ?)").run(WINDOWED_SINCE_KEY, String(boundAt));
5861
+ windowedSince = readWindowedSince(persistenceDb);
5862
+ } catch {}
5863
+ }
5864
+ function persistInsert(route, toolID, tokens) {
5865
+ if (!persistenceDb)
5866
+ return false;
5867
+ try {
5868
+ cachedInsertStmt ??= persistenceDb.prepare(`INSERT OR REPLACE INTO tool_definition_measurements
5869
+ (provider_id, model_id, agent_name, tool_id, token_count, recorded_at)
5870
+ VALUES (?, ?, ?, ?, ?, ?)`);
5871
+ cachedInsertStmt.run(route.providerID, route.modelID, route.agentName, toolID, tokens, Date.now());
5644
5872
  } catch {
5645
- paramsText = "";
5873
+ cachedInsertStmt = null;
5874
+ return false;
5646
5875
  }
5647
- const tokens = estimateTokens(description ?? "") + estimateTokens(paramsText);
5648
- let inner = measurements.get(key);
5649
- if (!inner) {
5650
- inner = new Map;
5651
- measurements.set(key, inner);
5876
+ if (route.legacyRows.delete(toolID) && route.legacyRows.size === 0)
5877
+ markWindowed();
5878
+ return true;
5879
+ }
5880
+ function persistDelete(route, toolIDs) {
5881
+ if (!persistenceDb)
5882
+ return false;
5883
+ try {
5884
+ cachedDeleteStmt ??= persistenceDb.prepare(`DELETE FROM tool_definition_measurements
5885
+ WHERE provider_id = ? AND model_id = ? AND agent_name = ?
5886
+ AND tool_id IN (SELECT value FROM json_each(?))`);
5887
+ cachedDeleteStmt.run(route.providerID, route.modelID, route.agentName, JSON.stringify(toolIDs));
5888
+ } catch {
5889
+ cachedDeleteStmt = null;
5890
+ return false;
5652
5891
  }
5653
- inner.set(toolID, tokens);
5654
- if (!innerFp) {
5655
- innerFp = new Map;
5656
- fingerprints.set(key, innerFp);
5892
+ for (const id of toolIDs)
5893
+ route.legacyRows.delete(id);
5894
+ markWindowed();
5895
+ return true;
5896
+ }
5897
+ function writeSlot(route, toolID, slot) {
5898
+ if (slot.persisted || !persistenceDb)
5899
+ return;
5900
+ const now = Date.now();
5901
+ if (slot.writeFailedAt !== undefined && now - slot.writeFailedAt < WRITE_RETRY_MS)
5902
+ return;
5903
+ if (persistInsert(route, toolID, slot.tokens)) {
5904
+ slot.persisted = true;
5905
+ slot.writeFailedAt = undefined;
5906
+ } else {
5907
+ slot.writeFailedAt = now;
5657
5908
  }
5658
- innerFp.set(toolID, fp);
5659
- if (persistenceDb) {
5660
- try {
5661
- const agent = agentName && agentName.length > 0 ? agentName : "default";
5662
- if (!cachedInsertStmt) {
5663
- cachedInsertStmt = persistenceDb.prepare(`INSERT OR REPLACE INTO tool_definition_measurements
5664
- (provider_id, model_id, agent_name, tool_id, token_count, recorded_at)
5665
- VALUES (?, ?, ?, ?, ?, ?)`);
5909
+ }
5910
+ function retire(route, toolID, slot, rowDeleted) {
5911
+ if (slot.fingerprint === undefined)
5912
+ return;
5913
+ route.retired.delete(toolID);
5914
+ route.retired.set(toolID, {
5915
+ fingerprint: slot.fingerprint,
5916
+ tokens: slot.tokens,
5917
+ rowKept: slot.persisted && !rowDeleted
5918
+ });
5919
+ if (route.retired.size > RETIRED_CACHE_LIMIT) {
5920
+ const oldest = route.retired.keys().next().value;
5921
+ if (oldest !== undefined)
5922
+ route.retired.delete(oldest);
5923
+ }
5924
+ }
5925
+ function freshSlot(route, toolID, description, parameters, fingerprint, now) {
5926
+ const retired = route.retired.get(toolID);
5927
+ if (retired)
5928
+ route.retired.delete(toolID);
5929
+ const reuse = retired?.fingerprint === fingerprint ? retired : undefined;
5930
+ return {
5931
+ tokens: reuse ? reuse.tokens : measure(description, parameters),
5932
+ fingerprint,
5933
+ lastFireAt: now,
5934
+ legacy: false,
5935
+ persisted: reuse?.rowKept === true
5936
+ };
5937
+ }
5938
+ function setDatabase(db) {
5939
+ const rebound = persistenceDb !== null && persistenceDb !== db;
5940
+ persistenceDb = db;
5941
+ boundAt = Date.now();
5942
+ cachedInsertStmt = null;
5943
+ cachedDeleteStmt = null;
5944
+ if (rebound) {
5945
+ for (const route of routes.values()) {
5946
+ for (const slot of route.tools.values()) {
5947
+ slot.persisted = false;
5948
+ slot.writeFailedAt = undefined;
5666
5949
  }
5667
- cachedInsertStmt.run(providerID, modelID, agent, toolID, tokens, Date.now());
5668
- } catch {
5669
- cachedInsertStmt = null;
5950
+ for (const retired of route.retired.values())
5951
+ retired.rowKept = false;
5952
+ route.legacyRows.clear();
5670
5953
  }
5671
5954
  }
5955
+ windowedSince = readWindowedSince(db);
5956
+ if (windowedSince !== undefined)
5957
+ return;
5958
+ try {
5959
+ if (!db.prepare("SELECT 1 FROM tool_definition_measurements LIMIT 1").get())
5960
+ markWindowed();
5961
+ } catch {}
5672
5962
  }
5673
- function getLargestMeasuredToolDefinitionTokens() {
5674
- let largest = 0;
5675
- for (const tools of measurements.values()) {
5676
- let total = 0;
5677
- for (const tokens of tools.values())
5678
- total += tokens;
5679
- largest = Math.max(largest, total);
5963
+ function loadToolDefinitionMeasurements(db) {
5964
+ let rows = [];
5965
+ try {
5966
+ rows = db.prepare("SELECT provider_id, model_id, agent_name, tool_id, token_count, recorded_at FROM tool_definition_measurements").all();
5967
+ } catch {
5968
+ return;
5969
+ }
5970
+ const since = readWindowedSince(db);
5971
+ const loadedAt = new Map;
5972
+ for (const row of rows) {
5973
+ const { route } = routeFor(row.provider_id, row.model_id, row.agent_name);
5974
+ if (route.live)
5975
+ continue;
5976
+ let now = loadedAt.get(route);
5977
+ if (now === undefined) {
5978
+ now = advanceClock(route);
5979
+ loadedAt.set(route, now);
5980
+ }
5981
+ const legacy = since === undefined || !(Number(row.recorded_at) >= since);
5982
+ route.tools.set(row.tool_id, {
5983
+ tokens: row.token_count,
5984
+ fingerprint: undefined,
5985
+ lastFireAt: now,
5986
+ legacy,
5987
+ persisted: !legacy
5988
+ });
5989
+ route.oldestFireAt = Math.min(route.oldestFireAt, now);
5990
+ if (legacy)
5991
+ route.legacyRows.add(row.tool_id);
5992
+ else
5993
+ route.legacyRows.delete(row.tool_id);
5680
5994
  }
5681
- return largest > 0 ? largest : undefined;
5682
5995
  }
5683
- function getMeasuredToolDefinitionTokens(providerID, modelID, agentName) {
5996
+ function recordToolDefinitionSet(providerID, modelID, agentName, tools, sessionId) {
5684
5997
  if (!providerID || !modelID)
5685
5998
  return;
5686
- const inner = measurements.get(keyFor(providerID, modelID, agentName));
5687
- if (!inner || inner.size === 0)
5999
+ const { key, route } = routeFor(providerID, modelID, agentName);
6000
+ const now = advanceClock(route);
6001
+ route.live = true;
6002
+ const next = new Map;
6003
+ for (const tool of tools) {
6004
+ if (!tool.id)
6005
+ continue;
6006
+ const fingerprint = fingerprintFor(tool.description ?? "", tool.parameters);
6007
+ const previous = route.tools.get(tool.id);
6008
+ if (previous && previous.fingerprint === fingerprint) {
6009
+ previous.lastFireAt = now;
6010
+ next.set(tool.id, previous);
6011
+ continue;
6012
+ }
6013
+ next.set(tool.id, freshSlot(route, tool.id, tool.description ?? "", tool.parameters, fingerprint, now));
6014
+ }
6015
+ const removed = [...route.tools].filter(([id]) => !next.has(id));
6016
+ route.tools = next;
6017
+ route.oldestFireAt = now;
6018
+ if (removed.length > 0) {
6019
+ const deleted = persistDelete(route, removed.map(([id]) => id));
6020
+ for (const [id, slot] of removed)
6021
+ retire(route, id, slot, deleted);
6022
+ }
6023
+ for (const [toolID, slot] of next)
6024
+ writeSlot(route, toolID, slot);
6025
+ if (sessionId)
6026
+ sessionFlights.set(sessionId, { key, exact: summarize([...next.entries()], true) });
6027
+ }
6028
+ function getCurrentToolSetHash(providerID, modelID, agentName, sessionId) {
6029
+ return resolve2(providerID, modelID, agentName, sessionId)?.hash ?? "";
6030
+ }
6031
+ function getToolDefinitionMeasurementSignature(providerID, modelID, agentName, sessionId) {
6032
+ return resolve2(providerID, modelID, agentName, sessionId)?.signature;
6033
+ }
6034
+ function getMeasuredToolDefinitionTokens(providerID, modelID, agentName, sessionId) {
6035
+ return resolve2(providerID, modelID, agentName, sessionId)?.total;
6036
+ }
6037
+ function getSessionToolDefinitionTokens(sessionId) {
6038
+ if (!sessionId)
5688
6039
  return;
5689
- let total = 0;
5690
- for (const tokens of inner.values())
5691
- total += tokens;
5692
- return total;
6040
+ const flight = sessionFlights.peek(sessionId);
6041
+ if (!flight)
6042
+ return;
6043
+ if (flight.exact)
6044
+ return flight.exact.total;
6045
+ const route = routes.get(flight.key);
6046
+ return route ? summarize(currentTools(route), route.live).total : undefined;
5693
6047
  }
5694
6048
 
5695
6049
  // src/hooks/magic-context/final-wire-token-estimate.ts
@@ -5834,7 +6188,7 @@ function createFinalWireUsageTracker() {
5834
6188
  const envelopeFor = (input) => {
5835
6189
  if (!input.providerID || !input.modelID || !input.systemPromptHash)
5836
6190
  return;
5837
- const tools = getToolDefinitionMeasurementSignature(input.providerID, input.modelID, input.agentName);
6191
+ const tools = getToolDefinitionMeasurementSignature(input.providerID, input.modelID, input.agentName, input.sessionId);
5838
6192
  if (!tools)
5839
6193
  return;
5840
6194
  return JSON.stringify([
@@ -5847,7 +6201,8 @@ function createFinalWireUsageTracker() {
5847
6201
  ]);
5848
6202
  };
5849
6203
  return {
5850
- estimate(sessionId, input, limit) {
6204
+ estimate(sessionId, request, limit) {
6205
+ const input = { ...request, sessionId: request.sessionId ?? sessionId };
5851
6206
  let measuredPrefix;
5852
6207
  try {
5853
6208
  const previous = served.get(sessionId);
@@ -5869,7 +6224,8 @@ function createFinalWireUsageTracker() {
5869
6224
  } catch {}
5870
6225
  return estimateOutgoingWireForRefusal({ ...input, measuredPrefix }, limit);
5871
6226
  },
5872
- capture(sessionId, input) {
6227
+ capture(sessionId, request) {
6228
+ const input = { ...request, sessionId: request.sessionId ?? sessionId };
5873
6229
  served.delete(sessionId);
5874
6230
  try {
5875
6231
  const envelope = envelopeFor(input);
@@ -5899,7 +6255,7 @@ function estimateOutgoingWireForRefusal(input, limit) {
5899
6255
  if (bytes) {
5900
6256
  const lower = baseline + Math.ceil(bytes.bytes / 4);
5901
6257
  const calibration = resolveDecisionCalibration(input.providerID, input.modelID);
5902
- const tools = input.providerID && input.modelID ? getMeasuredToolDefinitionTokens(input.providerID, input.modelID, input.agentName) : undefined;
6258
+ const tools = input.providerID && input.modelID ? getMeasuredToolDefinitionTokens(input.providerID, input.modelID, input.agentName, input.sessionId) : undefined;
5903
6259
  const envelope = measured ? baseline : tools !== undefined && Number.isFinite(input.systemPromptTokens) && input.systemPromptTokens > 0 ? providerMass({ system: input.systemPromptTokens, tools }, calibration, true) : undefined;
5904
6260
  const upper = envelope === undefined ? undefined : envelope + Math.ceil(bytes.bytes * Math.max(UNKNOWN_FIT_RATIO, calibration.toolsRatio, calibration.proseRatio));
5905
6261
  if (bytes.aborted || lower > limit || upper !== undefined && upper <= limit) {
@@ -5927,10 +6283,10 @@ function estimateFinalWireInputTokens(input) {
5927
6283
  total.toolCall += next.toolCall;
5928
6284
  return total;
5929
6285
  }, { conversation: 0, toolCall: 0 });
5930
- const measuredToolDefinitions = input.toolDefinitionTokens ?? (input.providerID && input.modelID ? getMeasuredToolDefinitionTokens(input.providerID, input.modelID, input.agentName) : undefined);
6286
+ const measuredToolDefinitions = input.toolDefinitionTokens ?? (input.providerID && input.modelID ? getMeasuredToolDefinitionTokens(input.providerID, input.modelID, input.agentName, input.sessionId) : undefined);
5931
6287
  const calibration = resolveDecisionCalibration(input.providerID, input.modelID);
5932
- const largestToolDefinitions = measuredToolDefinitions === undefined ? getLargestMeasuredToolDefinitionTokens() : undefined;
5933
- const toolDefinitions = measuredToolDefinitions ?? (largestToolDefinitions === undefined ? undefined : Math.ceil(largestToolDefinitions * UNKNOWN_FIT_RATIO / (calibration.seeded ? calibration.toolsRatio : UNKNOWN_FIT_RATIO)));
6288
+ const borrowedToolDefinitions = measuredToolDefinitions === undefined ? getSessionToolDefinitionTokens(input.sessionId) : undefined;
6289
+ const toolDefinitions = measuredToolDefinitions ?? (borrowedToolDefinitions === undefined ? undefined : Math.ceil(borrowedToolDefinitions * UNKNOWN_FIT_RATIO / (calibration.seeded ? calibration.toolsRatio : UNKNOWN_FIT_RATIO)));
5934
6290
  const rawComponents = {
5935
6291
  system: input.systemPromptTokens,
5936
6292
  tools: (toolDefinitions ?? 0) + messageTokens.toolCall,
@@ -6616,7 +6972,7 @@ class ToolMutationBatch {
6616
6972
  this.partsToRemove.add(servedPart(occurrence));
6617
6973
  this.affectedMessages.add(occurrence.message);
6618
6974
  }
6619
- wouldStrandConversationEnd(occurrences) {
6975
+ wouldStrandConversationEnd(occurrences, plannedRemovals) {
6620
6976
  const served = this.servedMessages ?? this.messages;
6621
6977
  let end;
6622
6978
  for (let i = served.length - 1;i >= 0 && end === undefined; i -= 1) {
@@ -6626,7 +6982,7 @@ class ToolMutationBatch {
6626
6982
  if (!end || !occurrences.some((occurrence) => occurrence.message === end))
6627
6983
  return false;
6628
6984
  const leaving = new Set(occurrences.map(servedPart));
6629
- const survives = (part) => !leaving.has(part) && !this.partsToRemove.has(part);
6985
+ const survives = (part) => !leaving.has(part) && !this.partsToRemove.has(part) && !plannedRemovals?.has(part);
6630
6986
  return end.info.role === "assistant" ? !end.parts.some((part) => partHasCompletedResult(part) && survives(part)) : !end.parts.some((part) => hasMeaningfulPart(part) && survives(part));
6631
6987
  }
6632
6988
  finalize() {
@@ -6800,11 +7156,16 @@ function createToolDropTarget(compositeKey, thinkingParts, index, batch, tagId)
6800
7156
  return null;
6801
7157
  return toolInputStringBytes(readRawInput());
6802
7158
  },
6803
- wouldStrandConversationEnd: () => {
7159
+ wouldStrandConversationEnd: (plannedRemovals) => {
6804
7160
  const entry = index.get(compositeKey);
6805
7161
  if (!entry || entry.occurrences.length === 0)
6806
7162
  return false;
6807
- return batch.wouldStrandConversationEnd(entry.occurrences);
7163
+ return batch.wouldStrandConversationEnd(entry.occurrences, plannedRemovals);
7164
+ },
7165
+ notePlannedRemoval: (plannedRemovals) => {
7166
+ for (const occurrence of index.get(compositeKey)?.occurrences ?? []) {
7167
+ plannedRemovals.add(servedPart(occurrence));
7168
+ }
6808
7169
  },
6809
7170
  prepareDrop: () => {
6810
7171
  const entry = index.get(compositeKey);
@@ -6896,9 +7257,11 @@ function setBoundedRawMessageProvider2(sessionId, provider) {
6896
7257
  }
6897
7258
  return setRawMessageProvider(sessionId, wrapper);
6898
7259
  }
6899
- var SYSTEM_REMINDER_BLOCK_REGEX = /<system-reminder>[\s\S]*?<\/system-reminder>/gi;
6900
7260
  function cleanUserText2(text) {
6901
- return stripOutsideSteeringWrappers(text, (segment) => segment.replace(SYSTEM_REMINDER_BLOCK_REGEX, "").replace(OMO_INTERNAL_INITIATOR_MARKER, "")).trim();
7261
+ return stripOutsideSteeringWrappers(text, (segment) => removeSystemReminders(segment).replace(OMO_INTERNAL_INITIATOR_MARKER, "")).trim();
7262
+ }
7263
+ function answerLineParts(rawText) {
7264
+ return askAnswerLines(rawText).map(normalizeText).filter((value) => value.length > 0);
6902
7265
  }
6903
7266
  function hasMeaningfulChunkUserText(parts) {
6904
7267
  for (const part of parts) {
@@ -6916,7 +7279,7 @@ function hasMeaningfulChunkUserText(parts) {
6916
7279
  continue;
6917
7280
  return true;
6918
7281
  }
6919
- return false;
7282
+ return parts.some((part) => part !== null && typeof part === "object" && part.type === "text" && typeof part.text === "string" && part.ignored !== true && askAnswerLines(part.text).length > 0);
6920
7283
  }
6921
7284
  function withRawSessionMessageCache2(fn) {
6922
7285
  const outerCache = activeRawMessageCache;
@@ -7522,6 +7885,10 @@ function readSessionChunk2(sessionId, tokenBudget, offset = 1, eligibleEndOrdina
7522
7885
  const meta = { ordinal: msg.ordinal, messageId: msg.id };
7523
7886
  if (isHostUnservedRow(msg))
7524
7887
  markHostUnservedRow(meta);
7888
+ if (msg.role === "system") {
7889
+ recordFilteredNoise(meta);
7890
+ continue;
7891
+ }
7525
7892
  if (msg.role === "user" && !hasMeaningfulChunkUserText(msg.parts)) {
7526
7893
  const tcSummaries = msg.parts.flatMap((part) => {
7527
7894
  if (expandedResults.has(part))
@@ -7568,8 +7935,10 @@ function readSessionChunk2(sessionId, tokenBudget, offset = 1, eligibleEndOrdina
7568
7935
  }
7569
7936
  const role = compactRole(msg.role);
7570
7937
  const textParts = extractTexts2(msg.parts).map((t) => msg.role === "user" ? cleanUserText2(t) : t).map(normalizeText).filter((value) => value.length > 0);
7938
+ const answerParts = msg.role === "user" ? extractTexts2(msg.parts).flatMap((text) => answerLineParts(text)) : [];
7939
+ const userParts = answerParts.length > 0 ? [...textParts, ...answerParts] : textParts;
7571
7940
  const allParts = options.expand === false ? [
7572
- ...textParts,
7941
+ ...userParts,
7573
7942
  ...textParts.length === 0 ? extractToolCallSummaries(msg.parts) : []
7574
7943
  ] : msg.parts.flatMap((part) => {
7575
7944
  if (expandedResults.has(part))
@@ -7578,6 +7947,9 @@ function readSessionChunk2(sessionId, tokenBudget, offset = 1, eligibleEndOrdina
7578
7947
  if (expansion !== null)
7579
7948
  return [`TC: ${expansion}`];
7580
7949
  const texts = extractTexts2([part]).map((t) => msg.role === "user" ? cleanUserText2(t) : t).map(normalizeText).filter(Boolean);
7950
+ if (msg.role === "user") {
7951
+ texts.push(...extractTexts2([part]).flatMap((text) => answerLineParts(text)));
7952
+ }
7581
7953
  return texts.length ? texts : textParts.length === 0 ? extractToolCallSummaries([part]) : [];
7582
7954
  });
7583
7955
  const compacted = compactTextForSummary(allParts.join(" / "), msg.role);
@@ -7586,7 +7958,7 @@ function readSessionChunk2(sessionId, tokenBudget, offset = 1, eligibleEndOrdina
7586
7958
  recordFilteredNoise(meta);
7587
7959
  continue;
7588
7960
  }
7589
- const msgHasNarrative = textParts.length > 0;
7961
+ const msgHasNarrative = userParts.length > 0;
7590
7962
  if (currentBlock && currentBlock.role === role) {
7591
7963
  currentBlock.endOrdinal = msg.ordinal;
7592
7964
  currentBlock.parts.push(text);
@@ -7668,4 +8040,4 @@ function readSessionChunk2(sessionId, tokenBudget, offset = 1, eligibleEndOrdina
7668
8040
  toolResultBoundaries
7669
8041
  };
7670
8042
  }
7671
- export { toolTemplateError, DEFAULT_PROTECTED_TOOLS, normalizeProtectedToolName, mergeProtectedTools, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isThinkingPart, isRecord, protectedToolTagNumbers, protectedToolTokenCount, textMentionsRecentCommit, removeSystemReminders, hasMeaningfulUserText2, extractTexts2, getTokenizerNativeMemoryStats, preloadTokenizer, estimateTokens, estimateFixedPromptTokens, currentReclaimableToolOutputCount, stableStringify, contentTagOwnerMessageId, estimateImageTokensFromDataUrl, estimateToolAttachmentImageTokens, providerVisibleMessage, normalizeTodoStateJson, buildSyntheticTodoPart, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, formatTailHygienePrefixMismatch, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchangedIfEnabled, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, isDroppedToolOutput, toolOutputTokens, decideChannel1, evaluateChannel2, formatChannel1Evaluation, formatChannel2Evaluation, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, estimateEmergencyDropReclaimTokens, planEmergencyDrop, measureEmergencyTag, installV3PerfSchema, queuePendingOp, queuePendingDropForUnchangedTag, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, tagTombstoneOwnerRange, tagTombstoneOwnerKey, tagRevisionKey, tagIdentityRevisionKey, installTagIdentityRevisionTrigger, deleteTagIdentityRevisions, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, getActiveTagTokenTotalsByMessage, getAllStatusTagTokenTotalsFlat, getReasoningTokenEstimatesByMessage, tryGetReasoningTokenEstimatesByMessage, getMaxTagNumberByOwnerMessage, scanTagOwnerSummary, isTagOwnerSummaryReady, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, markTagDropped, markWhitespaceAssistantTagInert, getInertWhitespaceAssistantTags, getInertWhitespaceAssistantTagsByNumbers, updateTagDropMode, updateCavemanDepth, updateTagMessageId, foldShrunkPartTags, markTagsCompactedByMessageIds, getMaxTagNumberBySession, getTagNumberByMessageId, getAssignableTagNumberByMessageId, deriveTagLoadFloor, TAG_SELECT_COLUMNS, getTagsBySession, getActiveTagsBySession, getTailHygieneTags, getTagsByNumbers, getNewestToolTagNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getTagById, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, getCandidateToolOwners, pickNearestPriorOwner, expandToolPart, markHostUnservedRow, retreatPastHostUnservedRows, snapTerminalCompartmentToServedRow, isHostRenderedSystemMessage, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, stripSystemInjection, isTextPart, isToolPartWithOutput, isFilePart, buildFileSourceContent, toolPartHasUserAnswer, recordToolParameters, createDroppedInputGuard, assertExecutableToolInput, isEditTool, getCurrentToolSetHash, setDatabase, loadToolDefinitionMeasurements, recordToolDefinition, getMeasuredToolDefinitionTokens, describeFinalWireTail, estimatePartImageTokens, estimateMessageTokens, wireContentBytes, createFinalWireUsageTracker, estimateFinalWireInputTokens, modelAcceptsEmptyContent, isAnthropicFamilyRoute, neutralizeDroppedReasoningPart, restoreNeutralizedReasoningPart, isNeutralizedReasoningPart, neutralizedReasoningSource, variantChangeBustsProviderCache, makeSentinel, makeWholeMessageSentinel, neutralizeWholeMessage, isSentinel, replaySentinelByMessageIds, SKELETON_REAL_INPUT_MAX_BYTES, partHasCompletedResult, extractToolCallObservation, ToolMutationBatch, createToolDropTarget, resolveHostServedBoundaryId2, hasRawMessageProvider2, setBoundedRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, visitRawSessionMessages2, readRawSessionMessageRange2, prepareRawSessionOrdinals2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageIdOrdinalsForRange2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, readSessionChunk2 };
8043
+ export { toolTemplateError, DEFAULT_PROTECTED_TOOLS, normalizeProtectedToolName, mergeProtectedTools, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isThinkingPart, isRecord, protectedToolTagNumbers, protectedToolTokenCount, textMentionsRecentCommit, removeSystemReminders, removeNestedBlocks, hasMeaningfulUserText2, extractTexts2, getTokenizerNativeMemoryStats, preloadTokenizer, estimateTokens, estimateFixedPromptTokens, currentReclaimableToolOutputCount, stableStringify, contentTagOwnerMessageId, estimateImageTokensFromDataUrl, estimateToolAttachmentImageTokens, providerVisibleMessage, normalizeTodoStateJson, buildSyntheticTodoPart, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, formatTailHygienePrefixMismatch, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchangedIfEnabled, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, isDroppedToolOutput, toolOutputTokens, decideChannel1, evaluateChannel2, formatChannel1Evaluation, formatChannel2Evaluation, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, estimateEmergencyDropReclaimTokens, planEmergencyDrop, measureEmergencyTag, installV3PerfSchema, queuePendingOp, queuePendingDropForUnchangedTag, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, tagTombstoneOwnerRange, tagTombstoneOwnerKey, tagRevisionKey, tagIdentityRevisionKey, installTagIdentityRevisionTrigger, deleteTagIdentityRevisions, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, getActiveTagTokenTotalsByMessage, getAllStatusTagTokenTotalsFlat, getReasoningTokenEstimatesByMessage, tryGetReasoningTokenEstimatesByMessage, getMaxTagNumberByOwnerMessage, scanTagOwnerSummary, isTagOwnerSummaryReady, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, markTagDropped, markWhitespaceAssistantTagInert, getInertWhitespaceAssistantTags, getInertWhitespaceAssistantTagsByNumbers, updateTagDropMode, updateCavemanDepth, updateTagMessageId, foldShrunkPartTags, markTagsCompactedByMessageIds, getMaxTagNumberBySession, getTagNumberByMessageId, getAssignableTagNumberByMessageId, deriveTagLoadFloor, TAG_SELECT_COLUMNS, getTagsBySession, getActiveTagsBySession, getTailHygieneTags, getTagsByNumbers, getNewestToolTagNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getTagById, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, getCandidateToolOwners, pickNearestPriorOwner, expandToolPart, markHostUnservedRow, retreatPastHostUnservedRows, snapTerminalCompartmentToServedRow, isHostRenderedSystemMessage, markCoveredInstructionRow, isCoveredInstructionRow, takeCoveredInstructionRows, cloneKeepingCoveredInstructionMarks, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, stripSystemInjection, isTextPart, isToolPartWithOutput, isFilePart, toolPartHasUserAnswer, recordToolParameters, createDroppedInputGuard, assertExecutableToolInput, isEditTool, BoundedSessionMap, setDatabase, loadToolDefinitionMeasurements, recordToolDefinitionSet, getCurrentToolSetHash, getMeasuredToolDefinitionTokens, describeFinalWireTail, estimatePartImageTokens, estimateMessageTokens, wireContentBytes, createFinalWireUsageTracker, estimateFinalWireInputTokens, modelAcceptsEmptyContent, isAnthropicFamilyRoute, neutralizeDroppedReasoningPart, restoreNeutralizedReasoningPart, isNeutralizedReasoningPart, neutralizedReasoningSource, variantChangeBustsProviderCache, makeSentinel, makeWholeMessageSentinel, neutralizeWholeMessage, isSentinel, replaySentinelByMessageIds, SKELETON_REAL_INPUT_MAX_BYTES, partHasCompletedResult, extractToolCallObservation, ToolMutationBatch, createToolDropTarget, resolveHostServedBoundaryId2, hasRawMessageProvider2, setBoundedRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, visitRawSessionMessages2, readRawSessionMessageRange2, prepareRawSessionOrdinals2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageIdOrdinalsForRange2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, readSessionChunk2 };