@cortexkit/opencode-magic-context 0.49.45 → 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 +1 -1
- package/dist/chunk-embedding-write-worker.js +1 -1
- package/dist/{context-y85dvs6j.js → context-cb51adcz.js} +362 -103
- package/dist/{derive-budgets-htj16n4x.js → derive-budgets-nkw09vq7.js} +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/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-tvd2j34s.js → index-44pp3vrj.js} +1 -1
- package/dist/{index-xejh7cqv.js → index-55ngkbqa.js} +28 -9
- package/dist/{index-980brvjr.js → index-5jk4h64j.js} +3 -3
- package/dist/{index-dnqqqc5f.js → index-8cfnaagj.js} +10 -2
- package/dist/{index-7na94cjf.js → index-a4t7pdmm.js} +3 -3
- package/dist/{index-z8dacvkt.js → index-b0xt5qz9.js} +1 -1
- package/dist/{index-bzq05g00.js → index-etn2hmb5.js} +1 -1
- package/dist/{index-rk5hyc41.js → index-gaxktvxm.js} +2 -2
- package/dist/{index-dcdvyaeh.js → index-kevd267m.js} +3 -3
- package/dist/{index-gf1vx3bn.js → index-kw7azjmy.js} +2 -2
- package/dist/{index-jwa5t1s4.js → index-n9q8c1dr.js} +2 -2
- package/dist/{index-qdx8dq60.js → index-pwfmcg4e.js} +4 -4
- package/dist/{index-fs3zfby1.js → index-snztv1f0.js} +608 -96
- package/dist/{index-0a79y98x.js → index-tajstyw4.js} +161 -81
- package/dist/{index-gxqr0sbd.js → index-x53gnmce.js} +10 -10
- package/dist/{index-wwg1je98.js → index-xgnh498s.js} +3 -2
- package/dist/index.js +19 -19
- package/dist/{message-index-bounded-d8xt6q5c.js → message-index-bounded-3qpg8dq5.js} +3 -3
- package/dist/migration-worker.js +1 -1
- package/dist/raw-ordinal-warmup-worker.js +4 -4
- package/dist/{read-session-chunk-k3fqshw8.js → read-session-chunk-7h9f32sz.js} +2 -2
- package/dist/{recomp-orchestrator-y75thsc3.js → recomp-orchestrator-qnactdw7.js} +8 -8
- package/dist/{render-3psbedzk.js → render-da999saz.js} +6 -6
- package/dist/{search-hd16c8gq.js → search-0a3hh5x6.js} +5 -5
- package/dist/{search-archive-rvr7j5gx.js → search-archive-0z9cxv8e.js} +4 -4
- package/dist/shared/window-geometry.d.ts +5 -0
- package/dist/shared/window-geometry.d.ts.map +1 -1
- package/dist/{storage-tags-ye9aqrqy.js → storage-tags-q8erkn48.js} +3 -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-1rzxmkhb.js → transform-postprocess-phase-k9d1r13f.js} +9 -9
- package/dist/v2/auto-search-worker.js +1 -1
- package/dist/v2/chunk-embedding-write-worker.js +1 -1
- package/dist/v2/{context-0e946t63.js → context-jtqj5e1r.js} +1077 -245
- package/dist/v2/{derive-budgets-sa0v7bz0.js → derive-budgets-b5cgrtp8.js} +2 -2
- 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-index-bounded-wt64v2rn.js → message-index-bounded-60tdhht5.js} +3 -3
- package/dist/v2/migration-worker.js +1 -1
- package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
- package/dist/v2/{read-session-chunk-4b31z6bz.js → read-session-chunk-9tmsxwb2.js} +2 -2
- package/dist/v2/{recomp-orchestrator-6qrm2nea.js → recomp-orchestrator-7y8smqqp.js} +9 -9
- package/dist/v2/{render-f8mw16pp.js → render-j0y57skn.js} +6 -6
- package/dist/v2/{search-archive-7d0xdp54.js → search-archive-1e2tr8eq.js} +4 -4
- package/dist/v2/{search-ecjd7e50.js → search-qhd2m8kn.js} +4 -4
- package/dist/v2/{server-ftyc8awt.js → server-3rp821fw.js} +1 -1
- package/dist/v2/{server-39kzpp8q.js → server-4m71jpaj.js} +2 -2
- package/dist/v2/{server-vnpnmrsv.js → server-5dtrzs6j.js} +3 -2
- package/dist/v2/{server-0ymsgh0j.js → server-5vy0xt3p.js} +1 -1
- package/dist/v2/{server-sd8hvzte.js → server-af1rmkyn.js} +1 -1
- package/dist/v2/{server-zqzh2ybj.js → server-ahy062xr.js} +30 -11
- package/dist/v2/{server-wbxbk3za.js → server-ht0dyq9r.js} +2 -2
- package/dist/v2/{server-2qyfev3b.js → server-rjn4msjj.js} +2 -2
- package/dist/v2/{server-an1ff8d8.js → server-rshcp4gy.js} +3 -3
- package/dist/v2/{server-hq7fdqfm.js → server-sscb1r3e.js} +2 -2
- package/dist/v2/{server-gwqfwtzq.js → server-t4hk02v1.js} +10 -10
- package/dist/v2/{server-vjhk8v41.js → server-wa4qhryh.js} +1 -1
- package/dist/v2/{server-qxzbmtqt.js → server-zt1m5rwj.js} +10 -2
- package/dist/v2/server.js +4 -4
- package/dist/v2/{storage-tags-8nttt1sk.js → storage-tags-ztar1k0g.js} +3 -1
- package/dist/v2/{v2-archive-reader-53kp5mme.js → v2-archive-reader-tme5988n.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-bng0dfxy.js → wrapup-orchestrator-k7m16xze.js} +9 -9
- package/dist/{v2-archive-reader-0fcxs5e9.js → v2-archive-reader-dq5ebwe6.js} +1 -1
- package/dist/{wrapup-orchestrator-r5cqgyrg.js → wrapup-orchestrator-4pqwet8p.js} +9 -9
- 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";
|
|
@@ -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,
|
|
@@ -590,7 +593,7 @@ 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,
|
|
@@ -601,7 +604,7 @@ import {
|
|
|
601
604
|
cleanSearchText,
|
|
602
605
|
matchedSearchSnippet,
|
|
603
606
|
getLastIndexedOrdinal
|
|
604
|
-
} from "./server-
|
|
607
|
+
} from "./server-3rp821fw.js";
|
|
605
608
|
import"./server-131h608x.js";
|
|
606
609
|
import {
|
|
607
610
|
getMessageIndexEpoch,
|
|
@@ -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,
|
|
@@ -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,7 +835,7 @@ 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
|
|
@@ -963,14 +966,14 @@ import {
|
|
|
963
966
|
renderMessageByOrdinal2,
|
|
964
967
|
renderVerboseRangeForTool2,
|
|
965
968
|
renderItemByTag2
|
|
966
|
-
} from "./server-
|
|
969
|
+
} from "./server-ht0dyq9r.js";
|
|
967
970
|
import"./server-kaqs6h31.js";
|
|
968
971
|
import {
|
|
969
972
|
readV2ArchiveOffThread2
|
|
970
|
-
} from "./server-
|
|
973
|
+
} from "./server-rshcp4gy.js";
|
|
971
974
|
import {
|
|
972
975
|
renderSearchArchiveOffThread2
|
|
973
|
-
} from "./server-
|
|
976
|
+
} from "./server-4m71jpaj.js";
|
|
974
977
|
import {
|
|
975
978
|
markHostInstructionRow,
|
|
976
979
|
hostInstructionRow,
|
|
@@ -1130,7 +1133,7 @@ __export(exports_external, {
|
|
|
1130
1133
|
cuid: () => cuid3,
|
|
1131
1134
|
cuid2: () => cuid22,
|
|
1132
1135
|
custom: () => custom,
|
|
1133
|
-
date: () =>
|
|
1136
|
+
date: () => date4,
|
|
1134
1137
|
decode: () => decode3,
|
|
1135
1138
|
decodeAsync: () => decodeAsync2,
|
|
1136
1139
|
discriminatedUnion: () => discriminatedUnion,
|
|
@@ -1599,7 +1602,7 @@ __export(exports_regexes, {
|
|
|
1599
1602
|
cidrv6: () => cidrv6,
|
|
1600
1603
|
cuid: () => cuid,
|
|
1601
1604
|
cuid2: () => cuid2,
|
|
1602
|
-
date: () =>
|
|
1605
|
+
date: () => date2,
|
|
1603
1606
|
datetime: () => datetime,
|
|
1604
1607
|
domain: () => domain,
|
|
1605
1608
|
duration: () => duration,
|
|
@@ -1710,7 +1713,7 @@ __export(exports_iso, {
|
|
|
1710
1713
|
ZodISODateTime: () => ZodISODateTime,
|
|
1711
1714
|
ZodISODuration: () => ZodISODuration,
|
|
1712
1715
|
ZodISOTime: () => ZodISOTime,
|
|
1713
|
-
date: () =>
|
|
1716
|
+
date: () => date3,
|
|
1714
1717
|
datetime: () => datetime2,
|
|
1715
1718
|
duration: () => duration2,
|
|
1716
1719
|
time: () => time2
|
|
@@ -1721,7 +1724,7 @@ var exports_coerce = {};
|
|
|
1721
1724
|
__export(exports_coerce, {
|
|
1722
1725
|
bigint: () => bigint3,
|
|
1723
1726
|
boolean: () => boolean4,
|
|
1724
|
-
date: () =>
|
|
1727
|
+
date: () => date5,
|
|
1725
1728
|
number: () => number4,
|
|
1726
1729
|
string: () => string4
|
|
1727
1730
|
});
|
|
@@ -8722,6 +8725,55 @@ function projectStructuralSentinels(args) {
|
|
|
8722
8725
|
return removed;
|
|
8723
8726
|
}
|
|
8724
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
|
+
|
|
8725
8777
|
// src/hooks/magic-context/strict-thinking-prefix.ts
|
|
8726
8778
|
function servedPrefixMatches(args) {
|
|
8727
8779
|
const heads = args.messages?.slice(0, 2);
|
|
@@ -9820,7 +9872,6 @@ function tagMessages(sessionId, messages, tagger, db, options = {}) {
|
|
|
9820
9872
|
var DEGRADE_CACHE_WARNING_THRESHOLD = 10;
|
|
9821
9873
|
var SYSTEM_INJECTION_ACTIONABLE_TAIL_MESSAGES = 40;
|
|
9822
9874
|
var degradedCacheCountBySession = new BoundedSessionMap(100);
|
|
9823
|
-
var routinePressureAppliedBySession = new BoundedSessionMap(100);
|
|
9824
9875
|
function isSyntheticHeadMessage(message) {
|
|
9825
9876
|
if (message.info.id !== undefined)
|
|
9826
9877
|
return false;
|
|
@@ -10477,11 +10528,15 @@ function evaluateEmergencyFailClosed(input) {
|
|
|
10477
10528
|
if (input.usagePercentage < 95) {
|
|
10478
10529
|
return { shouldAbort: false, reason: "below-emergency-band" };
|
|
10479
10530
|
}
|
|
10480
|
-
const
|
|
10481
|
-
|
|
10482
|
-
shouldAbort,
|
|
10483
|
-
|
|
10484
|
-
|
|
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" };
|
|
10485
10540
|
}
|
|
10486
10541
|
function finalizeMessageRepresentation(messages, resolvedProviderID, options) {
|
|
10487
10542
|
const protectedMessages = options?.protectedThinkingMessages ?? new Set;
|
|
@@ -10568,18 +10623,29 @@ async function runPostTransformPhase(args) {
|
|
|
10568
10623
|
const deferredMaterializationAtPassStart = args.deferredMaterializationSessions.has(args.sessionId);
|
|
10569
10624
|
let isExplicitFlush = pendingMaterializationAtPassStart;
|
|
10570
10625
|
const deferredMaterializationWasPending = deferredMaterializationAtPassStart;
|
|
10571
|
-
const alreadyRanThisTurn = args.
|
|
10572
|
-
const
|
|
10573
|
-
|
|
10574
|
-
|
|
10575
|
-
|
|
10576
|
-
|
|
10577
|
-
|
|
10578
|
-
|
|
10579
|
-
}
|
|
10580
|
-
|
|
10581
|
-
|
|
10582
|
-
|
|
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);
|
|
10583
10649
|
if (args.contextUsageFromEstimate !== true && args.contextUsage.percentage > 0 && args.contextUsage.percentage < args.forceMaterializationPercentage - 5 && getEmergencyInputSample(args.db, args.sessionId) > 0) {
|
|
10584
10650
|
clearEmergencyDropSample(args.db, args.sessionId);
|
|
10585
10651
|
}
|
|
@@ -10602,15 +10668,7 @@ async function runPostTransformPhase(args) {
|
|
|
10602
10668
|
let activeThinkingTurn = retainedThinking.size > 0;
|
|
10603
10669
|
const protectedThinkingMessages = new Set(args.messages.filter((message) => message.parts.some((part) => retainedThinking.has(part))));
|
|
10604
10670
|
let newTargets = protectNewTagMutations(args.messages, args.targets, retainedThinking, args.thinkingBindingRecoveryEnabledForModel === true);
|
|
10605
|
-
|
|
10606
|
-
for (const tag of args.messageTagNumbers.values())
|
|
10607
|
-
maxReasoningTag = Math.max(maxReasoningTag, tag);
|
|
10608
|
-
let safeReasoningCutoff = maxReasoningTag;
|
|
10609
|
-
for (const message of protectedThinkingMessages) {
|
|
10610
|
-
const tag = args.messageTagNumbers.get(message);
|
|
10611
|
-
if (tag && tag > 0)
|
|
10612
|
-
safeReasoningCutoff = Math.min(safeReasoningCutoff, tag - 1);
|
|
10613
|
-
}
|
|
10671
|
+
const safeReasoningCutoff2 = safeReasoningCutoff(args.messageTagNumbers, protectedThinkingMessages);
|
|
10614
10672
|
let activeThinkingPrefixHold = args.activeThinkingPrefixHold === true;
|
|
10615
10673
|
let freezeM0M1 = args.freezeM0M1 === true || activeThinkingPrefixHold;
|
|
10616
10674
|
let rewritingSignedPrefix = false;
|
|
@@ -10817,7 +10875,12 @@ async function runPostTransformPhase(args) {
|
|
|
10817
10875
|
executeReclaim: false,
|
|
10818
10876
|
subagentExecute: !args.fullFeatureMode && args.schedulerDecision === "execute",
|
|
10819
10877
|
hardFold: rewritingSignedPrefix || foldBustsServedPrefixThisPass || firstRenderBust,
|
|
10820
|
-
force:
|
|
10878
|
+
force: forceRide({
|
|
10879
|
+
bands,
|
|
10880
|
+
percentage: args.contextUsage.percentage,
|
|
10881
|
+
fromEstimate: args.contextUsageFromEstimate === true,
|
|
10882
|
+
emergencySample: () => getEmergencyInputSample(args.db, args.sessionId)
|
|
10883
|
+
}),
|
|
10821
10884
|
explicitFlush: isExplicitFlush && hasPendingMaterializationOrigin(args.pendingMaterializationSessions, args.sessionId, "user_flush"),
|
|
10822
10885
|
publishedHistory: !prefixPreflightFailed && (publishedM1RefreshedThisPass || !m0M1EnabledForFold && (args.pendingCompartmentInjection?.compartmentCount ?? 0) > 0 && legacyPublishedHeadChanged(args))
|
|
10823
10886
|
};
|
|
@@ -10844,7 +10907,18 @@ async function runPostTransformPhase(args) {
|
|
|
10844
10907
|
emergency: forceBandConfirmed
|
|
10845
10908
|
});
|
|
10846
10909
|
const shouldApplyPendingOps = !compactionOff && publishedWorkDrainAllowed;
|
|
10847
|
-
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
|
+
});
|
|
10848
10922
|
const isCacheBustingPass = publishedWorkDrainAllowed;
|
|
10849
10923
|
if (servedShapeRepair.needsRebuild && !isCacheBustingPass)
|
|
10850
10924
|
throw new Error("Served-shape repair requires a rebuilding pass");
|
|
@@ -10989,7 +11063,18 @@ async function runPostTransformPhase(args) {
|
|
|
10989
11063
|
recordFirstApplicationWireEdit(false);
|
|
10990
11064
|
firstApplicationLocations.set(message, Math.min(firstApplicationLocations.get(message) ?? Infinity, partIndex));
|
|
10991
11065
|
};
|
|
10992
|
-
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 : []);
|
|
10993
11078
|
for (const message of hostRowReclaim?.edits ?? []) {
|
|
10994
11079
|
const index = args.messages.indexOf(message);
|
|
10995
11080
|
recordFirstApplicationWireEdit(index < 0 || servesThinkingBlock(args.messages.slice(index + 1), args.resolvedProviderID, args.resolvedModelID));
|
|
@@ -11058,7 +11143,15 @@ async function runPostTransformPhase(args) {
|
|
|
11058
11143
|
if (forceBandConfirmed && emergencyRewriteAlreadyPriced && getEmergencyInputSample(args.db, args.sessionId) > 0) {
|
|
11059
11144
|
clearEmergencyDropSample(args.db, args.sessionId);
|
|
11060
11145
|
}
|
|
11061
|
-
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
|
+
});
|
|
11062
11155
|
let cleanup = applyHeuristicCleanup(args.sessionId, args.db, newTargets, args.messageTagNumbers, {
|
|
11063
11156
|
protectedTagNumbers: args.protectedTagNumbers,
|
|
11064
11157
|
protectedCutoff: args.protectedCutoff,
|
|
@@ -11096,7 +11189,7 @@ async function runPostTransformPhase(args) {
|
|
|
11096
11189
|
routineCleanupApplied = true;
|
|
11097
11190
|
}
|
|
11098
11191
|
if (routineCleanupApplied && args.fullFeatureMode && executePressureEligible) {
|
|
11099
|
-
|
|
11192
|
+
markRoutinePressureApplied(args.sessionId);
|
|
11100
11193
|
}
|
|
11101
11194
|
logTransformTiming(args.sessionId, "applyHeuristicCleanup", t5, `droppedTools=${cleanup.droppedTools} deduplicatedTools=${cleanup.deduplicatedTools} droppedInjections=${cleanup.droppedInjections} compressedTextTags=${cleanup.compressedTextTags} mutatedTextTags=${cleanup.mutatedTextTags}`);
|
|
11102
11195
|
const heuristicMutationCount = cleanup.droppedTools + cleanup.deduplicatedTools + cleanup.droppedInjections + cleanup.mutatedTextTags;
|
|
@@ -11115,7 +11208,7 @@ async function runPostTransformPhase(args) {
|
|
|
11115
11208
|
}
|
|
11116
11209
|
}
|
|
11117
11210
|
const reasoningEstimates = tryGetReasoningTokenEstimatesByMessage2(args.db, args.sessionId, sessionDecisionCalibration(args.db, args.sessionId).proseRatio);
|
|
11118
|
-
const budgetCutoff = routineCleanupApplied && !activeThinkingPrefixHold && reasoningEstimates ? Math.min(
|
|
11211
|
+
const budgetCutoff = routineCleanupApplied && !activeThinkingPrefixHold && reasoningEstimates ? Math.min(safeReasoningCutoff2, opencodeReasoningBudgetCutoff({
|
|
11119
11212
|
messages: args.messages,
|
|
11120
11213
|
messageTagNumbers: args.messageTagNumbers,
|
|
11121
11214
|
budget: args.keepReasoningTokens ?? DEFAULT_KEEP_REASONING_TOKENS,
|
|
@@ -11372,25 +11465,10 @@ async function runPostTransformPhase(args) {
|
|
|
11372
11465
|
}
|
|
11373
11466
|
}
|
|
11374
11467
|
const m0M1Enabled = m0M1EnabledForFold;
|
|
11375
|
-
if (
|
|
11376
|
-
|
|
11377
|
-
|
|
11378
|
-
|
|
11379
|
-
if (hostInstructionRetentionEnabled()) {
|
|
11380
|
-
try {
|
|
11381
|
-
retain = isHostInstructionRetentionOn(args.db, args.sessionId);
|
|
11382
|
-
} catch (error) {
|
|
11383
|
-
failPass("host-instruction-retention-read-failure", error);
|
|
11384
|
-
}
|
|
11385
|
-
if (!retain && canEditWholePrefix) {
|
|
11386
|
-
if (!markHostInstructionRetention(args.db, args.sessionId))
|
|
11387
|
-
failPass("host-instruction-retention-persistence-failure");
|
|
11388
|
-
retain = true;
|
|
11389
|
-
}
|
|
11390
|
-
}
|
|
11391
|
-
if (retain && covered.length > 0)
|
|
11392
|
-
args.messages.unshift(...covered);
|
|
11393
|
-
}
|
|
11468
|
+
if (retainCoveredInstructions && coveredHostInstructions.length > 0) {
|
|
11469
|
+
if (!coveredRetentionOn && coveredHostInstructions.some((m) => m.parts.length > 0))
|
|
11470
|
+
recordFirstApplicationWireEdit(true);
|
|
11471
|
+
args.messages.unshift(...coveredHostInstructions);
|
|
11394
11472
|
}
|
|
11395
11473
|
if (m0M1Enabled && args.m0M1) {
|
|
11396
11474
|
if (freezeM0M1 && !preparedPrefix) {
|
|
@@ -11957,6 +12035,8 @@ async function runPostTransformPhase(args) {
|
|
|
11957
12035
|
}
|
|
11958
12036
|
}
|
|
11959
12037
|
hostRowReclaim?.commit();
|
|
12038
|
+
if (retainCoveredInstructions && !coveredRetentionOn && !markHostInstructionRetention(args.db, args.sessionId))
|
|
12039
|
+
failPass("host-instruction-retention-persistence-failure");
|
|
11960
12040
|
let settledDroppedReasoning = 0;
|
|
11961
12041
|
if (!canUseEmptySentinels) {
|
|
11962
12042
|
let mode = "legacy";
|
|
@@ -12906,6 +12986,192 @@ function createPassOutcome() {
|
|
|
12906
12986
|
};
|
|
12907
12987
|
}
|
|
12908
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
|
+
|
|
12909
13175
|
// src/hooks/magic-context/release-recovery-prefix.ts
|
|
12910
13176
|
function groups(messages) {
|
|
12911
13177
|
const result = new Map;
|
|
@@ -15720,7 +15986,7 @@ function resolveUnknownUsageFromWireEstimate(input) {
|
|
|
15720
15986
|
const providerLimit = input.providerProvenLimitTokens;
|
|
15721
15987
|
const canUseProviderMass = input.wireEstimateTrusted === false && typeof providerTokens === "number" && Number.isFinite(providerTokens) && providerTokens > 0 && typeof providerLimit === "number" && Number.isFinite(providerLimit) && providerLimit > 0;
|
|
15722
15988
|
const tokens = canUseProviderMass ? Math.max(wireTokens, providerTokens) : wireTokens;
|
|
15723
|
-
const limit = input.
|
|
15989
|
+
const limit = input.windowTokens;
|
|
15724
15990
|
const estimatedPercentage = typeof limit === "number" && Number.isFinite(limit) && limit > 0 ? tokens / limit * 100 : input.usage.percentage;
|
|
15725
15991
|
return {
|
|
15726
15992
|
inputTokens: tokens,
|
|
@@ -16281,7 +16547,7 @@ function transformGeometryForWire(geometry) {
|
|
|
16281
16547
|
return;
|
|
16282
16548
|
const { window, reserve } = geometry.derivation;
|
|
16283
16549
|
let derivation;
|
|
16284
|
-
if (geometry.geometry === "separate" && geometry.usableSoft <
|
|
16550
|
+
if (geometry.geometry === "separate" && geometry.usableSoft < window) {
|
|
16285
16551
|
derivation = `s1-pre-carve/input=${geometry.usableSoft}`;
|
|
16286
16552
|
} else if (geometry.geometry === "separate") {
|
|
16287
16553
|
derivation = `s1-separate/context=${window}`;
|
|
@@ -19104,6 +19370,7 @@ function readServedTemporalDecisions(db, sessionId, runtime, messageIds) {
|
|
|
19104
19370
|
|
|
19105
19371
|
// src/hooks/magic-context/transform-compartment-phase.ts
|
|
19106
19372
|
var HISTORIAN_INLINE_JOIN_BUDGET_MS = 60000;
|
|
19373
|
+
var CHAINED_RECOVERY_RUN_MIN_BUDGET_MS = 15000;
|
|
19107
19374
|
function resolveHistorianInlineJoinBudget(configuredTimeoutMs) {
|
|
19108
19375
|
const requested = configuredTimeoutMs ?? HISTORIAN_INLINE_JOIN_BUDGET_MS;
|
|
19109
19376
|
return Math.max(0, Math.min(requested, HISTORIAN_INLINE_JOIN_BUDGET_MS));
|
|
@@ -19165,6 +19432,7 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19165
19432
|
let rebuiltHistoryThisPass = false;
|
|
19166
19433
|
let historianJoinTimedOut = false;
|
|
19167
19434
|
let historianJoinBudgetMs = null;
|
|
19435
|
+
let chainedRecoveryRuns = 0;
|
|
19168
19436
|
const historianRunnable = args.historianRunnable !== false;
|
|
19169
19437
|
if (args.compactionOff) {
|
|
19170
19438
|
if (args.sessionMeta.compartmentInProgress) {
|
|
@@ -19180,7 +19448,9 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19180
19448
|
justAwaitedPublication,
|
|
19181
19449
|
rebuiltHistoryThisPass,
|
|
19182
19450
|
historianJoinTimedOut,
|
|
19183
|
-
historianJoinBudgetMs
|
|
19451
|
+
historianJoinBudgetMs,
|
|
19452
|
+
chainedRecoveryRuns,
|
|
19453
|
+
recoveryHistoryRemains: false
|
|
19184
19454
|
};
|
|
19185
19455
|
}
|
|
19186
19456
|
let rawEligibility = args.preResolvedBoundarySnapshot ? {
|
|
@@ -19228,7 +19498,7 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19228
19498
|
const snapshot = getBoundarySnapshotForCompartment();
|
|
19229
19499
|
return snapshot !== null && hasRunnableCompartmentWindow(snapshot);
|
|
19230
19500
|
}
|
|
19231
|
-
async function awaitCompartmentRun(activeRun, reason) {
|
|
19501
|
+
async function awaitCompartmentRun(activeRun, reason, join = fullInlineJoinWindow()) {
|
|
19232
19502
|
await Promise.resolve();
|
|
19233
19503
|
if (activeRun.inlineJoinTimedOutBudgetMs !== undefined && !activeRun.settled) {
|
|
19234
19504
|
historianJoinTimedOut = true;
|
|
@@ -19237,8 +19507,8 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19237
19507
|
return "timed_out";
|
|
19238
19508
|
}
|
|
19239
19509
|
sessionLog2(args.sessionId, reason);
|
|
19240
|
-
const timeoutMs =
|
|
19241
|
-
historianJoinBudgetMs =
|
|
19510
|
+
const timeoutMs = join.timeoutMs;
|
|
19511
|
+
historianJoinBudgetMs = join.budgetMs;
|
|
19242
19512
|
let timer;
|
|
19243
19513
|
const timeout = new Promise((resolve) => {
|
|
19244
19514
|
timer = setTimeout(() => resolve("timeout"), timeoutMs);
|
|
@@ -19251,20 +19521,145 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19251
19521
|
clearTimeout(timer);
|
|
19252
19522
|
}
|
|
19253
19523
|
if (result === "timeout") {
|
|
19254
|
-
activeRun.inlineJoinTimedOutBudgetMs =
|
|
19524
|
+
activeRun.inlineJoinTimedOutBudgetMs = join.budgetMs;
|
|
19255
19525
|
historianJoinTimedOut = true;
|
|
19256
19526
|
sessionLog2(args.sessionId, `transform: compartment await timed out after ${timeoutMs}ms — proceeding without waiting`);
|
|
19257
19527
|
return "timed_out";
|
|
19258
19528
|
}
|
|
19259
|
-
|
|
19260
|
-
justAwaitedPublication = activeRun.published;
|
|
19529
|
+
justAwaitedPublication = justAwaitedPublication || activeRun.published;
|
|
19261
19530
|
published = published || activeRun.published;
|
|
19262
|
-
|
|
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);
|
|
19263
19536
|
pendingCompartmentInjection = prepareCompartmentInjection(args.db, args.resolvedSessionId, args.messages, historyReprepareShouldBust, args.coveredInstructions, args.projectPath, args.injectionBudgetTokens, args.experimentalTemporalAwareness);
|
|
19264
19537
|
if (historyReprepareShouldBust) {
|
|
19265
19538
|
rebuiltHistoryThisPass = true;
|
|
19266
19539
|
}
|
|
19267
|
-
|
|
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
|
+
});
|
|
19268
19663
|
}
|
|
19269
19664
|
if ((!historianRunnable || !args.canRunCompartments && !getActiveCompartmentRun(args.sessionId)) && args.sessionMeta.compartmentInProgress) {
|
|
19270
19665
|
sessionLog2(args.sessionId, "transform: historian unavailable; clearing stale compartmentInProgress flag");
|
|
@@ -19324,34 +19719,7 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19324
19719
|
let activeRun = getActiveCompartmentRun(args.sessionId);
|
|
19325
19720
|
if (!activeRun && hasEligibleHistoryForCompartment() && (args.client || args.hiddenCompletionExecutor)) {
|
|
19326
19721
|
sessionLog2(args.sessionId, `transform: 95% reached (${args.contextUsage.percentage.toFixed(1)}%), force-starting compartment agent and blocking`);
|
|
19327
|
-
startCompartmentAgent(
|
|
19328
|
-
client: args.client,
|
|
19329
|
-
hiddenCompletionExecutor: args.hiddenCompletionExecutor,
|
|
19330
|
-
compactionMarkerStrategy: args.compactionMarkerStrategy,
|
|
19331
|
-
db: args.db,
|
|
19332
|
-
sessionId: args.sessionId,
|
|
19333
|
-
historianChunkTokens: args.historianChunkTokens,
|
|
19334
|
-
boundarySnapshot: getBoundarySnapshotForCompartment() ?? undefined,
|
|
19335
|
-
currentContextLimit: args.boundaryContextLimit,
|
|
19336
|
-
historyBudgetTokens: args.historyBudgetTokens,
|
|
19337
|
-
historianTimeoutMs: args.historianTimeoutMs,
|
|
19338
|
-
model: args.historianModel,
|
|
19339
|
-
historianContextLimit: args.historianContextLimit,
|
|
19340
|
-
historianMaxOutputTokens: args.historianMaxOutputTokens,
|
|
19341
|
-
fallbackModels: args.fallbackModels,
|
|
19342
|
-
directory: args.compartmentDirectory,
|
|
19343
|
-
fallbackModelId: args.fallbackModelId,
|
|
19344
|
-
ensureProjectRegistered: args.ensureProjectRegistered,
|
|
19345
|
-
getNotificationParams: args.getNotificationParams,
|
|
19346
|
-
experimentalUserMemories: args.experimentalUserMemories,
|
|
19347
|
-
userObservationsRequested: args.userObservationsRequested,
|
|
19348
|
-
historianTwoPass: args.historianTwoPass,
|
|
19349
|
-
historianExpandTools: args.historianExpandTools,
|
|
19350
|
-
memoryEnabled: args.memoryEnabled,
|
|
19351
|
-
autoPromote: args.autoPromote,
|
|
19352
|
-
onCompartmentStatePublished: args.onCompartmentStatePublished,
|
|
19353
|
-
preserveInjectionCacheUntilConsumed: true
|
|
19354
|
-
});
|
|
19722
|
+
startCompartmentAgent(historianRunDeps(getBoundarySnapshotForCompartment() ?? undefined));
|
|
19355
19723
|
activeRun = getActiveCompartmentRun(args.sessionId);
|
|
19356
19724
|
} else if (!activeRun && hasEligibleHistoryForCompartment()) {
|
|
19357
19725
|
sessionLog2(args.sessionId, "transform: cannot force-start compartment agent without client");
|
|
@@ -19362,15 +19730,24 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19362
19730
|
const notifParams = args.getNotificationParams?.() ?? {};
|
|
19363
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));
|
|
19364
19732
|
}
|
|
19365
|
-
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);
|
|
19366
19736
|
if (awaitResult === "completed") {
|
|
19367
19737
|
awaitedCompartmentRun = true;
|
|
19368
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();
|
|
19369
19745
|
} else {
|
|
19370
19746
|
sessionLog2(args.sessionId, "transform: historian join timed out — reclaim and final fit checks continue; historian keeps running in the background");
|
|
19371
19747
|
}
|
|
19372
19748
|
}
|
|
19373
19749
|
}
|
|
19750
|
+
const recoveryHistoryRemains = args.projectRecoveryRequest !== undefined && recoveryHistoryRemainsAfterJoins();
|
|
19374
19751
|
return {
|
|
19375
19752
|
pendingCompartmentInjection,
|
|
19376
19753
|
awaitedCompartmentRun,
|
|
@@ -19379,7 +19756,9 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
19379
19756
|
justAwaitedPublication,
|
|
19380
19757
|
rebuiltHistoryThisPass,
|
|
19381
19758
|
historianJoinTimedOut,
|
|
19382
|
-
historianJoinBudgetMs
|
|
19759
|
+
historianJoinBudgetMs,
|
|
19760
|
+
chainedRecoveryRuns,
|
|
19761
|
+
recoveryHistoryRemains
|
|
19383
19762
|
};
|
|
19384
19763
|
}
|
|
19385
19764
|
|
|
@@ -19919,6 +20298,7 @@ function createTransform(deps) {
|
|
|
19919
20298
|
sessionID: sessionId
|
|
19920
20299
|
}) : undefined;
|
|
19921
20300
|
const hostEstimate = deps.hostInputEstimate?.(sessionId);
|
|
20301
|
+
const recoveryHostAddedTokens = typeof hostEstimate?.hostAddedTokens === "number" && Number.isFinite(hostEstimate.hostAddedTokens) && hostEstimate.hostAddedTokens > 0 ? hostEstimate.hostAddedTokens : 0;
|
|
19922
20302
|
const hostOverWindow = fullFeatureMode && !compactionOff && resolvedContextLimit !== undefined && resolvedContextLimit > 0 && hostEstimate !== undefined && Number.isFinite(hostEstimate.tokens) && Number.isFinite(hostEstimate.pressureTokens) && hostEstimate.tokens > resolvedContextLimit;
|
|
19923
20303
|
if (hostOverWindow) {
|
|
19924
20304
|
contextUsageEarly = {
|
|
@@ -20408,6 +20788,50 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20408
20788
|
const watermark = getMaxDroppedTagNumber2(db, sessionId);
|
|
20409
20789
|
let contextUsage = contextUsageEarly;
|
|
20410
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;
|
|
20411
20835
|
const tCompartmentPhase = performance.now();
|
|
20412
20836
|
const compartmentPhase = await runCompartmentPhase({
|
|
20413
20837
|
hiddenCompletionExecutor: deps.hiddenCompletionExecutor,
|
|
@@ -20423,6 +20847,17 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20423
20847
|
boundaryUsage: boundaryUsageForProtectedTail,
|
|
20424
20848
|
boundaryUsageSource,
|
|
20425
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
|
+
}),
|
|
20426
20861
|
client: deps.client,
|
|
20427
20862
|
db,
|
|
20428
20863
|
sessionId,
|
|
@@ -20526,44 +20961,149 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20526
20961
|
contextLimit: resolvedContextLimit,
|
|
20527
20962
|
lastResponseTime: sessionMeta.lastResponseTime
|
|
20528
20963
|
});
|
|
20529
|
-
|
|
20964
|
+
const servesHead = (!!projectIdentity || !!sessionDirectory) && (fullFeatureMode || compactionOff);
|
|
20965
|
+
const prefixBoundModel = isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID);
|
|
20966
|
+
let sizingInput;
|
|
20967
|
+
let planInput;
|
|
20530
20968
|
try {
|
|
20531
|
-
|
|
20532
|
-
|
|
20533
|
-
|
|
20534
|
-
|
|
20535
|
-
|
|
20536
|
-
|
|
20537
|
-
|
|
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
|
|
20538
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
|
+
};
|
|
20539
21002
|
} catch (error) {
|
|
20540
|
-
|
|
20541
|
-
|
|
20542
|
-
|
|
20543
|
-
const
|
|
20544
|
-
|
|
20545
|
-
|
|
20546
|
-
|
|
20547
|
-
|
|
20548
|
-
|
|
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
|
|
20549
21041
|
};
|
|
20550
|
-
|
|
20551
|
-
|
|
20552
|
-
|
|
20553
|
-
|
|
20554
|
-
|
|
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,
|
|
20555
21056
|
pricedPass: true,
|
|
20556
21057
|
wireEstimateTokens: overflowRecoveryPass ? pressureEstimate.tokens : pressureEstimate.pressureTokens,
|
|
20557
21058
|
wireEstimateTrusted: pressureEstimate.trusted,
|
|
20558
21059
|
providerProvenInputTokens: providerProvenInputForRecovery,
|
|
20559
21060
|
providerProvenLimitTokens: providerProvenLimitForRecovery,
|
|
20560
|
-
|
|
21061
|
+
windowTokens: localReadingWindow
|
|
20561
21062
|
});
|
|
20562
|
-
if (
|
|
20563
|
-
|
|
20564
|
-
|
|
20565
|
-
|
|
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;
|
|
20566
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}`);
|
|
20567
21107
|
}
|
|
20568
21108
|
}
|
|
20569
21109
|
const protectionUsableSoft = windowGeometry?.usableSoft ?? boundaryContextLimit;
|
|
@@ -20745,8 +21285,9 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20745
21285
|
logIncompleteFinalWire(finalWireEstimate, messages);
|
|
20746
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}`);
|
|
20747
21287
|
}
|
|
21288
|
+
const recoveryAdmissionPass = emergencyRecoveryArmed && emergencyRecoveryOrigin !== null && emergencyUsagePercentage >= 95;
|
|
20748
21289
|
let servedPressureTokens;
|
|
20749
|
-
if (providerReadingMissing) {
|
|
21290
|
+
if (providerReadingMissing || recoveryAdmissionPass) {
|
|
20750
21291
|
servedPressureTokens = finalWireEstimate?.pressureTokens;
|
|
20751
21292
|
if (servedPressureTokens === undefined) {
|
|
20752
21293
|
try {
|
|
@@ -20763,12 +21304,13 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20763
21304
|
}
|
|
20764
21305
|
}
|
|
20765
21306
|
}
|
|
21307
|
+
const recoveryAdmissionTokens = recoveryAdmissionPass && servedPressureTokens !== undefined ? servedPressureTokens + recoveryHostAddedTokens : undefined;
|
|
20766
21308
|
localWireReadings.record({
|
|
20767
21309
|
sessionId,
|
|
20768
21310
|
providerReadingMissing,
|
|
20769
21311
|
modelKey: localReadingModelKey,
|
|
20770
21312
|
usableWindow: localReadingWindow,
|
|
20771
|
-
pressureTokens: servedPressureTokens
|
|
21313
|
+
pressureTokens: providerReadingMissing ? servedPressureTokens : undefined
|
|
20772
21314
|
});
|
|
20773
21315
|
if ((finalWireEstimate?.refusalGrade || finalWireEstimate?.refusalBasis === "byte-bound" && finalWireEstimate.refusalTokens !== undefined) && boundaryContextLimit > 0 && (finalWireEstimate.refusalTokens ?? finalWireEstimate.tokens) > boundaryContextLimit) {
|
|
20774
21316
|
const signedFitRetryWanted = !thinkingFitRetries.has(sessionId) && activeThinkingPrefixHold && hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID);
|
|
@@ -20823,6 +21365,21 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20823
21365
|
unmanagedOverWindowSessions.delete(sessionId);
|
|
20824
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`);
|
|
20825
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
|
+
};
|
|
20826
21383
|
const timedOutHistorianFailure = compartmentPhase.historianJoinTimedOut ? historianJoinFailClosedMessage({
|
|
20827
21384
|
timedOut: true,
|
|
20828
21385
|
budgetMs: compartmentPhase.historianJoinBudgetMs,
|
|
@@ -20832,14 +21389,21 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20832
21389
|
}) : null;
|
|
20833
21390
|
if (timedOutHistorianFailure) {
|
|
20834
21391
|
sessionLog2(sessionId, `transform: ${timedOutHistorianFailure}; finalEstimate=${finalWireEstimate?.tokens ?? "unavailable"} estimateTrusted=${finalWireEstimate?.trusted ?? false} contextLimit=${boundaryContextLimit} emergencyReclaimed=${postTransformResult.emergencyReclaimedTokens}`);
|
|
21392
|
+
keepRecoveryArmed();
|
|
20835
21393
|
throw new EmergencyFailClosedError(timedOutHistorianFailure);
|
|
20836
21394
|
}
|
|
20837
21395
|
if (compartmentPhase.historianJoinTimedOut) {
|
|
20838
21396
|
sessionLog2(sessionId, `transform: proceeding after bounded historian join; trusted final-wire ${finalWireEstimate?.tokens} fits context limit ${boundaryContextLimit} after emergency reclaim=${postTransformResult.emergencyReclaimedTokens}`);
|
|
20839
21397
|
}
|
|
20840
|
-
const currentModelKeyForRecovery = deps.getModelKey?.(sessionId);
|
|
20841
21398
|
const overflowStateForFinalWire = getOverflowState(db, sessionId, currentModelKeyForRecovery);
|
|
20842
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;
|
|
20843
21407
|
const emergencyFailClosed = evaluateEmergencyFailClosed({
|
|
20844
21408
|
usagePercentage: emergencyUsagePercentage,
|
|
20845
21409
|
emergencyRecoveryArmed,
|
|
@@ -20848,18 +21412,27 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
20848
21412
|
finalWireEstimate,
|
|
20849
21413
|
providerProvenLimitTokens,
|
|
20850
21414
|
contextLimitTokens: boundaryContextLimit,
|
|
20851
|
-
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
|
|
20852
21417
|
});
|
|
20853
21418
|
if (emergencyFailClosed.disarm) {
|
|
20854
21419
|
clearEmergencyRecovery(db, sessionId);
|
|
20855
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`);
|
|
20856
21424
|
}
|
|
20857
21425
|
if (emergencyFailClosed.shouldAbort) {
|
|
21426
|
+
keepRecoveryArmed();
|
|
20858
21427
|
if (emergencyFailClosed.refusalMessage) {
|
|
20859
21428
|
throw contextRefusalError(emergencyFailClosed.refusalMessage);
|
|
20860
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
|
+
}
|
|
20861
21434
|
try {
|
|
20862
|
-
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);
|
|
20863
21436
|
} catch (error) {
|
|
20864
21437
|
throw new EmergencyFailClosedError("Emergency recovery notification failed", {
|
|
20865
21438
|
cause: error
|
|
@@ -24399,7 +24972,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
24399
24972
|
return { count: buildCompartmentCount(db, sessionId, moduleStatus) };
|
|
24400
24973
|
});
|
|
24401
24974
|
const buildManagedCtx = async (db) => {
|
|
24402
|
-
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-
|
|
24975
|
+
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-b5cgrtp8.js"));
|
|
24403
24976
|
const { resolveHistorianModel } = await importPluginModule(() => import("./model-resolution-280gmqvd.js"));
|
|
24404
24977
|
const { userObservationCollectionEnabled, userObservationsRequested } = await importPluginModule(() => import("./task-config-7md27rx8.js"));
|
|
24405
24978
|
const DEFAULT_HISTORIAN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
@@ -24451,7 +25024,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
24451
25024
|
const db = readDatabase();
|
|
24452
25025
|
if (!db)
|
|
24453
25026
|
return { ok: false, error: "db unavailable" };
|
|
24454
|
-
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-
|
|
25027
|
+
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-7y8smqqp.js"));
|
|
24455
25028
|
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-na3q825m.js"));
|
|
24456
25029
|
log2(`[rpc] recomp requested for session ${sessionId}`);
|
|
24457
25030
|
if (!args.client && !args.hiddenCompletionExecutor) {
|
|
@@ -24536,7 +25109,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
24536
25109
|
const db = readDatabase();
|
|
24537
25110
|
if (!db)
|
|
24538
25111
|
return { ok: false, error: "db unavailable" };
|
|
24539
|
-
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-
|
|
25112
|
+
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-k7m16xze.js"));
|
|
24540
25113
|
const model = liveSessionState.liveModelBySession.get(sessionId);
|
|
24541
25114
|
const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
|
|
24542
25115
|
const ctx = {
|
|
@@ -25290,9 +25863,9 @@ var FULL_PARAMETER_DESCRIPTIONS = {
|
|
|
25290
25863
|
},
|
|
25291
25864
|
ctx_memory: {
|
|
25292
25865
|
action: "write | update | archive | merge | get",
|
|
25293
|
-
content: "The memory text — one standalone fact (write, update, merge).",
|
|
25294
|
-
category: "Kind of fact
|
|
25295
|
-
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.",
|
|
25296
25869
|
reason: "Why it is being archived (optional)."
|
|
25297
25870
|
},
|
|
25298
25871
|
ctx_search: {
|
|
@@ -25325,9 +25898,9 @@ var LIGHT_PARAMETER_DESCRIPTIONS = {
|
|
|
25325
25898
|
},
|
|
25326
25899
|
ctx_memory: {
|
|
25327
25900
|
action: "write | update | archive | merge | get",
|
|
25328
|
-
content: "One standalone fact (write, update, merge).",
|
|
25329
|
-
category: "Kind of fact (
|
|
25330
|
-
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.",
|
|
25331
25904
|
reason: "Why it is archived (optional)."
|
|
25332
25905
|
},
|
|
25333
25906
|
ctx_search: {
|
|
@@ -25674,59 +26247,194 @@ var changed = "The Code Mode tool catalog has changed.";
|
|
|
25674
26247
|
var replacement = `${changed} This catalog supersedes the previous Code Mode tool catalog.`;
|
|
25675
26248
|
var codeMode = "core/codemode";
|
|
25676
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`)"];
|
|
25677
26254
|
var mcpReplacement = "The available MCP server instructions have changed. This list supersedes the previous one.";
|
|
25678
|
-
var
|
|
25679
|
-
|
|
25680
|
-
|
|
25681
|
-
|
|
25682
|
-
|
|
25683
|
-
|
|
25684
|
-
|
|
25685
|
-
|
|
25686
|
-
|
|
25687
|
-
|
|
25688
|
-
|
|
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}
|
|
25689
26266
|
|
|
25690
26267
|
`)) {
|
|
25691
|
-
|
|
25692
|
-
|
|
25693
|
-
`)
|
|
25694
|
-
|
|
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>")
|
|
25695
26322
|
return;
|
|
25696
|
-
|
|
25697
|
-
|
|
25698
|
-
return "delta";
|
|
25699
|
-
if (text.startsWith(`# Code Mode
|
|
25700
|
-
`) || text.startsWith("No Code Mode tools are currently available."))
|
|
25701
|
-
return "full";
|
|
25702
|
-
}
|
|
25703
|
-
if (source === mcp) {
|
|
25704
|
-
if (mcpDeltas.some(starts))
|
|
25705
|
-
return "delta";
|
|
25706
|
-
if ((starts(`${mcpReplacement}
|
|
25707
|
-
<mcp_instructions>
|
|
25708
|
-
`) || starts(`<mcp_instructions>
|
|
25709
|
-
`)) && text.includes("</mcp_instructions>"))
|
|
25710
|
-
return "full";
|
|
26323
|
+
names.push(open[1]);
|
|
26324
|
+
index = end + 1;
|
|
25711
26325
|
}
|
|
25712
|
-
|
|
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;
|
|
25713
26412
|
}
|
|
25714
26413
|
function supersededInstructionIDs(rows) {
|
|
25715
|
-
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;
|
|
25716
26423
|
const retired = new Set;
|
|
25717
26424
|
for (let index = rows.length - 1;index >= 0; index--) {
|
|
25718
|
-
const
|
|
25719
|
-
|
|
25720
|
-
|
|
25721
|
-
|
|
25722
|
-
|
|
25723
|
-
|
|
25724
|
-
|
|
25725
|
-
|
|
25726
|
-
|
|
25727
|
-
|
|
25728
|
-
|
|
25729
|
-
|
|
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);
|
|
25730
26438
|
});
|
|
25731
26439
|
}
|
|
25732
26440
|
return retired;
|
|
@@ -25734,6 +26442,7 @@ function supersededInstructionIDs(rows) {
|
|
|
25734
26442
|
|
|
25735
26443
|
// src/v2/fold/instruction-supersession.ts
|
|
25736
26444
|
var namespace = "instructionSupersession";
|
|
26445
|
+
var coveredNamespace = "coveredInstructionSupersession";
|
|
25737
26446
|
function decode(value) {
|
|
25738
26447
|
if (value === undefined)
|
|
25739
26448
|
return new Set;
|
|
@@ -25741,32 +26450,44 @@ function decode(value) {
|
|
|
25741
26450
|
throw new Error("Invalid instruction supersession replay state");
|
|
25742
26451
|
return new Set(value);
|
|
25743
26452
|
}
|
|
26453
|
+
var coveredOn = (value) => typeof value === "object" && value !== null && value.on === true;
|
|
25744
26454
|
function retiredLiveInstructionIDs(db, sessionID) {
|
|
25745
26455
|
return decode(readReplayEnvelope(db, sessionID)[namespace]);
|
|
25746
26456
|
}
|
|
25747
|
-
function
|
|
25748
|
-
|
|
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) => {
|
|
25749
26463
|
const row = hostInstructionRow(message.info);
|
|
25750
26464
|
return row ? [{ message, row }] : [];
|
|
25751
26465
|
});
|
|
26466
|
+
const coveredRows = coveredSupersessionEnabled ? instructionRows(covered) : [];
|
|
26467
|
+
const rows = [...coveredRows, ...instructionRows(messages)];
|
|
26468
|
+
const coveredMessages = new Set(coveredRows.map(({ message }) => message));
|
|
25752
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;
|
|
25753
26472
|
const selected = permitted ? supersededInstructionIDs(rows.map(({ row }) => row)) : new Set;
|
|
25754
26473
|
const newlyRetired = new Set([...selected].filter((id) => !retired.has(id)));
|
|
25755
26474
|
const omitted = new Set([...retired, ...newlyRetired]);
|
|
26475
|
+
const omits = (message, id) => omitted.has(id) && (!coveredMessages.has(message) || coveredFollowed || switchCovered);
|
|
25756
26476
|
const edits = [];
|
|
25757
26477
|
for (const { message, row } of rows) {
|
|
25758
|
-
if (!
|
|
26478
|
+
if (!omits(message, row.id))
|
|
25759
26479
|
continue;
|
|
25760
|
-
|
|
26480
|
+
const firstApplication = newlyRetired.has(row.id) || coveredMessages.has(message) && switchCovered;
|
|
26481
|
+
if (firstApplication && message.parts.length > 0)
|
|
25761
26482
|
edits.push(message);
|
|
25762
26483
|
message.parts = [];
|
|
25763
26484
|
}
|
|
25764
26485
|
return {
|
|
25765
26486
|
edits,
|
|
25766
26487
|
commit() {
|
|
25767
|
-
if (newlyRetired.size > 0 && !updateReplayDocument(db, sessionID, (doc) => {
|
|
26488
|
+
if ((newlyRetired.size > 0 || switchCovered) && !updateReplayDocument(db, sessionID, (doc) => {
|
|
25768
26489
|
const current = decode(doc[namespace]);
|
|
25769
|
-
if ([...newlyRetired].every((id) => current.has(id)))
|
|
26490
|
+
if ([...newlyRetired].every((id) => current.has(id)) && (!switchCovered || coveredOn(doc[coveredNamespace])))
|
|
25770
26491
|
return false;
|
|
25771
26492
|
for (const id of folded)
|
|
25772
26493
|
current.delete(id);
|
|
@@ -25774,11 +26495,13 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
|
|
|
25774
26495
|
current.add(id);
|
|
25775
26496
|
doc.version = 2;
|
|
25776
26497
|
doc[namespace] = [...current];
|
|
26498
|
+
if (switchCovered)
|
|
26499
|
+
doc[coveredNamespace] = { on: true };
|
|
25777
26500
|
return true;
|
|
25778
26501
|
}))
|
|
25779
26502
|
throw new Error("Cannot persist instruction supersession");
|
|
25780
26503
|
for (const { message, row } of rows) {
|
|
25781
|
-
if (
|
|
26504
|
+
if (omits(message, row.id))
|
|
25782
26505
|
markRetiredInstructionRow(message.info);
|
|
25783
26506
|
}
|
|
25784
26507
|
}
|
|
@@ -25817,6 +26540,35 @@ import { randomUUID as randomUUID4 } from "node:crypto";
|
|
|
25817
26540
|
|
|
25818
26541
|
// src/v2/fold/owner.ts
|
|
25819
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
|
|
25820
26572
|
var foldDigest = (value) => createHash7("sha256").update(value).digest("hex");
|
|
25821
26573
|
|
|
25822
26574
|
class FoldOwner {
|
|
@@ -25846,14 +26598,23 @@ class FoldOwner {
|
|
|
25846
26598
|
return this.serial(args.sessionID, async () => {
|
|
25847
26599
|
const previous = await this.read(args.sessionID);
|
|
25848
26600
|
const same = previous && (args.runningCut !== undefined ? previous.cutSeq === args.runningCut : previous.cutSeq === undefined && previous.watermark === args.watermark);
|
|
25849
|
-
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
|
+
}
|
|
25850
26607
|
return previous;
|
|
25851
|
-
|
|
26608
|
+
}
|
|
26609
|
+
const head = args.materialize();
|
|
26610
|
+
const submitted = args.checkpointText ?? head;
|
|
25852
26611
|
const next = {
|
|
25853
26612
|
watermark: args.watermark,
|
|
25854
26613
|
cutSeq: args.runningCut,
|
|
25855
26614
|
submitted,
|
|
25856
|
-
submittedSha: foldDigest(submitted)
|
|
26615
|
+
submittedSha: foldDigest(submitted),
|
|
26616
|
+
...submitted === head ? {} : { head },
|
|
26617
|
+
...args.checkpointID === undefined ? {} : { answered: [args.checkpointID] }
|
|
25857
26618
|
};
|
|
25858
26619
|
await this.storage.set(this.key(args.sessionID), next);
|
|
25859
26620
|
return next;
|
|
@@ -25862,8 +26623,12 @@ class FoldOwner {
|
|
|
25862
26623
|
async observe(args) {
|
|
25863
26624
|
return this.serial(args.sessionID, async () => {
|
|
25864
26625
|
let state = await this.read(args.sessionID);
|
|
25865
|
-
|
|
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;
|
|
25866
26630
|
state = undefined;
|
|
26631
|
+
}
|
|
25867
26632
|
let changed = !state;
|
|
25868
26633
|
const observedSha = foldDigest(JSON.stringify(args.rendered));
|
|
25869
26634
|
const rendered = structuredClone(args.rendered);
|
|
@@ -25876,6 +26641,7 @@ class FoldOwner {
|
|
|
25876
26641
|
watermark: args.cutSeq,
|
|
25877
26642
|
submitted: args.summary,
|
|
25878
26643
|
submittedSha: foldDigest(args.summary),
|
|
26644
|
+
...carriedHead === undefined ? {} : { head: carriedHead },
|
|
25879
26645
|
reason: "boot_recovery"
|
|
25880
26646
|
};
|
|
25881
26647
|
}
|
|
@@ -27704,6 +28470,7 @@ ${cached}
|
|
|
27704
28470
|
}
|
|
27705
28471
|
async supplyHeld(args) {
|
|
27706
28472
|
const { draft, reader, summary } = args;
|
|
28473
|
+
const stored = args.checkpointText ?? summary;
|
|
27707
28474
|
if (this.options.protocol === 3) {
|
|
27708
28475
|
if (this.unprovenControls.has(draft.sessionID))
|
|
27709
28476
|
return false;
|
|
@@ -27734,7 +28501,7 @@ ${cached}
|
|
|
27734
28501
|
source: this.storage.sourceID,
|
|
27735
28502
|
sessionID: draft.sessionID,
|
|
27736
28503
|
admissionID: running.id,
|
|
27737
|
-
summary
|
|
28504
|
+
summary: stored
|
|
27738
28505
|
}));
|
|
27739
28506
|
const value = {
|
|
27740
28507
|
version: 3,
|
|
@@ -27743,7 +28510,7 @@ ${cached}
|
|
|
27743
28510
|
sourceDigest: foldDigest(reader.hostIdentity()),
|
|
27744
28511
|
sessionID: draft.sessionID,
|
|
27745
28512
|
admissionID: running.id,
|
|
27746
|
-
summaryDigest: foldDigest(
|
|
28513
|
+
summaryDigest: foldDigest(stored),
|
|
27747
28514
|
historyDigest: historyDigest(reader, draft.sessionID, running.seq - 1, replay.floor.after)
|
|
27748
28515
|
}
|
|
27749
28516
|
};
|
|
@@ -27795,7 +28562,7 @@ ${cached}
|
|
|
27795
28562
|
source: this.storage.sourceID,
|
|
27796
28563
|
sessionID: draft.sessionID,
|
|
27797
28564
|
admissionID: running.id,
|
|
27798
|
-
summary
|
|
28565
|
+
summary: stored
|
|
27799
28566
|
}));
|
|
27800
28567
|
return true;
|
|
27801
28568
|
}
|
|
@@ -27831,7 +28598,7 @@ ${cached}
|
|
|
27831
28598
|
source: this.storage.sourceID,
|
|
27832
28599
|
sessionID: draft.sessionID,
|
|
27833
28600
|
admissionID: id,
|
|
27834
|
-
summary
|
|
28601
|
+
summary: stored
|
|
27835
28602
|
};
|
|
27836
28603
|
await this.storage.supply(draft.sessionID, id, JSON.stringify(snapshot));
|
|
27837
28604
|
if (this.admissions) {
|
|
@@ -27839,7 +28606,7 @@ ${cached}
|
|
|
27839
28606
|
sourceDigest: foldDigest(reader.hostIdentity()),
|
|
27840
28607
|
sessionID: draft.sessionID,
|
|
27841
28608
|
admissionID: id,
|
|
27842
|
-
summaryDigest: foldDigest(
|
|
28609
|
+
summaryDigest: foldDigest(stored),
|
|
27843
28610
|
historyDigest: historyDigest(reader, draft.sessionID, (running?.seq ?? through) - 1)
|
|
27844
28611
|
};
|
|
27845
28612
|
const payload = JSON.stringify(provenance);
|
|
@@ -27930,7 +28697,7 @@ ${cached}
|
|
|
27930
28697
|
await this.storage.saveTail(sessionID, JSON.stringify({
|
|
27931
28698
|
model,
|
|
27932
28699
|
sourceSeq: through,
|
|
27933
|
-
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)
|
|
27934
28701
|
}), []);
|
|
27935
28702
|
this.loaded.set(sessionID, through);
|
|
27936
28703
|
this.dirty.delete(sessionID);
|
|
@@ -28097,12 +28864,6 @@ class HostFoldPolicy {
|
|
|
28097
28864
|
}
|
|
28098
28865
|
}
|
|
28099
28866
|
|
|
28100
|
-
// src/v2/fold/summary.ts
|
|
28101
|
-
var RAW_HISTORY_ACCOUNT = "Magic Context retains the conversation as raw messages; no summarized history is available yet.";
|
|
28102
|
-
function hasFoldSummary(summary) {
|
|
28103
|
-
return typeof summary === "string" && summary.replace(/<[^>]*>/g, "").trim().length > 0;
|
|
28104
|
-
}
|
|
28105
|
-
|
|
28106
28867
|
// src/v2/fork-inheritance.ts
|
|
28107
28868
|
var RAW_TYPES = new Set(RAW_MESSAGE_TYPES2);
|
|
28108
28869
|
function forkBoundarySeq(origin, sequenceForId) {
|
|
@@ -41314,7 +42075,7 @@ var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?
|
|
|
41314
42075
|
var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
|
|
41315
42076
|
var e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
|
|
41316
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])))`;
|
|
41317
|
-
var
|
|
42078
|
+
var date2 = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
|
|
41318
42079
|
function timeSource(args) {
|
|
41319
42080
|
const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
|
|
41320
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+)?)?`;
|
|
@@ -42199,7 +42960,7 @@ var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def
|
|
|
42199
42960
|
$ZodStringFormat.init(inst, def);
|
|
42200
42961
|
});
|
|
42201
42962
|
var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
|
|
42202
|
-
def.pattern ?? (def.pattern =
|
|
42963
|
+
def.pattern ?? (def.pattern = date2);
|
|
42203
42964
|
$ZodStringFormat.init(inst, def);
|
|
42204
42965
|
});
|
|
42205
42966
|
var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
|
|
@@ -50954,7 +51715,7 @@ var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
|
|
|
50954
51715
|
$ZodISODate.init(inst, def);
|
|
50955
51716
|
ZodStringFormat.init(inst, def);
|
|
50956
51717
|
});
|
|
50957
|
-
function
|
|
51718
|
+
function date3(params) {
|
|
50958
51719
|
return _isoDate(ZodISODate, params);
|
|
50959
51720
|
}
|
|
50960
51721
|
var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
|
|
@@ -51143,7 +51904,7 @@ var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
|
|
|
51143
51904
|
inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
|
|
51144
51905
|
inst.e164 = (params) => inst.check(_e164(ZodE164, params));
|
|
51145
51906
|
inst.datetime = (params) => inst.check(datetime2(params));
|
|
51146
|
-
inst.date = (params) => inst.check(
|
|
51907
|
+
inst.date = (params) => inst.check(date3(params));
|
|
51147
51908
|
inst.time = (params) => inst.check(time2(params));
|
|
51148
51909
|
inst.duration = (params) => inst.check(duration2(params));
|
|
51149
51910
|
});
|
|
@@ -51470,7 +52231,7 @@ var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => {
|
|
|
51470
52231
|
inst.minDate = c.minimum ? new Date(c.minimum) : null;
|
|
51471
52232
|
inst.maxDate = c.maximum ? new Date(c.maximum) : null;
|
|
51472
52233
|
});
|
|
51473
|
-
function
|
|
52234
|
+
function date4(params) {
|
|
51474
52235
|
return _date(ZodDate, params);
|
|
51475
52236
|
}
|
|
51476
52237
|
var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
|
|
@@ -52033,7 +52794,7 @@ function boolean4(params) {
|
|
|
52033
52794
|
function bigint3(params) {
|
|
52034
52795
|
return _coercedBigint(ZodBigInt, params);
|
|
52035
52796
|
}
|
|
52036
|
-
function
|
|
52797
|
+
function date5(params) {
|
|
52037
52798
|
return _coercedDate(ZodDate, params);
|
|
52038
52799
|
}
|
|
52039
52800
|
|
|
@@ -54457,14 +55218,14 @@ function applyCheckpointHead(draft, head) {
|
|
|
54457
55218
|
const first = draft.messages.find((message) => message.id === HEAD_IDS[0]);
|
|
54458
55219
|
const baseline = first?.content.find((part) => part.type === "text")?.text;
|
|
54459
55220
|
if (typeof baseline !== "string") {
|
|
54460
|
-
draft.messages.unshift(checkpoint);
|
|
55221
|
+
draft.messages.unshift(withRecordedHead(checkpoint, submitted, head.head));
|
|
54461
55222
|
return true;
|
|
54462
55223
|
}
|
|
54463
55224
|
for (const part of checkpoint.content)
|
|
54464
55225
|
if (part.type === "text" && typeof part.text === "string") {
|
|
54465
55226
|
part.text = part.text.replace(`<summary>
|
|
54466
55227
|
${submitted}
|
|
54467
|
-
</summary>`, `<summary>
|
|
55228
|
+
</summary>`, () => `<summary>
|
|
54468
55229
|
${baseline}
|
|
54469
55230
|
</summary>`);
|
|
54470
55231
|
}
|
|
@@ -54474,24 +55235,46 @@ ${baseline}
|
|
|
54474
55235
|
draft.messages.splice(0, draft.messages.length, checkpoint, ...draft.messages.filter((message) => message !== first));
|
|
54475
55236
|
return true;
|
|
54476
55237
|
}
|
|
55238
|
+
function servableCarrier(stored, head) {
|
|
55239
|
+
return !isCheckpointNote(stored) || head !== undefined;
|
|
55240
|
+
}
|
|
54477
55241
|
function bindKeptInstructionCoordinates(messages, incoming, reader, sessionID) {
|
|
54478
55242
|
const rows = reader.instructionRowsThrough(sessionID, reader.latestSequence(sessionID));
|
|
54479
55243
|
let previous;
|
|
54480
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;
|
|
54481
55246
|
const bind = (next) => {
|
|
54482
55247
|
if (!pending.length)
|
|
54483
55248
|
return;
|
|
54484
55249
|
const candidates = rows.filter((row) => (previous === undefined || row.seq > previous) && (next === undefined || row.seq < next));
|
|
54485
55250
|
const selected = previous === undefined ? candidates.slice(-pending.length) : next === undefined ? candidates.slice(0, pending.length) : candidates;
|
|
54486
|
-
if (selected.length === pending.length && selected.every((row, index) => {
|
|
54487
|
-
const message = pending[index];
|
|
54488
|
-
return message?.role === "system" && message.content.length === 1 && message.content[0]?.type === "text" && message.content[0].text === row.data.text;
|
|
54489
|
-
})) {
|
|
55251
|
+
if (selected.length === pending.length && selected.every((row, index) => matches(pending[index], row))) {
|
|
54490
55252
|
selected.forEach((row, index) => {
|
|
54491
55253
|
const message = pending[index];
|
|
54492
55254
|
if (message)
|
|
54493
55255
|
bindNativeRowID(message, row.id, row.seq);
|
|
54494
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
|
+
});
|
|
54495
55278
|
}
|
|
54496
55279
|
pending = [];
|
|
54497
55280
|
};
|
|
@@ -54596,6 +55379,30 @@ function estimateCheckpointRequest(draft) {
|
|
|
54596
55379
|
sessionId: draft.sessionID
|
|
54597
55380
|
});
|
|
54598
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
|
+
}
|
|
54599
55406
|
var HIDDEN_SESSION_ERROR_GRACE_MS = 50;
|
|
54600
55407
|
var STORE_POOL_DISPOSE_WAIT_MS = 1000;
|
|
54601
55408
|
function isBlockingV2TransformError(error) {
|
|
@@ -55273,8 +56080,8 @@ async function registerContext(context) {
|
|
|
55273
56080
|
servedModuleM0Text(sessionID),
|
|
55274
56081
|
await nativeFoldReplay.baseline(sessionID),
|
|
55275
56082
|
meta.cachedM0Bytes?.toString("utf8")
|
|
55276
|
-
].find(
|
|
55277
|
-
return !meta.isSubagent &&
|
|
56083
|
+
].find(isHistoryHead);
|
|
56084
|
+
return !meta.isSubagent && isHistoryHead(summary) && nativeFoldReplay.canFold(sessionID, reader);
|
|
55278
56085
|
},
|
|
55279
56086
|
threshold: Number(process.env.MC_OC2_HOST_FOLD_ROWS ?? 1000),
|
|
55280
56087
|
log: sessionLog2
|
|
@@ -55492,12 +56299,13 @@ async function registerContext(context) {
|
|
|
55492
56299
|
const state = getOrCreateSessionMeta(storage.require(), draft.sessionID);
|
|
55493
56300
|
const staged = manual && moduleBaseline == null ? stageManualBaseline(storage.require(), draft.sessionID, () => materialize(draft)) : undefined;
|
|
55494
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);
|
|
55495
56303
|
const candidate = [
|
|
55496
56304
|
moduleBaseline,
|
|
55497
56305
|
await nativeFoldReplay.baseline(draft.sessionID),
|
|
55498
56306
|
state.cachedM0Bytes?.toString("utf8"),
|
|
55499
|
-
|
|
55500
|
-
].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)));
|
|
55501
56309
|
const manualHistory = manual && hasFoldSummary(staged?.summary ?? moduleBaseline);
|
|
55502
56310
|
const summary = manualHistory ? staged?.summary ?? candidate ?? RAW_HISTORY_ACCOUNT : candidate ?? RAW_HISTORY_ACCOUNT;
|
|
55503
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;
|
|
@@ -55506,6 +56314,7 @@ async function registerContext(context) {
|
|
|
55506
56314
|
reader,
|
|
55507
56315
|
previousCut: reader.latestCompaction(draft.sessionID),
|
|
55508
56316
|
summary,
|
|
56317
|
+
checkpointText: CHECKPOINT_NOTE,
|
|
55509
56318
|
manual: manualReplay ? { replay: manualReplay, commit: () => staged?.commit() } : undefined
|
|
55510
56319
|
})) {
|
|
55511
56320
|
if (manualHistory) {
|
|
@@ -55515,7 +56324,10 @@ async function registerContext(context) {
|
|
|
55515
56324
|
historyRefreshSessions.add(draft.sessionID);
|
|
55516
56325
|
requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "host_compaction");
|
|
55517
56326
|
}
|
|
55518
|
-
draft.result = {
|
|
56327
|
+
draft.result = {
|
|
56328
|
+
summary: CHECKPOINT_NOTE,
|
|
56329
|
+
metadata: { keepID: undefined }
|
|
56330
|
+
};
|
|
55519
56331
|
return;
|
|
55520
56332
|
}
|
|
55521
56333
|
if (manual)
|
|
@@ -55534,7 +56346,9 @@ async function registerContext(context) {
|
|
|
55534
56346
|
materialize: () => {
|
|
55535
56347
|
const summary = moduleBaseline ?? materialize(draft);
|
|
55536
56348
|
return hasFoldSummary(summary) ? summary : RAW_HISTORY_ACCOUNT;
|
|
55537
|
-
}
|
|
56349
|
+
},
|
|
56350
|
+
checkpointText: CHECKPOINT_NOTE,
|
|
56351
|
+
checkpointID: running?.id
|
|
55538
56352
|
});
|
|
55539
56353
|
sessionLog2(draft.sessionID, `v2 compaction hook: fired answered=true source=${source}`);
|
|
55540
56354
|
draft.result = { summary: fold.submitted, metadata: { keepID: undefined } };
|
|
@@ -55622,7 +56436,7 @@ async function registerContext(context) {
|
|
|
55622
56436
|
onPassPermission: (sessionID, permission) => {
|
|
55623
56437
|
checkpointPassPermissions.set(sessionID, permission);
|
|
55624
56438
|
},
|
|
55625
|
-
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),
|
|
55626
56440
|
compactionOff,
|
|
55627
56441
|
storeGeneration: "v2",
|
|
55628
56442
|
normalizeRestoredAssistantText: (text, providerID) => stripCopiedTagNotation(text, providerID === "anthropic"),
|
|
@@ -55975,6 +56789,7 @@ async function registerContext(context) {
|
|
|
55975
56789
|
const reader = openStoreReader();
|
|
55976
56790
|
let checkpoint;
|
|
55977
56791
|
let submitted;
|
|
56792
|
+
let recordedHead;
|
|
55978
56793
|
let upgradeCheckpointSequence;
|
|
55979
56794
|
try {
|
|
55980
56795
|
const candidates = syntheticCandidates(context, draft.sessionID, reader.syntheticMessageIDs(draft.sessionID));
|
|
@@ -56014,9 +56829,13 @@ async function registerContext(context) {
|
|
|
56014
56829
|
requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "host_compaction");
|
|
56015
56830
|
}
|
|
56016
56831
|
});
|
|
56017
|
-
|
|
56018
|
-
|
|
56019
|
-
|
|
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
|
+
}
|
|
56020
56839
|
}
|
|
56021
56840
|
}
|
|
56022
56841
|
let nativeRestored = localCut ? nativeFoldReplay?.legacyUpgradeInput(draft.sessionID, draft.model) : undefined;
|
|
@@ -56053,8 +56872,13 @@ async function registerContext(context) {
|
|
|
56053
56872
|
requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "host_compaction");
|
|
56054
56873
|
}
|
|
56055
56874
|
});
|
|
56056
|
-
|
|
56057
|
-
|
|
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");
|
|
56058
56882
|
}
|
|
56059
56883
|
draft.messages.splice(0, draft.messages.length, ...await restoreAfterCheckpoint({
|
|
56060
56884
|
db,
|
|
@@ -56094,11 +56918,15 @@ async function registerContext(context) {
|
|
|
56094
56918
|
if (stripCheckpointRecentContext(projected, submitted)) {
|
|
56095
56919
|
const estimate = estimateCheckpointRequest({
|
|
56096
56920
|
...draft,
|
|
56097
|
-
messages: [
|
|
56921
|
+
messages: [
|
|
56922
|
+
withRecordedHead(checkpoint, submitted, recordedHead),
|
|
56923
|
+
...draft.messages
|
|
56924
|
+
]
|
|
56098
56925
|
});
|
|
56099
56926
|
checkpointInputEstimates.set(draft.sessionID, {
|
|
56100
56927
|
tokens: estimate.tokens,
|
|
56101
|
-
pressureTokens: estimate.pressureTokens ?? estimate.tokens
|
|
56928
|
+
pressureTokens: estimate.pressureTokens ?? estimate.tokens,
|
|
56929
|
+
hostAddedTokens: estimateCheckpointFraming(draft, projected, submitted)
|
|
56102
56930
|
});
|
|
56103
56931
|
}
|
|
56104
56932
|
}
|
|
@@ -56144,7 +56972,11 @@ async function registerContext(context) {
|
|
|
56144
56972
|
if (db) {
|
|
56145
56973
|
await deliverPendingChannel2(context, db, draft.sessionID, channel1.get(draft.sessionID));
|
|
56146
56974
|
}
|
|
56147
|
-
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;
|
|
56148
56980
|
const servedHead = head && structuredClone(head);
|
|
56149
56981
|
const headApplied = head ? applyCheckpointHead(draft, head) : false;
|
|
56150
56982
|
if (nativeMessages && (!checkpoint || upgradeCheckpointSequence !== undefined)) {
|