@cortexkit/opencode-magic-context 0.49.44 → 0.49.46

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 (154) hide show
  1. package/dist/auto-search-worker.js +4 -4
  2. package/dist/chunk-embedding-write-worker.js +7 -7
  3. package/dist/{compartment-chunk-embedding-ypktm0tk.js → compartment-chunk-embedding-snj51nmg.js} +5 -5
  4. package/dist/{conflict-warning-hook-b75jn458.js → conflict-warning-hook-w1aw6w5t.js} +4 -4
  5. package/dist/{context-ws6gbyrr.js → context-cb51adcz.js} +374 -115
  6. package/dist/{derive-budgets-htj16n4x.js → derive-budgets-nkw09vq7.js} +1 -1
  7. package/dist/{embedding-backfill-zxj35jkq.js → embedding-backfill-kpy5shsa.js} +8 -8
  8. package/dist/embedding-worker.js +3 -3
  9. package/dist/features/magic-context/memory/embedding-openai.d.ts.map +1 -1
  10. package/dist/features/magic-context/memory/embedding-query-deadline.d.ts +8 -0
  11. package/dist/features/magic-context/memory/embedding-query-deadline.d.ts.map +1 -0
  12. package/dist/features/magic-context/overflow-detection.d.ts +16 -6
  13. package/dist/features/magic-context/overflow-detection.d.ts.map +1 -1
  14. package/dist/hooks/auto-update-checker/index.d.ts +6 -0
  15. package/dist/hooks/auto-update-checker/index.d.ts.map +1 -1
  16. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  17. package/dist/hooks/magic-context/inject-compartments.d.ts +21 -0
  18. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  19. package/dist/hooks/magic-context/priced-pass-sizing.d.ts +132 -0
  20. package/dist/hooks/magic-context/priced-pass-sizing.d.ts.map +1 -0
  21. package/dist/hooks/magic-context/read-session-formatting.d.ts +2 -1
  22. package/dist/hooks/magic-context/read-session-formatting.d.ts.map +1 -1
  23. package/dist/hooks/magic-context/read-session-raw.d.ts.map +1 -1
  24. package/dist/hooks/magic-context/reasoning-budget.d.ts.map +1 -1
  25. package/dist/hooks/magic-context/recovery-fit.d.ts +51 -0
  26. package/dist/hooks/magic-context/recovery-fit.d.ts.map +1 -0
  27. package/dist/hooks/magic-context/routine-cleanup-decision.d.ts +109 -0
  28. package/dist/hooks/magic-context/routine-cleanup-decision.d.ts.map +1 -0
  29. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  30. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +24 -0
  31. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  32. package/dist/hooks/magic-context/transform-context-state.d.ts +2 -1
  33. package/dist/hooks/magic-context/transform-context-state.d.ts.map +1 -1
  34. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +15 -2
  35. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  36. package/dist/hooks/magic-context/transform.d.ts +10 -2
  37. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  38. package/dist/{index-jggt5gf2.js → index-1hwn96x1.js} +1 -1
  39. package/dist/{index-ae1ar4v1.js → index-25ka1jza.js} +1 -1
  40. package/dist/{index-91y4xvx6.js → index-44pp3vrj.js} +2 -2
  41. package/dist/{index-wapyeb06.js → index-55ngkbqa.js} +36 -17
  42. package/dist/{index-v64se1t6.js → index-5jk4h64j.js} +8 -8
  43. package/dist/{index-dnqqqc5f.js → index-8cfnaagj.js} +10 -2
  44. package/dist/{index-7y8c2n52.js → index-a4t7pdmm.js} +3 -3
  45. package/dist/{index-4xyjr62e.js → index-ak11t3gm.js} +4 -0
  46. package/dist/{index-6qnhaaa0.js → index-b0xt5qz9.js} +3 -3
  47. package/dist/{index-vd2ywmfe.js → index-brj6was5.js} +1 -1
  48. package/dist/{index-66qexmjw.js → index-d4qw2h43.js} +3 -3
  49. package/dist/{index-g4t7850m.js → index-dj2p8653.js} +1 -1
  50. package/dist/{index-m1mttf6y.js → index-etn2hmb5.js} +3 -3
  51. package/dist/{index-g0mjm7e4.js → index-gaxktvxm.js} +5 -5
  52. package/dist/{index-b1ydbp95.js → index-h9m41624.js} +1 -1
  53. package/dist/{index-p6gs3xpx.js → index-hkh8x221.js} +1 -1
  54. package/dist/{index-24y47287.js → index-kevd267m.js} +4 -4
  55. package/dist/{index-knnscj54.js → index-kw7azjmy.js} +3 -3
  56. package/dist/{index-dasvhxwg.js → index-n9q8c1dr.js} +6 -6
  57. package/dist/{index-g7rrfjkq.js → index-pwfmcg4e.js} +5 -5
  58. package/dist/{index-dcjkw41m.js → index-qcz1fy7h.js} +3 -3
  59. package/dist/{index-rhcwddn9.js → index-s79g172v.js} +63 -21
  60. package/dist/{index-kgk64zyx.js → index-sd2s4t4p.js} +1 -1
  61. package/dist/{index-jkanybgq.js → index-smtbdmc3.js} +1 -1
  62. package/dist/{index-ntssp0dt.js → index-snztv1f0.js} +621 -111
  63. package/dist/{index-8w3y6pxc.js → index-tajstyw4.js} +167 -87
  64. package/dist/{index-8jjjmhab.js → index-x53gnmce.js} +11 -11
  65. package/dist/{index-r2epb000.js → index-xa9mmq6c.js} +2 -1
  66. package/dist/{index-1j8m4ad0.js → index-xgnh498s.js} +10 -6
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.js +43 -39
  69. package/dist/{message-fts-rowid-map-t6qsyg9s.js → message-fts-rowid-map-msffhkve.js} +2 -2
  70. package/dist/{message-index-bounded-dmq6ne7d.js → message-index-bounded-3qpg8dq5.js} +8 -8
  71. package/dist/migration-worker.js +5 -5
  72. package/dist/{project-embedding-registry-m47vg1ce.js → project-embedding-registry-r6xfsrbe.js} +7 -7
  73. package/dist/raw-ordinal-warmup-worker.js +7 -7
  74. package/dist/{read-session-chunk-3m7z9v3t.js → read-session-chunk-7h9f32sz.js} +6 -6
  75. package/dist/{read-session-raw-j7c9w57v.js → read-session-raw-x7a9b3jm.js} +1 -1
  76. package/dist/{recomp-orchestrator-9wtcpd7d.js → recomp-orchestrator-qnactdw7.js} +20 -20
  77. package/dist/{render-esw55s0k.js → render-da999saz.js} +13 -13
  78. package/dist/{search-3b4kbhtw.js → search-0a3hh5x6.js} +16 -16
  79. package/dist/{search-archive-wna5basn.js → search-archive-0z9cxv8e.js} +8 -8
  80. package/dist/{send-session-notification-14p3yje4.js → send-session-notification-j93pn2hn.js} +3 -3
  81. package/dist/shared/window-geometry.d.ts +5 -0
  82. package/dist/shared/window-geometry.d.ts.map +1 -1
  83. package/dist/{storage-tags-vj0yj7ed.js → storage-tags-q8erkn48.js} +4 -2
  84. package/dist/tools/ctx-search/tools.d.ts.map +1 -1
  85. package/dist/tools/parameter-descriptions.d.ts +6 -6
  86. package/dist/tools/parameter-descriptions.d.ts.map +1 -1
  87. package/dist/{transform-postprocess-phase-1y6p9ccc.js → transform-postprocess-phase-k9d1r13f.js} +21 -21
  88. package/dist/v2/auto-search-worker.js +4 -4
  89. package/dist/v2/chunk-embedding-write-worker.js +7 -7
  90. package/dist/v2/{compartment-chunk-embedding-qfk791bd.js → compartment-chunk-embedding-nj5nrnbj.js} +5 -5
  91. package/dist/v2/{context-sfgk72cj.js → context-jtqj5e1r.js} +1090 -260
  92. package/dist/v2/{derive-budgets-sa0v7bz0.js → derive-budgets-b5cgrtp8.js} +2 -2
  93. package/dist/v2/{embedding-backfill-ahwzfc7v.js → embedding-backfill-360efh1t.js} +8 -8
  94. package/dist/v2/embedding-worker.js +3 -3
  95. package/dist/v2/fold/code-mode-catalog.d.ts +11 -3
  96. package/dist/v2/fold/code-mode-catalog.d.ts.map +1 -1
  97. package/dist/v2/fold/instruction-supersession.d.ts +13 -2
  98. package/dist/v2/fold/instruction-supersession.d.ts.map +1 -1
  99. package/dist/v2/fold/native-replay.d.ts +5 -0
  100. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  101. package/dist/v2/fold/owner.d.ts +14 -0
  102. package/dist/v2/fold/owner.d.ts.map +1 -1
  103. package/dist/v2/fold/summary.d.ts +35 -0
  104. package/dist/v2/fold/summary.d.ts.map +1 -1
  105. package/dist/v2/hooks/context.d.ts +2 -1
  106. package/dist/v2/hooks/context.d.ts.map +1 -1
  107. package/dist/v2/hooks/lkg-system.d.ts +3 -0
  108. package/dist/v2/hooks/lkg-system.d.ts.map +1 -1
  109. package/dist/v2/{message-fts-rowid-map-z86avy0n.js → message-fts-rowid-map-qe7cpksd.js} +2 -2
  110. package/dist/v2/{message-index-bounded-mapha2ag.js → message-index-bounded-60tdhht5.js} +7 -7
  111. package/dist/v2/migration-worker.js +5 -5
  112. package/dist/v2/{project-embedding-registry-mn403rp5.js → project-embedding-registry-ek0cy0d5.js} +7 -7
  113. package/dist/v2/raw-ordinal-warmup-worker.js +7 -7
  114. package/dist/v2/{read-session-chunk-svcthp0n.js → read-session-chunk-9tmsxwb2.js} +5 -5
  115. package/dist/v2/{read-session-raw-qpp6x9kg.js → read-session-raw-yss2ev98.js} +1 -1
  116. package/dist/v2/{recomp-orchestrator-2bkv46am.js → recomp-orchestrator-7y8smqqp.js} +19 -19
  117. package/dist/v2/{render-315tv10c.js → render-j0y57skn.js} +12 -12
  118. package/dist/v2/{search-archive-hnx40ts0.js → search-archive-1e2tr8eq.js} +7 -7
  119. package/dist/v2/{search-bhrr075t.js → search-qhd2m8kn.js} +14 -14
  120. package/dist/v2/{send-session-notification-kxp47tsw.js → send-session-notification-na3q825m.js} +1 -1
  121. package/dist/v2/{server-nmyganc8.js → server-131h608x.js} +1 -1
  122. package/dist/v2/{server-86sk7h34.js → server-2gjqhmn9.js} +63 -21
  123. package/dist/v2/{server-xy7w7hrd.js → server-2j87594q.js} +1 -1
  124. package/dist/v2/{server-g8xvnxcf.js → server-3rp821fw.js} +3 -3
  125. package/dist/v2/{server-1yx5455s.js → server-4m71jpaj.js} +4 -4
  126. package/dist/v2/{server-78mc9sxx.js → server-5dtrzs6j.js} +9 -5
  127. package/dist/v2/{server-t5gxvcc3.js → server-5vy0xt3p.js} +3 -3
  128. package/dist/v2/{server-969cdpmg.js → server-7vb38e51.js} +4 -0
  129. package/dist/v2/{server-sd8hvzte.js → server-af1rmkyn.js} +1 -1
  130. package/dist/v2/{server-ngdrh7rv.js → server-ahy062xr.js} +36 -17
  131. package/dist/v2/{server-tnzbk64q.js → server-b3r080cm.js} +2 -1
  132. package/dist/v2/{server-zzgtgqmd.js → server-ddw42d76.js} +1 -1
  133. package/dist/v2/{server-63cz4w5t.js → server-ht0dyq9r.js} +3 -3
  134. package/dist/v2/{server-xnz3nrt2.js → server-pej5rnye.js} +1 -1
  135. package/dist/v2/{server-1c720m9s.js → server-rjn4msjj.js} +5 -5
  136. package/dist/v2/{server-rqypazrp.js → server-rshcp4gy.js} +3 -3
  137. package/dist/v2/{server-8xdnk7vz.js → server-sg2qjkrb.js} +1 -1
  138. package/dist/v2/{server-aqgg41wb.js → server-sr8tf5dt.js} +3 -3
  139. package/dist/v2/{server-qs0mdpc1.js → server-sscb1r3e.js} +7 -7
  140. package/dist/v2/{server-xfjjbrkt.js → server-t4hk02v1.js} +11 -11
  141. package/dist/v2/{server-vjhk8v41.js → server-wa4qhryh.js} +1 -1
  142. package/dist/v2/{server-cp1a03vc.js → server-y8n33d9j.js} +3 -3
  143. package/dist/v2/{server-qxzbmtqt.js → server-zt1m5rwj.js} +10 -2
  144. package/dist/v2/server.js +4 -4
  145. package/dist/v2/{storage-tags-cw07ky67.js → storage-tags-ztar1k0g.js} +4 -2
  146. package/dist/v2/{v2-archive-reader-qwn0me88.js → v2-archive-reader-tme5988n.js} +1 -1
  147. package/dist/v2/{wrapup-orchestrator-ts0sqwp3.js → wrapup-orchestrator-k7m16xze.js} +19 -19
  148. package/dist/{v2-archive-reader-vqqjkeaq.js → v2-archive-reader-dq5ebwe6.js} +1 -1
  149. package/dist/{wrapup-orchestrator-qxvbvr4r.js → wrapup-orchestrator-4pqwet8p.js} +21 -21
  150. package/package.json +1 -1
  151. package/src/agents/smart-notes-dreamer-gate.golden.json +169 -169
  152. package/src/shared/prompt-surface-a1-golden.md +4 -4
  153. package/src/shared/window-geometry.test.ts +85 -0
  154. package/src/shared/window-geometry.ts +29 -2
@@ -164,6 +164,9 @@ import {
164
164
  renderMemoryBlockV2,
165
165
  findHostCompactionWindow,
166
166
  capturePrefixTrimSourceOrder,
167
+ headMessagesForSizing,
168
+ rawTailAfterNewestCompartment,
169
+ hasCompleteCachedM0M1,
167
170
  resolveHiddenCompletionExecutor,
168
171
  createV1HiddenCompletionExecutor,
169
172
  readCoordinateGeneration,
@@ -191,7 +194,7 @@ import {
191
194
  snapRangeToCompartments,
192
195
  getActiveCompartmentRun,
193
196
  startCompartmentAgent
194
- } from "./index-wapyeb06.js";
197
+ } from "./index-55ngkbqa.js";
195
198
  import {
196
199
  hasTrustedAbsoluteWall,
197
200
  applyProvenInputFloor,
@@ -203,7 +206,7 @@ import {
203
206
  deriveTriggerBudget2,
204
207
  resolveKnownHistorianContextLimit2,
205
208
  resolveHistorianProducerLimits2
206
- } from "./index-dnqqqc5f.js";
209
+ } from "./index-8cfnaagj.js";
207
210
  import {
208
211
  resolveModelCalibration,
209
212
  calibrateBuckets,
@@ -217,7 +220,7 @@ import {
217
220
  estimateTokens,
218
221
  estimateFixedPromptTokens,
219
222
  normalizeText
220
- } from "./index-4xyjr62e.js";
223
+ } from "./index-ak11t3gm.js";
221
224
  import {
222
225
  protectedToolTokenCount,
223
226
  peelLeadingMcTagNotation,
@@ -244,6 +247,7 @@ import {
244
247
  getTriggerTagTokenUpperBound2,
245
248
  getActiveTagTokenTotalsByMessage2,
246
249
  tryGetReasoningTokenEstimatesByMessage2,
250
+ TagOwnerSummaryNotReady2,
247
251
  isTagOwnerSummaryReady2,
248
252
  updateTagStatus2,
249
253
  getInertWhitespaceAssistantTagsByNumbers2,
@@ -254,7 +258,7 @@ import {
254
258
  getTagsByNumbers2,
255
259
  getDroppedTagsByNumbers2,
256
260
  getMaxDroppedTagNumber2
257
- } from "./index-8jjjmhab.js";
261
+ } from "./index-x53gnmce.js";
258
262
  import {
259
263
  observeTemporalDecisions,
260
264
  stableStringify
@@ -285,7 +289,7 @@ import {
285
289
  extractInMemoryMessageViews2,
286
290
  buildInMemoryTailRawMessages2,
287
291
  RawOrdinalsNotReady2
288
- } from "./index-r2epb000.js";
292
+ } from "./index-xa9mmq6c.js";
289
293
  import {
290
294
  openCodeDbExists,
291
295
  withReadOnlySessionDb,
@@ -293,7 +297,7 @@ import {
293
297
  latestPersistedMessageForRecovery,
294
298
  latestRealUserTurnIdFromOpenCodeDb,
295
299
  findLastAssistantModelFromOpenCodeDb
296
- } from "./index-vd2ywmfe.js";
300
+ } from "./index-brj6was5.js";
297
301
  import {
298
302
  askAnswerLines,
299
303
  estimateTrueRawMessageTokens,
@@ -358,6 +362,7 @@ import {
358
362
  getPersistedCompactionMarkerState,
359
363
  setPersistedCompactionMarkerState,
360
364
  getStrippedPlaceholderIds,
365
+ THINKING_BINDING_RECOVERY_FROZEN_PREFIX,
361
366
  thinkingBindingRecoveryFrozenId,
362
367
  getThinkingBindingRecoveryTarget,
363
368
  armThinkingBindingRecovery,
@@ -371,6 +376,7 @@ import {
371
376
  clearPendingCompactionMarkerStateIf,
372
377
  getObservedEpochFloor,
373
378
  resolveEpochFloorForPass,
379
+ getReasoningRemovalState,
374
380
  detectLatestTurnThinkingMismatch,
375
381
  isPrefixBoundThinkingModel,
376
382
  detectOverflow,
@@ -383,10 +389,12 @@ import {
383
389
  stripClearedReasoning,
384
390
  findReasoningBearingAssistantIds,
385
391
  snapshotTrailingBlankSourceDecisions,
392
+ stripReasoningFromAssistantIds,
386
393
  projectOpencodeReasoningBudgetCutoff,
387
394
  resolveKeepReasoningTokens,
388
395
  reasoningStepCost,
389
396
  reasoningBudgetCutoff,
397
+ opencodeReasoningBudgetCutoff,
390
398
  describeFinalWireTail,
391
399
  estimateMessageTokens,
392
400
  wireContentBytes,
@@ -416,11 +424,11 @@ import {
416
424
  readRawSessionMessageById2,
417
425
  readSessionChunk2,
418
426
  readRawSessionSeedTail2
419
- } from "./index-1j8m4ad0.js";
427
+ } from "./index-xgnh498s.js";
420
428
  import {
421
429
  BoundedSessionMap,
422
430
  getMeasuredToolDefinitionTokens
423
- } from "./index-jkanybgq.js";
431
+ } from "./index-smtbdmc3.js";
424
432
  import {
425
433
  isFailClosedBlockingError,
426
434
  shouldBypassFailClosedBlock,
@@ -446,7 +454,7 @@ import {
446
454
  runSqliteOptimize,
447
455
  openDatabase,
448
456
  openCurrentDatabase
449
- } from "./index-6qnhaaa0.js";
457
+ } from "./index-b0xt5qz9.js";
450
458
  import {
451
459
  unescapeXml,
452
460
  resolveWorkspaceShareCategories,
@@ -477,7 +485,7 @@ import {
477
485
  toSynapseLaneDescriptor,
478
486
  formatSynapseLaneDescriptor,
479
487
  SynapseEmbeddingProvider
480
- } from "./index-g4t7850m.js";
488
+ } from "./index-dj2p8653.js";
481
489
  import {
482
490
  getCompartments,
483
491
  getLastCompartmentEndMessage,
@@ -555,10 +563,10 @@ import {
555
563
  GLOBAL_USER_PROFILE_PROJECT_PATH,
556
564
  getProjectState,
557
565
  bumpProjectUserProfileVersion
558
- } from "./index-dasvhxwg.js";
566
+ } from "./index-n9q8c1dr.js";
559
567
  import {
560
568
  getLastIndexedOrdinal
561
- } from "./index-m1mttf6y.js";
569
+ } from "./index-etn2hmb5.js";
562
570
  import {
563
571
  SESSION_NOTE_CONDITION_ERROR,
564
572
  getNoteByIdInScope,
@@ -596,8 +604,9 @@ import {
596
604
  getCachedLocalEmbeddingPooling,
597
605
  preflightLocalEmbeddingPooling,
598
606
  getLocalEmbeddingNativeMemoryStats
599
- } from "./index-p6gs3xpx.js";
607
+ } from "./index-hkh8x221.js";
600
608
  import {
609
+ withQueryEmbeddingDeadline,
601
610
  describeShadowBackfillWriteRefusal2,
602
611
  markProjectLoadUntrusted2,
603
612
  drainProjectEmbeddingIdentityMaintenance2,
@@ -616,7 +625,7 @@ import {
616
625
  embedSessionCompartmentChunks2,
617
626
  getEmbeddingCoverageStatus2,
618
627
  getAutoEmbeddingSessionCoverage2
619
- } from "./index-rhcwddn9.js";
628
+ } from "./index-s79g172v.js";
620
629
  import {
621
630
  saveEmbeddingIfHashMatches,
622
631
  invalidateProject2,
@@ -624,7 +633,7 @@ import {
624
633
  } from "./index-4dhv7mqz.js";
625
634
  import {
626
635
  cosineSimilarity
627
- } from "./index-66qexmjw.js";
636
+ } from "./index-d4qw2h43.js";
628
637
  import {
629
638
  computeCueContentHash,
630
639
  hasMuralCueColumns,
@@ -670,7 +679,7 @@ import {
670
679
  readGitFileChangeTimesSince,
671
680
  verificationFileExists,
672
681
  normalizeVerificationFiles
673
- } from "./index-kgk64zyx.js";
682
+ } from "./index-sd2s4t4p.js";
674
683
  import {
675
684
  renderSingleStoreMigrationRequiredRefusal,
676
685
  SingleStoreMigrationRequiredError,
@@ -691,23 +700,23 @@ import {
691
700
  resolveMemoriesByIdsForSearch2,
692
701
  unifiedSearch2,
693
702
  formatSearchResults2
694
- } from "./index-v64se1t6.js";
703
+ } from "./index-5jk4h64j.js";
695
704
  import {
696
705
  scheduleReconciliation,
697
706
  scheduleIncrementalIndex,
698
707
  getMessageIndexQueueHeapStats,
699
708
  clearSessionTracking
700
- } from "./index-91y4xvx6.js";
709
+ } from "./index-44pp3vrj.js";
701
710
  import {
702
711
  flushIgnoredMessages2,
703
712
  clearIgnoredMessages2,
704
713
  observeIgnoredNotificationEvent2,
705
714
  sendStatusNotification2
706
- } from "./index-ae1ar4v1.js";
715
+ } from "./index-25ka1jza.js";
707
716
  import {
708
717
  setRecompStarting2,
709
718
  setRecompTerminal2
710
- } from "./index-24y47287.js";
719
+ } from "./index-kevd267m.js";
711
720
  import {
712
721
  makeToolCompositeKey,
713
722
  searchMessageHistoryOffThread,
@@ -745,12 +754,23 @@ import {
745
754
  outgoingContextRefusal,
746
755
  signedTurnContextRefusal,
747
756
  EmergencyFailClosedError,
757
+ removeReasoningParts,
748
758
  latestAssistantTurnStart,
749
759
  latestAssistantTurnMessages,
750
760
  hasActiveAnthropicThinkingTurn,
761
+ retainedActiveThinkingParts,
751
762
  replayCavemanCompression,
752
763
  DegradedPassRefusalError,
753
764
  degradedPassError,
765
+ hostInstructionRetentionEnabled,
766
+ isHostInstructionRetentionOn,
767
+ pressureBands,
768
+ forceRide,
769
+ heuristicsRunOnPass,
770
+ routineCleanupRunsOnPass,
771
+ heuristicsAlreadyRanThisTurn,
772
+ routinePressureAlreadyApplied,
773
+ safeReasoningCutoff,
754
774
  isStructuralNoiseSentinel,
755
775
  stripStructuralNoise,
756
776
  prepareStructuralSentinelChoices,
@@ -772,7 +792,7 @@ import {
772
792
  abortSessionFailClosed2,
773
793
  evaluateEmergencyFailClosed2,
774
794
  runPostTransformPhase2
775
- } from "./index-8w3y6pxc.js";
795
+ } from "./index-tajstyw4.js";
776
796
  import {
777
797
  ANNOUNCEMENT_VERSION2,
778
798
  ANNOUNCEMENT_FEATURES2,
@@ -787,13 +807,13 @@ import {
787
807
  renderMessageByOrdinal2,
788
808
  renderVerboseRangeForTool2,
789
809
  renderItemByTag2
790
- } from "./index-knnscj54.js";
810
+ } from "./index-kw7azjmy.js";
791
811
  import {
792
812
  readV2ArchiveOffThread2
793
- } from "./index-7y8c2n52.js";
813
+ } from "./index-a4t7pdmm.js";
794
814
  import {
795
815
  renderSearchArchiveOffThread2
796
- } from "./index-g0mjm7e4.js";
816
+ } from "./index-gaxktvxm.js";
797
817
  import {
798
818
  COMPACTION_ENABLED_PATH,
799
819
  isDreamerRunnable,
@@ -16351,7 +16371,7 @@ function registerRpcHandlers(rpcServer, args) {
16351
16371
  return { count: buildCompartmentCount(db, sessionId, moduleStatus) };
16352
16372
  });
16353
16373
  const buildManagedCtx = async (db) => {
16354
- const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-htj16n4x.js"));
16374
+ const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-nkw09vq7.js"));
16355
16375
  const { resolveHistorianModel } = await importPluginModule(() => import("./model-resolution-280gmqvd.js"));
16356
16376
  const { userObservationCollectionEnabled, userObservationsRequested } = await importPluginModule(() => import("./task-config-t6bpyka7.js"));
16357
16377
  const DEFAULT_HISTORIAN_TIMEOUT_MS = 10 * 60 * 1000;
@@ -16403,8 +16423,8 @@ function registerRpcHandlers(rpcServer, args) {
16403
16423
  const db = readDatabase();
16404
16424
  if (!db)
16405
16425
  return { ok: false, error: "db unavailable" };
16406
- const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-9wtcpd7d.js"));
16407
- const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-14p3yje4.js"));
16426
+ const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-qnactdw7.js"));
16427
+ const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-j93pn2hn.js"));
16408
16428
  log2(`[rpc] recomp requested for session ${sessionId}`);
16409
16429
  if (!args.client && !args.hiddenCompletionExecutor) {
16410
16430
  return {
@@ -16488,7 +16508,7 @@ function registerRpcHandlers(rpcServer, args) {
16488
16508
  const db = readDatabase();
16489
16509
  if (!db)
16490
16510
  return { ok: false, error: "db unavailable" };
16491
- const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-qxvbvr4r.js"));
16511
+ const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-4pqwet8p.js"));
16492
16512
  const model = liveSessionState.liveModelBySession.get(sessionId);
16493
16513
  const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
16494
16514
  const ctx = {
@@ -17496,6 +17516,192 @@ function createPassOutcome() {
17496
17516
  };
17497
17517
  }
17498
17518
 
17519
+ // src/hooks/magic-context/priced-pass-sizing.ts
17520
+ var REASONING_PART_TYPES = new Set(["reasoning", "thinking", "redacted_thinking"]);
17521
+ var WIDEST_PRICED_PASS_PLAN = {
17522
+ editsWholePrefix: true,
17523
+ clearsReasoning: false
17524
+ };
17525
+ function planPricedPass(input, usage) {
17526
+ const bands = pressureBands({
17527
+ percentage: usage.percentage,
17528
+ fromEstimate: usage.fromEstimate,
17529
+ forceMaterializationPercentage: input.forceMaterializationPercentage,
17530
+ compactionOff: input.compactionOff,
17531
+ fullFeatureMode: input.fullFeatureMode,
17532
+ schedulerDecision: input.schedulerDecision
17533
+ });
17534
+ const emergencySample = () => getEmergencyInputSample(input.db, input.sessionId);
17535
+ const rides = {
17536
+ hardFold: input.folds || input.firstRender,
17537
+ force: forceRide({
17538
+ bands,
17539
+ percentage: usage.percentage,
17540
+ fromEstimate: usage.fromEstimate,
17541
+ emergencySample
17542
+ }),
17543
+ explicitFlush: input.explicitFlush,
17544
+ publishedHistory: false,
17545
+ subagentExecute: !input.fullFeatureMode && input.schedulerDecision === "execute",
17546
+ executeReclaim: false,
17547
+ servedShapeRepair: false
17548
+ };
17549
+ const drainAllowed = !input.compactionOff && reclaimRidePermitted(rides, {
17550
+ signedThinkingHold: input.signedThinkingHold,
17551
+ firstRender: input.firstRender,
17552
+ emergency: bands.forceBandConfirmed
17553
+ });
17554
+ const materializationRequested = !input.signedThinkingHold && input.materializationRequested;
17555
+ const heuristics = heuristicsRunOnPass({
17556
+ compactionOff: input.compactionOff,
17557
+ drainAllowed,
17558
+ rides,
17559
+ materializationRequested,
17560
+ bands,
17561
+ foldBustsServedPrefix: input.folds,
17562
+ firstRender: input.firstRender,
17563
+ schedulerDecision: input.schedulerDecision,
17564
+ alreadyRanThisTurn: input.alreadyRanThisTurn,
17565
+ fullFeatureMode: input.fullFeatureMode
17566
+ });
17567
+ const routine = heuristics && routineCleanupRunsOnPass({
17568
+ bands,
17569
+ percentage: usage.percentage,
17570
+ emergencySample,
17571
+ fullFeatureMode: input.fullFeatureMode,
17572
+ routinePressureAlreadyApplied: routinePressureAlreadyApplied(input.sessionId, {
17573
+ fullFeatureMode: input.fullFeatureMode,
17574
+ executePressureEligible: bands.executePressureEligible,
17575
+ alreadyRanThisTurn: input.alreadyRanThisTurn
17576
+ }),
17577
+ materializationRequested,
17578
+ rewriteAlreadyPriced: input.folds || input.firstRender || input.historyRebuilt
17579
+ });
17580
+ return {
17581
+ editsWholePrefix: drainAllowed && !input.signedThinkingHold,
17582
+ clearsReasoning: routine && !input.signedThinkingHold
17583
+ };
17584
+ }
17585
+ function sameSizingPlan(input, a, b) {
17586
+ const rowsDiffer = a.editsWholePrefix !== b.editsWholePrefix && input.coveredInstructions.length > 0 && hostInstructionRetentionEnabled() && !isHostInstructionRetentionOn(input.db, input.sessionId);
17587
+ const reasoningDiffers = a.clearsReasoning !== b.clearsReasoning && input.reasoning !== undefined;
17588
+ return !rowsDiffer && !reasoningDiffers;
17589
+ }
17590
+ function protectedThinkingMessagesForSizing(args) {
17591
+ if (!args.activeThinkingTurn)
17592
+ return new Set;
17593
+ const mergedIds = getMergedReasoningStrippedIds(args.db, args.sessionId);
17594
+ const bindingIds = new Set([...mergedIds].filter((id) => id.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX)).map((id) => id.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length)));
17595
+ const retained = retainedActiveThinkingParts({
17596
+ messages: [...args.messages],
17597
+ providerID: args.providerID,
17598
+ modelID: args.modelID,
17599
+ mergedIds,
17600
+ bindingIds,
17601
+ removedIds: getReasoningRemovalState(args.db, args.sessionId).messageIds
17602
+ });
17603
+ return new Set(args.messages.filter((message) => message.parts.some((part) => retained.has(part))));
17604
+ }
17605
+ function servedRequestForSizing(input, plan) {
17606
+ const head = input.head ? headMessagesForSizing(input.head, input.headFolds) : [];
17607
+ const instructions = input.coveredInstructions.length > 0 && hostInstructionRetentionEnabled() && (plan.editsWholePrefix || isHostInstructionRetentionOn(input.db, input.sessionId)) ? input.coveredInstructions : [];
17608
+ const removals = replayedReasoningRemovals(input);
17609
+ const cutoff = plan.clearsReasoning && input.reasoning ? Math.min(safeReasoningCutoff(input.messageTagNumbers, input.reasoning.protectedThinkingMessages), clearedReasoningCutoff(input, input.reasoning, removals.messageIds)) : 0;
17610
+ let conversation = withoutReplayedRemovals(input.messages, removals, input);
17611
+ if (cutoff > 0)
17612
+ conversation = conversation.map((message, index) => withoutClearedReasoning(message, input.messages[index] ?? message, input, cutoff));
17613
+ return [...head, ...instructions, ...conversation];
17614
+ }
17615
+ function replayedReasoningRemovals(input) {
17616
+ const bindingIds = new Set;
17617
+ if (input.replayedRemovals.bindingStrips)
17618
+ for (const id of getMergedReasoningStrippedIds(input.db, input.sessionId)) {
17619
+ if (!id.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX))
17620
+ continue;
17621
+ const messageId = id.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length);
17622
+ if (messageId.length > 0)
17623
+ bindingIds.add(messageId);
17624
+ }
17625
+ return {
17626
+ messageIds: input.replayedRemovals.wholePartRemoval ? getReasoningRemovalState(input.db, input.sessionId).messageIds : new Set,
17627
+ bindingIds
17628
+ };
17629
+ }
17630
+ function withoutReplayedRemovals(messages, removals, input) {
17631
+ if (removals.messageIds.size === 0 && removals.bindingIds.size === 0)
17632
+ return [...messages];
17633
+ const copies = messages.map((message) => {
17634
+ const id = message.info.id;
17635
+ return typeof id === "string" && (removals.messageIds.has(id) || removals.bindingIds.has(id)) ? countingCopy(message) : message;
17636
+ });
17637
+ const providerID = input.replayedRemovals.providerID;
17638
+ stripReasoningFromAssistantIds(copies, providerID, removals.bindingIds);
17639
+ removeReasoningParts(copies, removals.messageIds, providerID);
17640
+ return copies;
17641
+ }
17642
+ function countingCopy(message) {
17643
+ return {
17644
+ ...message,
17645
+ parts: message.parts.map((part) => {
17646
+ if (!isRecord(part) || !isRecord(part.metadata))
17647
+ return part;
17648
+ return {
17649
+ ...part,
17650
+ metadata: {
17651
+ ...part.metadata,
17652
+ ...isRecord(part.metadata.openrouter) ? { openrouter: { ...part.metadata.openrouter } } : {}
17653
+ }
17654
+ };
17655
+ })
17656
+ };
17657
+ }
17658
+ function clearedReasoningCutoff(input, reasoning, removedIds) {
17659
+ try {
17660
+ return projectOpencodeReasoningBudgetCutoff(input.db, input.sessionId, [...input.messages], reasoning.keepTokens, reasoning.clearedThroughTag, reasoning.proseRatio);
17661
+ } catch (error) {
17662
+ if (!(error instanceof TagOwnerSummaryNotReady2))
17663
+ throw error;
17664
+ }
17665
+ const gone = new Set(removedIds);
17666
+ for (const [message, tag] of input.messageTagNumbers) {
17667
+ if (tag > 0 && tag <= reasoning.clearedThroughTag && typeof message.info.id === "string")
17668
+ gone.add(message.info.id);
17669
+ }
17670
+ const frozenMergedIds = getMergedReasoningStrippedIds(input.db, input.sessionId);
17671
+ return opencodeReasoningBudgetCutoff({
17672
+ messages: [...input.messages],
17673
+ messageTagNumbers: input.messageTagNumbers,
17674
+ budget: reasoning.keepTokens,
17675
+ alreadyRemoved: gone,
17676
+ proseRatio: reasoning.proseRatio,
17677
+ frozenMergedIds,
17678
+ alsoGone: new Set([...frozenMergedIds].filter((id) => id.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX)).map((id) => id.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length)))
17679
+ });
17680
+ }
17681
+ function withoutClearedReasoning(message, original, input, cutoff) {
17682
+ const tag = input.messageTagNumbers.get(original) ?? 0;
17683
+ if (tag === 0 || tag > cutoff)
17684
+ return message;
17685
+ const parts = message.parts.filter((part) => !isReasoningPart(part));
17686
+ return parts.length === message.parts.length ? message : { ...message, parts };
17687
+ }
17688
+ function isReasoningPart(part) {
17689
+ return typeof part === "object" && part !== null && REASONING_PART_TYPES.has(String(part.type));
17690
+ }
17691
+
17692
+ // src/hooks/magic-context/recovery-fit.ts
17693
+ var RECOVERY_REFUSAL_NOTICE = "Magic Context is still summarizing older history so this conversation fits the model's context window. Send your message again to continue.";
17694
+ var RECOVERY_NO_HISTORY_REFUSAL_NOTICE = "This conversation no longer fits the model's context window, and Magic Context has no more older history it can summarize. Switch to a model with a larger context window to continue.";
17695
+ function recoveryLineTokens(windowTokens) {
17696
+ return Math.floor(windowTokens * BLOCK_UNTIL_DONE_PERCENTAGE / 100);
17697
+ }
17698
+ function recoveryAdmissionLimitTokens(windowTokens, historyRemains) {
17699
+ return historyRemains ? recoveryLineTokens(windowTokens) : Math.floor(windowTokens);
17700
+ }
17701
+ function recoveryRefusalNotice(historyRemains) {
17702
+ return historyRemains ? RECOVERY_REFUSAL_NOTICE : RECOVERY_NO_HISTORY_REFUSAL_NOTICE;
17703
+ }
17704
+
17499
17705
  // src/hooks/magic-context/release-recovery-prefix.ts
17500
17706
  function groups(messages) {
17501
17707
  const result = new Map;
@@ -20452,7 +20658,7 @@ function resolveUnknownUsageFromWireEstimate(input) {
20452
20658
  const providerLimit = input.providerProvenLimitTokens;
20453
20659
  const canUseProviderMass = input.wireEstimateTrusted === false && typeof providerTokens === "number" && Number.isFinite(providerTokens) && providerTokens > 0 && typeof providerLimit === "number" && Number.isFinite(providerLimit) && providerLimit > 0;
20454
20660
  const tokens = canUseProviderMass ? Math.max(wireTokens, providerTokens) : wireTokens;
20455
- const limit = input.usableHardLimit;
20661
+ const limit = input.windowTokens;
20456
20662
  const estimatedPercentage = typeof limit === "number" && Number.isFinite(limit) && limit > 0 ? tokens / limit * 100 : input.usage.percentage;
20457
20663
  return {
20458
20664
  inputTokens: tokens,
@@ -21154,7 +21360,7 @@ function transformGeometryForWire(geometry) {
21154
21360
  return;
21155
21361
  const { window, reserve } = geometry.derivation;
21156
21362
  let derivation;
21157
- if (geometry.geometry === "separate" && geometry.usableSoft < geometry.usableHard) {
21363
+ if (geometry.geometry === "separate" && geometry.usableSoft < window) {
21158
21364
  derivation = `s1-pre-carve/input=${geometry.usableSoft}`;
21159
21365
  } else if (geometry.geometry === "separate") {
21160
21366
  derivation = `s1-separate/context=${window}`;
@@ -23987,6 +24193,7 @@ function readServedTemporalDecisions(db, sessionId, runtime, messageIds) {
23987
24193
 
23988
24194
  // src/hooks/magic-context/transform-compartment-phase.ts
23989
24195
  var HISTORIAN_INLINE_JOIN_BUDGET_MS = 60000;
24196
+ var CHAINED_RECOVERY_RUN_MIN_BUDGET_MS = 15000;
23990
24197
  function resolveHistorianInlineJoinBudget(configuredTimeoutMs) {
23991
24198
  const requested = configuredTimeoutMs ?? HISTORIAN_INLINE_JOIN_BUDGET_MS;
23992
24199
  return Math.max(0, Math.min(requested, HISTORIAN_INLINE_JOIN_BUDGET_MS));
@@ -24048,6 +24255,7 @@ async function runCompartmentPhaseImpl(args) {
24048
24255
  let rebuiltHistoryThisPass = false;
24049
24256
  let historianJoinTimedOut = false;
24050
24257
  let historianJoinBudgetMs = null;
24258
+ let chainedRecoveryRuns = 0;
24051
24259
  const historianRunnable = args.historianRunnable !== false;
24052
24260
  if (args.compactionOff) {
24053
24261
  if (args.sessionMeta.compartmentInProgress) {
@@ -24063,7 +24271,9 @@ async function runCompartmentPhaseImpl(args) {
24063
24271
  justAwaitedPublication,
24064
24272
  rebuiltHistoryThisPass,
24065
24273
  historianJoinTimedOut,
24066
- historianJoinBudgetMs
24274
+ historianJoinBudgetMs,
24275
+ chainedRecoveryRuns,
24276
+ recoveryHistoryRemains: false
24067
24277
  };
24068
24278
  }
24069
24279
  let rawEligibility = args.preResolvedBoundarySnapshot ? {
@@ -24111,7 +24321,7 @@ async function runCompartmentPhaseImpl(args) {
24111
24321
  const snapshot = getBoundarySnapshotForCompartment();
24112
24322
  return snapshot !== null && hasRunnableCompartmentWindow(snapshot);
24113
24323
  }
24114
- async function awaitCompartmentRun(activeRun, reason) {
24324
+ async function awaitCompartmentRun(activeRun, reason, join = fullInlineJoinWindow()) {
24115
24325
  await Promise.resolve();
24116
24326
  if (activeRun.inlineJoinTimedOutBudgetMs !== undefined && !activeRun.settled) {
24117
24327
  historianJoinTimedOut = true;
@@ -24120,8 +24330,8 @@ async function runCompartmentPhaseImpl(args) {
24120
24330
  return "timed_out";
24121
24331
  }
24122
24332
  sessionLog2(args.sessionId, reason);
24123
- const timeoutMs = resolveHistorianInlineJoinBudget(args.historianTimeoutMs);
24124
- historianJoinBudgetMs = timeoutMs;
24333
+ const timeoutMs = join.timeoutMs;
24334
+ historianJoinBudgetMs = join.budgetMs;
24125
24335
  let timer;
24126
24336
  const timeout = new Promise((resolve) => {
24127
24337
  timer = setTimeout(() => resolve("timeout"), timeoutMs);
@@ -24134,20 +24344,145 @@ async function runCompartmentPhaseImpl(args) {
24134
24344
  clearTimeout(timer);
24135
24345
  }
24136
24346
  if (result === "timeout") {
24137
- activeRun.inlineJoinTimedOutBudgetMs = timeoutMs;
24347
+ activeRun.inlineJoinTimedOutBudgetMs = join.budgetMs;
24138
24348
  historianJoinTimedOut = true;
24139
24349
  sessionLog2(args.sessionId, `transform: compartment await timed out after ${timeoutMs}ms — proceeding without waiting`);
24140
24350
  return "timed_out";
24141
24351
  }
24142
- sessionLog2(args.sessionId, "transform: compartment agent completed, refreshing compartment coverage");
24143
- justAwaitedPublication = activeRun.published;
24352
+ justAwaitedPublication = justAwaitedPublication || activeRun.published;
24144
24353
  published = published || activeRun.published;
24145
- const historyReprepareShouldBust = activeRun.published && args.deferredHistoryRefreshSessions.has(args.sessionId);
24354
+ return "completed";
24355
+ }
24356
+ function refreshCompartmentCoverage() {
24357
+ sessionLog2(args.sessionId, "transform: compartment agent completed, refreshing compartment coverage");
24358
+ const historyReprepareShouldBust = published && args.deferredHistoryRefreshSessions.has(args.sessionId);
24146
24359
  pendingCompartmentInjection = prepareCompartmentInjection(args.db, args.resolvedSessionId, args.messages, historyReprepareShouldBust, args.coveredInstructions, args.projectPath, args.injectionBudgetTokens, args.experimentalTemporalAwareness);
24147
24360
  if (historyReprepareShouldBust) {
24148
24361
  rebuiltHistoryThisPass = true;
24149
24362
  }
24150
- return "completed";
24363
+ }
24364
+ function fullInlineJoinWindow() {
24365
+ const budgetMs = resolveHistorianInlineJoinBudget(args.historianTimeoutMs);
24366
+ return { timeoutMs: budgetMs, budgetMs };
24367
+ }
24368
+ function historianRunDeps(boundarySnapshot) {
24369
+ return {
24370
+ client: args.client,
24371
+ hiddenCompletionExecutor: args.hiddenCompletionExecutor,
24372
+ compactionMarkerStrategy: args.compactionMarkerStrategy,
24373
+ db: args.db,
24374
+ sessionId: args.sessionId,
24375
+ historianChunkTokens: args.historianChunkTokens,
24376
+ boundarySnapshot,
24377
+ currentContextLimit: args.boundaryContextLimit,
24378
+ historyBudgetTokens: args.historyBudgetTokens,
24379
+ historianTimeoutMs: args.historianTimeoutMs,
24380
+ model: args.historianModel,
24381
+ historianContextLimit: args.historianContextLimit,
24382
+ historianMaxOutputTokens: args.historianMaxOutputTokens,
24383
+ fallbackModels: args.fallbackModels,
24384
+ directory: args.compartmentDirectory,
24385
+ fallbackModelId: args.fallbackModelId,
24386
+ ensureProjectRegistered: args.ensureProjectRegistered,
24387
+ getNotificationParams: args.getNotificationParams,
24388
+ experimentalUserMemories: args.experimentalUserMemories,
24389
+ userObservationsRequested: args.userObservationsRequested,
24390
+ historianTwoPass: args.historianTwoPass,
24391
+ historianExpandTools: args.historianExpandTools,
24392
+ memoryEnabled: args.memoryEnabled,
24393
+ autoPromote: args.autoPromote,
24394
+ onCompartmentStatePublished: args.onCompartmentStatePublished,
24395
+ preserveInjectionCacheUntilConsumed: true
24396
+ };
24397
+ }
24398
+ function resolveNextRecoveryBoundary() {
24399
+ rawEligibility = null;
24400
+ cachedBoundarySnapshot = null;
24401
+ if (!hasNewRawHistoryForCompartment())
24402
+ return null;
24403
+ const resolve = args.resolveRecoveryBoundary ?? resolveBoundarySnapshot;
24404
+ let snapshot = resolve();
24405
+ if (!hasRunnableCompartmentWindow(snapshot)) {
24406
+ snapshot = resolve(args.contextUsage.percentage >= BLOCK_UNTIL_DONE_PERCENTAGE ? 0.25 : 0.5);
24407
+ }
24408
+ cachedBoundarySnapshot = snapshot;
24409
+ return hasRunnableCompartmentWindow(snapshot) ? snapshot : null;
24410
+ }
24411
+ async function chainRecoveryRuns(firstRun, project, deadline, budgetMs) {
24412
+ let lastRun = firstRun;
24413
+ const minimumRunBudgetMs = Math.min(CHAINED_RECOVERY_RUN_MIN_BUDGET_MS, budgetMs / 4);
24414
+ for (;; ) {
24415
+ if (!lastRun.published) {
24416
+ sessionLog2(args.sessionId, `transform: recovery chain stops: the last historian run published nothing (${chainedRecoveryRuns} chained runs)`);
24417
+ return "stopped";
24418
+ }
24419
+ let fit;
24420
+ try {
24421
+ fit = project();
24422
+ } catch (error) {
24423
+ sessionLog2(args.sessionId, "transform: recovery chain stops: the request could not be counted:", error);
24424
+ return "stopped";
24425
+ }
24426
+ if (!fit)
24427
+ return "stopped";
24428
+ if (Number.isFinite(fit.tokens) && fit.tokens <= fit.lineTokens) {
24429
+ sessionLog2(args.sessionId, `transform: recovery chain done: the request is about ${fit.tokens} tokens, under the 95% line ${fit.lineTokens} (${chainedRecoveryRuns} chained runs)`);
24430
+ return "stopped";
24431
+ }
24432
+ const remainingMs = deadline - Date.now();
24433
+ if (remainingMs < minimumRunBudgetMs) {
24434
+ sessionLog2(args.sessionId, `transform: recovery chain stops: ${Math.max(0, remainingMs)}ms of the ${budgetMs}ms inline join budget is left, under the ${minimumRunBudgetMs}ms a chained run needs; the request is still about ${fit.tokens} tokens, over the 95% line ${fit.lineTokens}`);
24435
+ return "stopped";
24436
+ }
24437
+ const boundary = resolveNextRecoveryBoundary();
24438
+ if (!boundary) {
24439
+ sessionLog2(args.sessionId, `transform: recovery chain stops: no eligible history before the protected tail; the request is still about ${fit.tokens} tokens, over the 95% line ${fit.lineTokens}`);
24440
+ return "stopped";
24441
+ }
24442
+ if (isHistorianDrainBudgetSpent({
24443
+ db: args.db,
24444
+ sessionId: args.sessionId,
24445
+ contextLimit: args.boundaryContextLimit,
24446
+ executeThresholdPercentage: args.boundaryExecuteThresholdPercentage,
24447
+ usagePercentage: args.boundaryUsage.percentage
24448
+ })) {
24449
+ sessionLog2(args.sessionId, `transform: recovery chain stops: the historian's drain budget is spent; the request is still about ${fit.tokens} tokens, over the 95% line ${fit.lineTokens}`);
24450
+ return "stopped";
24451
+ }
24452
+ startCompartmentAgent(historianRunDeps(boundary));
24453
+ const nextRun = getActiveCompartmentRun(args.sessionId);
24454
+ if (!nextRun || nextRun === lastRun) {
24455
+ sessionLog2(args.sessionId, "transform: recovery chain stops: the next historian run did not start");
24456
+ return "stopped";
24457
+ }
24458
+ chainedRecoveryRuns += 1;
24459
+ const result = await awaitCompartmentRun(nextRun, `transform: recovery request still about ${fit.tokens} tokens, over the 95% line ${fit.lineTokens}; blocking for historian run ${chainedRecoveryRuns + 1} on the next chunk`, { timeoutMs: remainingMs, budgetMs });
24460
+ if (result === "timed_out")
24461
+ return "timed_out";
24462
+ lastRun = nextRun;
24463
+ }
24464
+ }
24465
+ function recoveryHistoryRemainsAfterJoins() {
24466
+ if (!historianRunnable || !args.canRunCompartments)
24467
+ return false;
24468
+ if (getActiveCompartmentRun(args.sessionId))
24469
+ return true;
24470
+ if (!args.client && !args.hiddenCompletionExecutor)
24471
+ return false;
24472
+ try {
24473
+ if (resolveNextRecoveryBoundary() === null)
24474
+ return false;
24475
+ } catch (error) {
24476
+ sessionLog2(args.sessionId, "transform: recovery history check failed; keeping the 95% line:", error);
24477
+ return true;
24478
+ }
24479
+ return !isHistorianDrainBudgetSpent({
24480
+ db: args.db,
24481
+ sessionId: args.sessionId,
24482
+ contextLimit: args.boundaryContextLimit,
24483
+ executeThresholdPercentage: args.boundaryExecuteThresholdPercentage,
24484
+ usagePercentage: args.boundaryUsage.percentage
24485
+ });
24151
24486
  }
24152
24487
  if ((!historianRunnable || !args.canRunCompartments && !getActiveCompartmentRun(args.sessionId)) && args.sessionMeta.compartmentInProgress) {
24153
24488
  sessionLog2(args.sessionId, "transform: historian unavailable; clearing stale compartmentInProgress flag");
@@ -24207,34 +24542,7 @@ async function runCompartmentPhaseImpl(args) {
24207
24542
  let activeRun = getActiveCompartmentRun(args.sessionId);
24208
24543
  if (!activeRun && hasEligibleHistoryForCompartment() && (args.client || args.hiddenCompletionExecutor)) {
24209
24544
  sessionLog2(args.sessionId, `transform: 95% reached (${args.contextUsage.percentage.toFixed(1)}%), force-starting compartment agent and blocking`);
24210
- startCompartmentAgent({
24211
- client: args.client,
24212
- hiddenCompletionExecutor: args.hiddenCompletionExecutor,
24213
- compactionMarkerStrategy: args.compactionMarkerStrategy,
24214
- db: args.db,
24215
- sessionId: args.sessionId,
24216
- historianChunkTokens: args.historianChunkTokens,
24217
- boundarySnapshot: getBoundarySnapshotForCompartment() ?? undefined,
24218
- currentContextLimit: args.boundaryContextLimit,
24219
- historyBudgetTokens: args.historyBudgetTokens,
24220
- historianTimeoutMs: args.historianTimeoutMs,
24221
- model: args.historianModel,
24222
- historianContextLimit: args.historianContextLimit,
24223
- historianMaxOutputTokens: args.historianMaxOutputTokens,
24224
- fallbackModels: args.fallbackModels,
24225
- directory: args.compartmentDirectory,
24226
- fallbackModelId: args.fallbackModelId,
24227
- ensureProjectRegistered: args.ensureProjectRegistered,
24228
- getNotificationParams: args.getNotificationParams,
24229
- experimentalUserMemories: args.experimentalUserMemories,
24230
- userObservationsRequested: args.userObservationsRequested,
24231
- historianTwoPass: args.historianTwoPass,
24232
- historianExpandTools: args.historianExpandTools,
24233
- memoryEnabled: args.memoryEnabled,
24234
- autoPromote: args.autoPromote,
24235
- onCompartmentStatePublished: args.onCompartmentStatePublished,
24236
- preserveInjectionCacheUntilConsumed: true
24237
- });
24545
+ startCompartmentAgent(historianRunDeps(getBoundarySnapshotForCompartment() ?? undefined));
24238
24546
  activeRun = getActiveCompartmentRun(args.sessionId);
24239
24547
  } else if (!activeRun && hasEligibleHistoryForCompartment()) {
24240
24548
  sessionLog2(args.sessionId, "transform: cannot force-start compartment agent without client");
@@ -24245,15 +24553,24 @@ async function runCompartmentPhaseImpl(args) {
24245
24553
  const notifParams = args.getNotificationParams?.() ?? {};
24246
24554
  withoutSqliteTransformPass2(() => sendStatusNotification2(args.client, args.sessionId, `⏳ Context at ${args.contextUsage.percentage.toFixed(0)}% — Magic Context is comparting history before continuing. This may take up to ${HISTORIAN_INLINE_JOIN_BUDGET_MS / 1000} seconds.`, notifParams));
24247
24555
  }
24248
- const awaitResult = await awaitCompartmentRun(activeRun, `transform: blocking at ${args.contextUsage.percentage.toFixed(1)}% until compartment agent completes`);
24556
+ const join = fullInlineJoinWindow();
24557
+ const joinDeadline = Date.now() + join.budgetMs;
24558
+ const awaitResult = await awaitCompartmentRun(activeRun, `transform: blocking at ${args.contextUsage.percentage.toFixed(1)}% until compartment agent completes`, join);
24249
24559
  if (awaitResult === "completed") {
24250
24560
  awaitedCompartmentRun = true;
24251
24561
  compartmentInProgress = false;
24562
+ if (args.projectRecoveryRequest) {
24563
+ const chain = await chainRecoveryRuns(activeRun, args.projectRecoveryRequest, joinDeadline, join.budgetMs);
24564
+ if (chain === "timed_out")
24565
+ compartmentInProgress = true;
24566
+ }
24567
+ refreshCompartmentCoverage();
24252
24568
  } else {
24253
24569
  sessionLog2(args.sessionId, "transform: historian join timed out — reclaim and final fit checks continue; historian keeps running in the background");
24254
24570
  }
24255
24571
  }
24256
24572
  }
24573
+ const recoveryHistoryRemains = args.projectRecoveryRequest !== undefined && recoveryHistoryRemainsAfterJoins();
24257
24574
  return {
24258
24575
  pendingCompartmentInjection,
24259
24576
  awaitedCompartmentRun,
@@ -24262,7 +24579,9 @@ async function runCompartmentPhaseImpl(args) {
24262
24579
  justAwaitedPublication,
24263
24580
  rebuiltHistoryThisPass,
24264
24581
  historianJoinTimedOut,
24265
- historianJoinBudgetMs
24582
+ historianJoinBudgetMs,
24583
+ chainedRecoveryRuns,
24584
+ recoveryHistoryRemains
24266
24585
  };
24267
24586
  }
24268
24587
 
@@ -24811,6 +25130,7 @@ function createTransform(deps) {
24811
25130
  sessionID: sessionId
24812
25131
  }) : undefined;
24813
25132
  const hostEstimate = deps.hostInputEstimate?.(sessionId);
25133
+ const recoveryHostAddedTokens = typeof hostEstimate?.hostAddedTokens === "number" && Number.isFinite(hostEstimate.hostAddedTokens) && hostEstimate.hostAddedTokens > 0 ? hostEstimate.hostAddedTokens : 0;
24814
25134
  const hostOverWindow = fullFeatureMode && !compactionOff && resolvedContextLimit !== undefined && resolvedContextLimit > 0 && hostEstimate !== undefined && Number.isFinite(hostEstimate.tokens) && Number.isFinite(hostEstimate.pressureTokens) && hostEstimate.tokens > resolvedContextLimit;
24815
25135
  if (hostOverWindow) {
24816
25136
  contextUsageEarly = {
@@ -25300,6 +25620,50 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25300
25620
  const watermark = getMaxDroppedTagNumber2(db, sessionId);
25301
25621
  let contextUsage = contextUsageEarly;
25302
25622
  const rawGetNotifParams = runNotificationParams;
25623
+ const pricedPassSizingInputFor = (messagesToSize, options) => {
25624
+ const servesHead = (!!projectIdentity || !!sessionDirectory) && (fullFeatureMode || compactionOff);
25625
+ const prefixBoundModel = isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID);
25626
+ return {
25627
+ db,
25628
+ sessionId,
25629
+ messages: messagesToSize,
25630
+ messageTagNumbers,
25631
+ head: servesHead ? {
25632
+ db,
25633
+ sessionId,
25634
+ state: options.meta,
25635
+ projectDirectory: sessionDirectory,
25636
+ ...renderOptions,
25637
+ hardSignals: options.hardSignals,
25638
+ compactionOff
25639
+ } : undefined,
25640
+ headFolds: options.headFolds,
25641
+ coveredInstructions: deps.storeGeneration === "v2" && servesHead && !compactionOff ? coveredHostInstructions : [],
25642
+ replayedRemovals: {
25643
+ providerID: resolvedProviderID,
25644
+ wholePartRemoval: (!canUseEmptySentinels || prefixBoundModel) && !compactionOff,
25645
+ bindingStrips: !compactionOff
25646
+ },
25647
+ reasoning: options.reasoning
25648
+ };
25649
+ };
25650
+ const recoveryChainWindow = windowGeometry?.usableHard ?? resolvedContextLimit;
25651
+ const recoveryChainMeta = sessionMeta;
25652
+ const projectRecoveryRequest = fullFeatureMode && !compactionOff && emergencyRecoveryArmed && emergencyRecoveryOrigin !== null && typeof recoveryChainWindow === "number" && recoveryChainWindow > 0 ? () => {
25653
+ const served = servedRequestForSizing(pricedPassSizingInputFor(rawTailAfterNewestCompartment(db, sessionId, messages), { meta: recoveryChainMeta, headFolds: true, reasoning: undefined }), { editsWholePrefix: !activeThinkingPrefixHold, clearsReasoning: false });
25654
+ const estimate = estimateFinalWireInputTokens({
25655
+ messages: served,
25656
+ systemPromptTokens: recoveryChainMeta.systemPromptTokens,
25657
+ providerID: modelForBudget?.providerID,
25658
+ modelID: modelForBudget?.modelID,
25659
+ agentName: notificationParams.agent,
25660
+ sessionId
25661
+ });
25662
+ return {
25663
+ tokens: (estimate.pressureTokens ?? estimate.tokens) + recoveryHostAddedTokens,
25664
+ lineTokens: recoveryLineTokens(recoveryChainWindow)
25665
+ };
25666
+ } : undefined;
25303
25667
  const tCompartmentPhase = performance.now();
25304
25668
  const compartmentPhase = await runCompartmentPhase({
25305
25669
  hiddenCompletionExecutor: deps.hiddenCompletionExecutor,
@@ -25315,6 +25679,17 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25315
25679
  boundaryUsage: boundaryUsageForProtectedTail,
25316
25680
  boundaryUsageSource,
25317
25681
  preResolvedBoundarySnapshot: triggerBoundarySnapshot,
25682
+ projectRecoveryRequest,
25683
+ resolveRecoveryBoundary: (emergencyTailScale) => host.hostProtectedTailBoundary({
25684
+ db,
25685
+ sessionId: resolvedSessionId,
25686
+ mode: "transform-force",
25687
+ contextLimit: boundaryContextLimit,
25688
+ executeThresholdPercentage: boundaryExecuteThreshold,
25689
+ usage: boundaryUsageForProtectedTail,
25690
+ usageSource: boundaryUsageSource,
25691
+ emergencyTailScale
25692
+ }),
25318
25693
  client: deps.client,
25319
25694
  db,
25320
25695
  sessionId,
@@ -25418,44 +25793,149 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25418
25793
  contextLimit: resolvedContextLimit,
25419
25794
  lastResponseTime: sessionMeta.lastResponseTime
25420
25795
  });
25421
- let pressureEstimate;
25796
+ const servesHead = (!!projectIdentity || !!sessionDirectory) && (fullFeatureMode || compactionOff);
25797
+ const prefixBoundModel = isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID);
25798
+ let sizingInput;
25799
+ let planInput;
25422
25800
  try {
25423
- pressureEstimate = estimateFinalWireInputTokens({
25424
- messages,
25425
- systemPromptTokens: sessionMeta.systemPromptTokens,
25426
- providerID: modelForBudget?.providerID,
25427
- modelID: modelForBudget?.modelID,
25428
- agentName: notificationParams.agent,
25429
- sessionId
25801
+ sizingInput = pricedPassSizingInputFor(messages, {
25802
+ meta: sessionMeta,
25803
+ hardSignals: m0HardSignals,
25804
+ headFolds: protectionFoldWillBust,
25805
+ reasoning: !compactionOff && !activeThinkingPrefixHold && resolvedProviderID !== undefined && !prefixBoundModel ? {
25806
+ keepTokens: resolveKeepReasoningTokens(deps.keepReasoningTokens, currentModelKeyForBoundary),
25807
+ clearedThroughTag: sessionMeta.clearedReasoningThroughTag,
25808
+ proseRatio: sessionDecisionCalibration(db, sessionId).proseRatio,
25809
+ protectedThinkingMessages: protectedThinkingMessagesForSizing({
25810
+ db,
25811
+ sessionId,
25812
+ messages,
25813
+ activeThinkingTurn,
25814
+ providerID: resolvedProviderID,
25815
+ modelID: modelForBudget?.modelID
25816
+ })
25817
+ } : undefined
25430
25818
  });
25819
+ planInput = {
25820
+ db,
25821
+ sessionId,
25822
+ compactionOff,
25823
+ fullFeatureMode,
25824
+ schedulerDecision,
25825
+ forceMaterializationPercentage,
25826
+ signedThinkingHold: activeThinkingPrefixHold,
25827
+ firstRender: servesHead && !(sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) && !hasCompleteCachedM0M1(db, sessionId),
25828
+ folds: protectionFoldWillBust,
25829
+ explicitFlush: hasPendingMaterializationOrigin(deps.pendingMaterializationSessions, sessionId, "user_flush"),
25830
+ materializationRequested: deps.pendingMaterializationSessions.has(sessionId) || canConsumeDeferredLate && deferredMaterializationSessions.has(sessionId),
25831
+ historyRebuilt: historyRebuiltThisPass || pendingCompartmentInjection?.rebuiltFromDb === true || rebuiltHistoryFromInitialPrepare,
25832
+ alreadyRanThisTurn: heuristicsAlreadyRanThisTurn(deps.lastHeuristicsTurnId, sessionId, currentTurnId)
25833
+ };
25431
25834
  } catch (error) {
25432
- sessionLog2(sessionId, `transform: wire-estimate pressure fallback unavailable: ${getErrorMessage(error)}`);
25433
- }
25434
- const usableHard = windowGeometry?.usableHard;
25435
- const countPercentage = pressureEstimate?.pressureTokens !== undefined && Number.isFinite(pressureEstimate.pressureTokens) && typeof usableHard === "number" && usableHard > 0 ? pressureEstimate.pressureTokens / usableHard * 100 : 0;
25436
- const grewPastSavedReading = savedProviderReading !== null && countPercentage >= 95 && countPercentage > savedProviderReading.percentage;
25437
- if (savedProviderReading && !grewPastSavedReading) {
25438
- contextUsage = {
25439
- inputTokens: savedProviderReading.inputTokens,
25440
- percentage: Math.max(contextUsage.percentage, savedProviderReading.percentage)
25835
+ sizingInput = undefined;
25836
+ sessionLog2(sessionId, `transform: priced-pass sizing counts the array without the parts the pass adds: ${getErrorMessage(error)}`);
25837
+ }
25838
+ const countRequest = (plan) => {
25839
+ let sizingMessages = messages;
25840
+ if (sizingInput) {
25841
+ try {
25842
+ sizingMessages = servedRequestForSizing(sizingInput, plan);
25843
+ } catch (error) {
25844
+ sessionLog2(sessionId, `transform: priced-pass sizing counts the array without the parts the pass adds: ${getErrorMessage(error)}`);
25845
+ }
25846
+ }
25847
+ try {
25848
+ return estimateFinalWireInputTokens({
25849
+ messages: sizingMessages,
25850
+ systemPromptTokens: sessionMeta.systemPromptTokens,
25851
+ providerID: modelForBudget?.providerID,
25852
+ modelID: modelForBudget?.modelID,
25853
+ agentName: notificationParams.agent,
25854
+ sessionId
25855
+ });
25856
+ } catch (error) {
25857
+ sessionLog2(sessionId, `transform: wire-estimate pressure fallback unavailable: ${getErrorMessage(error)}`);
25858
+ return;
25859
+ }
25860
+ };
25861
+ const usageBeforeSizing = contextUsage;
25862
+ const readingFrom = (pressureEstimate) => {
25863
+ const countPercentage = pressureEstimate?.pressureTokens !== undefined && Number.isFinite(pressureEstimate.pressureTokens) && typeof localReadingWindow === "number" && localReadingWindow > 0 ? pressureEstimate.pressureTokens / localReadingWindow * 100 : 0;
25864
+ const grewPastSavedReading = savedProviderReading !== null && countPercentage >= 95 && countPercentage > savedProviderReading.percentage;
25865
+ const unchanged = {
25866
+ source: "none",
25867
+ usage: usageBeforeSizing,
25868
+ fromEstimate: hostOverWindow,
25869
+ countPercentage,
25870
+ grewPastSavedReading,
25871
+ pressureEstimate,
25872
+ usedProviderInput: false
25441
25873
  };
25442
- sessionLog2(sessionId, `transform: unknown provider usage; using saved provider reading for priced pass inputTokens=${contextUsage.inputTokens} percentage=${contextUsage.percentage.toFixed(1)} countPercentage=${countPercentage.toFixed(1)}`);
25443
- } else if (pressureEstimate) {
25444
- const percentageBeforeEstimate = contextUsage.percentage;
25445
- contextUsage = resolveUnknownUsageFromWireEstimate({
25446
- usage: contextUsage,
25874
+ if (savedProviderReading && !grewPastSavedReading) {
25875
+ return {
25876
+ ...unchanged,
25877
+ source: "saved",
25878
+ usage: {
25879
+ inputTokens: savedProviderReading.inputTokens,
25880
+ percentage: Math.max(usageBeforeSizing.percentage, savedProviderReading.percentage)
25881
+ }
25882
+ };
25883
+ }
25884
+ if (!pressureEstimate)
25885
+ return unchanged;
25886
+ const usage = resolveUnknownUsageFromWireEstimate({
25887
+ usage: usageBeforeSizing,
25447
25888
  pricedPass: true,
25448
25889
  wireEstimateTokens: overflowRecoveryPass ? pressureEstimate.tokens : pressureEstimate.pressureTokens,
25449
25890
  wireEstimateTrusted: pressureEstimate.trusted,
25450
25891
  providerProvenInputTokens: providerProvenInputForRecovery,
25451
25892
  providerProvenLimitTokens: providerProvenLimitForRecovery,
25452
- usableHardLimit: usableHard
25893
+ windowTokens: localReadingWindow
25453
25894
  });
25454
- if (contextUsage.inputTokens > 0) {
25455
- const usedProviderInput = !pressureEstimate.trusted && providerProvenLimitForRecovery !== undefined && providerProvenInputForRecovery !== undefined && contextUsage.inputTokens >= providerProvenInputForRecovery;
25456
- contextUsageFromEstimate = !overflowRecoveryPass && !usedProviderInput && !usagePercentageSynthetic && contextUsage.percentage > percentageBeforeEstimate;
25457
- sessionLog2(sessionId, `transform: unknown provider usage; using ${usedProviderInput ? "provider-proven input" : "wire estimate"} for priced pass inputTokens=${contextUsage.inputTokens} percentage=${contextUsage.percentage.toFixed(1)} trusted=${pressureEstimate.trusted} wireTokens=${pressureEstimate.tokens} pressureTokens=${pressureEstimate.pressureTokens}${grewPastSavedReading ? ` grewPastSavedReading=${savedProviderReading?.percentage.toFixed(1)}` : ""}`);
25895
+ if (usage.inputTokens <= 0)
25896
+ return { ...unchanged, usage };
25897
+ const usedProviderInput = !pressureEstimate.trusted && providerProvenLimitForRecovery !== undefined && providerProvenInputForRecovery !== undefined && usage.inputTokens >= providerProvenInputForRecovery;
25898
+ return {
25899
+ ...unchanged,
25900
+ source: "estimate",
25901
+ usage,
25902
+ usedProviderInput,
25903
+ fromEstimate: !overflowRecoveryPass && !usedProviderInput && !usagePercentageSynthetic && usage.percentage > usageBeforeSizing.percentage
25904
+ };
25905
+ };
25906
+ const planAt = (usage) => {
25907
+ if (!sizingInput || !planInput)
25908
+ return;
25909
+ try {
25910
+ return planPricedPass(planInput, usage);
25911
+ } catch (error) {
25912
+ sessionLog2(sessionId, `transform: priced-pass sizing counts the widest request: ${getErrorMessage(error)}`);
25913
+ return;
25458
25914
  }
25915
+ };
25916
+ let plan = planAt({
25917
+ percentage: usageBeforeSizing.percentage,
25918
+ fromEstimate: hostOverWindow
25919
+ }) ?? WIDEST_PRICED_PASS_PLAN;
25920
+ let reading = readingFrom(countRequest(plan));
25921
+ for (let attempt = 0;sizingInput && plan !== WIDEST_PRICED_PASS_PLAN; attempt++) {
25922
+ const next = planAt({
25923
+ percentage: reading.usage.percentage,
25924
+ fromEstimate: reading.fromEstimate
25925
+ });
25926
+ if (next && sameSizingPlan(sizingInput, next, plan))
25927
+ break;
25928
+ plan = next && attempt === 0 ? next : WIDEST_PRICED_PASS_PLAN;
25929
+ reading = readingFrom(countRequest(plan));
25930
+ }
25931
+ const sizedPlan = `sizedPlan=${plan.clearsReasoning ? "clears_reasoning" : "keeps_reasoning"}${plan.editsWholePrefix ? "+covered_rows" : ""}`;
25932
+ contextUsage = reading.usage;
25933
+ if (reading.source === "saved") {
25934
+ sessionLog2(sessionId, `transform: unknown provider usage; using saved provider reading for priced pass inputTokens=${contextUsage.inputTokens} percentage=${contextUsage.percentage.toFixed(1)} countPercentage=${reading.countPercentage.toFixed(1)} ${sizedPlan}`);
25935
+ } else if (reading.source === "estimate" && reading.pressureEstimate) {
25936
+ const pressureEstimate = reading.pressureEstimate;
25937
+ contextUsageFromEstimate = reading.fromEstimate;
25938
+ sessionLog2(sessionId, `transform: unknown provider usage; using ${reading.usedProviderInput ? "provider-proven input" : "wire estimate"} for priced pass inputTokens=${contextUsage.inputTokens} percentage=${contextUsage.percentage.toFixed(1)} trusted=${pressureEstimate.trusted} wireTokens=${pressureEstimate.tokens} pressureTokens=${pressureEstimate.pressureTokens}${reading.grewPastSavedReading ? ` grewPastSavedReading=${savedProviderReading?.percentage.toFixed(1)}` : ""} ${sizedPlan}`);
25459
25939
  }
25460
25940
  }
25461
25941
  const protectionUsableSoft = windowGeometry?.usableSoft ?? boundaryContextLimit;
@@ -25637,8 +26117,9 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25637
26117
  logIncompleteFinalWire(finalWireEstimate, messages);
25638
26118
  sessionLog2(sessionId, `transform: final-wire telemetry estimate=${finalWireEstimate.tokens} trusted=${finalWireEstimate.trusted} conversation=${finalWireEstimate.messageTokens.conversation} tools=${finalWireEstimate.messageTokens.toolCall} system=${finalWireEstimate.systemTokens} toolDefinitions=${finalWireEstimate.toolDefinitionTokens ?? "unknown"} tail=${finalWireTail}`);
25639
26119
  }
26120
+ const recoveryAdmissionPass = emergencyRecoveryArmed && emergencyRecoveryOrigin !== null && emergencyUsagePercentage >= 95;
25640
26121
  let servedPressureTokens;
25641
- if (providerReadingMissing) {
26122
+ if (providerReadingMissing || recoveryAdmissionPass) {
25642
26123
  servedPressureTokens = finalWireEstimate?.pressureTokens;
25643
26124
  if (servedPressureTokens === undefined) {
25644
26125
  try {
@@ -25655,12 +26136,13 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25655
26136
  }
25656
26137
  }
25657
26138
  }
26139
+ const recoveryAdmissionTokens = recoveryAdmissionPass && servedPressureTokens !== undefined ? servedPressureTokens + recoveryHostAddedTokens : undefined;
25658
26140
  localWireReadings.record({
25659
26141
  sessionId,
25660
26142
  providerReadingMissing,
25661
26143
  modelKey: localReadingModelKey,
25662
26144
  usableWindow: localReadingWindow,
25663
- pressureTokens: servedPressureTokens
26145
+ pressureTokens: providerReadingMissing ? servedPressureTokens : undefined
25664
26146
  });
25665
26147
  if ((finalWireEstimate?.refusalGrade || finalWireEstimate?.refusalBasis === "byte-bound" && finalWireEstimate.refusalTokens !== undefined) && boundaryContextLimit > 0 && (finalWireEstimate.refusalTokens ?? finalWireEstimate.tokens) > boundaryContextLimit) {
25666
26148
  const signedFitRetryWanted = !thinkingFitRetries.has(sessionId) && activeThinkingPrefixHold && hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID);
@@ -25715,6 +26197,21 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25715
26197
  unmanagedOverWindowSessions.delete(sessionId);
25716
26198
  sessionLog2(sessionId, `over-window first pass reduced: the request is about ${servedTokens} tokens (history started at ${unmanagedOverWindowPass.tokens}), under the ${unmanagedOverWindowPass.limit}-token window`);
25717
26199
  }
26200
+ const currentModelKeyForRecovery = deps.getModelKey?.(sessionId);
26201
+ const keepRecoveryArmed = () => {
26202
+ if (!emergencyRecoveryArmed || emergencyRecoveryOrigin === null)
26203
+ return;
26204
+ try {
26205
+ if (getOverflowState(db, sessionId).needsEmergencyRecovery)
26206
+ return;
26207
+ recordOverflowDetected(db, sessionId, undefined, currentModelKeyForRecovery, emergencyRecoveryOrigin);
26208
+ } catch (error) {
26209
+ throw new EmergencyFailClosedError("Emergency recovery re-arm failed", {
26210
+ cause: error
26211
+ });
26212
+ }
26213
+ sessionLog2(sessionId, `transform: recovery was cleared during a pass that is not sent; armed again (${emergencyRecoveryOrigin}) for the next turn`);
26214
+ };
25718
26215
  const timedOutHistorianFailure = compartmentPhase.historianJoinTimedOut ? historianJoinFailClosedMessage({
25719
26216
  timedOut: true,
25720
26217
  budgetMs: compartmentPhase.historianJoinBudgetMs,
@@ -25724,14 +26221,21 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25724
26221
  }) : null;
25725
26222
  if (timedOutHistorianFailure) {
25726
26223
  sessionLog2(sessionId, `transform: ${timedOutHistorianFailure}; finalEstimate=${finalWireEstimate?.tokens ?? "unavailable"} estimateTrusted=${finalWireEstimate?.trusted ?? false} contextLimit=${boundaryContextLimit} emergencyReclaimed=${postTransformResult.emergencyReclaimedTokens}`);
26224
+ keepRecoveryArmed();
25727
26225
  throw new EmergencyFailClosedError(timedOutHistorianFailure);
25728
26226
  }
25729
26227
  if (compartmentPhase.historianJoinTimedOut) {
25730
26228
  sessionLog2(sessionId, `transform: proceeding after bounded historian join; trusted final-wire ${finalWireEstimate?.tokens} fits context limit ${boundaryContextLimit} after emergency reclaim=${postTransformResult.emergencyReclaimedTokens}`);
25731
26229
  }
25732
- const currentModelKeyForRecovery = deps.getModelKey?.(sessionId);
25733
26230
  const overflowStateForFinalWire = getOverflowState(db, sessionId, currentModelKeyForRecovery);
25734
26231
  const providerProvenLimitTokens = typeof currentModelKeyForRecovery === "string" && currentModelKeyForRecovery.length > 0 && overflowStateForFinalWire.detectedContextLimit > 0 && piModelRefToCanonical(overflowStateForFinalWire.detectedContextLimitModelKey ?? "") === piModelRefToCanonical(currentModelKeyForRecovery) ? overflowStateForFinalWire.detectedContextLimit : undefined;
26232
+ const recoveryWindowTokens = windowGeometry?.usableHard ?? resolvedContextLimit;
26233
+ const recoveryHistoryRemains = compartmentPhase.recoveryHistoryRemains;
26234
+ const recoveryServedRequest = recoveryAdmissionTokens !== undefined && typeof recoveryWindowTokens === "number" && recoveryWindowTokens > 0 ? {
26235
+ tokens: recoveryAdmissionTokens,
26236
+ lineTokens: recoveryAdmissionLimitTokens(recoveryWindowTokens, recoveryHistoryRemains),
26237
+ historyRemains: recoveryHistoryRemains
26238
+ } : undefined;
25735
26239
  const emergencyFailClosed = evaluateEmergencyFailClosed2({
25736
26240
  usagePercentage: emergencyUsagePercentage,
25737
26241
  emergencyRecoveryArmed,
@@ -25740,18 +26244,27 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25740
26244
  finalWireEstimate,
25741
26245
  providerProvenLimitTokens,
25742
26246
  contextLimitTokens: boundaryContextLimit,
25743
- protectedToolTokens: protectedToolTokenCount(getActiveTagsBySession2(db, sessionId), deps.protectedTools, resolveDecisionCalibration(modelForBudget?.providerID, modelForBudget?.modelID))
26247
+ protectedToolTokens: protectedToolTokenCount(getActiveTagsBySession2(db, sessionId), deps.protectedTools, resolveDecisionCalibration(modelForBudget?.providerID, modelForBudget?.modelID)),
26248
+ recoveryServedRequest
25744
26249
  });
25745
26250
  if (emergencyFailClosed.disarm) {
25746
26251
  clearEmergencyRecovery(db, sessionId);
25747
26252
  sessionLog2(sessionId, `emergency disarm: trusted final-wire ${emergencyFailClosed.disarm.finalWireTokens} under limit ${emergencyFailClosed.disarm.provenLimitTokens}`);
26253
+ } else if (recoveryAdmissionPass && !emergencyFailClosed.shouldAbort && recoveryServedRequest !== undefined) {
26254
+ clearEmergencyRecovery(db, sessionId);
26255
+ sessionLog2(sessionId, `transform: recovery request admitted: about ${recoveryServedRequest.tokens} tokens, within ${recoveryServedRequest.lineTokens} of ${recoveryWindowTokens}; ${emergencyRecoveryOrigin} recovery ends`);
25748
26256
  }
25749
26257
  if (emergencyFailClosed.shouldAbort) {
26258
+ keepRecoveryArmed();
25750
26259
  if (emergencyFailClosed.refusalMessage) {
25751
26260
  throw contextRefusalError(emergencyFailClosed.refusalMessage);
25752
26261
  }
26262
+ const recoveryOverLimit = emergencyFailClosed.reason === "recovery-request-over-limit" && recoveryServedRequest !== undefined;
26263
+ if (recoveryOverLimit) {
26264
+ sessionLog2(sessionId, recoveryServedRequest.historyRemains ? `transform: recovery request still over the window: about ${recoveryServedRequest.tokens} tokens against the 95% line ${recoveryServedRequest.lineTokens} of ${recoveryWindowTokens}; not sending it, recovery stays armed for the next turn` : `transform: recovery request still over the window: about ${recoveryServedRequest.tokens} tokens against the whole window ${recoveryServedRequest.lineTokens}, with no older history left to summarize; not sending it`);
26265
+ }
25753
26266
  try {
25754
- await host.hostRefusalNotice(deps.client, sessionId, EMERGENCY_REFUSAL_NOTICE, notificationParams);
26267
+ await host.hostRefusalNotice(deps.client, sessionId, recoveryOverLimit ? recoveryRefusalNotice(recoveryServedRequest.historyRemains) : EMERGENCY_REFUSAL_NOTICE, notificationParams);
25755
26268
  } catch (error) {
25756
26269
  throw new EmergencyFailClosedError("Emergency recovery notification failed", {
25757
26270
  cause: error
@@ -29206,10 +29719,7 @@ function createCtxSearchTool(deps) {
29206
29719
  limit: normalizeLimit2(args.limit),
29207
29720
  memoryEnabled,
29208
29721
  embeddingEnabled,
29209
- embedQuery: async (text, signal) => {
29210
- const result = await embedTextForProject2(projectPath, text, signal, "query");
29211
- return result;
29212
- },
29722
+ embedQuery: (text, signal) => withQueryEmbeddingDeadline((embeddingSignal) => embedTextForProject2(projectPath, text, embeddingSignal, "query"), signal),
29213
29723
  isEmbeddingRuntimeEnabled: () => embeddingEnabled === true,
29214
29724
  readMessages: deps.readMessages,
29215
29725
  maxMessageOrdinal: messageOrdinalCutoff,
@@ -29261,9 +29771,9 @@ var FULL_PARAMETER_DESCRIPTIONS = {
29261
29771
  },
29262
29772
  ctx_memory: {
29263
29773
  action: "write | update | archive | merge | get",
29264
- content: "The memory text — one standalone fact (write, update, merge).",
29265
- category: "Kind of fact (required for write; on update/merge, pass the memory's current category to keep it).",
29266
- ids: "Memory ids from <project-memory>: one for update, one or more for archive, two or more for merge, 1–20 for get.",
29774
+ content: "The memory text — one standalone fact (write, update, merge). Archive and get take an empty string.",
29775
+ category: "Kind of fact: the new fact's kind for write; on update/merge, the memory's current category to keep it. Archive and get ignore it.",
29776
+ ids: "Memory ids from <project-memory>: one for update, one or more for archive, two or more for merge, 1–20 for get. Write takes an empty list.",
29267
29777
  reason: "Why it is being archived (optional)."
29268
29778
  },
29269
29779
  ctx_search: {
@@ -29296,9 +29806,9 @@ var LIGHT_PARAMETER_DESCRIPTIONS = {
29296
29806
  },
29297
29807
  ctx_memory: {
29298
29808
  action: "write | update | archive | merge | get",
29299
- content: "One standalone fact (write, update, merge).",
29300
- category: "Kind of fact (required for write; on update/merge pass the current category to keep it).",
29301
- ids: "Ids from <project-memory>: one for update, 1+ for archive, 2+ for merge, 1–20 for get.",
29809
+ content: "One standalone fact (write, update, merge). Archive and get: empty string.",
29810
+ category: "Kind of fact (write; on update/merge pass the current category to keep it). Archive and get ignore it.",
29811
+ ids: "Ids from <project-memory>: one for update, 1+ for archive, 2+ for merge, 1–20 for get. Write: empty list.",
29302
29812
  reason: "Why it is archived (optional)."
29303
29813
  },
29304
29814
  ctx_search: {