@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.
- package/dist/auto-search-worker.js +4 -4
- package/dist/chunk-embedding-write-worker.js +7 -7
- package/dist/{compartment-chunk-embedding-ypktm0tk.js → compartment-chunk-embedding-snj51nmg.js} +5 -5
- package/dist/{conflict-warning-hook-b75jn458.js → conflict-warning-hook-w1aw6w5t.js} +4 -4
- package/dist/{context-ws6gbyrr.js → context-cb51adcz.js} +374 -115
- package/dist/{derive-budgets-htj16n4x.js → derive-budgets-nkw09vq7.js} +1 -1
- package/dist/{embedding-backfill-zxj35jkq.js → embedding-backfill-kpy5shsa.js} +8 -8
- package/dist/embedding-worker.js +3 -3
- package/dist/features/magic-context/memory/embedding-openai.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-query-deadline.d.ts +8 -0
- package/dist/features/magic-context/memory/embedding-query-deadline.d.ts.map +1 -0
- package/dist/features/magic-context/overflow-detection.d.ts +16 -6
- package/dist/features/magic-context/overflow-detection.d.ts.map +1 -1
- package/dist/hooks/auto-update-checker/index.d.ts +6 -0
- package/dist/hooks/auto-update-checker/index.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts +21 -0
- package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
- package/dist/hooks/magic-context/priced-pass-sizing.d.ts +132 -0
- package/dist/hooks/magic-context/priced-pass-sizing.d.ts.map +1 -0
- package/dist/hooks/magic-context/read-session-formatting.d.ts +2 -1
- package/dist/hooks/magic-context/read-session-formatting.d.ts.map +1 -1
- package/dist/hooks/magic-context/read-session-raw.d.ts.map +1 -1
- package/dist/hooks/magic-context/reasoning-budget.d.ts.map +1 -1
- package/dist/hooks/magic-context/recovery-fit.d.ts +51 -0
- package/dist/hooks/magic-context/recovery-fit.d.ts.map +1 -0
- package/dist/hooks/magic-context/routine-cleanup-decision.d.ts +109 -0
- package/dist/hooks/magic-context/routine-cleanup-decision.d.ts.map +1 -0
- package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts +24 -0
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-context-state.d.ts +2 -1
- package/dist/hooks/magic-context/transform-context-state.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +15 -2
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts +10 -2
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/{index-jggt5gf2.js → index-1hwn96x1.js} +1 -1
- package/dist/{index-ae1ar4v1.js → index-25ka1jza.js} +1 -1
- package/dist/{index-91y4xvx6.js → index-44pp3vrj.js} +2 -2
- package/dist/{index-wapyeb06.js → index-55ngkbqa.js} +36 -17
- package/dist/{index-v64se1t6.js → index-5jk4h64j.js} +8 -8
- package/dist/{index-dnqqqc5f.js → index-8cfnaagj.js} +10 -2
- package/dist/{index-7y8c2n52.js → index-a4t7pdmm.js} +3 -3
- package/dist/{index-4xyjr62e.js → index-ak11t3gm.js} +4 -0
- package/dist/{index-6qnhaaa0.js → index-b0xt5qz9.js} +3 -3
- package/dist/{index-vd2ywmfe.js → index-brj6was5.js} +1 -1
- package/dist/{index-66qexmjw.js → index-d4qw2h43.js} +3 -3
- package/dist/{index-g4t7850m.js → index-dj2p8653.js} +1 -1
- package/dist/{index-m1mttf6y.js → index-etn2hmb5.js} +3 -3
- package/dist/{index-g0mjm7e4.js → index-gaxktvxm.js} +5 -5
- package/dist/{index-b1ydbp95.js → index-h9m41624.js} +1 -1
- package/dist/{index-p6gs3xpx.js → index-hkh8x221.js} +1 -1
- package/dist/{index-24y47287.js → index-kevd267m.js} +4 -4
- package/dist/{index-knnscj54.js → index-kw7azjmy.js} +3 -3
- package/dist/{index-dasvhxwg.js → index-n9q8c1dr.js} +6 -6
- package/dist/{index-g7rrfjkq.js → index-pwfmcg4e.js} +5 -5
- package/dist/{index-dcjkw41m.js → index-qcz1fy7h.js} +3 -3
- package/dist/{index-rhcwddn9.js → index-s79g172v.js} +63 -21
- package/dist/{index-kgk64zyx.js → index-sd2s4t4p.js} +1 -1
- package/dist/{index-jkanybgq.js → index-smtbdmc3.js} +1 -1
- package/dist/{index-ntssp0dt.js → index-snztv1f0.js} +621 -111
- package/dist/{index-8w3y6pxc.js → index-tajstyw4.js} +167 -87
- package/dist/{index-8jjjmhab.js → index-x53gnmce.js} +11 -11
- package/dist/{index-r2epb000.js → index-xa9mmq6c.js} +2 -1
- package/dist/{index-1j8m4ad0.js → index-xgnh498s.js} +10 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +43 -39
- package/dist/{message-fts-rowid-map-t6qsyg9s.js → message-fts-rowid-map-msffhkve.js} +2 -2
- package/dist/{message-index-bounded-dmq6ne7d.js → message-index-bounded-3qpg8dq5.js} +8 -8
- package/dist/migration-worker.js +5 -5
- package/dist/{project-embedding-registry-m47vg1ce.js → project-embedding-registry-r6xfsrbe.js} +7 -7
- package/dist/raw-ordinal-warmup-worker.js +7 -7
- package/dist/{read-session-chunk-3m7z9v3t.js → read-session-chunk-7h9f32sz.js} +6 -6
- package/dist/{read-session-raw-j7c9w57v.js → read-session-raw-x7a9b3jm.js} +1 -1
- package/dist/{recomp-orchestrator-9wtcpd7d.js → recomp-orchestrator-qnactdw7.js} +20 -20
- package/dist/{render-esw55s0k.js → render-da999saz.js} +13 -13
- package/dist/{search-3b4kbhtw.js → search-0a3hh5x6.js} +16 -16
- package/dist/{search-archive-wna5basn.js → search-archive-0z9cxv8e.js} +8 -8
- package/dist/{send-session-notification-14p3yje4.js → send-session-notification-j93pn2hn.js} +3 -3
- package/dist/shared/window-geometry.d.ts +5 -0
- package/dist/shared/window-geometry.d.ts.map +1 -1
- package/dist/{storage-tags-vj0yj7ed.js → storage-tags-q8erkn48.js} +4 -2
- package/dist/tools/ctx-search/tools.d.ts.map +1 -1
- package/dist/tools/parameter-descriptions.d.ts +6 -6
- package/dist/tools/parameter-descriptions.d.ts.map +1 -1
- package/dist/{transform-postprocess-phase-1y6p9ccc.js → transform-postprocess-phase-k9d1r13f.js} +21 -21
- package/dist/v2/auto-search-worker.js +4 -4
- package/dist/v2/chunk-embedding-write-worker.js +7 -7
- package/dist/v2/{compartment-chunk-embedding-qfk791bd.js → compartment-chunk-embedding-nj5nrnbj.js} +5 -5
- package/dist/v2/{context-sfgk72cj.js → context-jtqj5e1r.js} +1090 -260
- package/dist/v2/{derive-budgets-sa0v7bz0.js → derive-budgets-b5cgrtp8.js} +2 -2
- package/dist/v2/{embedding-backfill-ahwzfc7v.js → embedding-backfill-360efh1t.js} +8 -8
- package/dist/v2/embedding-worker.js +3 -3
- package/dist/v2/fold/code-mode-catalog.d.ts +11 -3
- package/dist/v2/fold/code-mode-catalog.d.ts.map +1 -1
- package/dist/v2/fold/instruction-supersession.d.ts +13 -2
- package/dist/v2/fold/instruction-supersession.d.ts.map +1 -1
- package/dist/v2/fold/native-replay.d.ts +5 -0
- package/dist/v2/fold/native-replay.d.ts.map +1 -1
- package/dist/v2/fold/owner.d.ts +14 -0
- package/dist/v2/fold/owner.d.ts.map +1 -1
- package/dist/v2/fold/summary.d.ts +35 -0
- package/dist/v2/fold/summary.d.ts.map +1 -1
- package/dist/v2/hooks/context.d.ts +2 -1
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/lkg-system.d.ts +3 -0
- package/dist/v2/hooks/lkg-system.d.ts.map +1 -1
- package/dist/v2/{message-fts-rowid-map-z86avy0n.js → message-fts-rowid-map-qe7cpksd.js} +2 -2
- package/dist/v2/{message-index-bounded-mapha2ag.js → message-index-bounded-60tdhht5.js} +7 -7
- package/dist/v2/migration-worker.js +5 -5
- package/dist/v2/{project-embedding-registry-mn403rp5.js → project-embedding-registry-ek0cy0d5.js} +7 -7
- package/dist/v2/raw-ordinal-warmup-worker.js +7 -7
- package/dist/v2/{read-session-chunk-svcthp0n.js → read-session-chunk-9tmsxwb2.js} +5 -5
- package/dist/v2/{read-session-raw-qpp6x9kg.js → read-session-raw-yss2ev98.js} +1 -1
- package/dist/v2/{recomp-orchestrator-2bkv46am.js → recomp-orchestrator-7y8smqqp.js} +19 -19
- package/dist/v2/{render-315tv10c.js → render-j0y57skn.js} +12 -12
- package/dist/v2/{search-archive-hnx40ts0.js → search-archive-1e2tr8eq.js} +7 -7
- package/dist/v2/{search-bhrr075t.js → search-qhd2m8kn.js} +14 -14
- package/dist/v2/{send-session-notification-kxp47tsw.js → send-session-notification-na3q825m.js} +1 -1
- package/dist/v2/{server-nmyganc8.js → server-131h608x.js} +1 -1
- package/dist/v2/{server-86sk7h34.js → server-2gjqhmn9.js} +63 -21
- package/dist/v2/{server-xy7w7hrd.js → server-2j87594q.js} +1 -1
- package/dist/v2/{server-g8xvnxcf.js → server-3rp821fw.js} +3 -3
- package/dist/v2/{server-1yx5455s.js → server-4m71jpaj.js} +4 -4
- package/dist/v2/{server-78mc9sxx.js → server-5dtrzs6j.js} +9 -5
- package/dist/v2/{server-t5gxvcc3.js → server-5vy0xt3p.js} +3 -3
- package/dist/v2/{server-969cdpmg.js → server-7vb38e51.js} +4 -0
- package/dist/v2/{server-sd8hvzte.js → server-af1rmkyn.js} +1 -1
- package/dist/v2/{server-ngdrh7rv.js → server-ahy062xr.js} +36 -17
- package/dist/v2/{server-tnzbk64q.js → server-b3r080cm.js} +2 -1
- package/dist/v2/{server-zzgtgqmd.js → server-ddw42d76.js} +1 -1
- package/dist/v2/{server-63cz4w5t.js → server-ht0dyq9r.js} +3 -3
- package/dist/v2/{server-xnz3nrt2.js → server-pej5rnye.js} +1 -1
- package/dist/v2/{server-1c720m9s.js → server-rjn4msjj.js} +5 -5
- package/dist/v2/{server-rqypazrp.js → server-rshcp4gy.js} +3 -3
- package/dist/v2/{server-8xdnk7vz.js → server-sg2qjkrb.js} +1 -1
- package/dist/v2/{server-aqgg41wb.js → server-sr8tf5dt.js} +3 -3
- package/dist/v2/{server-qs0mdpc1.js → server-sscb1r3e.js} +7 -7
- package/dist/v2/{server-xfjjbrkt.js → server-t4hk02v1.js} +11 -11
- package/dist/v2/{server-vjhk8v41.js → server-wa4qhryh.js} +1 -1
- package/dist/v2/{server-cp1a03vc.js → server-y8n33d9j.js} +3 -3
- package/dist/v2/{server-qxzbmtqt.js → server-zt1m5rwj.js} +10 -2
- package/dist/v2/server.js +4 -4
- package/dist/v2/{storage-tags-cw07ky67.js → storage-tags-ztar1k0g.js} +4 -2
- package/dist/v2/{v2-archive-reader-qwn0me88.js → v2-archive-reader-tme5988n.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-ts0sqwp3.js → wrapup-orchestrator-k7m16xze.js} +19 -19
- package/dist/{v2-archive-reader-vqqjkeaq.js → v2-archive-reader-dq5ebwe6.js} +1 -1
- package/dist/{wrapup-orchestrator-qxvbvr4r.js → wrapup-orchestrator-4pqwet8p.js} +21 -21
- package/package.json +1 -1
- package/src/agents/smart-notes-dreamer-gate.golden.json +169 -169
- package/src/shared/prompt-surface-a1-golden.md +4 -4
- package/src/shared/window-geometry.test.ts +85 -0
- package/src/shared/window-geometry.ts +29 -2
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
resolveLegacyConfigSources,
|
|
8
8
|
getProtectedTokensTierOverrides,
|
|
9
9
|
loadPluginConfigDetailed
|
|
10
|
-
} from "./server-
|
|
10
|
+
} from "./server-wa4qhryh.js";
|
|
11
11
|
import {
|
|
12
12
|
getHarness2,
|
|
13
13
|
harnessOwnsOpenCodeStore2
|
|
@@ -36,7 +36,7 @@ import {
|
|
|
36
36
|
getSdkContextLimit,
|
|
37
37
|
getSdkOutputLimit,
|
|
38
38
|
getModelsDevCacheState
|
|
39
|
-
} from "./server-
|
|
39
|
+
} from "./server-zt1m5rwj.js";
|
|
40
40
|
import {
|
|
41
41
|
string,
|
|
42
42
|
number,
|
|
@@ -177,6 +177,8 @@ import {
|
|
|
177
177
|
findHostCompactionWindow,
|
|
178
178
|
capturePrefixTrimSourceOrder,
|
|
179
179
|
prepareCachedM0M1Replay,
|
|
180
|
+
headMessagesForSizing,
|
|
181
|
+
rawTailAfterNewestCompartment,
|
|
180
182
|
hasCompleteCachedM0M1,
|
|
181
183
|
injectM0M1,
|
|
182
184
|
clampProducerAtomChars,
|
|
@@ -209,7 +211,7 @@ import {
|
|
|
209
211
|
startCompartmentAgent,
|
|
210
212
|
setRecompStarting2,
|
|
211
213
|
setRecompTerminal2
|
|
212
|
-
} from "./server-
|
|
214
|
+
} from "./server-ahy062xr.js";
|
|
213
215
|
import {
|
|
214
216
|
resolveHistorianModel2
|
|
215
217
|
} from "./server-5kym00ag.js";
|
|
@@ -266,7 +268,7 @@ import {
|
|
|
266
268
|
buildInMemoryTailRawMessages2,
|
|
267
269
|
RawOrdinalsNotReady2,
|
|
268
270
|
runSessionWarmupWorker
|
|
269
|
-
} from "./server-
|
|
271
|
+
} from "./server-b3r080cm.js";
|
|
270
272
|
import {
|
|
271
273
|
resolveModelCalibration,
|
|
272
274
|
calibrateBuckets,
|
|
@@ -326,6 +328,7 @@ import {
|
|
|
326
328
|
getActiveTagTokenTotalsByMessage2,
|
|
327
329
|
updateTagTokenCount2,
|
|
328
330
|
tryGetReasoningTokenEstimatesByMessage2,
|
|
331
|
+
TagOwnerSummaryNotReady2,
|
|
329
332
|
cachedTagOwnerRatios2,
|
|
330
333
|
tagOwnerWarmupState2,
|
|
331
334
|
installTagOwnerDelta2,
|
|
@@ -361,7 +364,7 @@ import {
|
|
|
361
364
|
adoptNullOwnerToolTag2,
|
|
362
365
|
getCandidateToolOwners2,
|
|
363
366
|
pickNearestPriorOwner2
|
|
364
|
-
} from "./server-
|
|
367
|
+
} from "./server-t4hk02v1.js";
|
|
365
368
|
import {
|
|
366
369
|
textMentionsRecentCommit,
|
|
367
370
|
hasMeaningfulUserText2,
|
|
@@ -372,7 +375,7 @@ import {
|
|
|
372
375
|
estimateTokens,
|
|
373
376
|
estimateFixedPromptTokens,
|
|
374
377
|
normalizeText
|
|
375
|
-
} from "./server-
|
|
378
|
+
} from "./server-7vb38e51.js";
|
|
376
379
|
import {
|
|
377
380
|
stableStringify,
|
|
378
381
|
getTableColumnNames,
|
|
@@ -590,19 +593,19 @@ import {
|
|
|
590
593
|
readRawSessionMessageOrdinalById2,
|
|
591
594
|
readSessionChunk2,
|
|
592
595
|
readRawSessionSeedTail2
|
|
593
|
-
} from "./server-
|
|
596
|
+
} from "./server-5dtrzs6j.js";
|
|
594
597
|
import {
|
|
595
598
|
BoundedSessionMap,
|
|
596
599
|
recordToolDefinitionSet,
|
|
597
600
|
getCurrentToolSetHash,
|
|
598
601
|
getMeasuredToolDefinitionTokens
|
|
599
|
-
} from "./server-
|
|
602
|
+
} from "./server-2j87594q.js";
|
|
600
603
|
import {
|
|
601
604
|
cleanSearchText,
|
|
602
605
|
matchedSearchSnippet,
|
|
603
606
|
getLastIndexedOrdinal
|
|
604
|
-
} from "./server-
|
|
605
|
-
import"./server-
|
|
607
|
+
} from "./server-3rp821fw.js";
|
|
608
|
+
import"./server-131h608x.js";
|
|
606
609
|
import {
|
|
607
610
|
getMessageIndexEpoch,
|
|
608
611
|
isMessageIndexSearchable,
|
|
@@ -628,7 +631,7 @@ import {
|
|
|
628
631
|
resolveMemoriesByIdsForSearch2,
|
|
629
632
|
unifiedSearch2,
|
|
630
633
|
formatSearchResults2
|
|
631
|
-
} from "./server-
|
|
634
|
+
} from "./server-sscb1r3e.js";
|
|
632
635
|
import {
|
|
633
636
|
embedPauseBySession,
|
|
634
637
|
embedRunStateBySession,
|
|
@@ -647,10 +650,10 @@ import {
|
|
|
647
650
|
toSynapseLaneDescriptor,
|
|
648
651
|
formatSynapseLaneDescriptor,
|
|
649
652
|
SynapseEmbeddingProvider
|
|
650
|
-
} from "./server-
|
|
653
|
+
} from "./server-ddw42d76.js";
|
|
651
654
|
import {
|
|
652
655
|
deleteChunkEmbedBackoffForSession2
|
|
653
|
-
} from "./server-
|
|
656
|
+
} from "./server-y8n33d9j.js";
|
|
654
657
|
import {
|
|
655
658
|
registerOwnRpcServerInstance,
|
|
656
659
|
rpcPortDir,
|
|
@@ -761,7 +764,7 @@ import {
|
|
|
761
764
|
saveSourceContent,
|
|
762
765
|
replaceSourceContent,
|
|
763
766
|
getSourceContents
|
|
764
|
-
} from "./server-
|
|
767
|
+
} from "./server-rjn4msjj.js";
|
|
765
768
|
import {
|
|
766
769
|
startBootDeadline,
|
|
767
770
|
getUnconfirmedMigrationHolders,
|
|
@@ -777,7 +780,7 @@ import {
|
|
|
777
780
|
openDatabaseAsync,
|
|
778
781
|
isDatabasePersisted,
|
|
779
782
|
getDatabasePersistenceError
|
|
780
|
-
} from "./server-
|
|
783
|
+
} from "./server-5vy0xt3p.js";
|
|
781
784
|
import {
|
|
782
785
|
V2_MEMORY_CATEGORIES,
|
|
783
786
|
CATEGORY_PRIORITY
|
|
@@ -832,12 +835,13 @@ import {
|
|
|
832
835
|
resolveKnownHistorianContextLimit2,
|
|
833
836
|
resolveHistorianProducerLimits2,
|
|
834
837
|
resolveHistorianContextLimit2
|
|
835
|
-
} from "./server-
|
|
838
|
+
} from "./server-af1rmkyn.js";
|
|
836
839
|
import"./server-gwxys0d0.js";
|
|
837
840
|
import {
|
|
838
841
|
isEmbeddingHostBusy2
|
|
839
842
|
} from "./server-qt1qqasc.js";
|
|
840
843
|
import {
|
|
844
|
+
withQueryEmbeddingDeadline,
|
|
841
845
|
describeShadowBackfillWriteRefusal2,
|
|
842
846
|
retainProjectEmbedding2,
|
|
843
847
|
markProjectLoadUntrusted2,
|
|
@@ -857,7 +861,7 @@ import {
|
|
|
857
861
|
embedSessionCompartmentChunks2,
|
|
858
862
|
getEmbeddingCoverageStatus2,
|
|
859
863
|
getAutoEmbeddingSessionCoverage2
|
|
860
|
-
} from "./server-
|
|
864
|
+
} from "./server-2gjqhmn9.js";
|
|
861
865
|
import {
|
|
862
866
|
GIT_SWEEP_LEASE_RENEWAL_MS,
|
|
863
867
|
acquireGitSweepLease,
|
|
@@ -877,10 +881,10 @@ import {
|
|
|
877
881
|
getCachedLocalEmbeddingPooling,
|
|
878
882
|
preflightLocalEmbeddingPooling,
|
|
879
883
|
getLocalEmbeddingNativeMemoryStats
|
|
880
|
-
} from "./server-
|
|
884
|
+
} from "./server-sg2qjkrb.js";
|
|
881
885
|
import {
|
|
882
886
|
cosineSimilarity
|
|
883
|
-
} from "./server-
|
|
887
|
+
} from "./server-sr8tf5dt.js";
|
|
884
888
|
import {
|
|
885
889
|
computeCueContentHash,
|
|
886
890
|
hasMuralCueColumns,
|
|
@@ -925,7 +929,7 @@ import {
|
|
|
925
929
|
readGitFileChangeTimesSince,
|
|
926
930
|
verificationFileExists,
|
|
927
931
|
normalizeVerificationFiles
|
|
928
|
-
} from "./server-
|
|
932
|
+
} from "./server-pej5rnye.js";
|
|
929
933
|
import {
|
|
930
934
|
registerNotificationSink2,
|
|
931
935
|
pushNotification2,
|
|
@@ -962,14 +966,14 @@ import {
|
|
|
962
966
|
renderMessageByOrdinal2,
|
|
963
967
|
renderVerboseRangeForTool2,
|
|
964
968
|
renderItemByTag2
|
|
965
|
-
} from "./server-
|
|
969
|
+
} from "./server-ht0dyq9r.js";
|
|
966
970
|
import"./server-kaqs6h31.js";
|
|
967
971
|
import {
|
|
968
972
|
readV2ArchiveOffThread2
|
|
969
|
-
} from "./server-
|
|
973
|
+
} from "./server-rshcp4gy.js";
|
|
970
974
|
import {
|
|
971
975
|
renderSearchArchiveOffThread2
|
|
972
|
-
} from "./server-
|
|
976
|
+
} from "./server-4m71jpaj.js";
|
|
973
977
|
import {
|
|
974
978
|
markHostInstructionRow,
|
|
975
979
|
hostInstructionRow,
|
|
@@ -1129,7 +1133,7 @@ __export(exports_external, {
|
|
|
1129
1133
|
cuid: () => cuid3,
|
|
1130
1134
|
cuid2: () => cuid22,
|
|
1131
1135
|
custom: () => custom,
|
|
1132
|
-
date: () =>
|
|
1136
|
+
date: () => date4,
|
|
1133
1137
|
decode: () => decode3,
|
|
1134
1138
|
decodeAsync: () => decodeAsync2,
|
|
1135
1139
|
discriminatedUnion: () => discriminatedUnion,
|
|
@@ -1598,7 +1602,7 @@ __export(exports_regexes, {
|
|
|
1598
1602
|
cidrv6: () => cidrv6,
|
|
1599
1603
|
cuid: () => cuid,
|
|
1600
1604
|
cuid2: () => cuid2,
|
|
1601
|
-
date: () =>
|
|
1605
|
+
date: () => date2,
|
|
1602
1606
|
datetime: () => datetime,
|
|
1603
1607
|
domain: () => domain,
|
|
1604
1608
|
duration: () => duration,
|
|
@@ -1709,7 +1713,7 @@ __export(exports_iso, {
|
|
|
1709
1713
|
ZodISODateTime: () => ZodISODateTime,
|
|
1710
1714
|
ZodISODuration: () => ZodISODuration,
|
|
1711
1715
|
ZodISOTime: () => ZodISOTime,
|
|
1712
|
-
date: () =>
|
|
1716
|
+
date: () => date3,
|
|
1713
1717
|
datetime: () => datetime2,
|
|
1714
1718
|
duration: () => duration2,
|
|
1715
1719
|
time: () => time2
|
|
@@ -1720,7 +1724,7 @@ var exports_coerce = {};
|
|
|
1720
1724
|
__export(exports_coerce, {
|
|
1721
1725
|
bigint: () => bigint3,
|
|
1722
1726
|
boolean: () => boolean4,
|
|
1723
|
-
date: () =>
|
|
1727
|
+
date: () => date5,
|
|
1724
1728
|
number: () => number4,
|
|
1725
1729
|
string: () => string4
|
|
1726
1730
|
});
|
|
@@ -8721,6 +8725,55 @@ function projectStructuralSentinels(args) {
|
|
|
8721
8725
|
return removed;
|
|
8722
8726
|
}
|
|
8723
8727
|
|
|
8728
|
+
// src/hooks/magic-context/routine-cleanup-decision.ts
|
|
8729
|
+
function pressureBands(args) {
|
|
8730
|
+
const emergencyDropEligible = !args.compactionOff && args.percentage >= args.forceMaterializationPercentage;
|
|
8731
|
+
const forceRideWaitsOnLocalCount = args.fromEstimate && args.percentage < 95;
|
|
8732
|
+
return {
|
|
8733
|
+
forceMaterialization: args.fullFeatureMode && emergencyDropEligible,
|
|
8734
|
+
emergencyDropEligible,
|
|
8735
|
+
forceRideWaitsOnLocalCount,
|
|
8736
|
+
forceBandConfirmed: emergencyDropEligible && !forceRideWaitsOnLocalCount,
|
|
8737
|
+
executePressureEligible: args.schedulerDecision === "execute" || emergencyDropEligible
|
|
8738
|
+
};
|
|
8739
|
+
}
|
|
8740
|
+
function forceRide(args) {
|
|
8741
|
+
return args.bands.emergencyDropEligible && (args.percentage >= 95 || !args.fromEstimate && args.emergencySample() === 0);
|
|
8742
|
+
}
|
|
8743
|
+
function heuristicsRunOnPass(args) {
|
|
8744
|
+
return !args.compactionOff && args.drainAllowed && (args.rides.publishedHistory || args.rides.executeReclaim === true || args.rides.servedShapeRepair === true || args.materializationRequested || args.bands.forceMaterialization || args.foldBustsServedPrefix || args.firstRender || args.bands.emergencyDropEligible || args.schedulerDecision === "execute" && (!args.alreadyRanThisTurn || !args.fullFeatureMode));
|
|
8745
|
+
}
|
|
8746
|
+
function routineCleanupRunsOnPass(args) {
|
|
8747
|
+
return (args.bands.forceBandConfirmed ? args.percentage >= 95 || args.emergencySample() === 0 : !args.fullFeatureMode || !args.routinePressureAlreadyApplied) || args.materializationRequested || args.rewriteAlreadyPriced;
|
|
8748
|
+
}
|
|
8749
|
+
var routinePressureAppliedBySession = new BoundedSessionMap(100);
|
|
8750
|
+
function heuristicsAlreadyRanThisTurn(lastHeuristicsTurnId, sessionId, currentTurnId) {
|
|
8751
|
+
return currentTurnId !== null && lastHeuristicsTurnId.get(sessionId) === currentTurnId;
|
|
8752
|
+
}
|
|
8753
|
+
function routinePressureAlreadyApplied(sessionId, args) {
|
|
8754
|
+
return args.fullFeatureMode && args.executePressureEligible && (args.alreadyRanThisTurn || routinePressureAppliedBySession.get(sessionId) === true);
|
|
8755
|
+
}
|
|
8756
|
+
function updateRoutinePressureEpisode(sessionId, args) {
|
|
8757
|
+
if (!args.executePressureEligible)
|
|
8758
|
+
routinePressureAppliedBySession.delete(sessionId);
|
|
8759
|
+
else if (args.fullFeatureMode && args.alreadyRanThisTurn)
|
|
8760
|
+
routinePressureAppliedBySession.set(sessionId, true);
|
|
8761
|
+
}
|
|
8762
|
+
function markRoutinePressureApplied(sessionId) {
|
|
8763
|
+
routinePressureAppliedBySession.set(sessionId, true);
|
|
8764
|
+
}
|
|
8765
|
+
function safeReasoningCutoff(messageTagNumbers, protectedThinkingMessages) {
|
|
8766
|
+
let cutoff = 0;
|
|
8767
|
+
for (const tag of messageTagNumbers.values())
|
|
8768
|
+
cutoff = Math.max(cutoff, tag);
|
|
8769
|
+
for (const message of protectedThinkingMessages) {
|
|
8770
|
+
const tag = messageTagNumbers.get(message);
|
|
8771
|
+
if (tag && tag > 0)
|
|
8772
|
+
cutoff = Math.min(cutoff, tag - 1);
|
|
8773
|
+
}
|
|
8774
|
+
return cutoff;
|
|
8775
|
+
}
|
|
8776
|
+
|
|
8724
8777
|
// src/hooks/magic-context/strict-thinking-prefix.ts
|
|
8725
8778
|
function servedPrefixMatches(args) {
|
|
8726
8779
|
const heads = args.messages?.slice(0, 2);
|
|
@@ -9819,7 +9872,6 @@ function tagMessages(sessionId, messages, tagger, db, options = {}) {
|
|
|
9819
9872
|
var DEGRADE_CACHE_WARNING_THRESHOLD = 10;
|
|
9820
9873
|
var SYSTEM_INJECTION_ACTIONABLE_TAIL_MESSAGES = 40;
|
|
9821
9874
|
var degradedCacheCountBySession = new BoundedSessionMap(100);
|
|
9822
|
-
var routinePressureAppliedBySession = new BoundedSessionMap(100);
|
|
9823
9875
|
function isSyntheticHeadMessage(message) {
|
|
9824
9876
|
if (message.info.id !== undefined)
|
|
9825
9877
|
return false;
|
|
@@ -10476,11 +10528,15 @@ function evaluateEmergencyFailClosed(input) {
|
|
|
10476
10528
|
if (input.usagePercentage < 95) {
|
|
10477
10529
|
return { shouldAbort: false, reason: "below-emergency-band" };
|
|
10478
10530
|
}
|
|
10479
|
-
const
|
|
10480
|
-
|
|
10481
|
-
shouldAbort,
|
|
10482
|
-
|
|
10483
|
-
|
|
10531
|
+
const recoveryOrigin = input.emergencyRecoveryArmed ? input.emergencyRecoveryOrigin : null;
|
|
10532
|
+
if (recoveryOrigin === "provider_overflow" && !input.foldMaterializedThisPass) {
|
|
10533
|
+
return { shouldAbort: true, reason: "provider-overflow-abort" };
|
|
10534
|
+
}
|
|
10535
|
+
const served = input.recoveryServedRequest;
|
|
10536
|
+
if (recoveryOrigin !== null && served !== undefined && served.lineTokens > 0 && (!Number.isFinite(served.tokens) || served.tokens > served.lineTokens)) {
|
|
10537
|
+
return { shouldAbort: true, reason: "recovery-request-over-limit" };
|
|
10538
|
+
}
|
|
10539
|
+
return { shouldAbort: false, reason: "proceed" };
|
|
10484
10540
|
}
|
|
10485
10541
|
function finalizeMessageRepresentation(messages, resolvedProviderID, options) {
|
|
10486
10542
|
const protectedMessages = options?.protectedThinkingMessages ?? new Set;
|
|
@@ -10567,18 +10623,29 @@ async function runPostTransformPhase(args) {
|
|
|
10567
10623
|
const deferredMaterializationAtPassStart = args.deferredMaterializationSessions.has(args.sessionId);
|
|
10568
10624
|
let isExplicitFlush = pendingMaterializationAtPassStart;
|
|
10569
10625
|
const deferredMaterializationWasPending = deferredMaterializationAtPassStart;
|
|
10570
|
-
const alreadyRanThisTurn = args.
|
|
10571
|
-
const
|
|
10572
|
-
|
|
10573
|
-
|
|
10574
|
-
|
|
10575
|
-
|
|
10576
|
-
|
|
10577
|
-
|
|
10578
|
-
}
|
|
10579
|
-
|
|
10580
|
-
|
|
10581
|
-
|
|
10626
|
+
const alreadyRanThisTurn = heuristicsAlreadyRanThisTurn(args.lastHeuristicsTurnId, args.sessionId, args.currentTurnId);
|
|
10627
|
+
const bands = pressureBands({
|
|
10628
|
+
percentage: args.contextUsage.percentage,
|
|
10629
|
+
fromEstimate: args.contextUsageFromEstimate === true,
|
|
10630
|
+
forceMaterializationPercentage: args.forceMaterializationPercentage,
|
|
10631
|
+
compactionOff,
|
|
10632
|
+
fullFeatureMode: args.fullFeatureMode,
|
|
10633
|
+
schedulerDecision: args.schedulerDecision
|
|
10634
|
+
});
|
|
10635
|
+
const {
|
|
10636
|
+
forceMaterialization,
|
|
10637
|
+
emergencyDropEligible,
|
|
10638
|
+
forceRideWaitsOnLocalCount,
|
|
10639
|
+
forceBandConfirmed,
|
|
10640
|
+
executePressureEligible
|
|
10641
|
+
} = bands;
|
|
10642
|
+
const episode = {
|
|
10643
|
+
fullFeatureMode: args.fullFeatureMode,
|
|
10644
|
+
executePressureEligible,
|
|
10645
|
+
alreadyRanThisTurn
|
|
10646
|
+
};
|
|
10647
|
+
updateRoutinePressureEpisode(args.sessionId, episode);
|
|
10648
|
+
const routinePressureApplied = routinePressureAlreadyApplied(args.sessionId, episode);
|
|
10582
10649
|
if (args.contextUsageFromEstimate !== true && args.contextUsage.percentage > 0 && args.contextUsage.percentage < args.forceMaterializationPercentage - 5 && getEmergencyInputSample(args.db, args.sessionId) > 0) {
|
|
10583
10650
|
clearEmergencyDropSample(args.db, args.sessionId);
|
|
10584
10651
|
}
|
|
@@ -10601,15 +10668,7 @@ async function runPostTransformPhase(args) {
|
|
|
10601
10668
|
let activeThinkingTurn = retainedThinking.size > 0;
|
|
10602
10669
|
const protectedThinkingMessages = new Set(args.messages.filter((message) => message.parts.some((part) => retainedThinking.has(part))));
|
|
10603
10670
|
let newTargets = protectNewTagMutations(args.messages, args.targets, retainedThinking, args.thinkingBindingRecoveryEnabledForModel === true);
|
|
10604
|
-
|
|
10605
|
-
for (const tag of args.messageTagNumbers.values())
|
|
10606
|
-
maxReasoningTag = Math.max(maxReasoningTag, tag);
|
|
10607
|
-
let safeReasoningCutoff = maxReasoningTag;
|
|
10608
|
-
for (const message of protectedThinkingMessages) {
|
|
10609
|
-
const tag = args.messageTagNumbers.get(message);
|
|
10610
|
-
if (tag && tag > 0)
|
|
10611
|
-
safeReasoningCutoff = Math.min(safeReasoningCutoff, tag - 1);
|
|
10612
|
-
}
|
|
10671
|
+
const safeReasoningCutoff2 = safeReasoningCutoff(args.messageTagNumbers, protectedThinkingMessages);
|
|
10613
10672
|
let activeThinkingPrefixHold = args.activeThinkingPrefixHold === true;
|
|
10614
10673
|
let freezeM0M1 = args.freezeM0M1 === true || activeThinkingPrefixHold;
|
|
10615
10674
|
let rewritingSignedPrefix = false;
|
|
@@ -10816,7 +10875,12 @@ async function runPostTransformPhase(args) {
|
|
|
10816
10875
|
executeReclaim: false,
|
|
10817
10876
|
subagentExecute: !args.fullFeatureMode && args.schedulerDecision === "execute",
|
|
10818
10877
|
hardFold: rewritingSignedPrefix || foldBustsServedPrefixThisPass || firstRenderBust,
|
|
10819
|
-
force:
|
|
10878
|
+
force: forceRide({
|
|
10879
|
+
bands,
|
|
10880
|
+
percentage: args.contextUsage.percentage,
|
|
10881
|
+
fromEstimate: args.contextUsageFromEstimate === true,
|
|
10882
|
+
emergencySample: () => getEmergencyInputSample(args.db, args.sessionId)
|
|
10883
|
+
}),
|
|
10820
10884
|
explicitFlush: isExplicitFlush && hasPendingMaterializationOrigin(args.pendingMaterializationSessions, args.sessionId, "user_flush"),
|
|
10821
10885
|
publishedHistory: !prefixPreflightFailed && (publishedM1RefreshedThisPass || !m0M1EnabledForFold && (args.pendingCompartmentInjection?.compartmentCount ?? 0) > 0 && legacyPublishedHeadChanged(args))
|
|
10822
10886
|
};
|
|
@@ -10843,7 +10907,18 @@ async function runPostTransformPhase(args) {
|
|
|
10843
10907
|
emergency: forceBandConfirmed
|
|
10844
10908
|
});
|
|
10845
10909
|
const shouldApplyPendingOps = !compactionOff && publishedWorkDrainAllowed;
|
|
10846
|
-
const shouldRunHeuristics =
|
|
10910
|
+
const shouldRunHeuristics = heuristicsRunOnPass({
|
|
10911
|
+
compactionOff,
|
|
10912
|
+
drainAllowed: publishedWorkDrainAllowed,
|
|
10913
|
+
rides: rideSignals,
|
|
10914
|
+
materializationRequested,
|
|
10915
|
+
bands,
|
|
10916
|
+
foldBustsServedPrefix: foldBustsServedPrefixThisPass,
|
|
10917
|
+
firstRender: firstRenderBust,
|
|
10918
|
+
schedulerDecision: args.schedulerDecision,
|
|
10919
|
+
alreadyRanThisTurn,
|
|
10920
|
+
fullFeatureMode: args.fullFeatureMode
|
|
10921
|
+
});
|
|
10847
10922
|
const isCacheBustingPass = publishedWorkDrainAllowed;
|
|
10848
10923
|
if (servedShapeRepair.needsRebuild && !isCacheBustingPass)
|
|
10849
10924
|
throw new Error("Served-shape repair requires a rebuilding pass");
|
|
@@ -10988,7 +11063,18 @@ async function runPostTransformPhase(args) {
|
|
|
10988
11063
|
recordFirstApplicationWireEdit(false);
|
|
10989
11064
|
firstApplicationLocations.set(message, Math.min(firstApplicationLocations.get(message) ?? Infinity, partIndex));
|
|
10990
11065
|
};
|
|
10991
|
-
const
|
|
11066
|
+
const coveredHostInstructions = args.coveredHostInstructions ?? [];
|
|
11067
|
+
let coveredRetentionOn = false;
|
|
11068
|
+
let retainCoveredInstructions = false;
|
|
11069
|
+
if (m0M1EnabledForFold && args.m0M1 && !compactionOff && args.opencode2 && (coveredHostInstructions.length > 0 || canEditWholePrefix) && hostInstructionRetentionEnabled()) {
|
|
11070
|
+
try {
|
|
11071
|
+
coveredRetentionOn = isHostInstructionRetentionOn(args.db, args.sessionId);
|
|
11072
|
+
} catch (error) {
|
|
11073
|
+
failPass("host-instruction-retention-read-failure", error);
|
|
11074
|
+
}
|
|
11075
|
+
retainCoveredInstructions = coveredRetentionOn || canEditWholePrefix;
|
|
11076
|
+
}
|
|
11077
|
+
const hostRowReclaim = args.reclaimHostRows?.(args.sessionId, args.messages, !compactionOff && canEditWholePrefix, retainCoveredInstructions ? coveredHostInstructions : []);
|
|
10992
11078
|
for (const message of hostRowReclaim?.edits ?? []) {
|
|
10993
11079
|
const index = args.messages.indexOf(message);
|
|
10994
11080
|
recordFirstApplicationWireEdit(index < 0 || servesThinkingBlock(args.messages.slice(index + 1), args.resolvedProviderID, args.resolvedModelID));
|
|
@@ -11057,7 +11143,15 @@ async function runPostTransformPhase(args) {
|
|
|
11057
11143
|
if (forceBandConfirmed && emergencyRewriteAlreadyPriced && getEmergencyInputSample(args.db, args.sessionId) > 0) {
|
|
11058
11144
|
clearEmergencyDropSample(args.db, args.sessionId);
|
|
11059
11145
|
}
|
|
11060
|
-
let routineCleanupApplied = (
|
|
11146
|
+
let routineCleanupApplied = routineCleanupRunsOnPass({
|
|
11147
|
+
bands,
|
|
11148
|
+
percentage: args.contextUsage.percentage,
|
|
11149
|
+
emergencySample: () => getEmergencyInputSample(args.db, args.sessionId),
|
|
11150
|
+
fullFeatureMode: args.fullFeatureMode,
|
|
11151
|
+
routinePressureAlreadyApplied: routinePressureApplied,
|
|
11152
|
+
materializationRequested,
|
|
11153
|
+
rewriteAlreadyPriced: emergencyRewriteAlreadyPriced
|
|
11154
|
+
});
|
|
11061
11155
|
let cleanup = applyHeuristicCleanup(args.sessionId, args.db, newTargets, args.messageTagNumbers, {
|
|
11062
11156
|
protectedTagNumbers: args.protectedTagNumbers,
|
|
11063
11157
|
protectedCutoff: args.protectedCutoff,
|
|
@@ -11095,7 +11189,7 @@ async function runPostTransformPhase(args) {
|
|
|
11095
11189
|
routineCleanupApplied = true;
|
|
11096
11190
|
}
|
|
11097
11191
|
if (routineCleanupApplied && args.fullFeatureMode && executePressureEligible) {
|
|
11098
|
-
|
|
11192
|
+
markRoutinePressureApplied(args.sessionId);
|
|
11099
11193
|
}
|
|
11100
11194
|
logTransformTiming(args.sessionId, "applyHeuristicCleanup", t5, `droppedTools=${cleanup.droppedTools} deduplicatedTools=${cleanup.deduplicatedTools} droppedInjections=${cleanup.droppedInjections} compressedTextTags=${cleanup.compressedTextTags} mutatedTextTags=${cleanup.mutatedTextTags}`);
|
|
11101
11195
|
const heuristicMutationCount = cleanup.droppedTools + cleanup.deduplicatedTools + cleanup.droppedInjections + cleanup.mutatedTextTags;
|
|
@@ -11114,7 +11208,7 @@ async function runPostTransformPhase(args) {
|
|
|
11114
11208
|
}
|
|
11115
11209
|
}
|
|
11116
11210
|
const reasoningEstimates = tryGetReasoningTokenEstimatesByMessage2(args.db, args.sessionId, sessionDecisionCalibration(args.db, args.sessionId).proseRatio);
|
|
11117
|
-
const budgetCutoff = routineCleanupApplied && !activeThinkingPrefixHold && reasoningEstimates ? Math.min(
|
|
11211
|
+
const budgetCutoff = routineCleanupApplied && !activeThinkingPrefixHold && reasoningEstimates ? Math.min(safeReasoningCutoff2, opencodeReasoningBudgetCutoff({
|
|
11118
11212
|
messages: args.messages,
|
|
11119
11213
|
messageTagNumbers: args.messageTagNumbers,
|
|
11120
11214
|
budget: args.keepReasoningTokens ?? DEFAULT_KEEP_REASONING_TOKENS,
|
|
@@ -11371,25 +11465,10 @@ async function runPostTransformPhase(args) {
|
|
|
11371
11465
|
}
|
|
11372
11466
|
}
|
|
11373
11467
|
const m0M1Enabled = m0M1EnabledForFold;
|
|
11374
|
-
if (
|
|
11375
|
-
|
|
11376
|
-
|
|
11377
|
-
|
|
11378
|
-
if (hostInstructionRetentionEnabled()) {
|
|
11379
|
-
try {
|
|
11380
|
-
retain = isHostInstructionRetentionOn(args.db, args.sessionId);
|
|
11381
|
-
} catch (error) {
|
|
11382
|
-
failPass("host-instruction-retention-read-failure", error);
|
|
11383
|
-
}
|
|
11384
|
-
if (!retain && canEditWholePrefix) {
|
|
11385
|
-
if (!markHostInstructionRetention(args.db, args.sessionId))
|
|
11386
|
-
failPass("host-instruction-retention-persistence-failure");
|
|
11387
|
-
retain = true;
|
|
11388
|
-
}
|
|
11389
|
-
}
|
|
11390
|
-
if (retain && covered.length > 0)
|
|
11391
|
-
args.messages.unshift(...covered);
|
|
11392
|
-
}
|
|
11468
|
+
if (retainCoveredInstructions && coveredHostInstructions.length > 0) {
|
|
11469
|
+
if (!coveredRetentionOn && coveredHostInstructions.some((m) => m.parts.length > 0))
|
|
11470
|
+
recordFirstApplicationWireEdit(true);
|
|
11471
|
+
args.messages.unshift(...coveredHostInstructions);
|
|
11393
11472
|
}
|
|
11394
11473
|
if (m0M1Enabled && args.m0M1) {
|
|
11395
11474
|
if (freezeM0M1 && !preparedPrefix) {
|
|
@@ -11956,6 +12035,8 @@ async function runPostTransformPhase(args) {
|
|
|
11956
12035
|
}
|
|
11957
12036
|
}
|
|
11958
12037
|
hostRowReclaim?.commit();
|
|
12038
|
+
if (retainCoveredInstructions && !coveredRetentionOn && !markHostInstructionRetention(args.db, args.sessionId))
|
|
12039
|
+
failPass("host-instruction-retention-persistence-failure");
|
|
11959
12040
|
let settledDroppedReasoning = 0;
|
|
11960
12041
|
if (!canUseEmptySentinels) {
|
|
11961
12042
|
let mode = "legacy";
|
|
@@ -12905,6 +12986,192 @@ function createPassOutcome() {
|
|
|
12905
12986
|
};
|
|
12906
12987
|
}
|
|
12907
12988
|
|
|
12989
|
+
// src/hooks/magic-context/priced-pass-sizing.ts
|
|
12990
|
+
var REASONING_PART_TYPES = new Set(["reasoning", "thinking", "redacted_thinking"]);
|
|
12991
|
+
var WIDEST_PRICED_PASS_PLAN = {
|
|
12992
|
+
editsWholePrefix: true,
|
|
12993
|
+
clearsReasoning: false
|
|
12994
|
+
};
|
|
12995
|
+
function planPricedPass(input, usage) {
|
|
12996
|
+
const bands = pressureBands({
|
|
12997
|
+
percentage: usage.percentage,
|
|
12998
|
+
fromEstimate: usage.fromEstimate,
|
|
12999
|
+
forceMaterializationPercentage: input.forceMaterializationPercentage,
|
|
13000
|
+
compactionOff: input.compactionOff,
|
|
13001
|
+
fullFeatureMode: input.fullFeatureMode,
|
|
13002
|
+
schedulerDecision: input.schedulerDecision
|
|
13003
|
+
});
|
|
13004
|
+
const emergencySample = () => getEmergencyInputSample(input.db, input.sessionId);
|
|
13005
|
+
const rides = {
|
|
13006
|
+
hardFold: input.folds || input.firstRender,
|
|
13007
|
+
force: forceRide({
|
|
13008
|
+
bands,
|
|
13009
|
+
percentage: usage.percentage,
|
|
13010
|
+
fromEstimate: usage.fromEstimate,
|
|
13011
|
+
emergencySample
|
|
13012
|
+
}),
|
|
13013
|
+
explicitFlush: input.explicitFlush,
|
|
13014
|
+
publishedHistory: false,
|
|
13015
|
+
subagentExecute: !input.fullFeatureMode && input.schedulerDecision === "execute",
|
|
13016
|
+
executeReclaim: false,
|
|
13017
|
+
servedShapeRepair: false
|
|
13018
|
+
};
|
|
13019
|
+
const drainAllowed = !input.compactionOff && reclaimRidePermitted(rides, {
|
|
13020
|
+
signedThinkingHold: input.signedThinkingHold,
|
|
13021
|
+
firstRender: input.firstRender,
|
|
13022
|
+
emergency: bands.forceBandConfirmed
|
|
13023
|
+
});
|
|
13024
|
+
const materializationRequested = !input.signedThinkingHold && input.materializationRequested;
|
|
13025
|
+
const heuristics = heuristicsRunOnPass({
|
|
13026
|
+
compactionOff: input.compactionOff,
|
|
13027
|
+
drainAllowed,
|
|
13028
|
+
rides,
|
|
13029
|
+
materializationRequested,
|
|
13030
|
+
bands,
|
|
13031
|
+
foldBustsServedPrefix: input.folds,
|
|
13032
|
+
firstRender: input.firstRender,
|
|
13033
|
+
schedulerDecision: input.schedulerDecision,
|
|
13034
|
+
alreadyRanThisTurn: input.alreadyRanThisTurn,
|
|
13035
|
+
fullFeatureMode: input.fullFeatureMode
|
|
13036
|
+
});
|
|
13037
|
+
const routine = heuristics && routineCleanupRunsOnPass({
|
|
13038
|
+
bands,
|
|
13039
|
+
percentage: usage.percentage,
|
|
13040
|
+
emergencySample,
|
|
13041
|
+
fullFeatureMode: input.fullFeatureMode,
|
|
13042
|
+
routinePressureAlreadyApplied: routinePressureAlreadyApplied(input.sessionId, {
|
|
13043
|
+
fullFeatureMode: input.fullFeatureMode,
|
|
13044
|
+
executePressureEligible: bands.executePressureEligible,
|
|
13045
|
+
alreadyRanThisTurn: input.alreadyRanThisTurn
|
|
13046
|
+
}),
|
|
13047
|
+
materializationRequested,
|
|
13048
|
+
rewriteAlreadyPriced: input.folds || input.firstRender || input.historyRebuilt
|
|
13049
|
+
});
|
|
13050
|
+
return {
|
|
13051
|
+
editsWholePrefix: drainAllowed && !input.signedThinkingHold,
|
|
13052
|
+
clearsReasoning: routine && !input.signedThinkingHold
|
|
13053
|
+
};
|
|
13054
|
+
}
|
|
13055
|
+
function sameSizingPlan(input, a, b) {
|
|
13056
|
+
const rowsDiffer = a.editsWholePrefix !== b.editsWholePrefix && input.coveredInstructions.length > 0 && hostInstructionRetentionEnabled() && !isHostInstructionRetentionOn(input.db, input.sessionId);
|
|
13057
|
+
const reasoningDiffers = a.clearsReasoning !== b.clearsReasoning && input.reasoning !== undefined;
|
|
13058
|
+
return !rowsDiffer && !reasoningDiffers;
|
|
13059
|
+
}
|
|
13060
|
+
function protectedThinkingMessagesForSizing(args) {
|
|
13061
|
+
if (!args.activeThinkingTurn)
|
|
13062
|
+
return new Set;
|
|
13063
|
+
const mergedIds = getMergedReasoningStrippedIds(args.db, args.sessionId);
|
|
13064
|
+
const bindingIds = new Set([...mergedIds].filter((id) => id.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX)).map((id) => id.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length)));
|
|
13065
|
+
const retained = retainedActiveThinkingParts({
|
|
13066
|
+
messages: [...args.messages],
|
|
13067
|
+
providerID: args.providerID,
|
|
13068
|
+
modelID: args.modelID,
|
|
13069
|
+
mergedIds,
|
|
13070
|
+
bindingIds,
|
|
13071
|
+
removedIds: getReasoningRemovalState(args.db, args.sessionId).messageIds
|
|
13072
|
+
});
|
|
13073
|
+
return new Set(args.messages.filter((message) => message.parts.some((part) => retained.has(part))));
|
|
13074
|
+
}
|
|
13075
|
+
function servedRequestForSizing(input, plan) {
|
|
13076
|
+
const head = input.head ? headMessagesForSizing(input.head, input.headFolds) : [];
|
|
13077
|
+
const instructions = input.coveredInstructions.length > 0 && hostInstructionRetentionEnabled() && (plan.editsWholePrefix || isHostInstructionRetentionOn(input.db, input.sessionId)) ? input.coveredInstructions : [];
|
|
13078
|
+
const removals = replayedReasoningRemovals(input);
|
|
13079
|
+
const cutoff = plan.clearsReasoning && input.reasoning ? Math.min(safeReasoningCutoff(input.messageTagNumbers, input.reasoning.protectedThinkingMessages), clearedReasoningCutoff(input, input.reasoning, removals.messageIds)) : 0;
|
|
13080
|
+
let conversation = withoutReplayedRemovals(input.messages, removals, input);
|
|
13081
|
+
if (cutoff > 0)
|
|
13082
|
+
conversation = conversation.map((message, index) => withoutClearedReasoning(message, input.messages[index] ?? message, input, cutoff));
|
|
13083
|
+
return [...head, ...instructions, ...conversation];
|
|
13084
|
+
}
|
|
13085
|
+
function replayedReasoningRemovals(input) {
|
|
13086
|
+
const bindingIds = new Set;
|
|
13087
|
+
if (input.replayedRemovals.bindingStrips)
|
|
13088
|
+
for (const id of getMergedReasoningStrippedIds(input.db, input.sessionId)) {
|
|
13089
|
+
if (!id.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX))
|
|
13090
|
+
continue;
|
|
13091
|
+
const messageId = id.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length);
|
|
13092
|
+
if (messageId.length > 0)
|
|
13093
|
+
bindingIds.add(messageId);
|
|
13094
|
+
}
|
|
13095
|
+
return {
|
|
13096
|
+
messageIds: input.replayedRemovals.wholePartRemoval ? getReasoningRemovalState(input.db, input.sessionId).messageIds : new Set,
|
|
13097
|
+
bindingIds
|
|
13098
|
+
};
|
|
13099
|
+
}
|
|
13100
|
+
function withoutReplayedRemovals(messages, removals, input) {
|
|
13101
|
+
if (removals.messageIds.size === 0 && removals.bindingIds.size === 0)
|
|
13102
|
+
return [...messages];
|
|
13103
|
+
const copies = messages.map((message) => {
|
|
13104
|
+
const id = message.info.id;
|
|
13105
|
+
return typeof id === "string" && (removals.messageIds.has(id) || removals.bindingIds.has(id)) ? countingCopy(message) : message;
|
|
13106
|
+
});
|
|
13107
|
+
const providerID = input.replayedRemovals.providerID;
|
|
13108
|
+
stripReasoningFromAssistantIds(copies, providerID, removals.bindingIds);
|
|
13109
|
+
removeReasoningParts(copies, removals.messageIds, providerID);
|
|
13110
|
+
return copies;
|
|
13111
|
+
}
|
|
13112
|
+
function countingCopy(message) {
|
|
13113
|
+
return {
|
|
13114
|
+
...message,
|
|
13115
|
+
parts: message.parts.map((part) => {
|
|
13116
|
+
if (!isRecord(part) || !isRecord(part.metadata))
|
|
13117
|
+
return part;
|
|
13118
|
+
return {
|
|
13119
|
+
...part,
|
|
13120
|
+
metadata: {
|
|
13121
|
+
...part.metadata,
|
|
13122
|
+
...isRecord(part.metadata.openrouter) ? { openrouter: { ...part.metadata.openrouter } } : {}
|
|
13123
|
+
}
|
|
13124
|
+
};
|
|
13125
|
+
})
|
|
13126
|
+
};
|
|
13127
|
+
}
|
|
13128
|
+
function clearedReasoningCutoff(input, reasoning, removedIds) {
|
|
13129
|
+
try {
|
|
13130
|
+
return projectOpencodeReasoningBudgetCutoff(input.db, input.sessionId, [...input.messages], reasoning.keepTokens, reasoning.clearedThroughTag, reasoning.proseRatio);
|
|
13131
|
+
} catch (error) {
|
|
13132
|
+
if (!(error instanceof TagOwnerSummaryNotReady2))
|
|
13133
|
+
throw error;
|
|
13134
|
+
}
|
|
13135
|
+
const gone = new Set(removedIds);
|
|
13136
|
+
for (const [message, tag] of input.messageTagNumbers) {
|
|
13137
|
+
if (tag > 0 && tag <= reasoning.clearedThroughTag && typeof message.info.id === "string")
|
|
13138
|
+
gone.add(message.info.id);
|
|
13139
|
+
}
|
|
13140
|
+
const frozenMergedIds = getMergedReasoningStrippedIds(input.db, input.sessionId);
|
|
13141
|
+
return opencodeReasoningBudgetCutoff({
|
|
13142
|
+
messages: [...input.messages],
|
|
13143
|
+
messageTagNumbers: input.messageTagNumbers,
|
|
13144
|
+
budget: reasoning.keepTokens,
|
|
13145
|
+
alreadyRemoved: gone,
|
|
13146
|
+
proseRatio: reasoning.proseRatio,
|
|
13147
|
+
frozenMergedIds,
|
|
13148
|
+
alsoGone: new Set([...frozenMergedIds].filter((id) => id.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX)).map((id) => id.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length)))
|
|
13149
|
+
});
|
|
13150
|
+
}
|
|
13151
|
+
function withoutClearedReasoning(message, original, input, cutoff) {
|
|
13152
|
+
const tag = input.messageTagNumbers.get(original) ?? 0;
|
|
13153
|
+
if (tag === 0 || tag > cutoff)
|
|
13154
|
+
return message;
|
|
13155
|
+
const parts = message.parts.filter((part) => !isReasoningPart2(part));
|
|
13156
|
+
return parts.length === message.parts.length ? message : { ...message, parts };
|
|
13157
|
+
}
|
|
13158
|
+
function isReasoningPart2(part) {
|
|
13159
|
+
return typeof part === "object" && part !== null && REASONING_PART_TYPES.has(String(part.type));
|
|
13160
|
+
}
|
|
13161
|
+
|
|
13162
|
+
// src/hooks/magic-context/recovery-fit.ts
|
|
13163
|
+
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.";
|
|
13164
|
+
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.";
|
|
13165
|
+
function recoveryLineTokens(windowTokens) {
|
|
13166
|
+
return Math.floor(windowTokens * BLOCK_UNTIL_DONE_PERCENTAGE / 100);
|
|
13167
|
+
}
|
|
13168
|
+
function recoveryAdmissionLimitTokens(windowTokens, historyRemains) {
|
|
13169
|
+
return historyRemains ? recoveryLineTokens(windowTokens) : Math.floor(windowTokens);
|
|
13170
|
+
}
|
|
13171
|
+
function recoveryRefusalNotice(historyRemains) {
|
|
13172
|
+
return historyRemains ? RECOVERY_REFUSAL_NOTICE : RECOVERY_NO_HISTORY_REFUSAL_NOTICE;
|
|
13173
|
+
}
|
|
13174
|
+
|
|
12908
13175
|
// src/hooks/magic-context/release-recovery-prefix.ts
|
|
12909
13176
|
function groups(messages) {
|
|
12910
13177
|
const result = new Map;
|
|
@@ -15719,7 +15986,7 @@ function resolveUnknownUsageFromWireEstimate(input) {
|
|
|
15719
15986
|
const providerLimit = input.providerProvenLimitTokens;
|
|
15720
15987
|
const canUseProviderMass = input.wireEstimateTrusted === false && typeof providerTokens === "number" && Number.isFinite(providerTokens) && providerTokens > 0 && typeof providerLimit === "number" && Number.isFinite(providerLimit) && providerLimit > 0;
|
|
15721
15988
|
const tokens = canUseProviderMass ? Math.max(wireTokens, providerTokens) : wireTokens;
|
|
15722
|
-
const limit = input.
|
|
15989
|
+
const limit = input.windowTokens;
|
|
15723
15990
|
const estimatedPercentage = typeof limit === "number" && Number.isFinite(limit) && limit > 0 ? tokens / limit * 100 : input.usage.percentage;
|
|
15724
15991
|
return {
|
|
15725
15992
|
inputTokens: tokens,
|
|
@@ -16280,7 +16547,7 @@ function transformGeometryForWire(geometry) {
|
|
|
16280
16547
|
return;
|
|
16281
16548
|
const { window, reserve } = geometry.derivation;
|
|
16282
16549
|
let derivation;
|
|
16283
|
-
if (geometry.geometry === "separate" && geometry.usableSoft <
|
|
16550
|
+
if (geometry.geometry === "separate" && geometry.usableSoft < window) {
|
|
16284
16551
|
derivation = `s1-pre-carve/input=${geometry.usableSoft}`;
|
|
16285
16552
|
} else if (geometry.geometry === "separate") {
|
|
16286
16553
|
derivation = `s1-separate/context=${window}`;
|
|
@@ -19103,6 +19370,7 @@ function readServedTemporalDecisions(db, sessionId, runtime, messageIds) {
|
|
|
19103
19370
|
|
|
19104
19371
|
// src/hooks/magic-context/transform-compartment-phase.ts
|
|
19105
19372
|
var HISTORIAN_INLINE_JOIN_BUDGET_MS = 60000;
|
|
19373
|
+
var CHAINED_RECOVERY_RUN_MIN_BUDGET_MS = 15000;
|
|
19106
19374
|
function resolveHistorianInlineJoinBudget(configuredTimeoutMs) {
|
|
19107
19375
|
const requested = configuredTimeoutMs ?? HISTORIAN_INLINE_JOIN_BUDGET_MS;
|
|
19108
19376
|
return Math.max(0, Math.min(requested, HISTORIAN_INLINE_JOIN_BUDGET_MS));
|
|
@@ -19164,6 +19432,7 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19164
19432
|
let rebuiltHistoryThisPass = false;
|
|
19165
19433
|
let historianJoinTimedOut = false;
|
|
19166
19434
|
let historianJoinBudgetMs = null;
|
|
19435
|
+
let chainedRecoveryRuns = 0;
|
|
19167
19436
|
const historianRunnable = args.historianRunnable !== false;
|
|
19168
19437
|
if (args.compactionOff) {
|
|
19169
19438
|
if (args.sessionMeta.compartmentInProgress) {
|
|
@@ -19179,7 +19448,9 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19179
19448
|
justAwaitedPublication,
|
|
19180
19449
|
rebuiltHistoryThisPass,
|
|
19181
19450
|
historianJoinTimedOut,
|
|
19182
|
-
historianJoinBudgetMs
|
|
19451
|
+
historianJoinBudgetMs,
|
|
19452
|
+
chainedRecoveryRuns,
|
|
19453
|
+
recoveryHistoryRemains: false
|
|
19183
19454
|
};
|
|
19184
19455
|
}
|
|
19185
19456
|
let rawEligibility = args.preResolvedBoundarySnapshot ? {
|
|
@@ -19227,7 +19498,7 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19227
19498
|
const snapshot = getBoundarySnapshotForCompartment();
|
|
19228
19499
|
return snapshot !== null && hasRunnableCompartmentWindow(snapshot);
|
|
19229
19500
|
}
|
|
19230
|
-
async function awaitCompartmentRun(activeRun, reason) {
|
|
19501
|
+
async function awaitCompartmentRun(activeRun, reason, join = fullInlineJoinWindow()) {
|
|
19231
19502
|
await Promise.resolve();
|
|
19232
19503
|
if (activeRun.inlineJoinTimedOutBudgetMs !== undefined && !activeRun.settled) {
|
|
19233
19504
|
historianJoinTimedOut = true;
|
|
@@ -19236,8 +19507,8 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19236
19507
|
return "timed_out";
|
|
19237
19508
|
}
|
|
19238
19509
|
sessionLog2(args.sessionId, reason);
|
|
19239
|
-
const timeoutMs =
|
|
19240
|
-
historianJoinBudgetMs =
|
|
19510
|
+
const timeoutMs = join.timeoutMs;
|
|
19511
|
+
historianJoinBudgetMs = join.budgetMs;
|
|
19241
19512
|
let timer;
|
|
19242
19513
|
const timeout = new Promise((resolve) => {
|
|
19243
19514
|
timer = setTimeout(() => resolve("timeout"), timeoutMs);
|
|
@@ -19250,20 +19521,145 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19250
19521
|
clearTimeout(timer);
|
|
19251
19522
|
}
|
|
19252
19523
|
if (result === "timeout") {
|
|
19253
|
-
activeRun.inlineJoinTimedOutBudgetMs =
|
|
19524
|
+
activeRun.inlineJoinTimedOutBudgetMs = join.budgetMs;
|
|
19254
19525
|
historianJoinTimedOut = true;
|
|
19255
19526
|
sessionLog2(args.sessionId, `transform: compartment await timed out after ${timeoutMs}ms — proceeding without waiting`);
|
|
19256
19527
|
return "timed_out";
|
|
19257
19528
|
}
|
|
19258
|
-
|
|
19259
|
-
justAwaitedPublication = activeRun.published;
|
|
19529
|
+
justAwaitedPublication = justAwaitedPublication || activeRun.published;
|
|
19260
19530
|
published = published || activeRun.published;
|
|
19261
|
-
|
|
19531
|
+
return "completed";
|
|
19532
|
+
}
|
|
19533
|
+
function refreshCompartmentCoverage() {
|
|
19534
|
+
sessionLog2(args.sessionId, "transform: compartment agent completed, refreshing compartment coverage");
|
|
19535
|
+
const historyReprepareShouldBust = published && args.deferredHistoryRefreshSessions.has(args.sessionId);
|
|
19262
19536
|
pendingCompartmentInjection = prepareCompartmentInjection(args.db, args.resolvedSessionId, args.messages, historyReprepareShouldBust, args.coveredInstructions, args.projectPath, args.injectionBudgetTokens, args.experimentalTemporalAwareness);
|
|
19263
19537
|
if (historyReprepareShouldBust) {
|
|
19264
19538
|
rebuiltHistoryThisPass = true;
|
|
19265
19539
|
}
|
|
19266
|
-
|
|
19540
|
+
}
|
|
19541
|
+
function fullInlineJoinWindow() {
|
|
19542
|
+
const budgetMs = resolveHistorianInlineJoinBudget(args.historianTimeoutMs);
|
|
19543
|
+
return { timeoutMs: budgetMs, budgetMs };
|
|
19544
|
+
}
|
|
19545
|
+
function historianRunDeps(boundarySnapshot) {
|
|
19546
|
+
return {
|
|
19547
|
+
client: args.client,
|
|
19548
|
+
hiddenCompletionExecutor: args.hiddenCompletionExecutor,
|
|
19549
|
+
compactionMarkerStrategy: args.compactionMarkerStrategy,
|
|
19550
|
+
db: args.db,
|
|
19551
|
+
sessionId: args.sessionId,
|
|
19552
|
+
historianChunkTokens: args.historianChunkTokens,
|
|
19553
|
+
boundarySnapshot,
|
|
19554
|
+
currentContextLimit: args.boundaryContextLimit,
|
|
19555
|
+
historyBudgetTokens: args.historyBudgetTokens,
|
|
19556
|
+
historianTimeoutMs: args.historianTimeoutMs,
|
|
19557
|
+
model: args.historianModel,
|
|
19558
|
+
historianContextLimit: args.historianContextLimit,
|
|
19559
|
+
historianMaxOutputTokens: args.historianMaxOutputTokens,
|
|
19560
|
+
fallbackModels: args.fallbackModels,
|
|
19561
|
+
directory: args.compartmentDirectory,
|
|
19562
|
+
fallbackModelId: args.fallbackModelId,
|
|
19563
|
+
ensureProjectRegistered: args.ensureProjectRegistered,
|
|
19564
|
+
getNotificationParams: args.getNotificationParams,
|
|
19565
|
+
experimentalUserMemories: args.experimentalUserMemories,
|
|
19566
|
+
userObservationsRequested: args.userObservationsRequested,
|
|
19567
|
+
historianTwoPass: args.historianTwoPass,
|
|
19568
|
+
historianExpandTools: args.historianExpandTools,
|
|
19569
|
+
memoryEnabled: args.memoryEnabled,
|
|
19570
|
+
autoPromote: args.autoPromote,
|
|
19571
|
+
onCompartmentStatePublished: args.onCompartmentStatePublished,
|
|
19572
|
+
preserveInjectionCacheUntilConsumed: true
|
|
19573
|
+
};
|
|
19574
|
+
}
|
|
19575
|
+
function resolveNextRecoveryBoundary() {
|
|
19576
|
+
rawEligibility = null;
|
|
19577
|
+
cachedBoundarySnapshot = null;
|
|
19578
|
+
if (!hasNewRawHistoryForCompartment())
|
|
19579
|
+
return null;
|
|
19580
|
+
const resolve = args.resolveRecoveryBoundary ?? resolveBoundarySnapshot;
|
|
19581
|
+
let snapshot = resolve();
|
|
19582
|
+
if (!hasRunnableCompartmentWindow(snapshot)) {
|
|
19583
|
+
snapshot = resolve(args.contextUsage.percentage >= BLOCK_UNTIL_DONE_PERCENTAGE ? 0.25 : 0.5);
|
|
19584
|
+
}
|
|
19585
|
+
cachedBoundarySnapshot = snapshot;
|
|
19586
|
+
return hasRunnableCompartmentWindow(snapshot) ? snapshot : null;
|
|
19587
|
+
}
|
|
19588
|
+
async function chainRecoveryRuns(firstRun, project, deadline, budgetMs) {
|
|
19589
|
+
let lastRun = firstRun;
|
|
19590
|
+
const minimumRunBudgetMs = Math.min(CHAINED_RECOVERY_RUN_MIN_BUDGET_MS, budgetMs / 4);
|
|
19591
|
+
for (;; ) {
|
|
19592
|
+
if (!lastRun.published) {
|
|
19593
|
+
sessionLog2(args.sessionId, `transform: recovery chain stops: the last historian run published nothing (${chainedRecoveryRuns} chained runs)`);
|
|
19594
|
+
return "stopped";
|
|
19595
|
+
}
|
|
19596
|
+
let fit;
|
|
19597
|
+
try {
|
|
19598
|
+
fit = project();
|
|
19599
|
+
} catch (error) {
|
|
19600
|
+
sessionLog2(args.sessionId, "transform: recovery chain stops: the request could not be counted:", error);
|
|
19601
|
+
return "stopped";
|
|
19602
|
+
}
|
|
19603
|
+
if (!fit)
|
|
19604
|
+
return "stopped";
|
|
19605
|
+
if (Number.isFinite(fit.tokens) && fit.tokens <= fit.lineTokens) {
|
|
19606
|
+
sessionLog2(args.sessionId, `transform: recovery chain done: the request is about ${fit.tokens} tokens, under the 95% line ${fit.lineTokens} (${chainedRecoveryRuns} chained runs)`);
|
|
19607
|
+
return "stopped";
|
|
19608
|
+
}
|
|
19609
|
+
const remainingMs = deadline - Date.now();
|
|
19610
|
+
if (remainingMs < minimumRunBudgetMs) {
|
|
19611
|
+
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}`);
|
|
19612
|
+
return "stopped";
|
|
19613
|
+
}
|
|
19614
|
+
const boundary = resolveNextRecoveryBoundary();
|
|
19615
|
+
if (!boundary) {
|
|
19616
|
+
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}`);
|
|
19617
|
+
return "stopped";
|
|
19618
|
+
}
|
|
19619
|
+
if (isHistorianDrainBudgetSpent({
|
|
19620
|
+
db: args.db,
|
|
19621
|
+
sessionId: args.sessionId,
|
|
19622
|
+
contextLimit: args.boundaryContextLimit,
|
|
19623
|
+
executeThresholdPercentage: args.boundaryExecuteThresholdPercentage,
|
|
19624
|
+
usagePercentage: args.boundaryUsage.percentage
|
|
19625
|
+
})) {
|
|
19626
|
+
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}`);
|
|
19627
|
+
return "stopped";
|
|
19628
|
+
}
|
|
19629
|
+
startCompartmentAgent(historianRunDeps(boundary));
|
|
19630
|
+
const nextRun = getActiveCompartmentRun(args.sessionId);
|
|
19631
|
+
if (!nextRun || nextRun === lastRun) {
|
|
19632
|
+
sessionLog2(args.sessionId, "transform: recovery chain stops: the next historian run did not start");
|
|
19633
|
+
return "stopped";
|
|
19634
|
+
}
|
|
19635
|
+
chainedRecoveryRuns += 1;
|
|
19636
|
+
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 });
|
|
19637
|
+
if (result === "timed_out")
|
|
19638
|
+
return "timed_out";
|
|
19639
|
+
lastRun = nextRun;
|
|
19640
|
+
}
|
|
19641
|
+
}
|
|
19642
|
+
function recoveryHistoryRemainsAfterJoins() {
|
|
19643
|
+
if (!historianRunnable || !args.canRunCompartments)
|
|
19644
|
+
return false;
|
|
19645
|
+
if (getActiveCompartmentRun(args.sessionId))
|
|
19646
|
+
return true;
|
|
19647
|
+
if (!args.client && !args.hiddenCompletionExecutor)
|
|
19648
|
+
return false;
|
|
19649
|
+
try {
|
|
19650
|
+
if (resolveNextRecoveryBoundary() === null)
|
|
19651
|
+
return false;
|
|
19652
|
+
} catch (error) {
|
|
19653
|
+
sessionLog2(args.sessionId, "transform: recovery history check failed; keeping the 95% line:", error);
|
|
19654
|
+
return true;
|
|
19655
|
+
}
|
|
19656
|
+
return !isHistorianDrainBudgetSpent({
|
|
19657
|
+
db: args.db,
|
|
19658
|
+
sessionId: args.sessionId,
|
|
19659
|
+
contextLimit: args.boundaryContextLimit,
|
|
19660
|
+
executeThresholdPercentage: args.boundaryExecuteThresholdPercentage,
|
|
19661
|
+
usagePercentage: args.boundaryUsage.percentage
|
|
19662
|
+
});
|
|
19267
19663
|
}
|
|
19268
19664
|
if ((!historianRunnable || !args.canRunCompartments && !getActiveCompartmentRun(args.sessionId)) && args.sessionMeta.compartmentInProgress) {
|
|
19269
19665
|
sessionLog2(args.sessionId, "transform: historian unavailable; clearing stale compartmentInProgress flag");
|
|
@@ -19323,34 +19719,7 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19323
19719
|
let activeRun = getActiveCompartmentRun(args.sessionId);
|
|
19324
19720
|
if (!activeRun && hasEligibleHistoryForCompartment() && (args.client || args.hiddenCompletionExecutor)) {
|
|
19325
19721
|
sessionLog2(args.sessionId, `transform: 95% reached (${args.contextUsage.percentage.toFixed(1)}%), force-starting compartment agent and blocking`);
|
|
19326
|
-
startCompartmentAgent(
|
|
19327
|
-
client: args.client,
|
|
19328
|
-
hiddenCompletionExecutor: args.hiddenCompletionExecutor,
|
|
19329
|
-
compactionMarkerStrategy: args.compactionMarkerStrategy,
|
|
19330
|
-
db: args.db,
|
|
19331
|
-
sessionId: args.sessionId,
|
|
19332
|
-
historianChunkTokens: args.historianChunkTokens,
|
|
19333
|
-
boundarySnapshot: getBoundarySnapshotForCompartment() ?? undefined,
|
|
19334
|
-
currentContextLimit: args.boundaryContextLimit,
|
|
19335
|
-
historyBudgetTokens: args.historyBudgetTokens,
|
|
19336
|
-
historianTimeoutMs: args.historianTimeoutMs,
|
|
19337
|
-
model: args.historianModel,
|
|
19338
|
-
historianContextLimit: args.historianContextLimit,
|
|
19339
|
-
historianMaxOutputTokens: args.historianMaxOutputTokens,
|
|
19340
|
-
fallbackModels: args.fallbackModels,
|
|
19341
|
-
directory: args.compartmentDirectory,
|
|
19342
|
-
fallbackModelId: args.fallbackModelId,
|
|
19343
|
-
ensureProjectRegistered: args.ensureProjectRegistered,
|
|
19344
|
-
getNotificationParams: args.getNotificationParams,
|
|
19345
|
-
experimentalUserMemories: args.experimentalUserMemories,
|
|
19346
|
-
userObservationsRequested: args.userObservationsRequested,
|
|
19347
|
-
historianTwoPass: args.historianTwoPass,
|
|
19348
|
-
historianExpandTools: args.historianExpandTools,
|
|
19349
|
-
memoryEnabled: args.memoryEnabled,
|
|
19350
|
-
autoPromote: args.autoPromote,
|
|
19351
|
-
onCompartmentStatePublished: args.onCompartmentStatePublished,
|
|
19352
|
-
preserveInjectionCacheUntilConsumed: true
|
|
19353
|
-
});
|
|
19722
|
+
startCompartmentAgent(historianRunDeps(getBoundarySnapshotForCompartment() ?? undefined));
|
|
19354
19723
|
activeRun = getActiveCompartmentRun(args.sessionId);
|
|
19355
19724
|
} else if (!activeRun && hasEligibleHistoryForCompartment()) {
|
|
19356
19725
|
sessionLog2(args.sessionId, "transform: cannot force-start compartment agent without client");
|
|
@@ -19361,15 +19730,24 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19361
19730
|
const notifParams = args.getNotificationParams?.() ?? {};
|
|
19362
19731
|
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));
|
|
19363
19732
|
}
|
|
19364
|
-
const
|
|
19733
|
+
const join = fullInlineJoinWindow();
|
|
19734
|
+
const joinDeadline = Date.now() + join.budgetMs;
|
|
19735
|
+
const awaitResult = await awaitCompartmentRun(activeRun, `transform: blocking at ${args.contextUsage.percentage.toFixed(1)}% until compartment agent completes`, join);
|
|
19365
19736
|
if (awaitResult === "completed") {
|
|
19366
19737
|
awaitedCompartmentRun = true;
|
|
19367
19738
|
compartmentInProgress = false;
|
|
19739
|
+
if (args.projectRecoveryRequest) {
|
|
19740
|
+
const chain = await chainRecoveryRuns(activeRun, args.projectRecoveryRequest, joinDeadline, join.budgetMs);
|
|
19741
|
+
if (chain === "timed_out")
|
|
19742
|
+
compartmentInProgress = true;
|
|
19743
|
+
}
|
|
19744
|
+
refreshCompartmentCoverage();
|
|
19368
19745
|
} else {
|
|
19369
19746
|
sessionLog2(args.sessionId, "transform: historian join timed out — reclaim and final fit checks continue; historian keeps running in the background");
|
|
19370
19747
|
}
|
|
19371
19748
|
}
|
|
19372
19749
|
}
|
|
19750
|
+
const recoveryHistoryRemains = args.projectRecoveryRequest !== undefined && recoveryHistoryRemainsAfterJoins();
|
|
19373
19751
|
return {
|
|
19374
19752
|
pendingCompartmentInjection,
|
|
19375
19753
|
awaitedCompartmentRun,
|
|
@@ -19378,7 +19756,9 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19378
19756
|
justAwaitedPublication,
|
|
19379
19757
|
rebuiltHistoryThisPass,
|
|
19380
19758
|
historianJoinTimedOut,
|
|
19381
|
-
historianJoinBudgetMs
|
|
19759
|
+
historianJoinBudgetMs,
|
|
19760
|
+
chainedRecoveryRuns,
|
|
19761
|
+
recoveryHistoryRemains
|
|
19382
19762
|
};
|
|
19383
19763
|
}
|
|
19384
19764
|
|
|
@@ -19918,6 +20298,7 @@ function createTransform(deps) {
|
|
|
19918
20298
|
sessionID: sessionId
|
|
19919
20299
|
}) : undefined;
|
|
19920
20300
|
const hostEstimate = deps.hostInputEstimate?.(sessionId);
|
|
20301
|
+
const recoveryHostAddedTokens = typeof hostEstimate?.hostAddedTokens === "number" && Number.isFinite(hostEstimate.hostAddedTokens) && hostEstimate.hostAddedTokens > 0 ? hostEstimate.hostAddedTokens : 0;
|
|
19921
20302
|
const hostOverWindow = fullFeatureMode && !compactionOff && resolvedContextLimit !== undefined && resolvedContextLimit > 0 && hostEstimate !== undefined && Number.isFinite(hostEstimate.tokens) && Number.isFinite(hostEstimate.pressureTokens) && hostEstimate.tokens > resolvedContextLimit;
|
|
19922
20303
|
if (hostOverWindow) {
|
|
19923
20304
|
contextUsageEarly = {
|
|
@@ -20407,6 +20788,50 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20407
20788
|
const watermark = getMaxDroppedTagNumber2(db, sessionId);
|
|
20408
20789
|
let contextUsage = contextUsageEarly;
|
|
20409
20790
|
const rawGetNotifParams = runNotificationParams;
|
|
20791
|
+
const pricedPassSizingInputFor = (messagesToSize, options) => {
|
|
20792
|
+
const servesHead = (!!projectIdentity || !!sessionDirectory) && (fullFeatureMode || compactionOff);
|
|
20793
|
+
const prefixBoundModel = isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID);
|
|
20794
|
+
return {
|
|
20795
|
+
db,
|
|
20796
|
+
sessionId,
|
|
20797
|
+
messages: messagesToSize,
|
|
20798
|
+
messageTagNumbers,
|
|
20799
|
+
head: servesHead ? {
|
|
20800
|
+
db,
|
|
20801
|
+
sessionId,
|
|
20802
|
+
state: options.meta,
|
|
20803
|
+
projectDirectory: sessionDirectory,
|
|
20804
|
+
...renderOptions,
|
|
20805
|
+
hardSignals: options.hardSignals,
|
|
20806
|
+
compactionOff
|
|
20807
|
+
} : undefined,
|
|
20808
|
+
headFolds: options.headFolds,
|
|
20809
|
+
coveredInstructions: deps.storeGeneration === "v2" && servesHead && !compactionOff ? coveredHostInstructions : [],
|
|
20810
|
+
replayedRemovals: {
|
|
20811
|
+
providerID: resolvedProviderID,
|
|
20812
|
+
wholePartRemoval: (!canUseEmptySentinels || prefixBoundModel) && !compactionOff,
|
|
20813
|
+
bindingStrips: !compactionOff
|
|
20814
|
+
},
|
|
20815
|
+
reasoning: options.reasoning
|
|
20816
|
+
};
|
|
20817
|
+
};
|
|
20818
|
+
const recoveryChainWindow = windowGeometry?.usableHard ?? resolvedContextLimit;
|
|
20819
|
+
const recoveryChainMeta = sessionMeta;
|
|
20820
|
+
const projectRecoveryRequest = fullFeatureMode && !compactionOff && emergencyRecoveryArmed && emergencyRecoveryOrigin !== null && typeof recoveryChainWindow === "number" && recoveryChainWindow > 0 ? () => {
|
|
20821
|
+
const served = servedRequestForSizing(pricedPassSizingInputFor(rawTailAfterNewestCompartment(db, sessionId, messages), { meta: recoveryChainMeta, headFolds: true, reasoning: undefined }), { editsWholePrefix: !activeThinkingPrefixHold, clearsReasoning: false });
|
|
20822
|
+
const estimate = estimateFinalWireInputTokens({
|
|
20823
|
+
messages: served,
|
|
20824
|
+
systemPromptTokens: recoveryChainMeta.systemPromptTokens,
|
|
20825
|
+
providerID: modelForBudget?.providerID,
|
|
20826
|
+
modelID: modelForBudget?.modelID,
|
|
20827
|
+
agentName: notificationParams.agent,
|
|
20828
|
+
sessionId
|
|
20829
|
+
});
|
|
20830
|
+
return {
|
|
20831
|
+
tokens: (estimate.pressureTokens ?? estimate.tokens) + recoveryHostAddedTokens,
|
|
20832
|
+
lineTokens: recoveryLineTokens(recoveryChainWindow)
|
|
20833
|
+
};
|
|
20834
|
+
} : undefined;
|
|
20410
20835
|
const tCompartmentPhase = performance.now();
|
|
20411
20836
|
const compartmentPhase = await runCompartmentPhase({
|
|
20412
20837
|
hiddenCompletionExecutor: deps.hiddenCompletionExecutor,
|
|
@@ -20422,6 +20847,17 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20422
20847
|
boundaryUsage: boundaryUsageForProtectedTail,
|
|
20423
20848
|
boundaryUsageSource,
|
|
20424
20849
|
preResolvedBoundarySnapshot: triggerBoundarySnapshot,
|
|
20850
|
+
projectRecoveryRequest,
|
|
20851
|
+
resolveRecoveryBoundary: (emergencyTailScale) => host.hostProtectedTailBoundary({
|
|
20852
|
+
db,
|
|
20853
|
+
sessionId: resolvedSessionId,
|
|
20854
|
+
mode: "transform-force",
|
|
20855
|
+
contextLimit: boundaryContextLimit,
|
|
20856
|
+
executeThresholdPercentage: boundaryExecuteThreshold,
|
|
20857
|
+
usage: boundaryUsageForProtectedTail,
|
|
20858
|
+
usageSource: boundaryUsageSource,
|
|
20859
|
+
emergencyTailScale
|
|
20860
|
+
}),
|
|
20425
20861
|
client: deps.client,
|
|
20426
20862
|
db,
|
|
20427
20863
|
sessionId,
|
|
@@ -20525,44 +20961,149 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20525
20961
|
contextLimit: resolvedContextLimit,
|
|
20526
20962
|
lastResponseTime: sessionMeta.lastResponseTime
|
|
20527
20963
|
});
|
|
20528
|
-
|
|
20964
|
+
const servesHead = (!!projectIdentity || !!sessionDirectory) && (fullFeatureMode || compactionOff);
|
|
20965
|
+
const prefixBoundModel = isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID);
|
|
20966
|
+
let sizingInput;
|
|
20967
|
+
let planInput;
|
|
20529
20968
|
try {
|
|
20530
|
-
|
|
20531
|
-
|
|
20532
|
-
|
|
20533
|
-
|
|
20534
|
-
|
|
20535
|
-
|
|
20536
|
-
|
|
20969
|
+
sizingInput = pricedPassSizingInputFor(messages, {
|
|
20970
|
+
meta: sessionMeta,
|
|
20971
|
+
hardSignals: m0HardSignals,
|
|
20972
|
+
headFolds: protectionFoldWillBust,
|
|
20973
|
+
reasoning: !compactionOff && !activeThinkingPrefixHold && resolvedProviderID !== undefined && !prefixBoundModel ? {
|
|
20974
|
+
keepTokens: resolveKeepReasoningTokens(deps.keepReasoningTokens, currentModelKeyForBoundary),
|
|
20975
|
+
clearedThroughTag: sessionMeta.clearedReasoningThroughTag,
|
|
20976
|
+
proseRatio: sessionDecisionCalibration(db, sessionId).proseRatio,
|
|
20977
|
+
protectedThinkingMessages: protectedThinkingMessagesForSizing({
|
|
20978
|
+
db,
|
|
20979
|
+
sessionId,
|
|
20980
|
+
messages,
|
|
20981
|
+
activeThinkingTurn,
|
|
20982
|
+
providerID: resolvedProviderID,
|
|
20983
|
+
modelID: modelForBudget?.modelID
|
|
20984
|
+
})
|
|
20985
|
+
} : undefined
|
|
20537
20986
|
});
|
|
20987
|
+
planInput = {
|
|
20988
|
+
db,
|
|
20989
|
+
sessionId,
|
|
20990
|
+
compactionOff,
|
|
20991
|
+
fullFeatureMode,
|
|
20992
|
+
schedulerDecision,
|
|
20993
|
+
forceMaterializationPercentage,
|
|
20994
|
+
signedThinkingHold: activeThinkingPrefixHold,
|
|
20995
|
+
firstRender: servesHead && !(sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) && !hasCompleteCachedM0M1(db, sessionId),
|
|
20996
|
+
folds: protectionFoldWillBust,
|
|
20997
|
+
explicitFlush: hasPendingMaterializationOrigin(deps.pendingMaterializationSessions, sessionId, "user_flush"),
|
|
20998
|
+
materializationRequested: deps.pendingMaterializationSessions.has(sessionId) || canConsumeDeferredLate && deferredMaterializationSessions.has(sessionId),
|
|
20999
|
+
historyRebuilt: historyRebuiltThisPass || pendingCompartmentInjection?.rebuiltFromDb === true || rebuiltHistoryFromInitialPrepare,
|
|
21000
|
+
alreadyRanThisTurn: heuristicsAlreadyRanThisTurn(deps.lastHeuristicsTurnId, sessionId, currentTurnId)
|
|
21001
|
+
};
|
|
20538
21002
|
} catch (error) {
|
|
20539
|
-
|
|
20540
|
-
|
|
20541
|
-
|
|
20542
|
-
const
|
|
20543
|
-
|
|
20544
|
-
|
|
20545
|
-
|
|
20546
|
-
|
|
20547
|
-
|
|
21003
|
+
sizingInput = undefined;
|
|
21004
|
+
sessionLog2(sessionId, `transform: priced-pass sizing counts the array without the parts the pass adds: ${getErrorMessage(error)}`);
|
|
21005
|
+
}
|
|
21006
|
+
const countRequest = (plan) => {
|
|
21007
|
+
let sizingMessages = messages;
|
|
21008
|
+
if (sizingInput) {
|
|
21009
|
+
try {
|
|
21010
|
+
sizingMessages = servedRequestForSizing(sizingInput, plan);
|
|
21011
|
+
} catch (error) {
|
|
21012
|
+
sessionLog2(sessionId, `transform: priced-pass sizing counts the array without the parts the pass adds: ${getErrorMessage(error)}`);
|
|
21013
|
+
}
|
|
21014
|
+
}
|
|
21015
|
+
try {
|
|
21016
|
+
return estimateFinalWireInputTokens({
|
|
21017
|
+
messages: sizingMessages,
|
|
21018
|
+
systemPromptTokens: sessionMeta.systemPromptTokens,
|
|
21019
|
+
providerID: modelForBudget?.providerID,
|
|
21020
|
+
modelID: modelForBudget?.modelID,
|
|
21021
|
+
agentName: notificationParams.agent,
|
|
21022
|
+
sessionId
|
|
21023
|
+
});
|
|
21024
|
+
} catch (error) {
|
|
21025
|
+
sessionLog2(sessionId, `transform: wire-estimate pressure fallback unavailable: ${getErrorMessage(error)}`);
|
|
21026
|
+
return;
|
|
21027
|
+
}
|
|
21028
|
+
};
|
|
21029
|
+
const usageBeforeSizing = contextUsage;
|
|
21030
|
+
const readingFrom = (pressureEstimate) => {
|
|
21031
|
+
const countPercentage = pressureEstimate?.pressureTokens !== undefined && Number.isFinite(pressureEstimate.pressureTokens) && typeof localReadingWindow === "number" && localReadingWindow > 0 ? pressureEstimate.pressureTokens / localReadingWindow * 100 : 0;
|
|
21032
|
+
const grewPastSavedReading = savedProviderReading !== null && countPercentage >= 95 && countPercentage > savedProviderReading.percentage;
|
|
21033
|
+
const unchanged = {
|
|
21034
|
+
source: "none",
|
|
21035
|
+
usage: usageBeforeSizing,
|
|
21036
|
+
fromEstimate: hostOverWindow,
|
|
21037
|
+
countPercentage,
|
|
21038
|
+
grewPastSavedReading,
|
|
21039
|
+
pressureEstimate,
|
|
21040
|
+
usedProviderInput: false
|
|
20548
21041
|
};
|
|
20549
|
-
|
|
20550
|
-
|
|
20551
|
-
|
|
20552
|
-
|
|
20553
|
-
|
|
21042
|
+
if (savedProviderReading && !grewPastSavedReading) {
|
|
21043
|
+
return {
|
|
21044
|
+
...unchanged,
|
|
21045
|
+
source: "saved",
|
|
21046
|
+
usage: {
|
|
21047
|
+
inputTokens: savedProviderReading.inputTokens,
|
|
21048
|
+
percentage: Math.max(usageBeforeSizing.percentage, savedProviderReading.percentage)
|
|
21049
|
+
}
|
|
21050
|
+
};
|
|
21051
|
+
}
|
|
21052
|
+
if (!pressureEstimate)
|
|
21053
|
+
return unchanged;
|
|
21054
|
+
const usage = resolveUnknownUsageFromWireEstimate({
|
|
21055
|
+
usage: usageBeforeSizing,
|
|
20554
21056
|
pricedPass: true,
|
|
20555
21057
|
wireEstimateTokens: overflowRecoveryPass ? pressureEstimate.tokens : pressureEstimate.pressureTokens,
|
|
20556
21058
|
wireEstimateTrusted: pressureEstimate.trusted,
|
|
20557
21059
|
providerProvenInputTokens: providerProvenInputForRecovery,
|
|
20558
21060
|
providerProvenLimitTokens: providerProvenLimitForRecovery,
|
|
20559
|
-
|
|
21061
|
+
windowTokens: localReadingWindow
|
|
20560
21062
|
});
|
|
20561
|
-
if (
|
|
20562
|
-
|
|
20563
|
-
|
|
20564
|
-
|
|
21063
|
+
if (usage.inputTokens <= 0)
|
|
21064
|
+
return { ...unchanged, usage };
|
|
21065
|
+
const usedProviderInput = !pressureEstimate.trusted && providerProvenLimitForRecovery !== undefined && providerProvenInputForRecovery !== undefined && usage.inputTokens >= providerProvenInputForRecovery;
|
|
21066
|
+
return {
|
|
21067
|
+
...unchanged,
|
|
21068
|
+
source: "estimate",
|
|
21069
|
+
usage,
|
|
21070
|
+
usedProviderInput,
|
|
21071
|
+
fromEstimate: !overflowRecoveryPass && !usedProviderInput && !usagePercentageSynthetic && usage.percentage > usageBeforeSizing.percentage
|
|
21072
|
+
};
|
|
21073
|
+
};
|
|
21074
|
+
const planAt = (usage) => {
|
|
21075
|
+
if (!sizingInput || !planInput)
|
|
21076
|
+
return;
|
|
21077
|
+
try {
|
|
21078
|
+
return planPricedPass(planInput, usage);
|
|
21079
|
+
} catch (error) {
|
|
21080
|
+
sessionLog2(sessionId, `transform: priced-pass sizing counts the widest request: ${getErrorMessage(error)}`);
|
|
21081
|
+
return;
|
|
20565
21082
|
}
|
|
21083
|
+
};
|
|
21084
|
+
let plan = planAt({
|
|
21085
|
+
percentage: usageBeforeSizing.percentage,
|
|
21086
|
+
fromEstimate: hostOverWindow
|
|
21087
|
+
}) ?? WIDEST_PRICED_PASS_PLAN;
|
|
21088
|
+
let reading = readingFrom(countRequest(plan));
|
|
21089
|
+
for (let attempt = 0;sizingInput && plan !== WIDEST_PRICED_PASS_PLAN; attempt++) {
|
|
21090
|
+
const next = planAt({
|
|
21091
|
+
percentage: reading.usage.percentage,
|
|
21092
|
+
fromEstimate: reading.fromEstimate
|
|
21093
|
+
});
|
|
21094
|
+
if (next && sameSizingPlan(sizingInput, next, plan))
|
|
21095
|
+
break;
|
|
21096
|
+
plan = next && attempt === 0 ? next : WIDEST_PRICED_PASS_PLAN;
|
|
21097
|
+
reading = readingFrom(countRequest(plan));
|
|
21098
|
+
}
|
|
21099
|
+
const sizedPlan = `sizedPlan=${plan.clearsReasoning ? "clears_reasoning" : "keeps_reasoning"}${plan.editsWholePrefix ? "+covered_rows" : ""}`;
|
|
21100
|
+
contextUsage = reading.usage;
|
|
21101
|
+
if (reading.source === "saved") {
|
|
21102
|
+
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}`);
|
|
21103
|
+
} else if (reading.source === "estimate" && reading.pressureEstimate) {
|
|
21104
|
+
const pressureEstimate = reading.pressureEstimate;
|
|
21105
|
+
contextUsageFromEstimate = reading.fromEstimate;
|
|
21106
|
+
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}`);
|
|
20566
21107
|
}
|
|
20567
21108
|
}
|
|
20568
21109
|
const protectionUsableSoft = windowGeometry?.usableSoft ?? boundaryContextLimit;
|
|
@@ -20744,8 +21285,9 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20744
21285
|
logIncompleteFinalWire(finalWireEstimate, messages);
|
|
20745
21286
|
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}`);
|
|
20746
21287
|
}
|
|
21288
|
+
const recoveryAdmissionPass = emergencyRecoveryArmed && emergencyRecoveryOrigin !== null && emergencyUsagePercentage >= 95;
|
|
20747
21289
|
let servedPressureTokens;
|
|
20748
|
-
if (providerReadingMissing) {
|
|
21290
|
+
if (providerReadingMissing || recoveryAdmissionPass) {
|
|
20749
21291
|
servedPressureTokens = finalWireEstimate?.pressureTokens;
|
|
20750
21292
|
if (servedPressureTokens === undefined) {
|
|
20751
21293
|
try {
|
|
@@ -20762,12 +21304,13 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20762
21304
|
}
|
|
20763
21305
|
}
|
|
20764
21306
|
}
|
|
21307
|
+
const recoveryAdmissionTokens = recoveryAdmissionPass && servedPressureTokens !== undefined ? servedPressureTokens + recoveryHostAddedTokens : undefined;
|
|
20765
21308
|
localWireReadings.record({
|
|
20766
21309
|
sessionId,
|
|
20767
21310
|
providerReadingMissing,
|
|
20768
21311
|
modelKey: localReadingModelKey,
|
|
20769
21312
|
usableWindow: localReadingWindow,
|
|
20770
|
-
pressureTokens: servedPressureTokens
|
|
21313
|
+
pressureTokens: providerReadingMissing ? servedPressureTokens : undefined
|
|
20771
21314
|
});
|
|
20772
21315
|
if ((finalWireEstimate?.refusalGrade || finalWireEstimate?.refusalBasis === "byte-bound" && finalWireEstimate.refusalTokens !== undefined) && boundaryContextLimit > 0 && (finalWireEstimate.refusalTokens ?? finalWireEstimate.tokens) > boundaryContextLimit) {
|
|
20773
21316
|
const signedFitRetryWanted = !thinkingFitRetries.has(sessionId) && activeThinkingPrefixHold && hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID);
|
|
@@ -20822,6 +21365,21 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20822
21365
|
unmanagedOverWindowSessions.delete(sessionId);
|
|
20823
21366
|
sessionLog2(sessionId, `over-window first pass reduced: the request is about ${servedTokens} tokens (history started at ${unmanagedOverWindowPass.tokens}), under the ${unmanagedOverWindowPass.limit}-token window`);
|
|
20824
21367
|
}
|
|
21368
|
+
const currentModelKeyForRecovery = deps.getModelKey?.(sessionId);
|
|
21369
|
+
const keepRecoveryArmed = () => {
|
|
21370
|
+
if (!emergencyRecoveryArmed || emergencyRecoveryOrigin === null)
|
|
21371
|
+
return;
|
|
21372
|
+
try {
|
|
21373
|
+
if (getOverflowState(db, sessionId).needsEmergencyRecovery)
|
|
21374
|
+
return;
|
|
21375
|
+
recordOverflowDetected(db, sessionId, undefined, currentModelKeyForRecovery, emergencyRecoveryOrigin);
|
|
21376
|
+
} catch (error) {
|
|
21377
|
+
throw new EmergencyFailClosedError("Emergency recovery re-arm failed", {
|
|
21378
|
+
cause: error
|
|
21379
|
+
});
|
|
21380
|
+
}
|
|
21381
|
+
sessionLog2(sessionId, `transform: recovery was cleared during a pass that is not sent; armed again (${emergencyRecoveryOrigin}) for the next turn`);
|
|
21382
|
+
};
|
|
20825
21383
|
const timedOutHistorianFailure = compartmentPhase.historianJoinTimedOut ? historianJoinFailClosedMessage({
|
|
20826
21384
|
timedOut: true,
|
|
20827
21385
|
budgetMs: compartmentPhase.historianJoinBudgetMs,
|
|
@@ -20831,14 +21389,21 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20831
21389
|
}) : null;
|
|
20832
21390
|
if (timedOutHistorianFailure) {
|
|
20833
21391
|
sessionLog2(sessionId, `transform: ${timedOutHistorianFailure}; finalEstimate=${finalWireEstimate?.tokens ?? "unavailable"} estimateTrusted=${finalWireEstimate?.trusted ?? false} contextLimit=${boundaryContextLimit} emergencyReclaimed=${postTransformResult.emergencyReclaimedTokens}`);
|
|
21392
|
+
keepRecoveryArmed();
|
|
20834
21393
|
throw new EmergencyFailClosedError(timedOutHistorianFailure);
|
|
20835
21394
|
}
|
|
20836
21395
|
if (compartmentPhase.historianJoinTimedOut) {
|
|
20837
21396
|
sessionLog2(sessionId, `transform: proceeding after bounded historian join; trusted final-wire ${finalWireEstimate?.tokens} fits context limit ${boundaryContextLimit} after emergency reclaim=${postTransformResult.emergencyReclaimedTokens}`);
|
|
20838
21397
|
}
|
|
20839
|
-
const currentModelKeyForRecovery = deps.getModelKey?.(sessionId);
|
|
20840
21398
|
const overflowStateForFinalWire = getOverflowState(db, sessionId, currentModelKeyForRecovery);
|
|
20841
21399
|
const providerProvenLimitTokens = typeof currentModelKeyForRecovery === "string" && currentModelKeyForRecovery.length > 0 && overflowStateForFinalWire.detectedContextLimit > 0 && piModelRefToCanonical(overflowStateForFinalWire.detectedContextLimitModelKey ?? "") === piModelRefToCanonical(currentModelKeyForRecovery) ? overflowStateForFinalWire.detectedContextLimit : undefined;
|
|
21400
|
+
const recoveryWindowTokens = windowGeometry?.usableHard ?? resolvedContextLimit;
|
|
21401
|
+
const recoveryHistoryRemains = compartmentPhase.recoveryHistoryRemains;
|
|
21402
|
+
const recoveryServedRequest = recoveryAdmissionTokens !== undefined && typeof recoveryWindowTokens === "number" && recoveryWindowTokens > 0 ? {
|
|
21403
|
+
tokens: recoveryAdmissionTokens,
|
|
21404
|
+
lineTokens: recoveryAdmissionLimitTokens(recoveryWindowTokens, recoveryHistoryRemains),
|
|
21405
|
+
historyRemains: recoveryHistoryRemains
|
|
21406
|
+
} : undefined;
|
|
20842
21407
|
const emergencyFailClosed = evaluateEmergencyFailClosed({
|
|
20843
21408
|
usagePercentage: emergencyUsagePercentage,
|
|
20844
21409
|
emergencyRecoveryArmed,
|
|
@@ -20847,18 +21412,27 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20847
21412
|
finalWireEstimate,
|
|
20848
21413
|
providerProvenLimitTokens,
|
|
20849
21414
|
contextLimitTokens: boundaryContextLimit,
|
|
20850
|
-
protectedToolTokens: protectedToolTokenCount(getActiveTagsBySession2(db, sessionId), deps.protectedTools, resolveDecisionCalibration(modelForBudget?.providerID, modelForBudget?.modelID))
|
|
21415
|
+
protectedToolTokens: protectedToolTokenCount(getActiveTagsBySession2(db, sessionId), deps.protectedTools, resolveDecisionCalibration(modelForBudget?.providerID, modelForBudget?.modelID)),
|
|
21416
|
+
recoveryServedRequest
|
|
20851
21417
|
});
|
|
20852
21418
|
if (emergencyFailClosed.disarm) {
|
|
20853
21419
|
clearEmergencyRecovery(db, sessionId);
|
|
20854
21420
|
sessionLog2(sessionId, `emergency disarm: trusted final-wire ${emergencyFailClosed.disarm.finalWireTokens} under limit ${emergencyFailClosed.disarm.provenLimitTokens}`);
|
|
21421
|
+
} else if (recoveryAdmissionPass && !emergencyFailClosed.shouldAbort && recoveryServedRequest !== undefined) {
|
|
21422
|
+
clearEmergencyRecovery(db, sessionId);
|
|
21423
|
+
sessionLog2(sessionId, `transform: recovery request admitted: about ${recoveryServedRequest.tokens} tokens, within ${recoveryServedRequest.lineTokens} of ${recoveryWindowTokens}; ${emergencyRecoveryOrigin} recovery ends`);
|
|
20855
21424
|
}
|
|
20856
21425
|
if (emergencyFailClosed.shouldAbort) {
|
|
21426
|
+
keepRecoveryArmed();
|
|
20857
21427
|
if (emergencyFailClosed.refusalMessage) {
|
|
20858
21428
|
throw contextRefusalError(emergencyFailClosed.refusalMessage);
|
|
20859
21429
|
}
|
|
21430
|
+
const recoveryOverLimit = emergencyFailClosed.reason === "recovery-request-over-limit" && recoveryServedRequest !== undefined;
|
|
21431
|
+
if (recoveryOverLimit) {
|
|
21432
|
+
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`);
|
|
21433
|
+
}
|
|
20860
21434
|
try {
|
|
20861
|
-
await host.hostRefusalNotice(deps.client, sessionId, EMERGENCY_REFUSAL_NOTICE, notificationParams);
|
|
21435
|
+
await host.hostRefusalNotice(deps.client, sessionId, recoveryOverLimit ? recoveryRefusalNotice(recoveryServedRequest.historyRemains) : EMERGENCY_REFUSAL_NOTICE, notificationParams);
|
|
20862
21436
|
} catch (error) {
|
|
20863
21437
|
throw new EmergencyFailClosedError("Emergency recovery notification failed", {
|
|
20864
21438
|
cause: error
|
|
@@ -24398,7 +24972,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
24398
24972
|
return { count: buildCompartmentCount(db, sessionId, moduleStatus) };
|
|
24399
24973
|
});
|
|
24400
24974
|
const buildManagedCtx = async (db) => {
|
|
24401
|
-
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-
|
|
24975
|
+
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-b5cgrtp8.js"));
|
|
24402
24976
|
const { resolveHistorianModel } = await importPluginModule(() => import("./model-resolution-280gmqvd.js"));
|
|
24403
24977
|
const { userObservationCollectionEnabled, userObservationsRequested } = await importPluginModule(() => import("./task-config-7md27rx8.js"));
|
|
24404
24978
|
const DEFAULT_HISTORIAN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
@@ -24450,8 +25024,8 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
24450
25024
|
const db = readDatabase();
|
|
24451
25025
|
if (!db)
|
|
24452
25026
|
return { ok: false, error: "db unavailable" };
|
|
24453
|
-
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-
|
|
24454
|
-
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-
|
|
25027
|
+
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-7y8smqqp.js"));
|
|
25028
|
+
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-na3q825m.js"));
|
|
24455
25029
|
log2(`[rpc] recomp requested for session ${sessionId}`);
|
|
24456
25030
|
if (!args.client && !args.hiddenCompletionExecutor) {
|
|
24457
25031
|
return {
|
|
@@ -24535,7 +25109,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
24535
25109
|
const db = readDatabase();
|
|
24536
25110
|
if (!db)
|
|
24537
25111
|
return { ok: false, error: "db unavailable" };
|
|
24538
|
-
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-
|
|
25112
|
+
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-k7m16xze.js"));
|
|
24539
25113
|
const model = liveSessionState.liveModelBySession.get(sessionId);
|
|
24540
25114
|
const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
|
|
24541
25115
|
const ctx = {
|
|
@@ -25289,9 +25863,9 @@ var FULL_PARAMETER_DESCRIPTIONS = {
|
|
|
25289
25863
|
},
|
|
25290
25864
|
ctx_memory: {
|
|
25291
25865
|
action: "write | update | archive | merge | get",
|
|
25292
|
-
content: "The memory text — one standalone fact (write, update, merge).",
|
|
25293
|
-
category: "Kind of fact
|
|
25294
|
-
ids: "Memory ids from <project-memory>: one for update, one or more for archive, two or more for merge, 1–20 for get.",
|
|
25866
|
+
content: "The memory text — one standalone fact (write, update, merge). Archive and get take an empty string.",
|
|
25867
|
+
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.",
|
|
25868
|
+
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.",
|
|
25295
25869
|
reason: "Why it is being archived (optional)."
|
|
25296
25870
|
},
|
|
25297
25871
|
ctx_search: {
|
|
@@ -25324,9 +25898,9 @@ var LIGHT_PARAMETER_DESCRIPTIONS = {
|
|
|
25324
25898
|
},
|
|
25325
25899
|
ctx_memory: {
|
|
25326
25900
|
action: "write | update | archive | merge | get",
|
|
25327
|
-
content: "One standalone fact (write, update, merge).",
|
|
25328
|
-
category: "Kind of fact (
|
|
25329
|
-
ids: "Ids from <project-memory>: one for update, 1+ for archive, 2+ for merge, 1–20 for get.",
|
|
25901
|
+
content: "One standalone fact (write, update, merge). Archive and get: empty string.",
|
|
25902
|
+
category: "Kind of fact (write; on update/merge pass the current category to keep it). Archive and get ignore it.",
|
|
25903
|
+
ids: "Ids from <project-memory>: one for update, 1+ for archive, 2+ for merge, 1–20 for get. Write: empty list.",
|
|
25330
25904
|
reason: "Why it is archived (optional)."
|
|
25331
25905
|
},
|
|
25332
25906
|
ctx_search: {
|
|
@@ -25673,59 +26247,194 @@ var changed = "The Code Mode tool catalog has changed.";
|
|
|
25673
26247
|
var replacement = `${changed} This catalog supersedes the previous Code Mode tool catalog.`;
|
|
25674
26248
|
var codeMode = "core/codemode";
|
|
25675
26249
|
var mcp = "core/mcp-guidance";
|
|
26250
|
+
var date = "core/date";
|
|
26251
|
+
var noCodeModeTools = "No Code Mode tools are currently available. Later Code Mode catalog updates may add or remove tools. Do not call `execute` unless there is at least one available Code Mode tool.";
|
|
26252
|
+
var codeModeRemoved = "Code Mode tools are no longer available. Do not use any previously listed Code Mode tools.";
|
|
26253
|
+
var catalogHeadings = ["## Available tools", "## Code Mode tools (call only inside `execute`)"];
|
|
25676
26254
|
var mcpReplacement = "The available MCP server instructions have changed. This list supersedes the previous one.";
|
|
25677
|
-
var
|
|
25678
|
-
|
|
25679
|
-
|
|
25680
|
-
|
|
25681
|
-
|
|
25682
|
-
|
|
25683
|
-
|
|
25684
|
-
|
|
25685
|
-
|
|
25686
|
-
|
|
25687
|
-
|
|
26255
|
+
var mcpRemoved = "MCP server instructions are no longer available.";
|
|
26256
|
+
var mcpAdded = "New MCP server instructions are available in addition to those previously listed:";
|
|
26257
|
+
var mcpChanged = "The following MCP server instructions have changed. Each entry replaces the previously listed server with the same name:";
|
|
26258
|
+
var mcpGone = "Instructions for the following MCP servers are no longer available: ";
|
|
26259
|
+
var dateLine = /^Today's date(?: is now)?: (?:Sun|Mon|Tue|Wed|Thu|Fri|Sat) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{2} \d{4}$/;
|
|
26260
|
+
var mentions = (part) => part.full ? [] : [...part.entries ?? [], ...part.removed ?? []];
|
|
26261
|
+
function codeModePart(text) {
|
|
26262
|
+
if (text === noCodeModeTools || text === codeModeRemoved || text.startsWith(`# Code Mode
|
|
26263
|
+
`))
|
|
26264
|
+
return { full: true };
|
|
26265
|
+
if (text.startsWith(`${replacement}
|
|
25688
26266
|
|
|
25689
26267
|
`)) {
|
|
25690
|
-
|
|
25691
|
-
|
|
25692
|
-
`)
|
|
25693
|
-
|
|
26268
|
+
const rendered = text.slice(replacement.length + 2);
|
|
26269
|
+
return rendered === noCodeModeTools || rendered.startsWith(`# Code Mode
|
|
26270
|
+
`) ? { full: true } : undefined;
|
|
26271
|
+
}
|
|
26272
|
+
return text.startsWith(`${changed}
|
|
26273
|
+
|
|
26274
|
+
`) ? { full: false } : undefined;
|
|
26275
|
+
}
|
|
26276
|
+
function startsWithFullCatalog(text) {
|
|
26277
|
+
const begins = (whole) => text === whole || text.startsWith(`${whole}
|
|
26278
|
+
|
|
26279
|
+
`);
|
|
26280
|
+
return text.startsWith(`# Code Mode
|
|
26281
|
+
`) || text.startsWith(`${replacement}
|
|
26282
|
+
|
|
26283
|
+
# Code Mode
|
|
26284
|
+
`) || begins(noCodeModeTools) || begins(`${replacement}
|
|
26285
|
+
|
|
26286
|
+
${noCodeModeTools}`) || begins(codeModeRemoved);
|
|
26287
|
+
}
|
|
26288
|
+
function wholeCatalog(text) {
|
|
26289
|
+
if (text === codeModeRemoved)
|
|
26290
|
+
return true;
|
|
26291
|
+
const rendered = text.startsWith(`${replacement}
|
|
26292
|
+
|
|
26293
|
+
`) ? text.slice(replacement.length + 2) : text;
|
|
26294
|
+
if (rendered === noCodeModeTools)
|
|
26295
|
+
return true;
|
|
26296
|
+
if (!rendered.startsWith(`# Code Mode
|
|
26297
|
+
`))
|
|
26298
|
+
return false;
|
|
26299
|
+
const ends = catalogHeadings.map((heading) => {
|
|
26300
|
+
const at = rendered.indexOf(`
|
|
26301
|
+
|
|
26302
|
+
${heading}
|
|
26303
|
+
|
|
26304
|
+
`);
|
|
26305
|
+
return at < 0 ? undefined : at + heading.length + 4;
|
|
26306
|
+
}).filter((end) => end !== undefined);
|
|
26307
|
+
return ends.length > 0 && !rendered.slice(Math.min(...ends)).includes(`
|
|
26308
|
+
|
|
26309
|
+
`);
|
|
26310
|
+
}
|
|
26311
|
+
function serverEntries(lines, start) {
|
|
26312
|
+
const names = [];
|
|
26313
|
+
let index = start;
|
|
26314
|
+
for (;; ) {
|
|
26315
|
+
const open = /^ {2}<server name="(.*)">$/.exec(lines[index] ?? "");
|
|
26316
|
+
if (!open)
|
|
26317
|
+
return { names, next: index };
|
|
26318
|
+
let end = index + 1;
|
|
26319
|
+
while (lines[end]?.startsWith(" "))
|
|
26320
|
+
end++;
|
|
26321
|
+
if (end === index + 1 || lines[end] !== " </server>")
|
|
25694
26322
|
return;
|
|
25695
|
-
|
|
25696
|
-
|
|
25697
|
-
return "delta";
|
|
25698
|
-
if (text.startsWith(`# Code Mode
|
|
25699
|
-
`) || text.startsWith("No Code Mode tools are currently available."))
|
|
25700
|
-
return "full";
|
|
25701
|
-
}
|
|
25702
|
-
if (source === mcp) {
|
|
25703
|
-
if (mcpDeltas.some(starts))
|
|
25704
|
-
return "delta";
|
|
25705
|
-
if ((starts(`${mcpReplacement}
|
|
25706
|
-
<mcp_instructions>
|
|
25707
|
-
`) || starts(`<mcp_instructions>
|
|
25708
|
-
`)) && text.includes("</mcp_instructions>"))
|
|
25709
|
-
return "full";
|
|
26323
|
+
names.push(open[1]);
|
|
26324
|
+
index = end + 1;
|
|
25710
26325
|
}
|
|
25711
|
-
|
|
26326
|
+
}
|
|
26327
|
+
function mcpPart(text) {
|
|
26328
|
+
if (text === mcpRemoved)
|
|
26329
|
+
return { full: true };
|
|
26330
|
+
const lines = text.split(`
|
|
26331
|
+
`);
|
|
26332
|
+
const listStart = lines[0] === mcpReplacement ? 1 : 0;
|
|
26333
|
+
if (lines[listStart] === "<mcp_instructions>") {
|
|
26334
|
+
const entries = serverEntries(lines, listStart + 1);
|
|
26335
|
+
return entries && entries.next === lines.length - 1 && lines[entries.next] === "</mcp_instructions>" ? { full: true, entries: entries.names } : undefined;
|
|
26336
|
+
}
|
|
26337
|
+
if (listStart > 0)
|
|
26338
|
+
return;
|
|
26339
|
+
const entries = [];
|
|
26340
|
+
let removed;
|
|
26341
|
+
let index = 0;
|
|
26342
|
+
for (const header of [mcpAdded, mcpChanged]) {
|
|
26343
|
+
if (lines[index] !== header)
|
|
26344
|
+
continue;
|
|
26345
|
+
const section = serverEntries(lines, index + 1);
|
|
26346
|
+
if (!section || section.names.length === 0)
|
|
26347
|
+
return;
|
|
26348
|
+
entries.push(...section.names);
|
|
26349
|
+
index = section.next;
|
|
26350
|
+
}
|
|
26351
|
+
const gone = lines[index];
|
|
26352
|
+
if (gone?.startsWith(mcpGone) && gone.endsWith(".") && gone.length > mcpGone.length + 1) {
|
|
26353
|
+
removed = gone.slice(mcpGone.length, -1).split(", ");
|
|
26354
|
+
index++;
|
|
26355
|
+
}
|
|
26356
|
+
return index === lines.length && (entries.length > 0 || removed) ? { full: false, entries, ...removed ? { removed } : {} } : undefined;
|
|
26357
|
+
}
|
|
26358
|
+
var datePart = (text) => dateLine.test(text) ? { full: true } : undefined;
|
|
26359
|
+
var parsers = {
|
|
26360
|
+
[codeMode]: codeModePart,
|
|
26361
|
+
[mcp]: mcpPart,
|
|
26362
|
+
[date]: datePart
|
|
26363
|
+
};
|
|
26364
|
+
function splitRow(text, sources) {
|
|
26365
|
+
const parts = sources.map(() => {
|
|
26366
|
+
return;
|
|
26367
|
+
});
|
|
26368
|
+
let rest = text;
|
|
26369
|
+
let index = sources.length - 1;
|
|
26370
|
+
for (;index > 0; index--) {
|
|
26371
|
+
const source = sources[index];
|
|
26372
|
+
const cut = rest.lastIndexOf(`
|
|
26373
|
+
|
|
26374
|
+
`);
|
|
26375
|
+
const part = source === codeMode || cut < 0 ? undefined : parsers[source]?.(rest.slice(cut + 2));
|
|
26376
|
+
if (!part)
|
|
26377
|
+
break;
|
|
26378
|
+
parts[index] = part;
|
|
26379
|
+
rest = rest.slice(0, cut);
|
|
26380
|
+
}
|
|
26381
|
+
if (index === 0)
|
|
26382
|
+
parts[0] = parsers[sources[0]]?.(rest);
|
|
26383
|
+
else if (sources[0] === codeMode && startsWithFullCatalog(text))
|
|
26384
|
+
parts[0] = { full: true };
|
|
26385
|
+
return parts;
|
|
26386
|
+
}
|
|
26387
|
+
function rowParts(data) {
|
|
26388
|
+
const text = data.text ?? "";
|
|
26389
|
+
const metadata = data.metadata;
|
|
26390
|
+
if (typeof metadata === "object" && metadata !== null && "instructionSources" in metadata) {
|
|
26391
|
+
const keys = metadata.instructionSources;
|
|
26392
|
+
const sources = Array.isArray(keys) && keys.length > 0 && keys.every((key) => typeof key === "string") && new Set(keys).size === keys.length ? keys : [];
|
|
26393
|
+
return { sources, parts: splitRow(text, sources) };
|
|
26394
|
+
}
|
|
26395
|
+
const cut = text.lastIndexOf(`
|
|
26396
|
+
|
|
26397
|
+
`);
|
|
26398
|
+
const guidance = cut < 0 ? undefined : mcpPart(text.slice(cut + 2));
|
|
26399
|
+
if (guidance && wholeCatalog(text.slice(0, cut)))
|
|
26400
|
+
return { sources: [codeMode, mcp], parts: [{ full: true }, guidance] };
|
|
26401
|
+
if (wholeCatalog(text))
|
|
26402
|
+
return { sources: [codeMode], parts: [{ full: true }] };
|
|
26403
|
+
const alone = mcpPart(text);
|
|
26404
|
+
return alone ? { sources: [mcp], parts: [alone] } : { sources: [], parts: [] };
|
|
26405
|
+
}
|
|
26406
|
+
function joinedRuns(names) {
|
|
26407
|
+
const runs = [];
|
|
26408
|
+
for (let start = 0;start < names.length; start++)
|
|
26409
|
+
for (let end = start + 2;end <= names.length; end++)
|
|
26410
|
+
runs.push(names.slice(start, end).join(", "));
|
|
26411
|
+
return runs;
|
|
25712
26412
|
}
|
|
25713
26413
|
function supersededInstructionIDs(rows) {
|
|
25714
|
-
const
|
|
26414
|
+
const parsed = rows.map((row) => rowParts(row.data));
|
|
26415
|
+
const named = new Set(parsed.flatMap(({ parts }) => parts.flatMap((part) => part?.entries ?? [])));
|
|
26416
|
+
for (const { parts } of parsed)
|
|
26417
|
+
parts.forEach((part, i) => {
|
|
26418
|
+
if (part?.removed && !(part.removed.every((name) => named.has(name)) && !joinedRuns(part.removed).some((name) => named.has(name))))
|
|
26419
|
+
parts[i] = undefined;
|
|
26420
|
+
});
|
|
26421
|
+
const restated = new Set;
|
|
26422
|
+
const mentioned = new Set;
|
|
25715
26423
|
const retired = new Set;
|
|
25716
26424
|
for (let index = rows.length - 1;index >= 0; index--) {
|
|
25717
|
-
const
|
|
25718
|
-
|
|
25719
|
-
|
|
25720
|
-
|
|
25721
|
-
|
|
25722
|
-
|
|
25723
|
-
|
|
25724
|
-
|
|
25725
|
-
|
|
25726
|
-
|
|
25727
|
-
|
|
25728
|
-
|
|
26425
|
+
const { sources, parts } = parsed[index];
|
|
26426
|
+
if (sources.length > 0 && parts.every((part, i) => {
|
|
26427
|
+
if (part === undefined)
|
|
26428
|
+
return false;
|
|
26429
|
+
const servers = mentions(part);
|
|
26430
|
+
return restated.has(sources[i]) || servers.length > 0 && servers.every((server) => mentioned.has(server));
|
|
26431
|
+
}))
|
|
26432
|
+
retired.add(rows[index].id);
|
|
26433
|
+
parts.forEach((part, i) => {
|
|
26434
|
+
if (part?.full)
|
|
26435
|
+
restated.add(sources[i]);
|
|
26436
|
+
for (const server of part ? mentions(part) : [])
|
|
26437
|
+
mentioned.add(server);
|
|
25729
26438
|
});
|
|
25730
26439
|
}
|
|
25731
26440
|
return retired;
|
|
@@ -25733,6 +26442,7 @@ function supersededInstructionIDs(rows) {
|
|
|
25733
26442
|
|
|
25734
26443
|
// src/v2/fold/instruction-supersession.ts
|
|
25735
26444
|
var namespace = "instructionSupersession";
|
|
26445
|
+
var coveredNamespace = "coveredInstructionSupersession";
|
|
25736
26446
|
function decode(value) {
|
|
25737
26447
|
if (value === undefined)
|
|
25738
26448
|
return new Set;
|
|
@@ -25740,32 +26450,44 @@ function decode(value) {
|
|
|
25740
26450
|
throw new Error("Invalid instruction supersession replay state");
|
|
25741
26451
|
return new Set(value);
|
|
25742
26452
|
}
|
|
26453
|
+
var coveredOn = (value) => typeof value === "object" && value !== null && value.on === true;
|
|
25743
26454
|
function retiredLiveInstructionIDs(db, sessionID) {
|
|
25744
26455
|
return decode(readReplayEnvelope(db, sessionID)[namespace]);
|
|
25745
26456
|
}
|
|
25746
|
-
function
|
|
25747
|
-
|
|
26457
|
+
function coveredInstructionSupersessionOn(db, sessionID) {
|
|
26458
|
+
return coveredOn(readReplayEnvelope(db, sessionID)[coveredNamespace]);
|
|
26459
|
+
}
|
|
26460
|
+
var coveredSupersessionEnabled = true;
|
|
26461
|
+
function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new Set, covered = []) {
|
|
26462
|
+
const instructionRows = (list) => list.flatMap((message) => {
|
|
25748
26463
|
const row = hostInstructionRow(message.info);
|
|
25749
26464
|
return row ? [{ message, row }] : [];
|
|
25750
26465
|
});
|
|
26466
|
+
const coveredRows = coveredSupersessionEnabled ? instructionRows(covered) : [];
|
|
26467
|
+
const rows = [...coveredRows, ...instructionRows(messages)];
|
|
26468
|
+
const coveredMessages = new Set(coveredRows.map(({ message }) => message));
|
|
25751
26469
|
const retired = rows.length ? retiredLiveInstructionIDs(db, sessionID) : new Set;
|
|
26470
|
+
const coveredFollowed = rows.length > 0 && (coveredRows.length > 0 || permitted) && coveredInstructionSupersessionOn(db, sessionID);
|
|
26471
|
+
const switchCovered = permitted && rows.length > 0 && !coveredFollowed && coveredSupersessionEnabled;
|
|
25752
26472
|
const selected = permitted ? supersededInstructionIDs(rows.map(({ row }) => row)) : new Set;
|
|
25753
26473
|
const newlyRetired = new Set([...selected].filter((id) => !retired.has(id)));
|
|
25754
26474
|
const omitted = new Set([...retired, ...newlyRetired]);
|
|
26475
|
+
const omits = (message, id) => omitted.has(id) && (!coveredMessages.has(message) || coveredFollowed || switchCovered);
|
|
25755
26476
|
const edits = [];
|
|
25756
26477
|
for (const { message, row } of rows) {
|
|
25757
|
-
if (!
|
|
26478
|
+
if (!omits(message, row.id))
|
|
25758
26479
|
continue;
|
|
25759
|
-
|
|
26480
|
+
const firstApplication = newlyRetired.has(row.id) || coveredMessages.has(message) && switchCovered;
|
|
26481
|
+
if (firstApplication && message.parts.length > 0)
|
|
25760
26482
|
edits.push(message);
|
|
25761
26483
|
message.parts = [];
|
|
25762
26484
|
}
|
|
25763
26485
|
return {
|
|
25764
26486
|
edits,
|
|
25765
26487
|
commit() {
|
|
25766
|
-
if (newlyRetired.size > 0 && !updateReplayDocument(db, sessionID, (doc) => {
|
|
26488
|
+
if ((newlyRetired.size > 0 || switchCovered) && !updateReplayDocument(db, sessionID, (doc) => {
|
|
25767
26489
|
const current = decode(doc[namespace]);
|
|
25768
|
-
if ([...newlyRetired].every((id) => current.has(id)))
|
|
26490
|
+
if ([...newlyRetired].every((id) => current.has(id)) && (!switchCovered || coveredOn(doc[coveredNamespace])))
|
|
25769
26491
|
return false;
|
|
25770
26492
|
for (const id of folded)
|
|
25771
26493
|
current.delete(id);
|
|
@@ -25773,11 +26495,13 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
|
|
|
25773
26495
|
current.add(id);
|
|
25774
26496
|
doc.version = 2;
|
|
25775
26497
|
doc[namespace] = [...current];
|
|
26498
|
+
if (switchCovered)
|
|
26499
|
+
doc[coveredNamespace] = { on: true };
|
|
25776
26500
|
return true;
|
|
25777
26501
|
}))
|
|
25778
26502
|
throw new Error("Cannot persist instruction supersession");
|
|
25779
26503
|
for (const { message, row } of rows) {
|
|
25780
|
-
if (
|
|
26504
|
+
if (omits(message, row.id))
|
|
25781
26505
|
markRetiredInstructionRow(message.info);
|
|
25782
26506
|
}
|
|
25783
26507
|
}
|
|
@@ -25816,6 +26540,35 @@ import { randomUUID as randomUUID4 } from "node:crypto";
|
|
|
25816
26540
|
|
|
25817
26541
|
// src/v2/fold/owner.ts
|
|
25818
26542
|
import { createHash as createHash7 } from "node:crypto";
|
|
26543
|
+
|
|
26544
|
+
// src/v2/fold/summary.ts
|
|
26545
|
+
var RAW_HISTORY_ACCOUNT = "Magic Context retains the conversation as raw messages; no summarized history is available yet.";
|
|
26546
|
+
var CHECKPOINT_NOTE = "Magic Context added a compaction marker here to keep this OpenCode session fast. Your history is unchanged: Magic Context still keeps it and sends it to the model.";
|
|
26547
|
+
var CHECKPOINT_NOTES = Object.freeze([CHECKPOINT_NOTE]);
|
|
26548
|
+
function isCheckpointNote(value) {
|
|
26549
|
+
return typeof value === "string" && CHECKPOINT_NOTES.includes(value);
|
|
26550
|
+
}
|
|
26551
|
+
function hasFoldSummary(summary) {
|
|
26552
|
+
return typeof summary === "string" && summary.replace(/<[^>]*>/g, "").trim().length > 0;
|
|
26553
|
+
}
|
|
26554
|
+
function isHistoryHead(value) {
|
|
26555
|
+
return value !== RAW_HISTORY_ACCOUNT && !isCheckpointNote(value) && hasFoldSummary(value);
|
|
26556
|
+
}
|
|
26557
|
+
function withRecordedHead(checkpoint, submitted, head) {
|
|
26558
|
+
if (!isCheckpointNote(submitted) || head === undefined || head === submitted)
|
|
26559
|
+
return checkpoint;
|
|
26560
|
+
const copy = structuredClone(checkpoint);
|
|
26561
|
+
for (const part of copy.content)
|
|
26562
|
+
if (part.type === "text" && typeof part.text === "string")
|
|
26563
|
+
part.text = part.text.replace(`<summary>
|
|
26564
|
+
${submitted}
|
|
26565
|
+
</summary>`, () => `<summary>
|
|
26566
|
+
${head}
|
|
26567
|
+
</summary>`);
|
|
26568
|
+
return copy;
|
|
26569
|
+
}
|
|
26570
|
+
|
|
26571
|
+
// src/v2/fold/owner.ts
|
|
25819
26572
|
var foldDigest = (value) => createHash7("sha256").update(value).digest("hex");
|
|
25820
26573
|
|
|
25821
26574
|
class FoldOwner {
|
|
@@ -25845,14 +26598,23 @@ class FoldOwner {
|
|
|
25845
26598
|
return this.serial(args.sessionID, async () => {
|
|
25846
26599
|
const previous = await this.read(args.sessionID);
|
|
25847
26600
|
const same = previous && (args.runningCut !== undefined ? previous.cutSeq === args.runningCut : previous.cutSeq === undefined && previous.watermark === args.watermark);
|
|
25848
|
-
if (same)
|
|
26601
|
+
if (same) {
|
|
26602
|
+
const id = args.checkpointID;
|
|
26603
|
+
if (id !== undefined && !previous.answered?.includes(id)) {
|
|
26604
|
+
previous.answered = [...previous.answered ?? [], id].slice(-8);
|
|
26605
|
+
await this.storage.set(this.key(args.sessionID), previous);
|
|
26606
|
+
}
|
|
25849
26607
|
return previous;
|
|
25850
|
-
|
|
26608
|
+
}
|
|
26609
|
+
const head = args.materialize();
|
|
26610
|
+
const submitted = args.checkpointText ?? head;
|
|
25851
26611
|
const next = {
|
|
25852
26612
|
watermark: args.watermark,
|
|
25853
26613
|
cutSeq: args.runningCut,
|
|
25854
26614
|
submitted,
|
|
25855
|
-
submittedSha: foldDigest(submitted)
|
|
26615
|
+
submittedSha: foldDigest(submitted),
|
|
26616
|
+
...submitted === head ? {} : { head },
|
|
26617
|
+
...args.checkpointID === undefined ? {} : { answered: [args.checkpointID] }
|
|
25856
26618
|
};
|
|
25857
26619
|
await this.storage.set(this.key(args.sessionID), next);
|
|
25858
26620
|
return next;
|
|
@@ -25861,8 +26623,12 @@ class FoldOwner {
|
|
|
25861
26623
|
async observe(args) {
|
|
25862
26624
|
return this.serial(args.sessionID, async () => {
|
|
25863
26625
|
let state = await this.read(args.sessionID);
|
|
25864
|
-
|
|
26626
|
+
let carriedHead;
|
|
26627
|
+
if (state && (state.rendered ? state.rendered.id !== args.rendered.id : state.answered !== undefined && !state.answered.includes(args.rendered.id ?? ""))) {
|
|
26628
|
+
if (isCheckpointNote(args.summary) && state.answered?.includes(args.rendered.id ?? ""))
|
|
26629
|
+
carriedHead = state.head;
|
|
25865
26630
|
state = undefined;
|
|
26631
|
+
}
|
|
25866
26632
|
let changed = !state;
|
|
25867
26633
|
const observedSha = foldDigest(JSON.stringify(args.rendered));
|
|
25868
26634
|
const rendered = structuredClone(args.rendered);
|
|
@@ -25875,6 +26641,7 @@ class FoldOwner {
|
|
|
25875
26641
|
watermark: args.cutSeq,
|
|
25876
26642
|
submitted: args.summary,
|
|
25877
26643
|
submittedSha: foldDigest(args.summary),
|
|
26644
|
+
...carriedHead === undefined ? {} : { head: carriedHead },
|
|
25878
26645
|
reason: "boot_recovery"
|
|
25879
26646
|
};
|
|
25880
26647
|
}
|
|
@@ -27703,6 +28470,7 @@ ${cached}
|
|
|
27703
28470
|
}
|
|
27704
28471
|
async supplyHeld(args) {
|
|
27705
28472
|
const { draft, reader, summary } = args;
|
|
28473
|
+
const stored = args.checkpointText ?? summary;
|
|
27706
28474
|
if (this.options.protocol === 3) {
|
|
27707
28475
|
if (this.unprovenControls.has(draft.sessionID))
|
|
27708
28476
|
return false;
|
|
@@ -27733,7 +28501,7 @@ ${cached}
|
|
|
27733
28501
|
source: this.storage.sourceID,
|
|
27734
28502
|
sessionID: draft.sessionID,
|
|
27735
28503
|
admissionID: running.id,
|
|
27736
|
-
summary
|
|
28504
|
+
summary: stored
|
|
27737
28505
|
}));
|
|
27738
28506
|
const value = {
|
|
27739
28507
|
version: 3,
|
|
@@ -27742,7 +28510,7 @@ ${cached}
|
|
|
27742
28510
|
sourceDigest: foldDigest(reader.hostIdentity()),
|
|
27743
28511
|
sessionID: draft.sessionID,
|
|
27744
28512
|
admissionID: running.id,
|
|
27745
|
-
summaryDigest: foldDigest(
|
|
28513
|
+
summaryDigest: foldDigest(stored),
|
|
27746
28514
|
historyDigest: historyDigest(reader, draft.sessionID, running.seq - 1, replay.floor.after)
|
|
27747
28515
|
}
|
|
27748
28516
|
};
|
|
@@ -27794,7 +28562,7 @@ ${cached}
|
|
|
27794
28562
|
source: this.storage.sourceID,
|
|
27795
28563
|
sessionID: draft.sessionID,
|
|
27796
28564
|
admissionID: running.id,
|
|
27797
|
-
summary
|
|
28565
|
+
summary: stored
|
|
27798
28566
|
}));
|
|
27799
28567
|
return true;
|
|
27800
28568
|
}
|
|
@@ -27830,7 +28598,7 @@ ${cached}
|
|
|
27830
28598
|
source: this.storage.sourceID,
|
|
27831
28599
|
sessionID: draft.sessionID,
|
|
27832
28600
|
admissionID: id,
|
|
27833
|
-
summary
|
|
28601
|
+
summary: stored
|
|
27834
28602
|
};
|
|
27835
28603
|
await this.storage.supply(draft.sessionID, id, JSON.stringify(snapshot));
|
|
27836
28604
|
if (this.admissions) {
|
|
@@ -27838,7 +28606,7 @@ ${cached}
|
|
|
27838
28606
|
sourceDigest: foldDigest(reader.hostIdentity()),
|
|
27839
28607
|
sessionID: draft.sessionID,
|
|
27840
28608
|
admissionID: id,
|
|
27841
|
-
summaryDigest: foldDigest(
|
|
28609
|
+
summaryDigest: foldDigest(stored),
|
|
27842
28610
|
historyDigest: historyDigest(reader, draft.sessionID, (running?.seq ?? through) - 1)
|
|
27843
28611
|
};
|
|
27844
28612
|
const payload = JSON.stringify(provenance);
|
|
@@ -27929,7 +28697,7 @@ ${cached}
|
|
|
27929
28697
|
await this.storage.saveTail(sessionID, JSON.stringify({
|
|
27930
28698
|
model,
|
|
27931
28699
|
sourceSeq: through,
|
|
27932
|
-
baseline: tail?.baseline ?? cut.data.summary
|
|
28700
|
+
baseline: tail?.baseline ?? (isCheckpointNote(cut.data.summary) ? readSessionMeta(this.storage.db, sessionID).cachedM0Bytes?.toString("utf8") : cut.data.summary)
|
|
27933
28701
|
}), []);
|
|
27934
28702
|
this.loaded.set(sessionID, through);
|
|
27935
28703
|
this.dirty.delete(sessionID);
|
|
@@ -28096,12 +28864,6 @@ class HostFoldPolicy {
|
|
|
28096
28864
|
}
|
|
28097
28865
|
}
|
|
28098
28866
|
|
|
28099
|
-
// src/v2/fold/summary.ts
|
|
28100
|
-
var RAW_HISTORY_ACCOUNT = "Magic Context retains the conversation as raw messages; no summarized history is available yet.";
|
|
28101
|
-
function hasFoldSummary(summary) {
|
|
28102
|
-
return typeof summary === "string" && summary.replace(/<[^>]*>/g, "").trim().length > 0;
|
|
28103
|
-
}
|
|
28104
|
-
|
|
28105
28867
|
// src/v2/fork-inheritance.ts
|
|
28106
28868
|
var RAW_TYPES = new Set(RAW_MESSAGE_TYPES2);
|
|
28107
28869
|
function forkBoundarySeq(origin, sequenceForId) {
|
|
@@ -41313,7 +42075,7 @@ var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?
|
|
|
41313
42075
|
var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
|
|
41314
42076
|
var e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
|
|
41315
42077
|
var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
|
|
41316
|
-
var
|
|
42078
|
+
var date2 = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
|
|
41317
42079
|
function timeSource(args) {
|
|
41318
42080
|
const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
|
|
41319
42081
|
const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
|
|
@@ -42198,7 +42960,7 @@ var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def
|
|
|
42198
42960
|
$ZodStringFormat.init(inst, def);
|
|
42199
42961
|
});
|
|
42200
42962
|
var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
|
|
42201
|
-
def.pattern ?? (def.pattern =
|
|
42963
|
+
def.pattern ?? (def.pattern = date2);
|
|
42202
42964
|
$ZodStringFormat.init(inst, def);
|
|
42203
42965
|
});
|
|
42204
42966
|
var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
|
|
@@ -50953,7 +51715,7 @@ var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
|
|
|
50953
51715
|
$ZodISODate.init(inst, def);
|
|
50954
51716
|
ZodStringFormat.init(inst, def);
|
|
50955
51717
|
});
|
|
50956
|
-
function
|
|
51718
|
+
function date3(params) {
|
|
50957
51719
|
return _isoDate(ZodISODate, params);
|
|
50958
51720
|
}
|
|
50959
51721
|
var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
|
|
@@ -51142,7 +51904,7 @@ var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
|
|
|
51142
51904
|
inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
|
|
51143
51905
|
inst.e164 = (params) => inst.check(_e164(ZodE164, params));
|
|
51144
51906
|
inst.datetime = (params) => inst.check(datetime2(params));
|
|
51145
|
-
inst.date = (params) => inst.check(
|
|
51907
|
+
inst.date = (params) => inst.check(date3(params));
|
|
51146
51908
|
inst.time = (params) => inst.check(time2(params));
|
|
51147
51909
|
inst.duration = (params) => inst.check(duration2(params));
|
|
51148
51910
|
});
|
|
@@ -51469,7 +52231,7 @@ var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => {
|
|
|
51469
52231
|
inst.minDate = c.minimum ? new Date(c.minimum) : null;
|
|
51470
52232
|
inst.maxDate = c.maximum ? new Date(c.maximum) : null;
|
|
51471
52233
|
});
|
|
51472
|
-
function
|
|
52234
|
+
function date4(params) {
|
|
51473
52235
|
return _date(ZodDate, params);
|
|
51474
52236
|
}
|
|
51475
52237
|
var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
|
|
@@ -52032,7 +52794,7 @@ function boolean4(params) {
|
|
|
52032
52794
|
function bigint3(params) {
|
|
52033
52795
|
return _coercedBigint(ZodBigInt, params);
|
|
52034
52796
|
}
|
|
52035
|
-
function
|
|
52797
|
+
function date5(params) {
|
|
52036
52798
|
return _coercedDate(ZodDate, params);
|
|
52037
52799
|
}
|
|
52038
52800
|
|
|
@@ -54086,10 +54848,7 @@ function createCtxSearchTool(deps) {
|
|
|
54086
54848
|
limit: normalizeLimit2(args.limit),
|
|
54087
54849
|
memoryEnabled,
|
|
54088
54850
|
embeddingEnabled,
|
|
54089
|
-
embedQuery:
|
|
54090
|
-
const result = await embedTextForProject2(projectPath, text, signal, "query");
|
|
54091
|
-
return result;
|
|
54092
|
-
},
|
|
54851
|
+
embedQuery: (text, signal) => withQueryEmbeddingDeadline((embeddingSignal) => embedTextForProject2(projectPath, text, embeddingSignal, "query"), signal),
|
|
54093
54852
|
isEmbeddingRuntimeEnabled: () => embeddingEnabled === true,
|
|
54094
54853
|
readMessages: deps.readMessages,
|
|
54095
54854
|
maxMessageOrdinal: messageOrdinalCutoff,
|
|
@@ -54459,14 +55218,14 @@ function applyCheckpointHead(draft, head) {
|
|
|
54459
55218
|
const first = draft.messages.find((message) => message.id === HEAD_IDS[0]);
|
|
54460
55219
|
const baseline = first?.content.find((part) => part.type === "text")?.text;
|
|
54461
55220
|
if (typeof baseline !== "string") {
|
|
54462
|
-
draft.messages.unshift(checkpoint);
|
|
55221
|
+
draft.messages.unshift(withRecordedHead(checkpoint, submitted, head.head));
|
|
54463
55222
|
return true;
|
|
54464
55223
|
}
|
|
54465
55224
|
for (const part of checkpoint.content)
|
|
54466
55225
|
if (part.type === "text" && typeof part.text === "string") {
|
|
54467
55226
|
part.text = part.text.replace(`<summary>
|
|
54468
55227
|
${submitted}
|
|
54469
|
-
</summary>`, `<summary>
|
|
55228
|
+
</summary>`, () => `<summary>
|
|
54470
55229
|
${baseline}
|
|
54471
55230
|
</summary>`);
|
|
54472
55231
|
}
|
|
@@ -54476,24 +55235,46 @@ ${baseline}
|
|
|
54476
55235
|
draft.messages.splice(0, draft.messages.length, checkpoint, ...draft.messages.filter((message) => message !== first));
|
|
54477
55236
|
return true;
|
|
54478
55237
|
}
|
|
55238
|
+
function servableCarrier(stored, head) {
|
|
55239
|
+
return !isCheckpointNote(stored) || head !== undefined;
|
|
55240
|
+
}
|
|
54479
55241
|
function bindKeptInstructionCoordinates(messages, incoming, reader, sessionID) {
|
|
54480
55242
|
const rows = reader.instructionRowsThrough(sessionID, reader.latestSequence(sessionID));
|
|
54481
55243
|
let previous;
|
|
54482
55244
|
let pending = [];
|
|
55245
|
+
const matches = (message, row) => message?.role === "system" && message.content.length === 1 && message.content[0]?.type === "text" && message.content[0].text === row?.data.text;
|
|
54483
55246
|
const bind = (next) => {
|
|
54484
55247
|
if (!pending.length)
|
|
54485
55248
|
return;
|
|
54486
55249
|
const candidates = rows.filter((row) => (previous === undefined || row.seq > previous) && (next === undefined || row.seq < next));
|
|
54487
55250
|
const selected = previous === undefined ? candidates.slice(-pending.length) : next === undefined ? candidates.slice(0, pending.length) : candidates;
|
|
54488
|
-
if (selected.length === pending.length && selected.every((row, index) => {
|
|
54489
|
-
const message = pending[index];
|
|
54490
|
-
return message?.role === "system" && message.content.length === 1 && message.content[0]?.type === "text" && message.content[0].text === row.data.text;
|
|
54491
|
-
})) {
|
|
55251
|
+
if (selected.length === pending.length && selected.every((row, index) => matches(pending[index], row))) {
|
|
54492
55252
|
selected.forEach((row, index) => {
|
|
54493
55253
|
const message = pending[index];
|
|
54494
55254
|
if (message)
|
|
54495
55255
|
bindNativeRowID(message, row.id, row.seq);
|
|
54496
55256
|
});
|
|
55257
|
+
} else {
|
|
55258
|
+
const earliest = [];
|
|
55259
|
+
let at = 0;
|
|
55260
|
+
for (const message of pending) {
|
|
55261
|
+
while (at < candidates.length && !matches(message, candidates[at]))
|
|
55262
|
+
at++;
|
|
55263
|
+
earliest.push(at++);
|
|
55264
|
+
}
|
|
55265
|
+
const latest = [];
|
|
55266
|
+
at = candidates.length - 1;
|
|
55267
|
+
for (let index = pending.length - 1;index >= 0; index--) {
|
|
55268
|
+
while (at >= 0 && !matches(pending[index], candidates[at]))
|
|
55269
|
+
at--;
|
|
55270
|
+
latest[index] = at--;
|
|
55271
|
+
}
|
|
55272
|
+
if (earliest.every((position) => position < candidates.length))
|
|
55273
|
+
pending.forEach((message, index) => {
|
|
55274
|
+
const row = candidates[earliest[index]];
|
|
55275
|
+
if (row && earliest[index] === latest[index])
|
|
55276
|
+
bindNativeRowID(message, row.id, row.seq);
|
|
55277
|
+
});
|
|
54497
55278
|
}
|
|
54498
55279
|
pending = [];
|
|
54499
55280
|
};
|
|
@@ -54598,6 +55379,30 @@ function estimateCheckpointRequest(draft) {
|
|
|
54598
55379
|
sessionId: draft.sessionID
|
|
54599
55380
|
});
|
|
54600
55381
|
}
|
|
55382
|
+
function estimateCheckpointFraming(draft, checkpoint, submitted) {
|
|
55383
|
+
const framing = structuredClone(checkpoint);
|
|
55384
|
+
for (const part of framing.content)
|
|
55385
|
+
if (part.type === "text" && typeof part.text === "string")
|
|
55386
|
+
part.text = part.text.replace(`<summary>
|
|
55387
|
+
${submitted}
|
|
55388
|
+
</summary>`, `<summary>
|
|
55389
|
+
|
|
55390
|
+
</summary>`);
|
|
55391
|
+
try {
|
|
55392
|
+
const estimate = estimateFinalWireInputTokens({
|
|
55393
|
+
messages: adaptPayload({ ...draft, messages: [framing] }).messages,
|
|
55394
|
+
toolDefinitionTokens: 0,
|
|
55395
|
+
systemPromptTokens: 0,
|
|
55396
|
+
providerID: draft.model.providerID,
|
|
55397
|
+
modelID: draft.model.id,
|
|
55398
|
+
agentName: draft.agent,
|
|
55399
|
+
sessionId: draft.sessionID
|
|
55400
|
+
});
|
|
55401
|
+
return estimate.pressureTokens ?? estimate.tokens;
|
|
55402
|
+
} catch {
|
|
55403
|
+
return;
|
|
55404
|
+
}
|
|
55405
|
+
}
|
|
54601
55406
|
var HIDDEN_SESSION_ERROR_GRACE_MS = 50;
|
|
54602
55407
|
var STORE_POOL_DISPOSE_WAIT_MS = 1000;
|
|
54603
55408
|
function isBlockingV2TransformError(error) {
|
|
@@ -55275,8 +56080,8 @@ async function registerContext(context) {
|
|
|
55275
56080
|
servedModuleM0Text(sessionID),
|
|
55276
56081
|
await nativeFoldReplay.baseline(sessionID),
|
|
55277
56082
|
meta.cachedM0Bytes?.toString("utf8")
|
|
55278
|
-
].find(
|
|
55279
|
-
return !meta.isSubagent &&
|
|
56083
|
+
].find(isHistoryHead);
|
|
56084
|
+
return !meta.isSubagent && isHistoryHead(summary) && nativeFoldReplay.canFold(sessionID, reader);
|
|
55280
56085
|
},
|
|
55281
56086
|
threshold: Number(process.env.MC_OC2_HOST_FOLD_ROWS ?? 1000),
|
|
55282
56087
|
log: sessionLog2
|
|
@@ -55494,12 +56299,13 @@ async function registerContext(context) {
|
|
|
55494
56299
|
const state = getOrCreateSessionMeta(storage.require(), draft.sessionID);
|
|
55495
56300
|
const staged = manual && moduleBaseline == null ? stageManualBaseline(storage.require(), draft.sessionID, () => materialize(draft)) : undefined;
|
|
55496
56301
|
const publishedHistory = Boolean(storage.require().prepare("SELECT 1 FROM compartments WHERE session_id = ? LIMIT 1").get(draft.sessionID));
|
|
56302
|
+
const owned = await folds.read(draft.sessionID);
|
|
55497
56303
|
const candidate = [
|
|
55498
56304
|
moduleBaseline,
|
|
55499
56305
|
await nativeFoldReplay.baseline(draft.sessionID),
|
|
55500
56306
|
state.cachedM0Bytes?.toString("utf8"),
|
|
55501
|
-
|
|
55502
|
-
].find((value) => value !== RAW_HISTORY_ACCOUNT && (publishedHistory && value?.includes("<session-history>") || hasFoldSummary(value)));
|
|
56307
|
+
owned?.head ?? owned?.submitted
|
|
56308
|
+
].find((value) => value !== RAW_HISTORY_ACCOUNT && !isCheckpointNote(value) && (publishedHistory && value?.includes("<session-history>") || hasFoldSummary(value)));
|
|
55503
56309
|
const manualHistory = manual && hasFoldSummary(staged?.summary ?? moduleBaseline);
|
|
55504
56310
|
const summary = manualHistory ? staged?.summary ?? candidate ?? RAW_HISTORY_ACCOUNT : candidate ?? RAW_HISTORY_ACCOUNT;
|
|
55505
56311
|
const manualReplay = manualHistory && summary ? await nativeFoldReplay.prepareManualFold(draft.sessionID, reader, staged ? staged.boundaryID : storage.require().prepare("SELECT cached_m0_last_baseline_end_message_id AS id FROM session_meta WHERE session_id = ?").get(draft.sessionID).id, summary) : undefined;
|
|
@@ -55508,6 +56314,7 @@ async function registerContext(context) {
|
|
|
55508
56314
|
reader,
|
|
55509
56315
|
previousCut: reader.latestCompaction(draft.sessionID),
|
|
55510
56316
|
summary,
|
|
56317
|
+
checkpointText: CHECKPOINT_NOTE,
|
|
55511
56318
|
manual: manualReplay ? { replay: manualReplay, commit: () => staged?.commit() } : undefined
|
|
55512
56319
|
})) {
|
|
55513
56320
|
if (manualHistory) {
|
|
@@ -55517,7 +56324,10 @@ async function registerContext(context) {
|
|
|
55517
56324
|
historyRefreshSessions.add(draft.sessionID);
|
|
55518
56325
|
requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "host_compaction");
|
|
55519
56326
|
}
|
|
55520
|
-
draft.result = {
|
|
56327
|
+
draft.result = {
|
|
56328
|
+
summary: CHECKPOINT_NOTE,
|
|
56329
|
+
metadata: { keepID: undefined }
|
|
56330
|
+
};
|
|
55521
56331
|
return;
|
|
55522
56332
|
}
|
|
55523
56333
|
if (manual)
|
|
@@ -55536,7 +56346,9 @@ async function registerContext(context) {
|
|
|
55536
56346
|
materialize: () => {
|
|
55537
56347
|
const summary = moduleBaseline ?? materialize(draft);
|
|
55538
56348
|
return hasFoldSummary(summary) ? summary : RAW_HISTORY_ACCOUNT;
|
|
55539
|
-
}
|
|
56349
|
+
},
|
|
56350
|
+
checkpointText: CHECKPOINT_NOTE,
|
|
56351
|
+
checkpointID: running?.id
|
|
55540
56352
|
});
|
|
55541
56353
|
sessionLog2(draft.sessionID, `v2 compaction hook: fired answered=true source=${source}`);
|
|
55542
56354
|
draft.result = { summary: fold.submitted, metadata: { keepID: undefined } };
|
|
@@ -55624,7 +56436,7 @@ async function registerContext(context) {
|
|
|
55624
56436
|
onPassPermission: (sessionID, permission) => {
|
|
55625
56437
|
checkpointPassPermissions.set(sessionID, permission);
|
|
55626
56438
|
},
|
|
55627
|
-
reclaimHostRows: (sessionID, messages, permitted) => reclaimInstructionRows(database, sessionID, messages, permitted, foldedInstructionIDs.get(sessionID)),
|
|
56439
|
+
reclaimHostRows: (sessionID, messages, permitted, covered) => reclaimInstructionRows(database, sessionID, messages, permitted, foldedInstructionIDs.get(sessionID), covered),
|
|
55628
56440
|
compactionOff,
|
|
55629
56441
|
storeGeneration: "v2",
|
|
55630
56442
|
normalizeRestoredAssistantText: (text, providerID) => stripCopiedTagNotation(text, providerID === "anthropic"),
|
|
@@ -55977,6 +56789,7 @@ async function registerContext(context) {
|
|
|
55977
56789
|
const reader = openStoreReader();
|
|
55978
56790
|
let checkpoint;
|
|
55979
56791
|
let submitted;
|
|
56792
|
+
let recordedHead;
|
|
55980
56793
|
let upgradeCheckpointSequence;
|
|
55981
56794
|
try {
|
|
55982
56795
|
const candidates = syntheticCandidates(context, draft.sessionID, reader.syntheticMessageIDs(draft.sessionID));
|
|
@@ -56016,9 +56829,13 @@ async function registerContext(context) {
|
|
|
56016
56829
|
requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "host_compaction");
|
|
56017
56830
|
}
|
|
56018
56831
|
});
|
|
56019
|
-
|
|
56020
|
-
|
|
56021
|
-
|
|
56832
|
+
const stored = identity.renderedSummary ?? carrier.submitted;
|
|
56833
|
+
if (servableCarrier(stored, identity.head)) {
|
|
56834
|
+
checkpoint = structuredClone(identity.rendered ?? carrier.rendered);
|
|
56835
|
+
submitted = stored;
|
|
56836
|
+
recordedHead = identity.head;
|
|
56837
|
+
upgradeCheckpointSequence = carrier.row.seq;
|
|
56838
|
+
}
|
|
56022
56839
|
}
|
|
56023
56840
|
}
|
|
56024
56841
|
let nativeRestored = localCut ? nativeFoldReplay?.legacyUpgradeInput(draft.sessionID, draft.model) : undefined;
|
|
@@ -56055,8 +56872,13 @@ async function registerContext(context) {
|
|
|
56055
56872
|
requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "host_compaction");
|
|
56056
56873
|
}
|
|
56057
56874
|
});
|
|
56058
|
-
|
|
56059
|
-
|
|
56875
|
+
const stored = identity.rendered ? identity.renderedSummary ?? identity.submitted : cut.data.summary ?? "";
|
|
56876
|
+
if (servableCarrier(stored, identity.head)) {
|
|
56877
|
+
checkpoint = structuredClone(identity.rendered ?? incoming);
|
|
56878
|
+
submitted = stored;
|
|
56879
|
+
recordedHead = identity.head;
|
|
56880
|
+
} else
|
|
56881
|
+
sessionLog2(draft.sessionID, "v2 host fold: note checkpoint without a recorded head; serving restored history");
|
|
56060
56882
|
}
|
|
56061
56883
|
draft.messages.splice(0, draft.messages.length, ...await restoreAfterCheckpoint({
|
|
56062
56884
|
db,
|
|
@@ -56096,11 +56918,15 @@ async function registerContext(context) {
|
|
|
56096
56918
|
if (stripCheckpointRecentContext(projected, submitted)) {
|
|
56097
56919
|
const estimate = estimateCheckpointRequest({
|
|
56098
56920
|
...draft,
|
|
56099
|
-
messages: [
|
|
56921
|
+
messages: [
|
|
56922
|
+
withRecordedHead(checkpoint, submitted, recordedHead),
|
|
56923
|
+
...draft.messages
|
|
56924
|
+
]
|
|
56100
56925
|
});
|
|
56101
56926
|
checkpointInputEstimates.set(draft.sessionID, {
|
|
56102
56927
|
tokens: estimate.tokens,
|
|
56103
|
-
pressureTokens: estimate.pressureTokens ?? estimate.tokens
|
|
56928
|
+
pressureTokens: estimate.pressureTokens ?? estimate.tokens,
|
|
56929
|
+
hostAddedTokens: estimateCheckpointFraming(draft, projected, submitted)
|
|
56104
56930
|
});
|
|
56105
56931
|
}
|
|
56106
56932
|
}
|
|
@@ -56146,7 +56972,11 @@ async function registerContext(context) {
|
|
|
56146
56972
|
if (db) {
|
|
56147
56973
|
await deliverPendingChannel2(context, db, draft.sessionID, channel1.get(draft.sessionID));
|
|
56148
56974
|
}
|
|
56149
|
-
const head = replayHead !== undefined ? replayHead : checkpoint && submitted !== undefined ? {
|
|
56975
|
+
const head = replayHead !== undefined ? replayHead : checkpoint && submitted !== undefined ? {
|
|
56976
|
+
checkpoint,
|
|
56977
|
+
submitted,
|
|
56978
|
+
...recordedHead === undefined ? {} : { head: recordedHead }
|
|
56979
|
+
} : null;
|
|
56150
56980
|
const servedHead = head && structuredClone(head);
|
|
56151
56981
|
const headApplied = head ? applyCheckpointHead(draft, head) : false;
|
|
56152
56982
|
if (nativeMessages && (!checkpoint || upgradeCheckpointSequence !== undefined)) {
|