@cortexkit/opencode-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.
Files changed (128) hide show
  1. package/dist/auto-search-worker.js +1 -1
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{context-y85dvs6j.js → context-hvkjxqhs.js} +416 -106
  4. package/dist/{derive-budgets-htj16n4x.js → derive-budgets-nkw09vq7.js} +1 -1
  5. package/dist/features/magic-context/request-tool-definitions.d.ts +57 -0
  6. package/dist/features/magic-context/request-tool-definitions.d.ts.map +1 -1
  7. package/dist/hooks/magic-context/cache-busting-signals.d.ts +6 -3
  8. package/dist/hooks/magic-context/cache-busting-signals.d.ts.map +1 -1
  9. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  10. package/dist/hooks/magic-context/host-checkpoint-ride.d.ts +80 -0
  11. package/dist/hooks/magic-context/host-checkpoint-ride.d.ts.map +1 -0
  12. package/dist/hooks/magic-context/inject-compartments.d.ts +21 -0
  13. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  14. package/dist/hooks/magic-context/latest-thinking-recovery.d.ts +19 -0
  15. package/dist/hooks/magic-context/latest-thinking-recovery.d.ts.map +1 -1
  16. package/dist/hooks/magic-context/pending-materialization.d.ts +3 -0
  17. package/dist/hooks/magic-context/pending-materialization.d.ts.map +1 -1
  18. package/dist/hooks/magic-context/priced-pass-sizing.d.ts +132 -0
  19. package/dist/hooks/magic-context/priced-pass-sizing.d.ts.map +1 -0
  20. package/dist/hooks/magic-context/reasoning-budget.d.ts.map +1 -1
  21. package/dist/hooks/magic-context/recovery-fit.d.ts +51 -0
  22. package/dist/hooks/magic-context/recovery-fit.d.ts.map +1 -0
  23. package/dist/hooks/magic-context/request-tools-release.d.ts +26 -0
  24. package/dist/hooks/magic-context/request-tools-release.d.ts.map +1 -0
  25. package/dist/hooks/magic-context/routine-cleanup-decision.d.ts +109 -0
  26. package/dist/hooks/magic-context/routine-cleanup-decision.d.ts.map +1 -0
  27. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  28. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +24 -0
  29. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  30. package/dist/hooks/magic-context/transform-context-state.d.ts +2 -1
  31. package/dist/hooks/magic-context/transform-context-state.d.ts.map +1 -1
  32. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +22 -2
  33. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  34. package/dist/hooks/magic-context/transform.d.ts +19 -2
  35. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  36. package/dist/{index-jwa5t1s4.js → index-1qmv26ga.js} +17 -4
  37. package/dist/{index-0a79y98x.js → index-2x3kd999.js} +301 -90
  38. package/dist/{index-qdx8dq60.js → index-37a9bfta.js} +4 -4
  39. package/dist/{index-tvd2j34s.js → index-44pp3vrj.js} +1 -1
  40. package/dist/{index-980brvjr.js → index-5jk4h64j.js} +3 -3
  41. package/dist/{index-66a50f3e.js → index-6athgjba.js} +66 -14
  42. package/dist/{index-dnqqqc5f.js → index-8cfnaagj.js} +10 -2
  43. package/dist/{index-z8dacvkt.js → index-b0xt5qz9.js} +1 -1
  44. package/dist/{index-xejh7cqv.js → index-bqhjzhv4.js} +173 -9
  45. package/dist/{index-fs3zfby1.js → index-c99tqfge.js} +724 -98
  46. package/dist/{index-dcdvyaeh.js → index-eej9kwad.js} +3 -3
  47. package/dist/{index-rk5hyc41.js → index-esr8qcc4.js} +2 -2
  48. package/dist/{index-bzq05g00.js → index-etn2hmb5.js} +1 -1
  49. package/dist/{index-gf1vx3bn.js → index-kw7azjmy.js} +2 -2
  50. package/dist/{index-29gd1zcx.js → index-w6fh4v87.js} +1 -1
  51. package/dist/{index-gxqr0sbd.js → index-x53gnmce.js} +10 -10
  52. package/dist/{index-7na94cjf.js → index-xgczbhyx.js} +5 -5
  53. package/dist/{index-wwg1je98.js → index-xgnh498s.js} +3 -2
  54. package/dist/index.js +20 -20
  55. package/dist/{message-index-bounded-d8xt6q5c.js → message-index-bounded-3qpg8dq5.js} +3 -3
  56. package/dist/migration-worker.js +1 -1
  57. package/dist/raw-ordinal-warmup-worker.js +4 -4
  58. package/dist/{read-session-chunk-k3fqshw8.js → read-session-chunk-7h9f32sz.js} +2 -2
  59. package/dist/{recomp-orchestrator-y75thsc3.js → recomp-orchestrator-43g9tjya.js} +9 -9
  60. package/dist/{render-3psbedzk.js → render-4m7x9cq4.js} +7 -7
  61. package/dist/{search-hd16c8gq.js → search-0a3hh5x6.js} +5 -5
  62. package/dist/{search-archive-rvr7j5gx.js → search-archive-f6kwv02s.js} +4 -4
  63. package/dist/shared/window-geometry.d.ts +5 -0
  64. package/dist/shared/window-geometry.d.ts.map +1 -1
  65. package/dist/{storage-tags-ye9aqrqy.js → storage-tags-q8erkn48.js} +3 -1
  66. package/dist/{store-pd1e9hnr.js → store-h20ny8b8.js} +2 -2
  67. package/dist/{store-reader-yh19h38c.js → store-reader-3eh1s1m8.js} +1 -1
  68. package/dist/tools/parameter-descriptions.d.ts +6 -6
  69. package/dist/tools/parameter-descriptions.d.ts.map +1 -1
  70. package/dist/{transform-postprocess-phase-1rzxmkhb.js → transform-postprocess-phase-5746a5b6.js} +10 -10
  71. package/dist/v2/auto-search-worker.js +1 -1
  72. package/dist/v2/chunk-embedding-write-worker.js +1 -1
  73. package/dist/v2/{context-0e946t63.js → context-e9n2mxax.js} +1424 -295
  74. package/dist/v2/{derive-budgets-sa0v7bz0.js → derive-budgets-b5cgrtp8.js} +2 -2
  75. package/dist/v2/fold/code-mode-catalog.d.ts +11 -3
  76. package/dist/v2/fold/code-mode-catalog.d.ts.map +1 -1
  77. package/dist/v2/fold/instruction-supersession.d.ts +13 -2
  78. package/dist/v2/fold/instruction-supersession.d.ts.map +1 -1
  79. package/dist/v2/fold/manual-baseline.d.ts +7 -0
  80. package/dist/v2/fold/manual-baseline.d.ts.map +1 -1
  81. package/dist/v2/fold/native-replay.d.ts +5 -0
  82. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  83. package/dist/v2/fold/owner.d.ts +14 -0
  84. package/dist/v2/fold/owner.d.ts.map +1 -1
  85. package/dist/v2/fold/summary.d.ts +35 -0
  86. package/dist/v2/fold/summary.d.ts.map +1 -1
  87. package/dist/v2/hooks/context.d.ts +10 -1
  88. package/dist/v2/hooks/context.d.ts.map +1 -1
  89. package/dist/v2/hooks/lkg-system.d.ts +3 -0
  90. package/dist/v2/hooks/lkg-system.d.ts.map +1 -1
  91. package/dist/v2/{message-index-bounded-wt64v2rn.js → message-index-bounded-na8debr6.js} +3 -3
  92. package/dist/v2/migration-worker.js +1 -1
  93. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  94. package/dist/v2/{read-session-chunk-4b31z6bz.js → read-session-chunk-x33xeg2g.js} +2 -2
  95. package/dist/v2/{recomp-orchestrator-6qrm2nea.js → recomp-orchestrator-jyjpn5jm.js} +10 -10
  96. package/dist/v2/{render-f8mw16pp.js → render-mp82ns36.js} +7 -7
  97. package/dist/v2/{search-archive-7d0xdp54.js → search-archive-d0fcqch9.js} +4 -4
  98. package/dist/v2/{search-ecjd7e50.js → search-ebd0yr40.js} +4 -4
  99. package/dist/v2/{server-wbxbk3za.js → server-1f03b92k.js} +2 -2
  100. package/dist/v2/{server-ymn9w46x.js → server-5zzt9rah.js} +1 -1
  101. package/dist/v2/{server-sd8hvzte.js → server-af1rmkyn.js} +1 -1
  102. package/dist/v2/{server-vnpnmrsv.js → server-c43zxc9k.js} +27 -3
  103. package/dist/v2/{server-hq7fdqfm.js → server-epvj1cey.js} +2 -2
  104. package/dist/v2/{server-39kzpp8q.js → server-fhxe5jgm.js} +2 -2
  105. package/dist/v2/{server-0ymsgh0j.js → server-gy26cwvw.js} +1 -1
  106. package/dist/v2/{server-zqzh2ybj.js → server-rg92e592.js} +175 -11
  107. package/dist/v2/{server-ef1mskas.js → server-rthnpmbp.js} +66 -14
  108. package/dist/v2/{server-gwqfwtzq.js → server-t4hk02v1.js} +10 -10
  109. package/dist/v2/{server-vjhk8v41.js → server-wa4qhryh.js} +1 -1
  110. package/dist/v2/{server-an1ff8d8.js → server-wwmaqtxy.js} +5 -5
  111. package/dist/v2/{server-2qyfev3b.js → server-xsrykjkj.js} +17 -4
  112. package/dist/v2/{server-qxzbmtqt.js → server-zt1m5rwj.js} +10 -2
  113. package/dist/v2/{server-ftyc8awt.js → server-zypeavf0.js} +1 -1
  114. package/dist/v2/server.js +4 -4
  115. package/dist/v2/{storage-tags-8nttt1sk.js → storage-tags-ztar1k0g.js} +3 -1
  116. package/dist/v2/{store-reader-cgx47zkp.js → store-reader-yaxtdy6f.js} +1 -1
  117. package/dist/v2/store-reader.d.ts +22 -1
  118. package/dist/v2/store-reader.d.ts.map +1 -1
  119. package/dist/v2/{store-pebs9m52.js → store-skkhh3rd.js} +2 -2
  120. package/dist/v2/{v2-archive-reader-53kp5mme.js → v2-archive-reader-gm6mygag.js} +1 -1
  121. package/dist/v2/{wrapup-orchestrator-bng0dfxy.js → wrapup-orchestrator-y9a02xpd.js} +10 -10
  122. package/dist/{v2-archive-reader-0fcxs5e9.js → v2-archive-reader-yp9956t8.js} +1 -1
  123. package/dist/{wrapup-orchestrator-r5cqgyrg.js → wrapup-orchestrator-ese0epyk.js} +10 -10
  124. package/package.json +1 -1
  125. package/src/agents/smart-notes-dreamer-gate.golden.json +169 -169
  126. package/src/shared/prompt-surface-a1-golden.md +4 -4
  127. package/src/shared/window-geometry.test.ts +85 -0
  128. package/src/shared/window-geometry.ts +29 -2
@@ -31,13 +31,14 @@ import {
31
31
  createPromptSurfaceRuntime,
32
32
  runTokenLog,
33
33
  v2ToolDefinitionsHash,
34
+ v2RequestToolsFingerprint,
34
35
  clearInjectionCache,
35
36
  materializeM0,
36
37
  resetPrefixTrimFallbackState,
37
38
  rebaseSessionCoordinatesAsync,
38
39
  resolveOpenCodeProtectedTailBoundary,
39
40
  getActiveCompartmentRun
40
- } from "./index-xejh7cqv.js";
41
+ } from "./index-bqhjzhv4.js";
41
42
  import"./index-sd3egckz.js";
42
43
  import {
43
44
  getHarness2
@@ -60,7 +61,7 @@ import {
60
61
  deriveHistorianChunkTokens2,
61
62
  resolveKnownHistorianContextLimit2,
62
63
  resolveHistorianContextLimit2
63
- } from "./index-dnqqqc5f.js";
64
+ } from "./index-8cfnaagj.js";
64
65
  import"./index-4dpvnp8k.js";
65
66
  import {
66
67
  CANONICAL_DREAM_TASKS,
@@ -99,6 +100,7 @@ import {
99
100
  stageOpenCodeV2TransformDecision,
100
101
  bindOpenCodeV2TransformDecision,
101
102
  armLatestThinkingRecoveryFromError,
103
+ armThinkingBindingRecoveryFromError,
102
104
  createM0RenderOptions,
103
105
  lkgReplayLimit,
104
106
  measureLkgReplay,
@@ -131,7 +133,7 @@ import {
131
133
  applyJsonSchemaParameterDescriptions,
132
134
  MagicContextRpcServer,
133
135
  subagentTemperature
134
- } from "./index-fs3zfby1.js";
136
+ } from "./index-c99tqfge.js";
135
137
  import {
136
138
  resolveHistorianModel2
137
139
  } from "./index-5kym00ag.js";
@@ -165,7 +167,7 @@ import {
165
167
  isDroppedToolOutput,
166
168
  evaluateChannel2,
167
169
  buildChannel2Reminder
168
- } from "./index-gxqr0sbd.js";
170
+ } from "./index-x53gnmce.js";
169
171
  import {
170
172
  hasMeaningfulUserText2,
171
173
  preloadTokenizer,
@@ -200,6 +202,7 @@ import {
200
202
  clearPendingPiCompactionMarkerStateIf,
201
203
  logPiCompactionMarkerClear,
202
204
  getObservedEpochFloor,
205
+ isPrefixBoundThinkingModel,
203
206
  detectOverflow,
204
207
  modelAcceptsEmptyContent,
205
208
  markServedShapeRepair,
@@ -210,17 +213,17 @@ import {
210
213
  cleanUserText2,
211
214
  readRawSessionMessageIdOrdinalsForRange2,
212
215
  readRawSessionMessageOrdinalById2
213
- } from "./index-wwg1je98.js";
216
+ } from "./index-xgnh498s.js";
214
217
  import {
215
218
  BoundedSessionMap,
216
219
  recordToolDefinitionSet,
217
220
  getCurrentToolSetHash
218
221
  } from "./index-smtbdmc3.js";
219
- import"./index-bzq05g00.js";
222
+ import"./index-etn2hmb5.js";
220
223
  import"./index-h9m41624.js";
221
224
  import {
222
225
  scheduleClearAndReindex
223
- } from "./index-tvd2j34s.js";
226
+ } from "./index-44pp3vrj.js";
224
227
  import {
225
228
  invalidateAutoEmbedSession,
226
229
  clearEmbedSessionState
@@ -257,7 +260,7 @@ import {
257
260
  getSlot,
258
261
  dropSlot,
259
262
  copySessionStateForClone
260
- } from "./index-jwa5t1s4.js";
263
+ } from "./index-1qmv26ga.js";
261
264
  import {
262
265
  startBootDeadline,
263
266
  BOOT_SQLITE_BUSY_TIMEOUT_MS,
@@ -265,7 +268,7 @@ import {
265
268
  openDatabaseAsync,
266
269
  isDatabasePersisted,
267
270
  getDatabasePersistenceError
268
- } from "./index-z8dacvkt.js";
271
+ } from "./index-b0xt5qz9.js";
269
272
  import"./index-fr0wbhdn.js";
270
273
  import"./index-nj360hcs.js";
271
274
  import {
@@ -273,7 +276,7 @@ import {
273
276
  RAW_MESSAGE_TYPES2,
274
277
  V2StoreReaderPool2,
275
278
  V2StoreReader2
276
- } from "./index-66a50f3e.js";
279
+ } from "./index-6athgjba.js";
277
280
  import"./index-fb3zxn06.js";
278
281
  import"./index-2qbtqg1w.js";
279
282
  import {
@@ -283,8 +286,10 @@ import {
283
286
  resolveCtxReduceAvailabilityFromMessages,
284
287
  EmergencyFailClosedError,
285
288
  DegradedPassRefusalError,
289
+ servedHeadChanged,
290
+ noteHostCheckpointCommit,
286
291
  isSyntheticHeadMessage2
287
- } from "./index-0a79y98x.js";
292
+ } from "./index-2x3kd999.js";
288
293
  import"./index-gn6gfz4y.js";
289
294
  import"./index-qt1qqasc.js";
290
295
  import {
@@ -305,8 +310,8 @@ import {
305
310
  } from "./index-x8a7jmkh.js";
306
311
  import"./index-fw42ms3m.js";
307
312
  import"./index-25ka1jza.js";
308
- import"./index-980brvjr.js";
309
- import"./index-dcdvyaeh.js";
313
+ import"./index-5jk4h64j.js";
314
+ import"./index-eej9kwad.js";
310
315
  import"./index-gp3kcpc4.js";
311
316
  import {
312
317
  detectConflicts
@@ -327,12 +332,12 @@ import {
327
332
  readV2RawMessagePagesForConversion2,
328
333
  createV2RawMessageReader2,
329
334
  createV2RawMessageProvider2
330
- } from "./index-29gd1zcx.js";
335
+ } from "./index-w6fh4v87.js";
331
336
  import"./index-fmsr7v69.js";
332
- import"./index-gf1vx3bn.js";
337
+ import"./index-kw7azjmy.js";
333
338
  import"./index-kaqs6h31.js";
334
- import"./index-7na94cjf.js";
335
- import"./index-rk5hyc41.js";
339
+ import"./index-xgczbhyx.js";
340
+ import"./index-esr8qcc4.js";
336
341
  import {
337
342
  isDreamerRunnable,
338
343
  isSmartNoteSurfaceAvailable,
@@ -863,59 +868,194 @@ var changed = "The Code Mode tool catalog has changed.";
863
868
  var replacement = `${changed} This catalog supersedes the previous Code Mode tool catalog.`;
864
869
  var codeMode = "core/codemode";
865
870
  var mcp = "core/mcp-guidance";
871
+ var date = "core/date";
872
+ var noCodeModeTools = "No Code Mode tools are currently available. Later Code Mode catalog updates may add or remove tools. Do not call `execute` unless there is at least one available Code Mode tool.";
873
+ var codeModeRemoved = "Code Mode tools are no longer available. Do not use any previously listed Code Mode tools.";
874
+ var catalogHeadings = ["## Available tools", "## Code Mode tools (call only inside `execute`)"];
866
875
  var mcpReplacement = "The available MCP server instructions have changed. This list supersedes the previous one.";
867
- var mcpDeltas = [
868
- "New MCP server instructions are available in addition to those previously listed:",
869
- "The following MCP server instructions have changed. Each entry replaces the previously listed server with the same name:",
870
- "Instructions for the following MCP servers are no longer available:"
871
- ];
872
- function sourceState(text, source) {
873
- const starts = (prefix) => text.startsWith(prefix) || text.includes(`
874
-
875
- ${prefix}`);
876
- if (source === codeMode) {
877
- if (text.startsWith(`${replacement}
876
+ var mcpRemoved = "MCP server instructions are no longer available.";
877
+ var mcpAdded = "New MCP server instructions are available in addition to those previously listed:";
878
+ var mcpChanged = "The following MCP server instructions have changed. Each entry replaces the previously listed server with the same name:";
879
+ var mcpGone = "Instructions for the following MCP servers are no longer available: ";
880
+ var dateLine = /^Today's date(?: is now)?: (?:Sun|Mon|Tue|Wed|Thu|Fri|Sat) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{2} \d{4}$/;
881
+ var mentions = (part) => part.full ? [] : [...part.entries ?? [], ...part.removed ?? []];
882
+ function codeModePart(text) {
883
+ if (text === noCodeModeTools || text === codeModeRemoved || text.startsWith(`# Code Mode
884
+ `))
885
+ return { full: true };
886
+ if (text.startsWith(`${replacement}
878
887
 
879
888
  `)) {
880
- const rendered = text.slice(replacement.length + 2);
881
- if (rendered.startsWith(`# Code Mode
882
- `) || rendered.startsWith("No Code Mode tools are currently available."))
883
- return "full";
889
+ const rendered = text.slice(replacement.length + 2);
890
+ return rendered === noCodeModeTools || rendered.startsWith(`# Code Mode
891
+ `) ? { full: true } : undefined;
892
+ }
893
+ return text.startsWith(`${changed}
894
+
895
+ `) ? { full: false } : undefined;
896
+ }
897
+ function startsWithFullCatalog(text) {
898
+ const begins = (whole) => text === whole || text.startsWith(`${whole}
899
+
900
+ `);
901
+ return text.startsWith(`# Code Mode
902
+ `) || text.startsWith(`${replacement}
903
+
904
+ # Code Mode
905
+ `) || begins(noCodeModeTools) || begins(`${replacement}
906
+
907
+ ${noCodeModeTools}`) || begins(codeModeRemoved);
908
+ }
909
+ function wholeCatalog(text) {
910
+ if (text === codeModeRemoved)
911
+ return true;
912
+ const rendered = text.startsWith(`${replacement}
913
+
914
+ `) ? text.slice(replacement.length + 2) : text;
915
+ if (rendered === noCodeModeTools)
916
+ return true;
917
+ if (!rendered.startsWith(`# Code Mode
918
+ `))
919
+ return false;
920
+ const ends = catalogHeadings.map((heading) => {
921
+ const at = rendered.indexOf(`
922
+
923
+ ${heading}
924
+
925
+ `);
926
+ return at < 0 ? undefined : at + heading.length + 4;
927
+ }).filter((end) => end !== undefined);
928
+ return ends.length > 0 && !rendered.slice(Math.min(...ends)).includes(`
929
+
930
+ `);
931
+ }
932
+ function serverEntries(lines, start) {
933
+ const names = [];
934
+ let index = start;
935
+ for (;; ) {
936
+ const open = /^ {2}<server name="(.*)">$/.exec(lines[index] ?? "");
937
+ if (!open)
938
+ return { names, next: index };
939
+ let end = index + 1;
940
+ while (lines[end]?.startsWith(" "))
941
+ end++;
942
+ if (end === index + 1 || lines[end] !== " </server>")
884
943
  return;
885
- }
886
- if (text.startsWith(changed))
887
- return "delta";
888
- if (text.startsWith(`# Code Mode
889
- `) || text.startsWith("No Code Mode tools are currently available."))
890
- return "full";
891
- }
892
- if (source === mcp) {
893
- if (mcpDeltas.some(starts))
894
- return "delta";
895
- if ((starts(`${mcpReplacement}
896
- <mcp_instructions>
897
- `) || starts(`<mcp_instructions>
898
- `)) && text.includes("</mcp_instructions>"))
899
- return "full";
944
+ names.push(open[1]);
945
+ index = end + 1;
900
946
  }
901
- return;
947
+ }
948
+ function mcpPart(text) {
949
+ if (text === mcpRemoved)
950
+ return { full: true };
951
+ const lines = text.split(`
952
+ `);
953
+ const listStart = lines[0] === mcpReplacement ? 1 : 0;
954
+ if (lines[listStart] === "<mcp_instructions>") {
955
+ const entries = serverEntries(lines, listStart + 1);
956
+ return entries && entries.next === lines.length - 1 && lines[entries.next] === "</mcp_instructions>" ? { full: true, entries: entries.names } : undefined;
957
+ }
958
+ if (listStart > 0)
959
+ return;
960
+ const entries = [];
961
+ let removed;
962
+ let index = 0;
963
+ for (const header of [mcpAdded, mcpChanged]) {
964
+ if (lines[index] !== header)
965
+ continue;
966
+ const section = serverEntries(lines, index + 1);
967
+ if (!section || section.names.length === 0)
968
+ return;
969
+ entries.push(...section.names);
970
+ index = section.next;
971
+ }
972
+ const gone = lines[index];
973
+ if (gone?.startsWith(mcpGone) && gone.endsWith(".") && gone.length > mcpGone.length + 1) {
974
+ removed = gone.slice(mcpGone.length, -1).split(", ");
975
+ index++;
976
+ }
977
+ return index === lines.length && (entries.length > 0 || removed) ? { full: false, entries, ...removed ? { removed } : {} } : undefined;
978
+ }
979
+ var datePart = (text) => dateLine.test(text) ? { full: true } : undefined;
980
+ var parsers = {
981
+ [codeMode]: codeModePart,
982
+ [mcp]: mcpPart,
983
+ [date]: datePart
984
+ };
985
+ function splitRow(text, sources) {
986
+ const parts = sources.map(() => {
987
+ return;
988
+ });
989
+ let rest = text;
990
+ let index = sources.length - 1;
991
+ for (;index > 0; index--) {
992
+ const source = sources[index];
993
+ const cut = rest.lastIndexOf(`
994
+
995
+ `);
996
+ const part = source === codeMode || cut < 0 ? undefined : parsers[source]?.(rest.slice(cut + 2));
997
+ if (!part)
998
+ break;
999
+ parts[index] = part;
1000
+ rest = rest.slice(0, cut);
1001
+ }
1002
+ if (index === 0)
1003
+ parts[0] = parsers[sources[0]]?.(rest);
1004
+ else if (sources[0] === codeMode && startsWithFullCatalog(text))
1005
+ parts[0] = { full: true };
1006
+ return parts;
1007
+ }
1008
+ function rowParts(data) {
1009
+ const text = data.text ?? "";
1010
+ const metadata = data.metadata;
1011
+ if (typeof metadata === "object" && metadata !== null && "instructionSources" in metadata) {
1012
+ const keys = metadata.instructionSources;
1013
+ const sources = Array.isArray(keys) && keys.length > 0 && keys.every((key) => typeof key === "string") && new Set(keys).size === keys.length ? keys : [];
1014
+ return { sources, parts: splitRow(text, sources) };
1015
+ }
1016
+ const cut = text.lastIndexOf(`
1017
+
1018
+ `);
1019
+ const guidance = cut < 0 ? undefined : mcpPart(text.slice(cut + 2));
1020
+ if (guidance && wholeCatalog(text.slice(0, cut)))
1021
+ return { sources: [codeMode, mcp], parts: [{ full: true }, guidance] };
1022
+ if (wholeCatalog(text))
1023
+ return { sources: [codeMode], parts: [{ full: true }] };
1024
+ const alone = mcpPart(text);
1025
+ return alone ? { sources: [mcp], parts: [alone] } : { sources: [], parts: [] };
1026
+ }
1027
+ function joinedRuns(names) {
1028
+ const runs = [];
1029
+ for (let start = 0;start < names.length; start++)
1030
+ for (let end = start + 2;end <= names.length; end++)
1031
+ runs.push(names.slice(start, end).join(", "));
1032
+ return runs;
902
1033
  }
903
1034
  function supersededInstructionIDs(rows) {
904
- const covered = new Set;
1035
+ const parsed = rows.map((row) => rowParts(row.data));
1036
+ const named = new Set(parsed.flatMap(({ parts }) => parts.flatMap((part) => part?.entries ?? [])));
1037
+ for (const { parts } of parsed)
1038
+ parts.forEach((part, i) => {
1039
+ if (part?.removed && !(part.removed.every((name) => named.has(name)) && !joinedRuns(part.removed).some((name) => named.has(name))))
1040
+ parts[i] = undefined;
1041
+ });
1042
+ const restated = new Set;
1043
+ const mentioned = new Set;
905
1044
  const retired = new Set;
906
1045
  for (let index = rows.length - 1;index >= 0; index--) {
907
- const row = rows[index];
908
- const metadata = row.data.metadata;
909
- const keyed = typeof metadata === "object" && metadata !== null && "instructionSources" in metadata;
910
- const keys = keyed ? metadata.instructionSources : undefined;
911
- const text = row.data.text ?? "";
912
- const sources = keyed ? Array.isArray(keys) && keys.length > 0 && keys.every((key) => typeof key === "string") ? keys : [] : [codeMode, mcp].filter((source) => sourceState(text, source) !== undefined);
913
- const states = sources.map((source) => sourceState(text, source));
914
- if (sources.length > 0 && sources.every((source, i) => states[i] !== undefined && covered.has(source)))
915
- retired.add(row.id);
916
- sources.forEach((source, i) => {
917
- if (states[i] === "full")
918
- covered.add(source);
1046
+ const { sources, parts } = parsed[index];
1047
+ if (sources.length > 0 && parts.every((part, i) => {
1048
+ if (part === undefined)
1049
+ return false;
1050
+ const servers = mentions(part);
1051
+ return restated.has(sources[i]) || servers.length > 0 && servers.every((server) => mentioned.has(server));
1052
+ }))
1053
+ retired.add(rows[index].id);
1054
+ parts.forEach((part, i) => {
1055
+ if (part?.full)
1056
+ restated.add(sources[i]);
1057
+ for (const server of part ? mentions(part) : [])
1058
+ mentioned.add(server);
919
1059
  });
920
1060
  }
921
1061
  return retired;
@@ -923,6 +1063,7 @@ function supersededInstructionIDs(rows) {
923
1063
 
924
1064
  // src/v2/fold/instruction-supersession.ts
925
1065
  var namespace = "instructionSupersession";
1066
+ var coveredNamespace = "coveredInstructionSupersession";
926
1067
  function decode(value) {
927
1068
  if (value === undefined)
928
1069
  return new Set;
@@ -930,32 +1071,44 @@ function decode(value) {
930
1071
  throw new Error("Invalid instruction supersession replay state");
931
1072
  return new Set(value);
932
1073
  }
1074
+ var coveredOn = (value) => typeof value === "object" && value !== null && value.on === true;
933
1075
  function retiredLiveInstructionIDs(db, sessionID) {
934
1076
  return decode(readReplayEnvelope(db, sessionID)[namespace]);
935
1077
  }
936
- function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new Set) {
937
- const rows = messages.flatMap((message) => {
1078
+ function coveredInstructionSupersessionOn(db, sessionID) {
1079
+ return coveredOn(readReplayEnvelope(db, sessionID)[coveredNamespace]);
1080
+ }
1081
+ var coveredSupersessionEnabled = true;
1082
+ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new Set, covered = []) {
1083
+ const instructionRows = (list) => list.flatMap((message) => {
938
1084
  const row = hostInstructionRow(message.info);
939
1085
  return row ? [{ message, row }] : [];
940
1086
  });
1087
+ const coveredRows = coveredSupersessionEnabled ? instructionRows(covered) : [];
1088
+ const rows = [...coveredRows, ...instructionRows(messages)];
1089
+ const coveredMessages = new Set(coveredRows.map(({ message }) => message));
941
1090
  const retired = rows.length ? retiredLiveInstructionIDs(db, sessionID) : new Set;
1091
+ const coveredFollowed = rows.length > 0 && (coveredRows.length > 0 || permitted) && coveredInstructionSupersessionOn(db, sessionID);
1092
+ const switchCovered = permitted && rows.length > 0 && !coveredFollowed && coveredSupersessionEnabled;
942
1093
  const selected = permitted ? supersededInstructionIDs(rows.map(({ row }) => row)) : new Set;
943
1094
  const newlyRetired = new Set([...selected].filter((id) => !retired.has(id)));
944
1095
  const omitted = new Set([...retired, ...newlyRetired]);
1096
+ const omits = (message, id) => omitted.has(id) && (!coveredMessages.has(message) || coveredFollowed || switchCovered);
945
1097
  const edits = [];
946
1098
  for (const { message, row } of rows) {
947
- if (!omitted.has(row.id))
1099
+ if (!omits(message, row.id))
948
1100
  continue;
949
- if (newlyRetired.has(row.id) && message.parts.length > 0)
1101
+ const firstApplication = newlyRetired.has(row.id) || coveredMessages.has(message) && switchCovered;
1102
+ if (firstApplication && message.parts.length > 0)
950
1103
  edits.push(message);
951
1104
  message.parts = [];
952
1105
  }
953
1106
  return {
954
1107
  edits,
955
1108
  commit() {
956
- if (newlyRetired.size > 0 && !updateReplayDocument(db, sessionID, (doc) => {
1109
+ if ((newlyRetired.size > 0 || switchCovered) && !updateReplayDocument(db, sessionID, (doc) => {
957
1110
  const current = decode(doc[namespace]);
958
- if ([...newlyRetired].every((id) => current.has(id)))
1111
+ if ([...newlyRetired].every((id) => current.has(id)) && (!switchCovered || coveredOn(doc[coveredNamespace])))
959
1112
  return false;
960
1113
  for (const id of folded)
961
1114
  current.delete(id);
@@ -963,11 +1116,13 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
963
1116
  current.add(id);
964
1117
  doc.version = 2;
965
1118
  doc[namespace] = [...current];
1119
+ if (switchCovered)
1120
+ doc[coveredNamespace] = { on: true };
966
1121
  return true;
967
1122
  }))
968
1123
  throw new Error("Cannot persist instruction supersession");
969
1124
  for (const { message, row } of rows) {
970
- if (omitted.has(row.id))
1125
+ if (omits(message, row.id))
971
1126
  markRetiredInstructionRow(message.info);
972
1127
  }
973
1128
  }
@@ -975,6 +1130,12 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
975
1130
  }
976
1131
 
977
1132
  // src/v2/fold/manual-baseline.ts
1133
+ var text = (value) => value == null ? null : typeof value === "string" ? value : Buffer.from(value).toString("utf8");
1134
+ var headOf = (row) => ({
1135
+ m0Text: text(row.cached_m0_bytes),
1136
+ m1Text: text(row.cached_m1_bytes),
1137
+ muralDataUrl: row.cached_m0_mural_data_url ?? null
1138
+ });
978
1139
  function stageManualBaseline(db, sessionID, render) {
979
1140
  const read = () => db.prepare("SELECT * FROM session_meta WHERE session_id = ?").get(sessionID);
980
1141
  const before = read();
@@ -983,6 +1144,7 @@ function stageManualBaseline(db, sessionID, render) {
983
1144
  const restore = (row) => update.run(...columns.map((key) => row[key] ?? null), sessionID);
984
1145
  let summary;
985
1146
  let staged;
1147
+ let committed = false;
986
1148
  try {
987
1149
  summary = render();
988
1150
  staged = read();
@@ -997,6 +1159,13 @@ function stageManualBaseline(db, sessionID, render) {
997
1159
  const result = commit.run(...columns.map((key) => staged[key] ?? null), sessionID, ...columns.map((key) => before[key] ?? null));
998
1160
  if (result.changes !== 1)
999
1161
  throw new Error("Manual compaction baseline changed during admission");
1162
+ committed = true;
1163
+ },
1164
+ headCommit() {
1165
+ return {
1166
+ changed: committed && servedHeadChanged(headOf(before), headOf(staged)),
1167
+ previousCoverage: before.cached_m0_bytes == null ? -1 : before.cached_m0_max_compartment_seq ?? null
1168
+ };
1000
1169
  }
1001
1170
  };
1002
1171
  }
@@ -1006,6 +1175,35 @@ import { randomUUID } from "node:crypto";
1006
1175
 
1007
1176
  // src/v2/fold/owner.ts
1008
1177
  import { createHash } from "node:crypto";
1178
+
1179
+ // src/v2/fold/summary.ts
1180
+ var RAW_HISTORY_ACCOUNT = "Magic Context retains the conversation as raw messages; no summarized history is available yet.";
1181
+ var CHECKPOINT_NOTE = "Magic Context added a compaction marker here to keep this OpenCode session fast. Your history is unchanged: Magic Context still keeps it and sends it to the model.";
1182
+ var CHECKPOINT_NOTES = Object.freeze([CHECKPOINT_NOTE]);
1183
+ function isCheckpointNote(value) {
1184
+ return typeof value === "string" && CHECKPOINT_NOTES.includes(value);
1185
+ }
1186
+ function hasFoldSummary(summary) {
1187
+ return typeof summary === "string" && summary.replace(/<[^>]*>/g, "").trim().length > 0;
1188
+ }
1189
+ function isHistoryHead(value) {
1190
+ return value !== RAW_HISTORY_ACCOUNT && !isCheckpointNote(value) && hasFoldSummary(value);
1191
+ }
1192
+ function withRecordedHead(checkpoint, submitted, head) {
1193
+ if (!isCheckpointNote(submitted) || head === undefined || head === submitted)
1194
+ return checkpoint;
1195
+ const copy = structuredClone(checkpoint);
1196
+ for (const part of copy.content)
1197
+ if (part.type === "text" && typeof part.text === "string")
1198
+ part.text = part.text.replace(`<summary>
1199
+ ${submitted}
1200
+ </summary>`, () => `<summary>
1201
+ ${head}
1202
+ </summary>`);
1203
+ return copy;
1204
+ }
1205
+
1206
+ // src/v2/fold/owner.ts
1009
1207
  var foldDigest = (value) => createHash("sha256").update(value).digest("hex");
1010
1208
 
1011
1209
  class FoldOwner {
@@ -1035,14 +1233,23 @@ class FoldOwner {
1035
1233
  return this.serial(args.sessionID, async () => {
1036
1234
  const previous = await this.read(args.sessionID);
1037
1235
  const same = previous && (args.runningCut !== undefined ? previous.cutSeq === args.runningCut : previous.cutSeq === undefined && previous.watermark === args.watermark);
1038
- if (same)
1236
+ if (same) {
1237
+ const id = args.checkpointID;
1238
+ if (id !== undefined && !previous.answered?.includes(id)) {
1239
+ previous.answered = [...previous.answered ?? [], id].slice(-8);
1240
+ await this.storage.set(this.key(args.sessionID), previous);
1241
+ }
1039
1242
  return previous;
1040
- const submitted = args.materialize();
1243
+ }
1244
+ const head = args.materialize();
1245
+ const submitted = args.checkpointText ?? head;
1041
1246
  const next = {
1042
1247
  watermark: args.watermark,
1043
1248
  cutSeq: args.runningCut,
1044
1249
  submitted,
1045
- submittedSha: foldDigest(submitted)
1250
+ submittedSha: foldDigest(submitted),
1251
+ ...submitted === head ? {} : { head },
1252
+ ...args.checkpointID === undefined ? {} : { answered: [args.checkpointID] }
1046
1253
  };
1047
1254
  await this.storage.set(this.key(args.sessionID), next);
1048
1255
  return next;
@@ -1051,8 +1258,12 @@ class FoldOwner {
1051
1258
  async observe(args) {
1052
1259
  return this.serial(args.sessionID, async () => {
1053
1260
  let state = await this.read(args.sessionID);
1054
- if (state?.rendered && state.rendered.id !== args.rendered.id)
1261
+ let carriedHead;
1262
+ if (state && (state.rendered ? state.rendered.id !== args.rendered.id : state.answered !== undefined && !state.answered.includes(args.rendered.id ?? ""))) {
1263
+ if (isCheckpointNote(args.summary) && state.answered?.includes(args.rendered.id ?? ""))
1264
+ carriedHead = state.head;
1055
1265
  state = undefined;
1266
+ }
1056
1267
  let changed = !state;
1057
1268
  const observedSha = foldDigest(JSON.stringify(args.rendered));
1058
1269
  const rendered = structuredClone(args.rendered);
@@ -1065,6 +1276,7 @@ class FoldOwner {
1065
1276
  watermark: args.cutSeq,
1066
1277
  submitted: args.summary,
1067
1278
  submittedSha: foldDigest(args.summary),
1279
+ ...carriedHead === undefined ? {} : { head: carriedHead },
1068
1280
  reason: "boot_recovery"
1069
1281
  };
1070
1282
  }
@@ -2893,6 +3105,7 @@ ${cached}
2893
3105
  }
2894
3106
  async supplyHeld(args) {
2895
3107
  const { draft, reader, summary } = args;
3108
+ const stored = args.checkpointText ?? summary;
2896
3109
  if (this.options.protocol === 3) {
2897
3110
  if (this.unprovenControls.has(draft.sessionID))
2898
3111
  return false;
@@ -2923,7 +3136,7 @@ ${cached}
2923
3136
  source: this.storage.sourceID,
2924
3137
  sessionID: draft.sessionID,
2925
3138
  admissionID: running.id,
2926
- summary
3139
+ summary: stored
2927
3140
  }));
2928
3141
  const value = {
2929
3142
  version: 3,
@@ -2932,7 +3145,7 @@ ${cached}
2932
3145
  sourceDigest: foldDigest(reader.hostIdentity()),
2933
3146
  sessionID: draft.sessionID,
2934
3147
  admissionID: running.id,
2935
- summaryDigest: foldDigest(summary),
3148
+ summaryDigest: foldDigest(stored),
2936
3149
  historyDigest: historyDigest(reader, draft.sessionID, running.seq - 1, replay.floor.after)
2937
3150
  }
2938
3151
  };
@@ -2984,7 +3197,7 @@ ${cached}
2984
3197
  source: this.storage.sourceID,
2985
3198
  sessionID: draft.sessionID,
2986
3199
  admissionID: running.id,
2987
- summary
3200
+ summary: stored
2988
3201
  }));
2989
3202
  return true;
2990
3203
  }
@@ -3020,7 +3233,7 @@ ${cached}
3020
3233
  source: this.storage.sourceID,
3021
3234
  sessionID: draft.sessionID,
3022
3235
  admissionID: id,
3023
- summary
3236
+ summary: stored
3024
3237
  };
3025
3238
  await this.storage.supply(draft.sessionID, id, JSON.stringify(snapshot));
3026
3239
  if (this.admissions) {
@@ -3028,7 +3241,7 @@ ${cached}
3028
3241
  sourceDigest: foldDigest(reader.hostIdentity()),
3029
3242
  sessionID: draft.sessionID,
3030
3243
  admissionID: id,
3031
- summaryDigest: foldDigest(summary),
3244
+ summaryDigest: foldDigest(stored),
3032
3245
  historyDigest: historyDigest(reader, draft.sessionID, (running?.seq ?? through) - 1)
3033
3246
  };
3034
3247
  const payload = JSON.stringify(provenance);
@@ -3119,7 +3332,7 @@ ${cached}
3119
3332
  await this.storage.saveTail(sessionID, JSON.stringify({
3120
3333
  model,
3121
3334
  sourceSeq: through,
3122
- baseline: tail?.baseline ?? cut.data.summary
3335
+ baseline: tail?.baseline ?? (isCheckpointNote(cut.data.summary) ? readSessionMeta(this.storage.db, sessionID).cachedM0Bytes?.toString("utf8") : cut.data.summary)
3123
3336
  }), []);
3124
3337
  this.loaded.set(sessionID, through);
3125
3338
  this.dirty.delete(sessionID);
@@ -3286,12 +3499,6 @@ class HostFoldPolicy {
3286
3499
  }
3287
3500
  }
3288
3501
 
3289
- // src/v2/fold/summary.ts
3290
- var RAW_HISTORY_ACCOUNT = "Magic Context retains the conversation as raw messages; no summarized history is available yet.";
3291
- function hasFoldSummary(summary) {
3292
- return typeof summary === "string" && summary.replace(/<[^>]*>/g, "").trim().length > 0;
3293
- }
3294
-
3295
3502
  // src/v2/fork-inheritance.ts
3296
3503
  var RAW_TYPES = new Set(RAW_MESSAGE_TYPES2);
3297
3504
  function forkBoundarySeq(origin, sequenceForId) {
@@ -5992,14 +6199,14 @@ function applyCheckpointHead(draft, head) {
5992
6199
  const first = draft.messages.find((message) => message.id === HEAD_IDS[0]);
5993
6200
  const baseline = first?.content.find((part) => part.type === "text")?.text;
5994
6201
  if (typeof baseline !== "string") {
5995
- draft.messages.unshift(checkpoint);
6202
+ draft.messages.unshift(withRecordedHead(checkpoint, submitted, head.head));
5996
6203
  return true;
5997
6204
  }
5998
6205
  for (const part of checkpoint.content)
5999
6206
  if (part.type === "text" && typeof part.text === "string") {
6000
6207
  part.text = part.text.replace(`<summary>
6001
6208
  ${submitted}
6002
- </summary>`, `<summary>
6209
+ </summary>`, () => `<summary>
6003
6210
  ${baseline}
6004
6211
  </summary>`);
6005
6212
  }
@@ -6009,24 +6216,46 @@ ${baseline}
6009
6216
  draft.messages.splice(0, draft.messages.length, checkpoint, ...draft.messages.filter((message) => message !== first));
6010
6217
  return true;
6011
6218
  }
6219
+ function servableCarrier(stored, head) {
6220
+ return !isCheckpointNote(stored) || head !== undefined;
6221
+ }
6012
6222
  function bindKeptInstructionCoordinates(messages, incoming, reader, sessionID) {
6013
6223
  const rows = reader.instructionRowsThrough(sessionID, reader.latestSequence(sessionID));
6014
6224
  let previous;
6015
6225
  let pending = [];
6226
+ const matches = (message, row) => message?.role === "system" && message.content.length === 1 && message.content[0]?.type === "text" && message.content[0].text === row?.data.text;
6016
6227
  const bind = (next) => {
6017
6228
  if (!pending.length)
6018
6229
  return;
6019
6230
  const candidates = rows.filter((row) => (previous === undefined || row.seq > previous) && (next === undefined || row.seq < next));
6020
6231
  const selected = previous === undefined ? candidates.slice(-pending.length) : next === undefined ? candidates.slice(0, pending.length) : candidates;
6021
- if (selected.length === pending.length && selected.every((row, index) => {
6022
- const message = pending[index];
6023
- return message?.role === "system" && message.content.length === 1 && message.content[0]?.type === "text" && message.content[0].text === row.data.text;
6024
- })) {
6232
+ if (selected.length === pending.length && selected.every((row, index) => matches(pending[index], row))) {
6025
6233
  selected.forEach((row, index) => {
6026
6234
  const message = pending[index];
6027
6235
  if (message)
6028
6236
  bindNativeRowID(message, row.id, row.seq);
6029
6237
  });
6238
+ } else {
6239
+ const earliest = [];
6240
+ let at = 0;
6241
+ for (const message of pending) {
6242
+ while (at < candidates.length && !matches(message, candidates[at]))
6243
+ at++;
6244
+ earliest.push(at++);
6245
+ }
6246
+ const latest = [];
6247
+ at = candidates.length - 1;
6248
+ for (let index = pending.length - 1;index >= 0; index--) {
6249
+ while (at >= 0 && !matches(pending[index], candidates[at]))
6250
+ at--;
6251
+ latest[index] = at--;
6252
+ }
6253
+ if (earliest.every((position) => position < candidates.length))
6254
+ pending.forEach((message, index) => {
6255
+ const row = candidates[earliest[index]];
6256
+ if (row && earliest[index] === latest[index])
6257
+ bindNativeRowID(message, row.id, row.seq);
6258
+ });
6030
6259
  }
6031
6260
  pending = [];
6032
6261
  };
@@ -6131,6 +6360,30 @@ function estimateCheckpointRequest(draft) {
6131
6360
  sessionId: draft.sessionID
6132
6361
  });
6133
6362
  }
6363
+ function estimateCheckpointFraming(draft, checkpoint, submitted) {
6364
+ const framing = structuredClone(checkpoint);
6365
+ for (const part of framing.content)
6366
+ if (part.type === "text" && typeof part.text === "string")
6367
+ part.text = part.text.replace(`<summary>
6368
+ ${submitted}
6369
+ </summary>`, `<summary>
6370
+
6371
+ </summary>`);
6372
+ try {
6373
+ const estimate = estimateFinalWireInputTokens({
6374
+ messages: adaptPayload({ ...draft, messages: [framing] }).messages,
6375
+ toolDefinitionTokens: 0,
6376
+ systemPromptTokens: 0,
6377
+ providerID: draft.model.providerID,
6378
+ modelID: draft.model.id,
6379
+ agentName: draft.agent,
6380
+ sessionId: draft.sessionID
6381
+ });
6382
+ return estimate.pressureTokens ?? estimate.tokens;
6383
+ } catch {
6384
+ return;
6385
+ }
6386
+ }
6134
6387
  var HIDDEN_SESSION_ERROR_GRACE_MS = 50;
6135
6388
  var STORE_POOL_DISPOSE_WAIT_MS = 1000;
6136
6389
  function isBlockingV2TransformError(error) {
@@ -6293,6 +6546,9 @@ function recordV2ToolDefinitions(draft) {
6293
6546
  }
6294
6547
  recordToolDefinitionSet(draft.model.providerID, draft.model.id, draft.agent, tools, draft.sessionID);
6295
6548
  }
6549
+ function v2DraftRequestToolsFingerprint(draft) {
6550
+ return v2RequestToolsFingerprint(draft.tools ?? {}, draft.messages);
6551
+ }
6296
6552
  async function applyV2SystemPrompt(systemPrompt, draft) {
6297
6553
  resolveCtxReduceAvailabilityFromMessages(draft.sessionID, draft.messages.map((message) => ({
6298
6554
  info: {
@@ -6377,6 +6633,7 @@ async function registerContext(context) {
6377
6633
  const hiddenModelActivity = new HiddenModelActivity;
6378
6634
  const liveModels = new Map;
6379
6635
  const toolDefinitionsHashes = new BoundedSessionMap(1000);
6636
+ const requestToolsFingerprints = new BoundedSessionMap(1000);
6380
6637
  const promptSurfaceRuntime = createPromptSurfaceRuntime({
6381
6638
  harness: "opencode2",
6382
6639
  directory,
@@ -6808,13 +7065,30 @@ async function registerContext(context) {
6808
7065
  servedModuleM0Text(sessionID),
6809
7066
  await nativeFoldReplay.baseline(sessionID),
6810
7067
  meta.cachedM0Bytes?.toString("utf8")
6811
- ].find((value) => value !== RAW_HISTORY_ACCOUNT && hasFoldSummary(value));
6812
- return !meta.isSubagent && summary !== RAW_HISTORY_ACCOUNT && hasFoldSummary(summary) && nativeFoldReplay.canFold(sessionID, reader);
7068
+ ].find(isHistoryHead);
7069
+ return !meta.isSubagent && isHistoryHead(summary) && nativeFoldReplay.canFold(sessionID, reader);
6813
7070
  },
6814
7071
  threshold: Number(process.env.MC_OC2_HOST_FOLD_ROWS ?? 1000),
6815
7072
  log: sessionLog2
6816
7073
  }) : undefined;
6817
7074
  const hostFoldIdle = hostFolds ? new HostFoldIdle((sessionID, eligible) => hostFolds.idle(sessionID, eligible)) : undefined;
7075
+ const armBindingRecoveryFromEvent = (sessionID, error, source) => {
7076
+ if (error === undefined || !db || compactionOff)
7077
+ return;
7078
+ const model = liveModels.get(sessionID);
7079
+ try {
7080
+ armThinkingBindingRecoveryFromError({
7081
+ db,
7082
+ sessionId: sessionID,
7083
+ error,
7084
+ providerID: model?.providerID,
7085
+ modelID: model?.modelID,
7086
+ source: source ?? "session event"
7087
+ });
7088
+ } catch (armError) {
7089
+ log2("[magic-context] v2 thinking binding recovery arm failed", armError);
7090
+ }
7091
+ };
6818
7092
  const usageController = new AbortController;
6819
7093
  const usageDone = (async () => {
6820
7094
  let retry = 0;
@@ -6867,6 +7141,8 @@ async function registerContext(context) {
6867
7141
  if (typeof messageID === "string")
6868
7142
  messageTimesCache.deleteMessage(sessionID, messageID);
6869
7143
  }
7144
+ if (event.type === "session.step.failed")
7145
+ armBindingRecoveryFromEvent(sessionID, event.data.error, "session.step.failed");
6870
7146
  if (event.type === "session.error" || event.type === "session.execution.failed") {
6871
7147
  hostFoldIdle?.active(sessionID);
6872
7148
  const error = hiddenTerminalError(event);
@@ -6874,8 +7150,9 @@ async function registerContext(context) {
6874
7150
  hiddenSessionErrors.set(sessionID, error);
6875
7151
  if (error !== undefined && db && !compactionOff) {
6876
7152
  const model = liveModels.get(sessionID);
7153
+ let latestTurnRejection = false;
6877
7154
  try {
6878
- armLatestThinkingRecoveryFromError({
7155
+ latestTurnRejection = armLatestThinkingRecoveryFromError({
6879
7156
  db,
6880
7157
  sessionId: sessionID,
6881
7158
  error,
@@ -6885,6 +7162,8 @@ async function registerContext(context) {
6885
7162
  } catch (armError) {
6886
7163
  log2("[magic-context] v2 latest-thinking recovery arm failed", armError);
6887
7164
  }
7165
+ if (!latestTurnRejection)
7166
+ armBindingRecoveryFromEvent(sessionID, error, event.type);
6888
7167
  }
6889
7168
  continue;
6890
7169
  }
@@ -7027,12 +7306,13 @@ async function registerContext(context) {
7027
7306
  const state = getOrCreateSessionMeta(storage.require(), draft.sessionID);
7028
7307
  const staged = manual && moduleBaseline == null ? stageManualBaseline(storage.require(), draft.sessionID, () => materialize(draft)) : undefined;
7029
7308
  const publishedHistory = Boolean(storage.require().prepare("SELECT 1 FROM compartments WHERE session_id = ? LIMIT 1").get(draft.sessionID));
7309
+ const owned = await folds.read(draft.sessionID);
7030
7310
  const candidate = [
7031
7311
  moduleBaseline,
7032
7312
  await nativeFoldReplay.baseline(draft.sessionID),
7033
7313
  state.cachedM0Bytes?.toString("utf8"),
7034
- (await folds.read(draft.sessionID))?.submitted
7035
- ].find((value) => value !== RAW_HISTORY_ACCOUNT && (publishedHistory && value?.includes("<session-history>") || hasFoldSummary(value)));
7314
+ owned?.head ?? owned?.submitted
7315
+ ].find((value) => value !== RAW_HISTORY_ACCOUNT && !isCheckpointNote(value) && (publishedHistory && value?.includes("<session-history>") || hasFoldSummary(value)));
7036
7316
  const manualHistory = manual && hasFoldSummary(staged?.summary ?? moduleBaseline);
7037
7317
  const summary = manualHistory ? staged?.summary ?? candidate ?? RAW_HISTORY_ACCOUNT : candidate ?? RAW_HISTORY_ACCOUNT;
7038
7318
  const manualReplay = manualHistory && summary ? await nativeFoldReplay.prepareManualFold(draft.sessionID, reader, staged ? staged.boundaryID : storage.require().prepare("SELECT cached_m0_last_baseline_end_message_id AS id FROM session_meta WHERE session_id = ?").get(draft.sessionID).id, summary) : undefined;
@@ -7041,6 +7321,7 @@ async function registerContext(context) {
7041
7321
  reader,
7042
7322
  previousCut: reader.latestCompaction(draft.sessionID),
7043
7323
  summary,
7324
+ checkpointText: CHECKPOINT_NOTE,
7044
7325
  manual: manualReplay ? { replay: manualReplay, commit: () => staged?.commit() } : undefined
7045
7326
  })) {
7046
7327
  if (manualHistory) {
@@ -7048,9 +7329,13 @@ async function registerContext(context) {
7048
7329
  generateReplay.forget(draft.sessionID);
7049
7330
  restoredRows.forget(draft.sessionID);
7050
7331
  historyRefreshSessions.add(draft.sessionID);
7332
+ noteHostCheckpointCommit(draft.sessionID, staged?.headCommit() ?? { changed: false, previousCoverage: null });
7051
7333
  requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "host_compaction");
7052
7334
  }
7053
- draft.result = { summary, metadata: { keepID: undefined } };
7335
+ draft.result = {
7336
+ summary: CHECKPOINT_NOTE,
7337
+ metadata: { keepID: undefined }
7338
+ };
7054
7339
  return;
7055
7340
  }
7056
7341
  if (manual)
@@ -7069,7 +7354,9 @@ async function registerContext(context) {
7069
7354
  materialize: () => {
7070
7355
  const summary = moduleBaseline ?? materialize(draft);
7071
7356
  return hasFoldSummary(summary) ? summary : RAW_HISTORY_ACCOUNT;
7072
- }
7357
+ },
7358
+ checkpointText: CHECKPOINT_NOTE,
7359
+ checkpointID: running?.id
7073
7360
  });
7074
7361
  sessionLog2(draft.sessionID, `v2 compaction hook: fired answered=true source=${source}`);
7075
7362
  draft.result = { summary: fold.submitted, metadata: { keepID: undefined } };
@@ -7157,7 +7444,7 @@ async function registerContext(context) {
7157
7444
  onPassPermission: (sessionID, permission) => {
7158
7445
  checkpointPassPermissions.set(sessionID, permission);
7159
7446
  },
7160
- reclaimHostRows: (sessionID, messages, permitted) => reclaimInstructionRows(database, sessionID, messages, permitted, foldedInstructionIDs.get(sessionID)),
7447
+ reclaimHostRows: (sessionID, messages, permitted, covered) => reclaimInstructionRows(database, sessionID, messages, permitted, foldedInstructionIDs.get(sessionID), covered),
7161
7448
  compactionOff,
7162
7449
  storeGeneration: "v2",
7163
7450
  normalizeRestoredAssistantText: (text, providerID) => stripCopiedTagNotation(text, providerID === "anthropic"),
@@ -7178,6 +7465,7 @@ async function registerContext(context) {
7178
7465
  return getCurrentToolSetHash(model.providerID, model.modelID, agents.get(sessionId), sessionId);
7179
7466
  },
7180
7467
  getToolDefinitionsHash: (sessionId) => toolDefinitionsHashes.get(sessionId),
7468
+ getRequestToolsFingerprint: (sessionId) => requestToolsFingerprints.get(sessionId),
7181
7469
  channel1StateBySession: channel1,
7182
7470
  historyRefreshSessions,
7183
7471
  pendingMaterializationSessions,
@@ -7422,6 +7710,10 @@ async function registerContext(context) {
7422
7710
  hideSubagentTools(draft, admissionDb);
7423
7711
  recordV2ToolDefinitions(draft);
7424
7712
  toolDefinitionsHashes.set(draft.sessionID, v2ToolDefinitionsHash(draft.tools));
7713
+ if (isPrefixBoundThinkingModel(draft.model.providerID, draft.model.id))
7714
+ requestToolsFingerprints.set(draft.sessionID, v2DraftRequestToolsFingerprint(draft));
7715
+ else
7716
+ requestToolsFingerprints.delete(draft.sessionID);
7425
7717
  if (await recordUsage(draft, true) && !compactionOff) {
7426
7718
  const storageReason = storage.current() ? null : storage.reason();
7427
7719
  if (storageReason) {
@@ -7510,6 +7802,7 @@ async function registerContext(context) {
7510
7802
  const reader = openStoreReader();
7511
7803
  let checkpoint;
7512
7804
  let submitted;
7805
+ let recordedHead;
7513
7806
  let upgradeCheckpointSequence;
7514
7807
  try {
7515
7808
  const candidates = syntheticCandidates(context, draft.sessionID, reader.syntheticMessageIDs(draft.sessionID));
@@ -7549,9 +7842,13 @@ async function registerContext(context) {
7549
7842
  requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "host_compaction");
7550
7843
  }
7551
7844
  });
7552
- checkpoint = structuredClone(identity.rendered ?? carrier.rendered);
7553
- submitted = identity.renderedSummary ?? carrier.submitted;
7554
- upgradeCheckpointSequence = carrier.row.seq;
7845
+ const stored = identity.renderedSummary ?? carrier.submitted;
7846
+ if (servableCarrier(stored, identity.head)) {
7847
+ checkpoint = structuredClone(identity.rendered ?? carrier.rendered);
7848
+ submitted = stored;
7849
+ recordedHead = identity.head;
7850
+ upgradeCheckpointSequence = carrier.row.seq;
7851
+ }
7555
7852
  }
7556
7853
  }
7557
7854
  let nativeRestored = localCut ? nativeFoldReplay?.legacyUpgradeInput(draft.sessionID, draft.model) : undefined;
@@ -7588,8 +7885,13 @@ async function registerContext(context) {
7588
7885
  requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "host_compaction");
7589
7886
  }
7590
7887
  });
7591
- checkpoint = structuredClone(identity.rendered ?? incoming);
7592
- submitted = identity.rendered ? identity.renderedSummary ?? identity.submitted : cut.data.summary ?? "";
7888
+ const stored = identity.rendered ? identity.renderedSummary ?? identity.submitted : cut.data.summary ?? "";
7889
+ if (servableCarrier(stored, identity.head)) {
7890
+ checkpoint = structuredClone(identity.rendered ?? incoming);
7891
+ submitted = stored;
7892
+ recordedHead = identity.head;
7893
+ } else
7894
+ sessionLog2(draft.sessionID, "v2 host fold: note checkpoint without a recorded head; serving restored history");
7593
7895
  }
7594
7896
  draft.messages.splice(0, draft.messages.length, ...await restoreAfterCheckpoint({
7595
7897
  db,
@@ -7629,11 +7931,15 @@ async function registerContext(context) {
7629
7931
  if (stripCheckpointRecentContext(projected, submitted)) {
7630
7932
  const estimate = estimateCheckpointRequest({
7631
7933
  ...draft,
7632
- messages: [checkpoint, ...draft.messages]
7934
+ messages: [
7935
+ withRecordedHead(checkpoint, submitted, recordedHead),
7936
+ ...draft.messages
7937
+ ]
7633
7938
  });
7634
7939
  checkpointInputEstimates.set(draft.sessionID, {
7635
7940
  tokens: estimate.tokens,
7636
- pressureTokens: estimate.pressureTokens ?? estimate.tokens
7941
+ pressureTokens: estimate.pressureTokens ?? estimate.tokens,
7942
+ hostAddedTokens: estimateCheckpointFraming(draft, projected, submitted)
7637
7943
  });
7638
7944
  }
7639
7945
  }
@@ -7679,7 +7985,11 @@ async function registerContext(context) {
7679
7985
  if (db) {
7680
7986
  await deliverPendingChannel2(context, db, draft.sessionID, channel1.get(draft.sessionID));
7681
7987
  }
7682
- const head = replayHead !== undefined ? replayHead : checkpoint && submitted !== undefined ? { checkpoint, submitted } : null;
7988
+ const head = replayHead !== undefined ? replayHead : checkpoint && submitted !== undefined ? {
7989
+ checkpoint,
7990
+ submitted,
7991
+ ...recordedHead === undefined ? {} : { head: recordedHead }
7992
+ } : null;
7683
7993
  const servedHead = head && structuredClone(head);
7684
7994
  const headApplied = head ? applyCheckpointHead(draft, head) : false;
7685
7995
  if (nativeMessages && (!checkpoint || upgradeCheckpointSequence !== undefined)) {