@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
@@ -69,21 +69,21 @@ import {
69
69
  import {
70
70
  matchedSearchSnippet,
71
71
  getIndexedMessageCorpusSize
72
- } from "./index-bzq05g00.js";
72
+ } from "./index-etn2hmb5.js";
73
73
  import {
74
74
  getMessageIndexEpoch,
75
75
  isMessageIndexSearchable,
76
76
  withMemoryHintContent,
77
77
  autoSearchRelevance,
78
78
  recordAutoSearchLane
79
- } from "./index-tvd2j34s.js";
79
+ } from "./index-44pp3vrj.js";
80
80
  import {
81
81
  MESSAGE_FTS_SESSION_FILTER_SQL,
82
82
  withMessageFtsSessionFilter
83
83
  } from "./index-kaqs6h31.js";
84
84
  import {
85
85
  isRecord
86
- } from "./index-gxqr0sbd.js";
86
+ } from "./index-x53gnmce.js";
87
87
  import {
88
88
  resolveWorkspaceShareCategories,
89
89
  resolveWorkspaceIdentitySet,
@@ -301,6 +301,50 @@ class V2StoreReader2 {
301
301
  }
302
302
  return statement;
303
303
  }
304
+ hasPartTable() {
305
+ this.connection.partTable ??= Boolean(this.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'session_part'").get());
306
+ return this.connection.partTable;
307
+ }
308
+ withParts(rows) {
309
+ const ids = rows.flatMap((row) => row.type === "assistant" ? [row.id] : []);
310
+ if (ids.length === 0 || !this.hasPartTable())
311
+ return rows;
312
+ const parts = new Map;
313
+ for (let offset = 0;offset < ids.length; offset += 500) {
314
+ const chunk = ids.slice(offset, offset + 500);
315
+ const partRows = this.prepare(`SELECT message_id, ordinal, data FROM session_part
316
+ WHERE message_id IN (${chunk.map(() => "?").join(", ")})
317
+ ORDER BY message_id ASC, ordinal ASC`).all(...chunk);
318
+ for (const part of partRows) {
319
+ let data;
320
+ try {
321
+ data = JSON.parse(part.data);
322
+ } catch {
323
+ throw new Error(`Invalid session_part data for ${part.message_id} at ordinal ${part.ordinal}`);
324
+ }
325
+ const list = parts.get(part.message_id);
326
+ if (list)
327
+ list.push(data);
328
+ else
329
+ parts.set(part.message_id, [data]);
330
+ }
331
+ }
332
+ if (parts.size === 0)
333
+ return rows;
334
+ return rows.map((row) => {
335
+ const content = parts.get(row.id);
336
+ if (!content)
337
+ return row;
338
+ const inline = row.data.content;
339
+ return {
340
+ ...row,
341
+ data: {
342
+ ...row.data,
343
+ content: Array.isArray(inline) ? [...content, ...inline] : content
344
+ }
345
+ };
346
+ });
347
+ }
304
348
  close() {
305
349
  if (this.closed)
306
350
  return;
@@ -330,9 +374,9 @@ class V2StoreReader2 {
330
374
  predicates.push("type = ?");
331
375
  parameters.push(options.type);
332
376
  }
333
- const rows = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
377
+ const rows = this.withParts(this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
334
378
  WHERE ${predicates.join(" AND ")}
335
- ORDER BY seq ASC LIMIT ?`).all(...parameters, limit).map(decode);
379
+ ORDER BY seq ASC LIMIT ?`).all(...parameters, limit).map(decode));
336
380
  return { rows, cursor: rows.at(-1)?.seq };
337
381
  });
338
382
  }
@@ -350,14 +394,14 @@ class V2StoreReader2 {
350
394
  if (after) {
351
395
  const anchor = this.prepare("SELECT seq FROM session_message WHERE session_id = ? AND id = ?").get(sessionID, after.id);
352
396
  if (anchor) {
353
- return this.prepare(`SELECT id, session_id, type, seq, time_created, data
397
+ return this.withParts(this.prepare(`SELECT id, session_id, type, seq, time_created, data
354
398
  FROM session_message WHERE session_id = ? AND seq > ?
355
- AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS}) ORDER BY seq ASC LIMIT ?`).all(sessionID, anchor.seq, ...RAW_MESSAGE_TYPES2, pageSize).map(decode);
399
+ AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS}) ORDER BY seq ASC LIMIT ?`).all(sessionID, anchor.seq, ...RAW_MESSAGE_TYPES2, pageSize).map(decode));
356
400
  }
357
401
  }
358
402
  const maximumSeq = Number.MAX_SAFE_INTEGER;
359
403
  const rows = this.prepare(V2_MESSAGE_PAGE_SQL).all(afterOrdinal, sessionID, ...RAW_MESSAGE_TYPES2, Math.max(0, afterOrdinal - 1), sessionID, sessionID, ...RAW_MESSAGE_TYPES2, finalWatermark - 1, maximumSeq, sessionID, ...RAW_MESSAGE_TYPES2, pageSize);
360
- return rows.map(decode);
404
+ return this.withParts(rows.map(decode));
361
405
  });
362
406
  }
363
407
  messageCount(sessionID) {
@@ -491,7 +535,7 @@ class V2StoreReader2 {
491
535
  const rawTypes = RAW_MESSAGE_TYPES2.map(() => "?").join(", ");
492
536
  const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
493
537
  WHERE session_id = ? AND id = ? AND type IN (${rawTypes}) LIMIT 1`).get(sessionID, id, ...RAW_MESSAGE_TYPES2);
494
- return row ? decode(row) : null;
538
+ return row ? this.withParts([decode(row)])[0] ?? null : null;
495
539
  });
496
540
  }
497
541
  messageTimeVersions(sessionID, ids, span) {
@@ -626,12 +670,20 @@ class V2StoreReader2 {
626
670
  spanRowStamps(sessionID, after, through) {
627
671
  if (!Number.isSafeInteger(after) || !Number.isSafeInteger(through))
628
672
  throw new Error("Invalid seq span");
629
- const rows = this.prepare(`SELECT seq, id, time_updated AS updated, length(CAST(data AS BLOB)) AS bytes
630
- FROM session_message WHERE session_id = ? AND seq > ? AND seq <= ?
631
- ORDER BY seq ASC`).all(sessionID, after, through);
673
+ const partJoin = this.hasPartTable() ? `LEFT JOIN (SELECT p.message_id AS message_id, COUNT(*) AS parts,
674
+ MAX(p.time_updated) AS partsUpdated,
675
+ SUM(length(CAST(p.data AS BLOB))) AS partsBytes
676
+ FROM session_message s JOIN session_part p ON p.message_id = s.id
677
+ WHERE s.session_id = ? AND s.seq > ? AND s.seq <= ?
678
+ GROUP BY p.message_id) g ON g.message_id = m.id` : "";
679
+ const rows = this.prepare(`SELECT m.seq AS seq, m.id AS id, m.time_updated AS updated,
680
+ length(CAST(m.data AS BLOB)) AS bytes${partJoin ? ", g.parts AS parts, g.partsUpdated AS partsUpdated, g.partsBytes AS partsBytes" : ""}
681
+ FROM session_message m ${partJoin}
682
+ WHERE m.session_id = ? AND m.seq > ? AND m.seq <= ?
683
+ ORDER BY m.seq ASC`).all(...partJoin ? [sessionID, after, through] : [], sessionID, after, through);
632
684
  const stamps = new Map;
633
685
  for (const row of rows)
634
- stamps.set(row.seq, `${row.id}\x00${row.updated ?? ""}\x00${row.bytes ?? ""}`);
686
+ stamps.set(row.seq, `${row.id}\x00${row.updated ?? ""}\x00${row.bytes ?? ""}${row.parts ? `\x00${row.parts}\x00${row.partsUpdated ?? ""}\x00${row.partsBytes ?? ""}` : ""}`);
635
687
  return stamps;
636
688
  }
637
689
  rawRowsThrough(sessionID, throughSeq, limit) {
@@ -641,9 +693,9 @@ class V2StoreReader2 {
641
693
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
642
694
  throw new Error("Invalid page limit");
643
695
  const rawTypes = RAW_MESSAGE_TYPES2.map(() => "?").join(", ");
644
- return this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
696
+ return this.withParts(this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
645
697
  WHERE session_id = ? AND type IN (${rawTypes}) AND seq <= ?
646
- ORDER BY seq DESC LIMIT ?`).all(sessionID, ...RAW_MESSAGE_TYPES2, throughSeq, limit).map(decode);
698
+ ORDER BY seq DESC LIMIT ?`).all(sessionID, ...RAW_MESSAGE_TYPES2, throughSeq, limit).map(decode));
647
699
  });
648
700
  }
649
701
  instructionRowsThrough(sessionID, throughSeq) {
@@ -734,7 +786,7 @@ class V2StoreReader2 {
734
786
  const rows = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
735
787
  WHERE session_id = ? AND type = 'assistant' AND seq > ?
736
788
  ORDER BY seq ASC`).all(sessionID, afterSeq);
737
- return rows.map((row) => decode(row));
789
+ return this.withParts(rows.map(decode));
738
790
  });
739
791
  }
740
792
  latestAssistant(sessionID) {
@@ -742,7 +794,7 @@ class V2StoreReader2 {
742
794
  const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
743
795
  WHERE session_id = ? AND type = 'assistant'
744
796
  ORDER BY seq DESC LIMIT 1`).get(sessionID);
745
- return row ? decode(row) : undefined;
797
+ return row ? this.withParts([decode(row)])[0] : undefined;
746
798
  });
747
799
  }
748
800
  latestIdle(sessionID) {
@@ -142,6 +142,11 @@ function deriveWindowGeometry(providerID, modelID, catalogLimit, options = {}) {
142
142
  const requestedOutput = Math.min(output ?? OPENCODE_OUTPUT_CAP, OPENCODE_OUTPUT_CAP);
143
143
  usableHard = hardWindow - requestedOutput;
144
144
  }
145
+ let hardWithoutInputCap;
146
+ if (isFinitePositive(input) && input < usableHard) {
147
+ hardWithoutInputCap = Math.max(MIN_PLAUSIBLE_CONTEXT_LIMIT, Math.floor(usableHard));
148
+ usableHard = input;
149
+ }
145
150
  usableHard = Math.max(MIN_PLAUSIBLE_CONTEXT_LIMIT, Math.floor(usableHard));
146
151
  if (usableHard < usableSoft) {
147
152
  logGeometryClampOnce(`${providerID}/${modelID}|${usableSoft}|${usableHard}`, `usable hard limit clamped for ${providerID}/${modelID}: ${usableHard} → ${usableSoft} (window limit inversion)`, options.log);
@@ -158,7 +163,8 @@ function deriveWindowGeometry(providerID, modelID, catalogLimit, options = {}) {
158
163
  reserveSource,
159
164
  geometry,
160
165
  windowSource,
161
- absoluteWall: Math.floor(hardWindow)
166
+ absoluteWall: Math.floor(hardWindow),
167
+ ...hardWithoutInputCap !== undefined ? { hardWithoutInputCap } : {}
162
168
  }
163
169
  };
164
170
  }
@@ -180,11 +186,13 @@ function applyProvenInputFloor(geometry, provenInputTokens) {
180
186
  }
181
187
  const trustedAbsoluteWall = hasTrustedAbsoluteWall(geometry);
182
188
  const window = trustedAbsoluteWall ? geometry.derivation.window : Math.max(geometry.derivation.window, provenInputTokens);
189
+ const inputCapDisproved = geometry.derivation.hardWithoutInputCap !== undefined && provenInputTokens > geometry.usableHard;
190
+ const hardBeforeFloor = inputCapDisproved ? geometry.derivation.hardWithoutInputCap : geometry.usableHard;
183
191
  return {
184
192
  geometry: {
185
193
  ...geometry,
186
194
  usableSoft: provenInputTokens,
187
- usableHard: trustedAbsoluteWall ? geometry.usableHard : Math.max(geometry.usableHard, provenInputTokens),
195
+ usableHard: trustedAbsoluteWall ? hardBeforeFloor : Math.max(hardBeforeFloor, provenInputTokens),
188
196
  derivation: {
189
197
  ...geometry.derivation,
190
198
  window,
@@ -1024,7 +1024,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
1024
1024
  state.running = startMessageFtsRowidMapBackfill2(db, signal).then(async () => {
1025
1025
  if (signal.aborted || !readsOpenCodeStore)
1026
1026
  return;
1027
- const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-k3fqshw8.js"));
1027
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-7h9f32sz.js"));
1028
1028
  const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-39bm498k.js"));
1029
1029
  if (signal.aborted)
1030
1030
  return;
@@ -72,7 +72,7 @@ import {
72
72
  getRawSessionTagKeysThrough2,
73
73
  getLegacyProtectedTailStartOrdinal2,
74
74
  readSessionChunk2
75
- } from "./index-wwg1je98.js";
75
+ } from "./index-xgnh498s.js";
76
76
  import {
77
77
  getHarness2,
78
78
  harnessOwnsOpenCodeStore2
@@ -110,7 +110,7 @@ import {
110
110
  deriveTriggerBudget2,
111
111
  resolveHistorianProducerLimits2,
112
112
  producerSourceLocalBudget2
113
- } from "./index-dnqqqc5f.js";
113
+ } from "./index-8cfnaagj.js";
114
114
  import {
115
115
  withContentLanguageDirective,
116
116
  buildPrimaryLanguageDirective,
@@ -153,7 +153,7 @@ import {
153
153
  LATEST_SUPPORTED_VERSION,
154
154
  getPersistedSchemaVersion,
155
155
  openDatabase
156
- } from "./index-z8dacvkt.js";
156
+ } from "./index-b0xt5qz9.js";
157
157
  import {
158
158
  areRustHistorianSyntheticParts2,
159
159
  isStrictGapHealingMessage2,
@@ -239,14 +239,14 @@ import {
239
239
  getProjectState,
240
240
  recordSubagentInvocation,
241
241
  getLatestHistorianInvocationId
242
- } from "./index-jwa5t1s4.js";
242
+ } from "./index-1qmv26ga.js";
243
243
  import {
244
244
  clearCompressionDepth,
245
245
  clearCompressionDepthRange,
246
246
  toMessageIndexSource,
247
247
  clearIndexedMessagesInTransaction,
248
248
  indexSourcesAfterOrdinal
249
- } from "./index-bzq05g00.js";
249
+ } from "./index-etn2hmb5.js";
250
250
  import {
251
251
  stripWellFormedLeadingTagPrefix,
252
252
  peelLeadingMcTagNotation,
@@ -257,7 +257,7 @@ import {
257
257
  foldShrunkPartTags2,
258
258
  getTagNumberByMessageId2,
259
259
  getActiveTagsBySession2
260
- } from "./index-gxqr0sbd.js";
260
+ } from "./index-x53gnmce.js";
261
261
  import {
262
262
  openCodeDbExists,
263
263
  withReadOnlySessionDb,
@@ -7895,6 +7895,151 @@ function describeRequestToolDefinitionChange(previous, current) {
7895
7895
  }
7896
7896
  return { previousHash: before.hash, currentHash: after.hash, firstDifferingTool };
7897
7897
  }
7898
+ var v2SchemaDigests = new Map;
7899
+ var V2_SCHEMA_DIGEST_NAMES = 2048;
7900
+ function v2SchemaDigest(name, schema) {
7901
+ let text;
7902
+ try {
7903
+ text = JSON.stringify(schema);
7904
+ } catch {
7905
+ return requestToolSchemaDigest(schema);
7906
+ }
7907
+ if (text === undefined)
7908
+ return requestToolSchemaDigest(schema);
7909
+ const cached = v2SchemaDigests.get(name);
7910
+ if (cached?.text === text)
7911
+ return cached.digest;
7912
+ const digest = requestToolSchemaDigest(schema);
7913
+ if (!cached && v2SchemaDigests.size >= V2_SCHEMA_DIGEST_NAMES) {
7914
+ const oldest = v2SchemaDigests.keys().next().value;
7915
+ if (oldest !== undefined)
7916
+ v2SchemaDigests.delete(oldest);
7917
+ }
7918
+ v2SchemaDigests.set(name, { text, digest });
7919
+ return digest;
7920
+ }
7921
+ function v2RequestToolsFingerprint(tools, messages = []) {
7922
+ const entries = [];
7923
+ for (const [name, tool] of Object.entries(tools)) {
7924
+ if (!tool)
7925
+ continue;
7926
+ const declared = tool;
7927
+ entries.push({
7928
+ name,
7929
+ description: typeof tool.description === "string" ? tool.description : "",
7930
+ schemaDigest: v2SchemaDigest(name, tool.input),
7931
+ deferLoading: declared.defer_loading === true || declared.deferLoading === true
7932
+ });
7933
+ }
7934
+ return requestToolsFingerprint(entries, () => {
7935
+ const referenced = new Set;
7936
+ for (const message of messages)
7937
+ for (const part of message.content) {
7938
+ if (typeof part.type !== "string" || !part.type.includes("tool"))
7939
+ continue;
7940
+ if (typeof part.name === "string")
7941
+ referenced.add(part.name);
7942
+ if (typeof part.tool === "string")
7943
+ referenced.add(part.tool);
7944
+ }
7945
+ return referenced;
7946
+ });
7947
+ }
7948
+ function requestToolsFingerprint(tools, referencedNames) {
7949
+ let referenced;
7950
+ const included = [];
7951
+ for (const tool of tools) {
7952
+ if (tool.deferLoading === true) {
7953
+ referenced ??= referencedNames?.() ?? new Set;
7954
+ if (!referenced.has(tool.name))
7955
+ continue;
7956
+ }
7957
+ included.push(tool);
7958
+ }
7959
+ included.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
7960
+ return {
7961
+ names: sha(included.map((tool) => tool.name)),
7962
+ descriptions: sha(included.map((tool) => [tool.name, tool.description])),
7963
+ schemas: sha(included.map((tool) => tool.deferLoading === true ? [tool.name, tool.description, tool.schemaDigest, "defer_loading"] : [tool.name, tool.description, tool.schemaDigest]))
7964
+ };
7965
+ }
7966
+ function classifyRequestToolsChange(previous, current) {
7967
+ if (previous.names !== current.names)
7968
+ return "names";
7969
+ if (previous.descriptions !== current.descriptions)
7970
+ return "descriptions";
7971
+ if (previous.schemas !== current.schemas)
7972
+ return "schemas";
7973
+ return null;
7974
+ }
7975
+ function requestToolSchemaDigest(schema) {
7976
+ const pieces = [];
7977
+ writeCanonicalJson(toJsonValue(schema, ""), [], pieces);
7978
+ return createHash6("sha256").update(pieces.join("")).digest("hex");
7979
+ }
7980
+ function isJsonValue(value) {
7981
+ return value !== undefined && typeof value !== "function" && typeof value !== "symbol";
7982
+ }
7983
+ function toJsonValue(value, key) {
7984
+ if (typeof value !== "object" || value === null)
7985
+ return value;
7986
+ const toJSON = value.toJSON;
7987
+ const resolved = typeof toJSON === "function" ? toJSON.call(value, key) : value;
7988
+ if (resolved instanceof Number)
7989
+ return Number(resolved);
7990
+ if (resolved instanceof String)
7991
+ return String(resolved);
7992
+ if (resolved instanceof Boolean)
7993
+ return resolved.valueOf();
7994
+ return resolved;
7995
+ }
7996
+ function writeCanonicalJson(value, ancestors, out) {
7997
+ if (value === null || typeof value === "boolean" || typeof value === "string") {
7998
+ out.push(JSON.stringify(value));
7999
+ return;
8000
+ }
8001
+ if (typeof value === "number") {
8002
+ out.push(Number.isFinite(value) ? JSON.stringify(value) : "null");
8003
+ return;
8004
+ }
8005
+ if (typeof value === "bigint") {
8006
+ out.push(JSON.stringify(value.toString()));
8007
+ return;
8008
+ }
8009
+ if (typeof value !== "object") {
8010
+ out.push("null");
8011
+ return;
8012
+ }
8013
+ if (ancestors.includes(value)) {
8014
+ out.push('"[Circular]"');
8015
+ return;
8016
+ }
8017
+ ancestors.push(value);
8018
+ if (Array.isArray(value)) {
8019
+ out.push("[");
8020
+ for (let index = 0;index < value.length; index += 1) {
8021
+ if (index > 0)
8022
+ out.push(",");
8023
+ const item = toJsonValue(value[index], String(index));
8024
+ if (isJsonValue(item))
8025
+ writeCanonicalJson(item, ancestors, out);
8026
+ else
8027
+ out.push("null");
8028
+ }
8029
+ out.push("]");
8030
+ } else {
8031
+ const entries = Object.entries(value).map(([key, child]) => [key, toJsonValue(child, key)]).filter(([, child]) => isJsonValue(child)).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
8032
+ out.push("{");
8033
+ entries.forEach(([key, child], index) => {
8034
+ if (index > 0)
8035
+ out.push(",");
8036
+ out.push(JSON.stringify(key), ":");
8037
+ writeCanonicalJson(child, ancestors, out);
8038
+ });
8039
+ out.push("}");
8040
+ }
8041
+ ancestors.pop();
8042
+ }
7898
8043
 
7899
8044
  // src/features/magic-context/user-memory/storage-user-memory.ts
7900
8045
  var USER_MEMORY_CANDIDATE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
@@ -12020,6 +12165,27 @@ function prepareCachedM0M1Replay(db, sessionId) {
12020
12165
  preparedTrimBoundaryId: row.cached_m0_last_baseline_end_message_id
12021
12166
  };
12022
12167
  }
12168
+ function headMessagesForSizing(options, folds = false) {
12169
+ if (!folds) {
12170
+ const cached = prepareCachedM0M1Replay(options.db, options.sessionId);
12171
+ if (cached?.preparedMessages)
12172
+ return cached.preparedMessages;
12173
+ }
12174
+ const state = { ...options.state };
12175
+ const fresh = renderFreshM0NonPersisted({ ...options, state });
12176
+ const head = [];
12177
+ prependM0M1Messages(options.sessionId, head, fresh.m0Bytes.toString("utf8"), M1_EMPTY_PLACEHOLDER, state.cachedM0MuralDataUrl ? { enabled: true, supportsVision: true, dataUrl: state.cachedM0MuralDataUrl } : undefined);
12178
+ return head;
12179
+ }
12180
+ function rawTailAfterNewestCompartment(db, sessionId, messages) {
12181
+ const boundary = newestCompartmentEndId(getCompartments(db, sessionId));
12182
+ if (!boundary)
12183
+ return messages;
12184
+ const index = findBoundaryIndex(sessionId, messages, boundary);
12185
+ if (index < 0)
12186
+ return messages;
12187
+ return messages.slice(index + (isPartialCompartmentEnd(db, sessionId, boundary) ? 0 : 1));
12188
+ }
12023
12189
  function hasCompleteCachedM0M1(db, sessionId) {
12024
12190
  const row = db.prepare("SELECT length(cached_m0_bytes) > 0 AND length(cached_m1_bytes) > 0 AS complete FROM session_meta WHERE session_id = ?").get(sessionId);
12025
12191
  return row?.complete === 1;
@@ -17624,8 +17790,6 @@ ${chunkText}`,
17624
17790
  clearHistorianFailureState(db, sessionId);
17625
17791
  clearHistorianDrainFailure(db, sessionId);
17626
17792
  recordProtectedTailPublicationFloor(db, sessionId, lastCompartmentEnd + 1);
17627
- if (!isWrapupInProgress(db, sessionId))
17628
- clearEmergencyRecovery(db, sessionId);
17629
17793
  drainReservation = null;
17630
17794
  if (deferMarkerApplication && lastNewEndMessageId) {
17631
17795
  (deps.compactionMarkerStrategy?.setPending ?? setPendingCompactionMarkerState)(db, sessionId, {
@@ -18773,4 +18937,4 @@ async function executeContextRecomp(deps, options = {}) {
18773
18937
  return (await executeContextRecompWithResult(deps, options)).message;
18774
18938
  }
18775
18939
 
18776
- export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, isCommitRetentionPaused, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, withDreamerModelCooldown, providerOutputFailureFromInvalidManifest, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, parseProviderModel, modelBodyField, toModelEntry, ModelProducedNoOutputError, noteModelActivityMonitored, noteModelOutputReceived, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, annotateSubagentInvocationError, failedInvocationStatus, emptyTokenTotals, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, v2ToolDefinitionsHash, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };
18940
+ export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, isCommitRetentionPaused, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, withDreamerModelCooldown, providerOutputFailureFromInvalidManifest, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, parseProviderModel, modelBodyField, toModelEntry, ModelProducedNoOutputError, noteModelActivityMonitored, noteModelOutputReceived, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, annotateSubagentInvocationError, failedInvocationStatus, emptyTokenTotals, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, stripMemoryMuralBlock, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, headMessagesForSizing, rawTailAfterNewestCompartment, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };