@cortexkit/opencode-magic-context 0.49.51 → 0.49.53
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 +3 -3
- package/dist/chunk-embedding-write-worker.js +1 -1
- package/dist/{context-r77d4fdy.js → context-p6r0bk7a.js} +90 -51
- package/dist/{embedding-backfill-3wdjzrvs.js → embedding-backfill-qes2kf1c.js} +2 -2
- package/dist/features/magic-context/compartment-embedding.d.ts.map +1 -1
- package/dist/features/magic-context/message-fts-session-filter.d.ts +1 -1
- package/dist/features/magic-context/message-fts-session-filter.d.ts.map +1 -1
- package/dist/features/magic-context/project-embedding-registry.d.ts +8 -0
- package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
- package/dist/features/magic-context/search.d.ts.map +1 -1
- package/dist/features/magic-context/storage-host-instruction-retention.d.ts +10 -3
- package/dist/features/magic-context/storage-host-instruction-retention.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta-persisted.d.ts +20 -1
- package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta.d.ts +1 -1
- package/dist/features/magic-context/storage-meta.d.ts.map +1 -1
- package/dist/features/magic-context/storage.d.ts +1 -1
- package/dist/features/magic-context/storage.d.ts.map +1 -1
- package/dist/features/magic-context/transform-decision-log.d.ts +1 -1
- package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
- package/dist/hooks/magic-context/active-anthropic-turn.d.ts +6 -0
- package/dist/hooks/magic-context/active-anthropic-turn.d.ts.map +1 -1
- package/dist/hooks/magic-context/compaction-marker-manager.d.ts +2 -1
- package/dist/hooks/magic-context/compaction-marker-manager.d.ts.map +1 -1
- package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
- package/dist/hooks/magic-context/history-boundary-recovery.d.ts +15 -0
- package/dist/hooks/magic-context/history-boundary-recovery.d.ts.map +1 -0
- package/dist/hooks/magic-context/hook.d.ts.map +1 -1
- package/dist/hooks/magic-context/host-served-rows.d.ts +12 -2
- package/dist/hooks/magic-context/host-served-rows.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/latest-assistant-turn.d.ts +43 -0
- package/dist/hooks/magic-context/latest-assistant-turn.d.ts.map +1 -1
- package/dist/hooks/magic-context/latest-thinking-recovery.d.ts +102 -26
- package/dist/hooks/magic-context/latest-thinking-recovery.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts +18 -2
- package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
- package/dist/hooks/magic-context/pass-outcome.d.ts.map +1 -1
- package/dist/hooks/magic-context/pending-marker-rearm.d.ts +20 -0
- package/dist/hooks/magic-context/pending-marker-rearm.d.ts.map +1 -0
- package/dist/hooks/magic-context/persist-filtered-noise.d.ts +1 -1
- package/dist/hooks/magic-context/persist-filtered-noise.d.ts.map +1 -1
- package/dist/hooks/magic-context/priced-pass-sizing.d.ts +7 -0
- package/dist/hooks/magic-context/priced-pass-sizing.d.ts.map +1 -1
- package/dist/hooks/magic-context/routine-cleanup-decision.d.ts +11 -1
- package/dist/hooks/magic-context/routine-cleanup-decision.d.ts.map +1 -1
- package/dist/hooks/magic-context/rust-mode-transform.d.ts +1 -1
- package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
- package/dist/hooks/magic-context/served-check.d.ts +127 -0
- package/dist/hooks/magic-context/served-check.d.ts.map +1 -0
- package/dist/hooks/magic-context/signed-thinking-hold.d.ts +32 -4
- package/dist/hooks/magic-context/signed-thinking-hold.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +37 -2
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/hooks/magic-context/unresolved-history-boundary.d.ts +21 -2
- package/dist/hooks/magic-context/unresolved-history-boundary.d.ts.map +1 -1
- package/dist/{index-n0twfvah.js → index-2ctn7q09.js} +531 -17
- package/dist/{index-bamnjp2t.js → index-2m54t4g1.js} +9 -5
- package/dist/{index-30sf7e5k.js → index-3b5k5vma.js} +27 -16
- package/dist/{index-ct3ettqt.js → index-3h0wyv22.js} +3 -3
- package/dist/{index-hkveze74.js → index-3hhq18q0.js} +1 -1
- package/dist/{index-kaqs6h31.js → index-52x68mj4.js} +1 -1
- package/dist/{index-wr2t8zb0.js → index-5684dzbv.js} +648 -69
- package/dist/{index-s131svmx.js → index-7wasafnb.js} +1 -1
- package/dist/{index-8d7gkgjs.js → index-85chg6fw.js} +1 -1
- package/dist/{index-z4832qfe.js → index-a6bxwv4a.js} +1 -1
- package/dist/{index-h8g08nxs.js → index-chjsdqg6.js} +104 -62
- package/dist/{index-5dptmnvd.js → index-esm4farg.js} +8 -7
- package/dist/{index-97bjd14c.js → index-fbs0f5ch.js} +4 -4
- package/dist/{index-cwj6qhmf.js → index-kwpweqzs.js} +8 -3
- package/dist/{index-07rp6xcn.js → index-n3rxwtwt.js} +48 -15
- package/dist/{index-gv7dwx5b.js → index-p7ssfv6p.js} +503 -395
- package/dist/{index-v4a1pnny.js → index-pgbmbtdq.js} +4 -4
- package/dist/{index-mjh63zvw.js → index-wpab17w4.js} +1 -1
- package/dist/index.js +53 -32
- package/dist/{message-index-bounded-k0ebpy3y.js → message-index-bounded-7p3064st.js} +2 -2
- package/dist/migration-worker.js +1 -1
- package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
- package/dist/plugin/messages-transform.d.ts +6 -0
- package/dist/plugin/messages-transform.d.ts.map +1 -1
- package/dist/{project-embedding-registry-5dwh5zfn.js → project-embedding-registry-m8t547fb.js} +3 -1
- package/dist/raw-ordinal-warmup-worker.js +3 -3
- package/dist/{read-session-chunk-6712p893.js → read-session-chunk-cyks9yx4.js} +1 -1
- package/dist/{recomp-orchestrator-8ebydg5j.js → recomp-orchestrator-d4nks9da.js} +9 -9
- package/dist/{render-dtc4qkq4.js → render-gc1fn4nz.js} +5 -5
- package/dist/{search-75bj2430.js → search-1bjy7yhc.js} +8 -8
- package/dist/{search-archive-f6hjbnsa.js → search-archive-hdrfjgv8.js} +4 -4
- package/dist/shared/test-open-files.d.ts +17 -0
- package/dist/shared/test-open-files.d.ts.map +1 -0
- package/dist/shared/user-facing-codes.d.ts +7 -2
- package/dist/shared/user-facing-codes.d.ts.map +1 -1
- package/dist/tools/ctx-expand/search-archive.d.ts.map +1 -1
- package/dist/{transform-postprocess-phase-1bg25094.js → transform-postprocess-phase-9e53b1dr.js} +10 -10
- package/dist/v2/auto-search-worker.js +3 -3
- package/dist/v2/chunk-embedding-write-worker.js +1 -1
- package/dist/v2/{context-cpbhpxks.js → context-1p22880w.js} +1084 -370
- package/dist/v2/{embedding-backfill-x1zpc04f.js → embedding-backfill-bwcmw1te.js} +2 -2
- package/dist/v2/fold/instruction-supersession.d.ts.map +1 -1
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/{message-index-bounded-a36rw93p.js → message-index-bounded-mjpxz7wp.js} +2 -2
- package/dist/v2/migration-worker.js +1 -1
- package/dist/v2/{project-embedding-registry-v2fxrs8b.js → project-embedding-registry-7qcs8c61.js} +3 -1
- package/dist/v2/raw-ordinal-warmup-worker.js +3 -3
- package/dist/v2/{read-session-chunk-hzhxvhyv.js → read-session-chunk-cxk2kssy.js} +1 -1
- package/dist/v2/{recomp-orchestrator-yzr49pd0.js → recomp-orchestrator-e560ryjm.js} +8 -8
- package/dist/v2/{render-rhaevxv1.js → render-rk17pvy0.js} +5 -5
- package/dist/v2/{search-archive-9924fyk8.js → search-archive-a51g9sp7.js} +4 -4
- package/dist/v2/{search-3yrdpr38.js → search-kvzyj2mf.js} +7 -7
- package/dist/v2/{server-scp3y4dh.js → server-28g1b00j.js} +1 -1
- package/dist/v2/{server-kaqs6h31.js → server-52x68mj4.js} +1 -1
- package/dist/v2/{server-0k586y7d.js → server-71bg2psk.js} +3 -3
- package/dist/v2/{server-3bfc26r7.js → server-77rvx3wn.js} +34 -15
- package/dist/v2/{server-jxrqsn84.js → server-ah1j996f.js} +1 -1
- package/dist/v2/{server-sgn61hht.js → server-bjsmb6zs.js} +8 -3
- package/dist/v2/{server-16kfxcxj.js → server-bzh1fkvd.js} +1 -1
- package/dist/v2/{server-vjadwb3j.js → server-d5zgah57.js} +1 -1
- package/dist/v2/{server-q93jdtz8.js → server-e37d2zt4.js} +8 -7
- package/dist/v2/{server-016a1whm.js → server-fh6dhx8c.js} +104 -62
- package/dist/v2/{server-eznem83k.js → server-jmrd7vwc.js} +26 -15
- package/dist/v2/{server-4h4acntc.js → server-k3vtc89v.js} +9 -5
- package/dist/v2/{server-88yvx6r9.js → server-zq704789.js} +531 -17
- package/dist/v2/server.js +2 -2
- package/dist/v2/{v2-archive-reader-5ggewg8q.js → v2-archive-reader-hsvddme0.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-36c5wyvq.js → wrapup-orchestrator-ckpj1yvj.js} +8 -8
- package/dist/{v2-archive-reader-gx5ke1d7.js → v2-archive-reader-qgqrxgrq.js} +1 -1
- package/dist/{wrapup-orchestrator-ya31knav.js → wrapup-orchestrator-6189f37j.js} +10 -10
- package/package.json +1 -1
- package/src/shared/escalation-bands.test.ts +16 -1
- package/src/shared/sqlite-placeholders.test.ts +103 -0
- package/src/shared/storage-file-mutex-review.test.ts +5 -7
- package/src/shared/test-open-files.test.ts +194 -0
- package/src/shared/test-open-files.ts +71 -0
- package/src/shared/user-facing-codes.ts +8 -2
|
@@ -175,6 +175,7 @@ import {
|
|
|
175
175
|
trimMemoriesToBudgetV2,
|
|
176
176
|
renderMemoryBlockV2,
|
|
177
177
|
stripMemoryMuralBlock,
|
|
178
|
+
servedHeadTexts,
|
|
178
179
|
materializeM0,
|
|
179
180
|
hydrateCachedM0Mural,
|
|
180
181
|
resetPrefixTrimFallbackState,
|
|
@@ -215,7 +216,7 @@ import {
|
|
|
215
216
|
startCompartmentAgent,
|
|
216
217
|
setRecompStarting2,
|
|
217
218
|
setRecompTerminal2
|
|
218
|
-
} from "./server-
|
|
219
|
+
} from "./server-fh6dhx8c.js";
|
|
219
220
|
import {
|
|
220
221
|
resolveHistorianModel2
|
|
221
222
|
} from "./server-5kym00ag.js";
|
|
@@ -498,6 +499,9 @@ import {
|
|
|
498
499
|
compactionOffFrozenThinkingIds,
|
|
499
500
|
getThinkingBindingRecoveryTarget,
|
|
500
501
|
armThinkingBindingRecovery,
|
|
502
|
+
noteBindingRecoveryAwaitingClear,
|
|
503
|
+
bindingRecoveryAwaitingClear,
|
|
504
|
+
retryBindingRecoveryClear,
|
|
501
505
|
clearThinkingBindingRecoveryIf,
|
|
502
506
|
getMergedReasoningStrippedIds,
|
|
503
507
|
addMergedReasoningStrippedIds,
|
|
@@ -600,7 +604,7 @@ import {
|
|
|
600
604
|
readRawSessionMessageOrdinalById2,
|
|
601
605
|
readSessionChunk2,
|
|
602
606
|
readRawSessionSeedTail2
|
|
603
|
-
} from "./server-
|
|
607
|
+
} from "./server-77rvx3wn.js";
|
|
604
608
|
import {
|
|
605
609
|
BoundedSessionMap,
|
|
606
610
|
recordToolDefinitionSet,
|
|
@@ -611,7 +615,7 @@ import {
|
|
|
611
615
|
cleanSearchText,
|
|
612
616
|
matchedSearchSnippet,
|
|
613
617
|
getLastIndexedOrdinal
|
|
614
|
-
} from "./server-
|
|
618
|
+
} from "./server-bzh1fkvd.js";
|
|
615
619
|
import"./server-966dq3pd.js";
|
|
616
620
|
import {
|
|
617
621
|
getMessageIndexEpoch,
|
|
@@ -638,7 +642,7 @@ import {
|
|
|
638
642
|
resolveMemoriesByIdsForSearch2,
|
|
639
643
|
unifiedSearch2,
|
|
640
644
|
formatSearchResults2
|
|
641
|
-
} from "./server-
|
|
645
|
+
} from "./server-jmrd7vwc.js";
|
|
642
646
|
import {
|
|
643
647
|
embedPauseBySession,
|
|
644
648
|
embedRunStateBySession,
|
|
@@ -745,6 +749,16 @@ import {
|
|
|
745
749
|
noteLkgHealthyPrefix,
|
|
746
750
|
lkgRecoveryReplayUnproven,
|
|
747
751
|
lkgRecoveryEntryUnproven,
|
|
752
|
+
beginServedRequest,
|
|
753
|
+
noteServedPassPermission,
|
|
754
|
+
noteServedModel,
|
|
755
|
+
noteServedReplay,
|
|
756
|
+
noteServedHostInput,
|
|
757
|
+
noteServedRefusal,
|
|
758
|
+
countServedRefusal,
|
|
759
|
+
dropServedRecord,
|
|
760
|
+
forgetServedRecord,
|
|
761
|
+
commitServedRequest,
|
|
748
762
|
lkgInputIdentity,
|
|
749
763
|
beginLkgPass,
|
|
750
764
|
visitMessageContentFields,
|
|
@@ -753,6 +767,7 @@ import {
|
|
|
753
767
|
signatureForFields,
|
|
754
768
|
exactReusablePrefix,
|
|
755
769
|
incrementalLkgContentDigests,
|
|
770
|
+
lkgContentDigest,
|
|
756
771
|
lkgSlotRejection,
|
|
757
772
|
captureSlot,
|
|
758
773
|
getInMemorySlot,
|
|
@@ -773,7 +788,7 @@ import {
|
|
|
773
788
|
saveSourceContent,
|
|
774
789
|
replaceSourceContent,
|
|
775
790
|
getSourceContents
|
|
776
|
-
} from "./server-
|
|
791
|
+
} from "./server-zq704789.js";
|
|
777
792
|
import {
|
|
778
793
|
startBootDeadline,
|
|
779
794
|
getUnconfirmedMigrationHolders,
|
|
@@ -789,7 +804,7 @@ import {
|
|
|
789
804
|
openDatabaseAsync,
|
|
790
805
|
isDatabasePersisted,
|
|
791
806
|
getDatabasePersistenceError
|
|
792
|
-
} from "./server-
|
|
807
|
+
} from "./server-28g1b00j.js";
|
|
793
808
|
import {
|
|
794
809
|
V2_MEMORY_CATEGORIES,
|
|
795
810
|
CATEGORY_PRIORITY
|
|
@@ -870,7 +885,7 @@ import {
|
|
|
870
885
|
embedSessionCompartmentChunks2,
|
|
871
886
|
getEmbeddingCoverageStatus2,
|
|
872
887
|
getAutoEmbeddingSessionCoverage2
|
|
873
|
-
} from "./server-
|
|
888
|
+
} from "./server-k3vtc89v.js";
|
|
874
889
|
import {
|
|
875
890
|
GIT_SWEEP_LEASE_RENEWAL_MS,
|
|
876
891
|
acquireGitSweepLease,
|
|
@@ -893,7 +908,7 @@ import {
|
|
|
893
908
|
} from "./server-brsx45r6.js";
|
|
894
909
|
import {
|
|
895
910
|
cosineSimilarity
|
|
896
|
-
} from "./server-
|
|
911
|
+
} from "./server-d5zgah57.js";
|
|
897
912
|
import {
|
|
898
913
|
computeCueContentHash,
|
|
899
914
|
hasMuralCueColumns,
|
|
@@ -938,7 +953,7 @@ import {
|
|
|
938
953
|
readGitFileChangeTimesSince,
|
|
939
954
|
verificationFileExists,
|
|
940
955
|
normalizeVerificationFiles
|
|
941
|
-
} from "./server-
|
|
956
|
+
} from "./server-bjsmb6zs.js";
|
|
942
957
|
import {
|
|
943
958
|
registerNotificationSink2,
|
|
944
959
|
pushNotification2,
|
|
@@ -975,14 +990,14 @@ import {
|
|
|
975
990
|
renderMessageByOrdinal2,
|
|
976
991
|
renderVerboseRangeForTool2,
|
|
977
992
|
renderItemByTag2
|
|
978
|
-
} from "./server-
|
|
979
|
-
import"./server-
|
|
993
|
+
} from "./server-ah1j996f.js";
|
|
994
|
+
import"./server-52x68mj4.js";
|
|
980
995
|
import {
|
|
981
996
|
readV2ArchiveOffThread2
|
|
982
|
-
} from "./server-
|
|
997
|
+
} from "./server-71bg2psk.js";
|
|
983
998
|
import {
|
|
984
999
|
renderSearchArchiveOffThread2
|
|
985
|
-
} from "./server-
|
|
1000
|
+
} from "./server-e37d2zt4.js";
|
|
986
1001
|
import {
|
|
987
1002
|
markHostInstructionRow,
|
|
988
1003
|
hostInstructionRow,
|
|
@@ -2607,7 +2622,8 @@ var canonicalReasons = new Set([
|
|
|
2607
2622
|
"coverage_fold",
|
|
2608
2623
|
"profile_transition",
|
|
2609
2624
|
"host_compaction",
|
|
2610
|
-
"tag_identity_repair"
|
|
2625
|
+
"tag_identity_repair",
|
|
2626
|
+
"latest_turn_thinking_removed"
|
|
2611
2627
|
]);
|
|
2612
2628
|
var piReasonAliases = {
|
|
2613
2629
|
project_memory_change: "project_memory_epoch",
|
|
@@ -2647,11 +2663,12 @@ function normalizeMaterializeReason(harness, reason, rematerialized) {
|
|
|
2647
2663
|
function writeRustTransformDecision(args) {
|
|
2648
2664
|
const rawDecision = args.decision.trim();
|
|
2649
2665
|
const decisionUpper = rawDecision.toUpperCase();
|
|
2650
|
-
const
|
|
2666
|
+
const scheduled = decisionUpper === "HARD" || decisionUpper === "MIGRATE_HARD" ? { decision: "execute", materialized: true, bustedThisPass: true } : decisionUpper === "SOFT" || decisionUpper === "EXECUTE" || args.materializeReason === "ttl_idle" ? { decision: "execute", materialized: false, bustedThisPass: true } : decisionUpper === "SOFT+" ? { decision: "defer", materialized: false, bustedThisPass: false } : {
|
|
2651
2667
|
decision: rawDecision.toLowerCase() || "unknown",
|
|
2652
2668
|
materialized: false,
|
|
2653
2669
|
bustedThisPass: false
|
|
2654
2670
|
};
|
|
2671
|
+
const mapped = args.materializeReason === "latest_turn_thinking_removed" ? { ...scheduled, bustedThisPass: true } : scheduled;
|
|
2655
2672
|
pendingDecisionBySession.set(args.sessionId, {
|
|
2656
2673
|
tsMs: args.tsMs ?? Date.now(),
|
|
2657
2674
|
decision: mapped.decision,
|
|
@@ -7198,6 +7215,66 @@ function latestAssistantTurnStart(messages) {
|
|
|
7198
7215
|
function latestAssistantTurnMessages(messages) {
|
|
7199
7216
|
return new Set(messages.slice(latestAssistantTurnStart(messages)));
|
|
7200
7217
|
}
|
|
7218
|
+
function isSentAssistantMessage(message) {
|
|
7219
|
+
if (!isRecord(message) || role(message) !== "assistant")
|
|
7220
|
+
return false;
|
|
7221
|
+
const parts = content(message);
|
|
7222
|
+
if (!Array.isArray(parts) || parts.length === 0)
|
|
7223
|
+
return false;
|
|
7224
|
+
if (message.stopReason === "error" || message.stopReason === "aborted")
|
|
7225
|
+
return false;
|
|
7226
|
+
const error = isRecord(message.info) ? message.info.error : undefined;
|
|
7227
|
+
if (error === undefined || error === null)
|
|
7228
|
+
return true;
|
|
7229
|
+
return isRecord(error) && error.name === "MessageAbortedError" && parts.some((part) => isRecord(part) && part.type !== "step-start" && part.type !== "reasoning");
|
|
7230
|
+
}
|
|
7231
|
+
var PI_USER_ON_WIRE_ROLES = new Set([
|
|
7232
|
+
"user",
|
|
7233
|
+
"developer",
|
|
7234
|
+
"custom",
|
|
7235
|
+
"hookMessage",
|
|
7236
|
+
"bashExecution",
|
|
7237
|
+
"pythonExecution",
|
|
7238
|
+
"fileMention",
|
|
7239
|
+
"branchSummary",
|
|
7240
|
+
"compactionSummary"
|
|
7241
|
+
]);
|
|
7242
|
+
var TOOL_RESULT_TYPES = new Set(["tool_result", "toolResult", "tool-result"]);
|
|
7243
|
+
function isUserMessageOnWire(message) {
|
|
7244
|
+
if (!isRecord(message))
|
|
7245
|
+
return false;
|
|
7246
|
+
if (isRecord(message.info)) {
|
|
7247
|
+
if (message.info.role !== "user" || !Array.isArray(message.parts))
|
|
7248
|
+
return false;
|
|
7249
|
+
return message.parts.some((part) => isRecord(part) && part.ignored !== true && !TOOL_RESULT_TYPES.has(String(part.type)) && !(part.type === "text" && part.text === ""));
|
|
7250
|
+
}
|
|
7251
|
+
if (!PI_USER_ON_WIRE_ROLES.has(String(message.role)))
|
|
7252
|
+
return false;
|
|
7253
|
+
if (message.excludeFromContext === true)
|
|
7254
|
+
return false;
|
|
7255
|
+
if (message.role !== "user")
|
|
7256
|
+
return true;
|
|
7257
|
+
if (typeof message.content === "string")
|
|
7258
|
+
return message.content.length > 0;
|
|
7259
|
+
return Array.isArray(message.content) && message.content.some((block) => !isRecord(block) || !TOOL_RESULT_TYPES.has(String(block.type)));
|
|
7260
|
+
}
|
|
7261
|
+
function providerLatestTurn(messages) {
|
|
7262
|
+
let last = messages.length - 1;
|
|
7263
|
+
while (last >= 0 && !isSentAssistantMessage(messages[last]))
|
|
7264
|
+
last -= 1;
|
|
7265
|
+
if (last < 0)
|
|
7266
|
+
return;
|
|
7267
|
+
let start = last;
|
|
7268
|
+
while (start > 0 && !isUserMessageOnWire(messages[start - 1]))
|
|
7269
|
+
start -= 1;
|
|
7270
|
+
let first = start;
|
|
7271
|
+
while (first < last && !isSentAssistantMessage(messages[first]))
|
|
7272
|
+
first += 1;
|
|
7273
|
+
let end = last + 1;
|
|
7274
|
+
while (end < messages.length && !isUserMessageOnWire(messages[end]))
|
|
7275
|
+
end += 1;
|
|
7276
|
+
return { start, first, last, end };
|
|
7277
|
+
}
|
|
7201
7278
|
function isAnthropicThinkingPart(part, familyRoute) {
|
|
7202
7279
|
return isRecord(part) && THINKING_TYPES.has(String(part.type ?? part.kind)) && (familyRoute || isRecord(part.metadata) && isRecord(part.metadata.anthropic));
|
|
7203
7280
|
}
|
|
@@ -7286,18 +7363,113 @@ function retainedActiveThinkingParts(args) {
|
|
|
7286
7363
|
|
|
7287
7364
|
// src/hooks/magic-context/latest-thinking-recovery.ts
|
|
7288
7365
|
var LATEST_THINKING_RESTORE = "latest_thinking_original";
|
|
7366
|
+
var TURN_STATE = `${LATEST_THINKING_RESTORE}_turn:`;
|
|
7289
7367
|
var knownRejectedSessions = new Set;
|
|
7290
|
-
|
|
7291
|
-
|
|
7292
|
-
|
|
7293
|
-
var
|
|
7294
|
-
var
|
|
7295
|
-
function
|
|
7368
|
+
function isLatestThinkingRecoveryTarget(target) {
|
|
7369
|
+
return typeof target === "string" && target.startsWith(LATEST_THINKING_RESTORE);
|
|
7370
|
+
}
|
|
7371
|
+
var REFUSE_AT_REJECTION = 3;
|
|
7372
|
+
var STAGES = new Set(["armed", "restoring", "remove", "removed", "refused"]);
|
|
7373
|
+
function readState2(target) {
|
|
7374
|
+
if (!target.startsWith(TURN_STATE))
|
|
7375
|
+
return;
|
|
7376
|
+
try {
|
|
7377
|
+
const value = JSON.parse(target.slice(TURN_STATE.length));
|
|
7378
|
+
if (!isRecord(value) || !STAGES.has(String(value.stage)) || typeof value.first !== "string" || typeof value.last !== "string" || typeof value.rejections !== "number")
|
|
7379
|
+
return;
|
|
7380
|
+
return {
|
|
7381
|
+
stage: value.stage,
|
|
7382
|
+
first: value.first,
|
|
7383
|
+
last: value.last,
|
|
7384
|
+
rejections: value.rejections,
|
|
7385
|
+
...typeof value.pass === "string" ? { pass: value.pass } : {},
|
|
7386
|
+
...typeof value.model === "string" ? { model: value.model } : {},
|
|
7387
|
+
...typeof value.provider === "string" ? { provider: value.provider } : {},
|
|
7388
|
+
...value.accepted === true ? { accepted: true } : {}
|
|
7389
|
+
};
|
|
7390
|
+
} catch {
|
|
7391
|
+
return;
|
|
7392
|
+
}
|
|
7393
|
+
}
|
|
7394
|
+
function encodeState(state) {
|
|
7395
|
+
return TURN_STATE + JSON.stringify({
|
|
7396
|
+
stage: state.stage,
|
|
7397
|
+
first: state.first,
|
|
7398
|
+
last: state.last,
|
|
7399
|
+
rejections: state.rejections,
|
|
7400
|
+
...state.pass ? { pass: state.pass } : {},
|
|
7401
|
+
...state.model ? { model: state.model } : {},
|
|
7402
|
+
...state.provider ? { provider: state.provider } : {},
|
|
7403
|
+
...state.accepted ? { accepted: true } : {}
|
|
7404
|
+
});
|
|
7405
|
+
}
|
|
7406
|
+
function identifyTurn(messages, id) {
|
|
7407
|
+
const turn = providerLatestTurn(messages);
|
|
7408
|
+
if (!turn)
|
|
7409
|
+
return;
|
|
7410
|
+
const first = id(messages[turn.first], turn.first);
|
|
7411
|
+
const last = id(messages[turn.last], turn.last);
|
|
7412
|
+
return first && last ? { turn, bound: { first, last } } : undefined;
|
|
7413
|
+
}
|
|
7414
|
+
var lastPassTurn = new Map;
|
|
7415
|
+
var PROCESS_TOKEN = Math.random().toString(36).slice(2, 10);
|
|
7416
|
+
var passCounter = 0;
|
|
7417
|
+
var LATEST_THINKING_UNSAFE = "ANTHROPIC_LATEST_TURN_EDIT_UNSAFE: The provider keeps rejecting the thinking of this conversation's latest assistant turn, even after Magic Context restored or removed it. Sending a new message does not help, because the provider checks that same turn again. Switch the model once, or run /clear, to continue.";
|
|
7418
|
+
var LATEST_THINKING_NOT_SAVED = "Magic Context could not save the change this request needs after the provider rejected the thinking of the latest assistant turn (its database was busy or changed at the same moment). Nothing was sent. Send your message again.";
|
|
7419
|
+
function escalate(state, rejections) {
|
|
7420
|
+
switch (state.stage) {
|
|
7421
|
+
case "armed":
|
|
7422
|
+
return "armed";
|
|
7423
|
+
case "restoring":
|
|
7424
|
+
case "remove":
|
|
7425
|
+
return "remove";
|
|
7426
|
+
case "removed":
|
|
7427
|
+
if (state.accepted)
|
|
7428
|
+
return "remove";
|
|
7429
|
+
return rejections >= REFUSE_AT_REJECTION ? "refused" : "removed";
|
|
7430
|
+
case "refused":
|
|
7431
|
+
return "refused";
|
|
7432
|
+
}
|
|
7433
|
+
}
|
|
7434
|
+
function armLatestThinkingRecovery(db, sessionId, modelID) {
|
|
7296
7435
|
knownRejectedSessions.add(sessionId);
|
|
7297
7436
|
ensureSessionMetaRow(db, sessionId);
|
|
7298
7437
|
const current = getThinkingBindingRecoveryTarget(db, sessionId);
|
|
7299
|
-
const
|
|
7300
|
-
const
|
|
7438
|
+
const state = current ? readState2(current) : undefined;
|
|
7439
|
+
const pass = lastPassTurn.get(sessionId);
|
|
7440
|
+
let next;
|
|
7441
|
+
if (state) {
|
|
7442
|
+
if (pass !== undefined && state.pass === pass.pass)
|
|
7443
|
+
return;
|
|
7444
|
+
const rejections = state.accepted ? 1 : state.rejections + 1;
|
|
7445
|
+
const stage = escalate(state, rejections);
|
|
7446
|
+
const last = pass?.first === state.first ? pass.last : state.last;
|
|
7447
|
+
next = encodeState({
|
|
7448
|
+
...state,
|
|
7449
|
+
stage,
|
|
7450
|
+
last,
|
|
7451
|
+
rejections,
|
|
7452
|
+
pass: pass?.pass,
|
|
7453
|
+
accepted: false
|
|
7454
|
+
});
|
|
7455
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: provider rejected the bound turn again (rejection ${rejections}, first=${state.first} last=${last}); ${state.stage} -> ${stage}`);
|
|
7456
|
+
} else if (pass) {
|
|
7457
|
+
const model = pass.model ?? modelID;
|
|
7458
|
+
const provider = pass.model ? pass.provider : undefined;
|
|
7459
|
+
next = encodeState({
|
|
7460
|
+
stage: "armed",
|
|
7461
|
+
first: pass.first,
|
|
7462
|
+
last: pass.last,
|
|
7463
|
+
rejections: 1,
|
|
7464
|
+
pass: pass.pass,
|
|
7465
|
+
...model ? { model } : {},
|
|
7466
|
+
...provider ? { provider } : {}
|
|
7467
|
+
});
|
|
7468
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: armed for the provider's latest turn (first=${pass.first} last=${pass.last} model=${provider ? `${provider}/` : ""}${model ?? "unknown"})`);
|
|
7469
|
+
} else {
|
|
7470
|
+
next = LATEST_THINKING_RESTORE;
|
|
7471
|
+
sessionLog2(sessionId, "latest-turn thinking recovery: rejection not bound, no pass in this process built the rejected request");
|
|
7472
|
+
}
|
|
7301
7473
|
db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ?").run(next, sessionId);
|
|
7302
7474
|
}
|
|
7303
7475
|
function clone(value) {
|
|
@@ -7320,66 +7492,246 @@ function replayableOriginal(part) {
|
|
|
7320
7492
|
const signature = part.signature ?? part.thinkingSignature ?? metadata.signature ?? part.data ?? metadata.redactedData;
|
|
7321
7493
|
return typeof signature === "string" && signature.length > 0 && part.text !== "[cleared]" && part.thinking !== "[cleared]";
|
|
7322
7494
|
}
|
|
7495
|
+
var NO_RECOVERY = { restore: false, ended: false };
|
|
7496
|
+
var LATEST_TURN_THINKING_REMOVED_REASON = "latest_turn_thinking_removed";
|
|
7497
|
+
function replaceTarget(db, sessionId, expected, next) {
|
|
7498
|
+
return db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(next, sessionId, expected).changes > 0;
|
|
7499
|
+
}
|
|
7500
|
+
function decisionMessageId(decision) {
|
|
7501
|
+
if (decision === "binding_mismatch_order:end" || decision === TOOL_SWEEP_SCOPED_MARKER)
|
|
7502
|
+
return;
|
|
7503
|
+
return decodeMergedReasoningParts(decision)?.[0] ?? (decision.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX) ? decision.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length) : decision);
|
|
7504
|
+
}
|
|
7505
|
+
function sentAssistantIds(args, turn) {
|
|
7506
|
+
const ids = [];
|
|
7507
|
+
for (let index = turn.start;index < turn.end; index += 1) {
|
|
7508
|
+
const message = args.messages[index];
|
|
7509
|
+
if (!isSentAssistantMessage(message))
|
|
7510
|
+
continue;
|
|
7511
|
+
const id = args.id(message, index);
|
|
7512
|
+
if (id)
|
|
7513
|
+
ids.push(id);
|
|
7514
|
+
}
|
|
7515
|
+
return ids;
|
|
7516
|
+
}
|
|
7517
|
+
function magicContextEditedTurn(args, turn, modelID) {
|
|
7518
|
+
const ids = new Set(sentAssistantIds(args, turn));
|
|
7519
|
+
for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
7520
|
+
const id = decisionMessageId(decision);
|
|
7521
|
+
if (id !== undefined && ids.has(id))
|
|
7522
|
+
return true;
|
|
7523
|
+
}
|
|
7524
|
+
try {
|
|
7525
|
+
for (const id of getReasoningRemovalState(args.db, args.sessionId).messageIds) {
|
|
7526
|
+
if (ids.has(id))
|
|
7527
|
+
return true;
|
|
7528
|
+
}
|
|
7529
|
+
} catch {}
|
|
7530
|
+
return !isPrefixBoundThinkingModel(undefined, modelID) && clearedByWatermark(args, turn);
|
|
7531
|
+
}
|
|
7532
|
+
function clearedByWatermark(args, turn) {
|
|
7533
|
+
try {
|
|
7534
|
+
const row = args.db.prepare("SELECT cleared_reasoning_through_tag AS watermark FROM session_meta WHERE session_id = ?").get(args.sessionId);
|
|
7535
|
+
const watermark = row?.watermark ?? 0;
|
|
7536
|
+
if (!(watermark > 0))
|
|
7537
|
+
return false;
|
|
7538
|
+
const textTags = args.db.prepare("SELECT MAX(tag_number) AS n FROM tags WHERE session_id = ? AND message_id >= ? AND message_id < ?");
|
|
7539
|
+
const toolTags = args.db.prepare("SELECT MAX(tag_number) AS n FROM tags WHERE session_id = ? AND type = 'tool' AND tool_owner_message_id = ?");
|
|
7540
|
+
for (let index = turn.start;index < turn.end; index += 1) {
|
|
7541
|
+
const message = args.messages[index];
|
|
7542
|
+
if (!isSentAssistantMessage(message))
|
|
7543
|
+
continue;
|
|
7544
|
+
if (!args.parts(message).some(isThinkingPart2))
|
|
7545
|
+
continue;
|
|
7546
|
+
const id = args.id(message, index);
|
|
7547
|
+
if (!id)
|
|
7548
|
+
continue;
|
|
7549
|
+
const text = textTags.get(args.sessionId, `${id}:`, `${id};`);
|
|
7550
|
+
const tool = toolTags.get(args.sessionId, id);
|
|
7551
|
+
const newest = Math.max(text?.n ?? 0, tool?.n ?? 0);
|
|
7552
|
+
if (newest > 0 && newest <= watermark)
|
|
7553
|
+
return true;
|
|
7554
|
+
}
|
|
7555
|
+
} catch {}
|
|
7556
|
+
return false;
|
|
7557
|
+
}
|
|
7558
|
+
function restoreBlocker(args, turn) {
|
|
7559
|
+
if (turn.start === 0)
|
|
7560
|
+
return "no-turn-start";
|
|
7561
|
+
const turnMessages = args.messages.slice(turn.start, turn.end);
|
|
7562
|
+
if (!turnMessages.some((message) => args.parts(message).some(replayableOriginal)))
|
|
7563
|
+
return "missing-thinking-original";
|
|
7564
|
+
const ids = new Map(args.messages.map((message, index) => [args.id(message, index), index]));
|
|
7565
|
+
for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
7566
|
+
const id = decisionMessageId(decision);
|
|
7567
|
+
if (id === undefined)
|
|
7568
|
+
continue;
|
|
7569
|
+
const index = ids.get(id);
|
|
7570
|
+
if (index === undefined || index >= turn.start && !args.parts(args.messages[index]).some(replayableOriginal))
|
|
7571
|
+
return `missing-original:${id}`;
|
|
7572
|
+
}
|
|
7573
|
+
return;
|
|
7574
|
+
}
|
|
7575
|
+
function refuse(sessionId, why) {
|
|
7576
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: refused locally (${why})`);
|
|
7577
|
+
throw contextRefusalError(LATEST_THINKING_UNSAFE);
|
|
7578
|
+
}
|
|
7579
|
+
function refuseUnsaved(sessionId, why) {
|
|
7580
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: refused locally (${why})`);
|
|
7581
|
+
throw contextRefusalError(LATEST_THINKING_NOT_SAVED);
|
|
7582
|
+
}
|
|
7583
|
+
function frozenBindingIds(args) {
|
|
7584
|
+
const frozen = new Set;
|
|
7585
|
+
for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
7586
|
+
if (decision.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX))
|
|
7587
|
+
frozen.add(decision.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length));
|
|
7588
|
+
}
|
|
7589
|
+
return frozen;
|
|
7590
|
+
}
|
|
7591
|
+
function frozenTurnIds(args, turn) {
|
|
7592
|
+
const frozen = frozenBindingIds(args);
|
|
7593
|
+
return sentAssistantIds(args, turn).filter((id) => frozen.has(id));
|
|
7594
|
+
}
|
|
7595
|
+
function persistBindingRemoval(db, sessionId, ids) {
|
|
7596
|
+
return addMergedReasoningStrippedIds(db, sessionId, ids.map(thinkingBindingRecoveryFrozenId));
|
|
7597
|
+
}
|
|
7598
|
+
function removeTurnThinking(args, target, state, turn, current) {
|
|
7599
|
+
const frozen = frozenBindingIds(args);
|
|
7600
|
+
const ids = [];
|
|
7601
|
+
let parts = 0;
|
|
7602
|
+
for (let index = turn.start;index < turn.end; index += 1) {
|
|
7603
|
+
const message = args.messages[index];
|
|
7604
|
+
if (!isSentAssistantMessage(message))
|
|
7605
|
+
continue;
|
|
7606
|
+
const thinking = args.parts(message).filter(isThinkingPart2).length;
|
|
7607
|
+
if (thinking === 0)
|
|
7608
|
+
continue;
|
|
7609
|
+
const id = args.id(message, index);
|
|
7610
|
+
if (!id)
|
|
7611
|
+
refuse(args.sessionId, "a thinking message of the turn has no stable id");
|
|
7612
|
+
if (frozen.has(id))
|
|
7613
|
+
continue;
|
|
7614
|
+
ids.push(id);
|
|
7615
|
+
parts += thinking;
|
|
7616
|
+
}
|
|
7617
|
+
if (ids.length === 0) {
|
|
7618
|
+
replaceTarget(args.db, args.sessionId, target, encodeState({ ...state, stage: "refused", last: current.last }));
|
|
7619
|
+
refuse(args.sessionId, "the rejected turn has no thinking left to remove");
|
|
7620
|
+
}
|
|
7621
|
+
const persist = args.persistRemoval ?? ((next) => persistBindingRemoval(args.db, args.sessionId, next));
|
|
7622
|
+
let persisted = false;
|
|
7623
|
+
try {
|
|
7624
|
+
args.db.transaction(() => {
|
|
7625
|
+
if (!persist(ids))
|
|
7626
|
+
throw new Error("thinking removal was not persisted");
|
|
7627
|
+
const next = encodeState({ ...state, stage: "removed", last: current.last });
|
|
7628
|
+
if (!replaceTarget(args.db, args.sessionId, target, next))
|
|
7629
|
+
throw new Error("recovery state changed concurrently");
|
|
7630
|
+
}).immediate();
|
|
7631
|
+
persisted = true;
|
|
7632
|
+
} catch (error) {
|
|
7633
|
+
sessionLog2(args.sessionId, "latest-turn thinking recovery: removal write failed:", error);
|
|
7634
|
+
}
|
|
7635
|
+
if (!persisted)
|
|
7636
|
+
refuseUnsaved(args.sessionId, "the thinking removal could not be saved");
|
|
7637
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: removed thinking from the bound turn (parts=${parts} messages=${ids.length} first=${state.first} last=${current.last})`);
|
|
7638
|
+
return {
|
|
7639
|
+
restore: false,
|
|
7640
|
+
ended: false,
|
|
7641
|
+
removedThisPass: true,
|
|
7642
|
+
removedIds: frozenTurnIds(args, turn)
|
|
7643
|
+
};
|
|
7644
|
+
}
|
|
7323
7645
|
function prepareLatestThinkingRecovery(args) {
|
|
7324
|
-
const
|
|
7325
|
-
|
|
7326
|
-
|
|
7327
|
-
|
|
7646
|
+
const identified = identifyTurn(args.messages, args.id);
|
|
7647
|
+
if (identified)
|
|
7648
|
+
lastPassTurn.set(args.sessionId, {
|
|
7649
|
+
...identified.bound,
|
|
7650
|
+
pass: `${PROCESS_TOKEN}:${++passCounter}`,
|
|
7651
|
+
...args.modelID ? { model: args.modelID } : {},
|
|
7652
|
+
...args.modelID && args.providerID ? { provider: args.providerID } : {}
|
|
7653
|
+
});
|
|
7328
7654
|
else
|
|
7329
|
-
|
|
7655
|
+
lastPassTurn.delete(args.sessionId);
|
|
7330
7656
|
let target;
|
|
7331
7657
|
try {
|
|
7332
7658
|
target = getThinkingBindingRecoveryTarget(args.db, args.sessionId);
|
|
7333
7659
|
} catch (error) {
|
|
7334
7660
|
if (knownRejectedSessions.has(args.sessionId))
|
|
7335
|
-
|
|
7336
|
-
return
|
|
7661
|
+
refuseUnsaved(args.sessionId, "the recovery state could not be read");
|
|
7662
|
+
return NO_RECOVERY;
|
|
7337
7663
|
}
|
|
7338
7664
|
if (!target || !target.startsWith(LATEST_THINKING_RESTORE)) {
|
|
7339
7665
|
knownRejectedSessions.delete(args.sessionId);
|
|
7340
|
-
return
|
|
7666
|
+
return NO_RECOVERY;
|
|
7341
7667
|
}
|
|
7342
|
-
const
|
|
7343
|
-
if (
|
|
7344
|
-
args.db
|
|
7668
|
+
const state = readState2(target);
|
|
7669
|
+
if (!state) {
|
|
7670
|
+
replaceTarget(args.db, args.sessionId, target, "");
|
|
7345
7671
|
knownRejectedSessions.delete(args.sessionId);
|
|
7346
|
-
|
|
7672
|
+
sessionLog2(args.sessionId, "latest-turn thinking recovery: cleared a rejection that names no turn");
|
|
7673
|
+
return NO_RECOVERY;
|
|
7347
7674
|
}
|
|
7348
|
-
|
|
7349
|
-
|
|
7350
|
-
if (savedAnchor !== undefined && savedAnchor !== anchor) {
|
|
7351
|
-
args.db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(args.sessionId, target);
|
|
7675
|
+
const unbind = (why) => {
|
|
7676
|
+
replaceTarget(args.db, args.sessionId, target, "");
|
|
7352
7677
|
knownRejectedSessions.delete(args.sessionId);
|
|
7353
|
-
|
|
7354
|
-
|
|
7355
|
-
|
|
7356
|
-
|
|
7357
|
-
|
|
7358
|
-
|
|
7678
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: unbound because ${why} (stage=${state.stage} first=${state.first} last=${state.last})`);
|
|
7679
|
+
return { restore: false, ended: state.stage === "restoring" };
|
|
7680
|
+
};
|
|
7681
|
+
if (args.modelID && state.model && args.modelID.toLowerCase() !== state.model.toLowerCase())
|
|
7682
|
+
return unbind(`the request now goes to ${args.modelID}`);
|
|
7683
|
+
if (args.providerID && state.provider && args.providerID.toLowerCase() !== state.provider.toLowerCase())
|
|
7684
|
+
return unbind(`the request now goes through ${args.providerID}`);
|
|
7685
|
+
const current = identified?.bound;
|
|
7686
|
+
if (!identified || !current || current.first !== state.first)
|
|
7687
|
+
return unbind(`a newer turn was accepted (now first=${current?.first ?? "none"} last=${current?.last ?? "none"})`);
|
|
7688
|
+
const turn = identified.turn;
|
|
7689
|
+
if (current.last !== state.last && state.stage !== "restoring") {
|
|
7690
|
+
if (state.stage !== "removed")
|
|
7691
|
+
return unbind(`a newer message of the turn was accepted (now last=${current.last})`);
|
|
7692
|
+
replaceTarget(args.db, args.sessionId, target, encodeState({ ...state, last: current.last, accepted: true }));
|
|
7693
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: a request without the turn's removed thinking was accepted (first=${state.first} last=${current.last})`);
|
|
7694
|
+
return { ...NO_RECOVERY, removedIds: frozenTurnIds(args, identified.turn) };
|
|
7359
7695
|
}
|
|
7360
|
-
|
|
7361
|
-
|
|
7362
|
-
|
|
7363
|
-
|
|
7364
|
-
|
|
7365
|
-
|
|
7366
|
-
|
|
7367
|
-
|
|
7368
|
-
|
|
7369
|
-
|
|
7370
|
-
|
|
7696
|
+
knownRejectedSessions.add(args.sessionId);
|
|
7697
|
+
switch (state.stage) {
|
|
7698
|
+
case "refused":
|
|
7699
|
+
return refuse(args.sessionId, `the provider rejected the turn first=${state.first} ${state.rejections} times`);
|
|
7700
|
+
case "removed":
|
|
7701
|
+
return { ...NO_RECOVERY, removedIds: frozenTurnIds(args, turn) };
|
|
7702
|
+
case "restoring": {
|
|
7703
|
+
const blocker = restoreBlocker(args, turn);
|
|
7704
|
+
if (blocker === undefined)
|
|
7705
|
+
return { restore: true, ended: false };
|
|
7706
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: restore no longer possible (${blocker}); removing the turn's thinking instead`);
|
|
7707
|
+
return removeTurnThinking(args, target, state, turn, current);
|
|
7708
|
+
}
|
|
7709
|
+
case "armed": {
|
|
7710
|
+
if (magicContextEditedTurn(args, turn, args.modelID)) {
|
|
7711
|
+
const blocker = restoreBlocker(args, turn);
|
|
7712
|
+
if (blocker === undefined) {
|
|
7713
|
+
replaceTarget(args.db, args.sessionId, target, encodeState({ ...state, stage: "restoring", last: current.last }));
|
|
7714
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: restore applied to the bound turn (first=${state.first} last=${current.last})`);
|
|
7715
|
+
return { restore: true, ended: false };
|
|
7716
|
+
}
|
|
7717
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: restore unavailable (${blocker}); removing the turn's thinking instead`);
|
|
7718
|
+
}
|
|
7719
|
+
return removeTurnThinking(args, target, state, turn, current);
|
|
7720
|
+
}
|
|
7721
|
+
case "remove":
|
|
7722
|
+
return removeTurnThinking(args, target, state, turn, current);
|
|
7371
7723
|
}
|
|
7372
|
-
return { restore: true, ended: false };
|
|
7373
7724
|
}
|
|
7374
7725
|
function endLatestThinkingRecoveryAfterReset(db, sessionId) {
|
|
7375
7726
|
const target = getThinkingBindingRecoveryTarget(db, sessionId);
|
|
7376
7727
|
if (target?.startsWith(LATEST_THINKING_RESTORE)) {
|
|
7377
7728
|
db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(sessionId, target);
|
|
7729
|
+
sessionLog2(sessionId, "latest-turn thinking recovery: ended after a signed-thinking reset removed the turn's thinking");
|
|
7378
7730
|
}
|
|
7379
7731
|
knownRejectedSessions.delete(sessionId);
|
|
7380
7732
|
}
|
|
7381
7733
|
function captureOriginalTurn(messages, parts, setParts) {
|
|
7382
|
-
const start = Math.max(0, latestAssistantTurnStart(messages) - 1);
|
|
7734
|
+
const start = Math.max(0, (providerLatestTurn(messages)?.start ?? latestAssistantTurnStart(messages)) - 1);
|
|
7383
7735
|
const originals = messages.slice(start).map((message) => ({ message, parts: clone(parts(message)) }));
|
|
7384
7736
|
const before = messages.slice(0, start);
|
|
7385
7737
|
return (target = messages) => {
|
|
@@ -7392,23 +7744,34 @@ function captureOriginalTurn(messages, parts, setParts) {
|
|
|
7392
7744
|
target.push(...prefix, ...originals.map((original) => original.message));
|
|
7393
7745
|
};
|
|
7394
7746
|
}
|
|
7747
|
+
function restoredTurnMessages(messages, activeTurn) {
|
|
7748
|
+
const turn = providerLatestTurn(messages);
|
|
7749
|
+
return turn ? new Set(messages.slice(turn.start)) : new Set(activeTurn);
|
|
7750
|
+
}
|
|
7395
7751
|
function captureLatestTurnOriginals(messages) {
|
|
7396
7752
|
return captureOriginalTurn(messages, (message) => message.parts, (message, parts) => {
|
|
7397
7753
|
message.parts = parts;
|
|
7398
7754
|
});
|
|
7399
7755
|
}
|
|
7400
7756
|
function armBindingRecoverySafely(db, sessionId) {
|
|
7401
|
-
|
|
7402
|
-
|
|
7403
|
-
|
|
7404
|
-
|
|
7757
|
+
const target = getThinkingBindingRecoveryTarget(db, sessionId);
|
|
7758
|
+
if (target?.startsWith(LATEST_THINKING_RESTORE)) {
|
|
7759
|
+
const stage = readState2(target)?.stage;
|
|
7760
|
+
if (stage !== "removed" && stage !== "refused") {
|
|
7761
|
+
armLatestThinkingRecovery(db, sessionId);
|
|
7762
|
+
return;
|
|
7763
|
+
}
|
|
7764
|
+
knownRejectedSessions.delete(sessionId);
|
|
7765
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: binding rejection handed to the binding recovery (stage=${stage})`);
|
|
7766
|
+
}
|
|
7767
|
+
armThinkingBindingRecovery(db, sessionId);
|
|
7405
7768
|
}
|
|
7406
7769
|
function armLatestThinkingRecoveryFromError(args) {
|
|
7407
7770
|
if (!detectLatestTurnThinkingMismatch(args.error))
|
|
7408
7771
|
return false;
|
|
7409
7772
|
if (!isAnthropicFamilyRoute(args.providerID, args.modelID))
|
|
7410
7773
|
return true;
|
|
7411
|
-
armLatestThinkingRecovery(args.db, args.sessionId);
|
|
7774
|
+
armLatestThinkingRecovery(args.db, args.sessionId, args.modelID);
|
|
7412
7775
|
dropSlot(args.sessionId, "latest-thinking-recovery-arm");
|
|
7413
7776
|
return true;
|
|
7414
7777
|
}
|
|
@@ -7573,15 +7936,15 @@ function isHostInstructionRetentionOn(db, sessionId) {
|
|
|
7573
7936
|
const lane = readReplayEnvelope(db, sessionId)[NAMESPACE2];
|
|
7574
7937
|
return typeof lane === "object" && lane !== null && lane.on === true;
|
|
7575
7938
|
}
|
|
7576
|
-
function
|
|
7577
|
-
|
|
7578
|
-
|
|
7579
|
-
|
|
7580
|
-
return false;
|
|
7939
|
+
function recordHostInstructionDecisions(doc, decisions) {
|
|
7940
|
+
let changed = decisions.record?.(doc) ?? false;
|
|
7941
|
+
const lane = doc[NAMESPACE2];
|
|
7942
|
+
if (decisions.retention && !(typeof lane === "object" && lane !== null && lane.on === true)) {
|
|
7581
7943
|
doc.version = 2;
|
|
7582
7944
|
doc[NAMESPACE2] = { on: true };
|
|
7583
|
-
|
|
7584
|
-
}
|
|
7945
|
+
changed = true;
|
|
7946
|
+
}
|
|
7947
|
+
return changed;
|
|
7585
7948
|
}
|
|
7586
7949
|
|
|
7587
7950
|
// src/hooks/magic-context/apply-operations.ts
|
|
@@ -8851,15 +9214,26 @@ function projectStructuralSentinels(args) {
|
|
|
8851
9214
|
}
|
|
8852
9215
|
|
|
8853
9216
|
// src/hooks/magic-context/routine-cleanup-decision.ts
|
|
8854
|
-
function
|
|
9217
|
+
function forceBandOf(args) {
|
|
8855
9218
|
const emergencyDropEligible = !args.compactionOff && args.percentage >= args.forceMaterializationPercentage;
|
|
8856
9219
|
const forceRideWaitsOnLocalCount = args.fromEstimate && args.percentage < 95;
|
|
8857
9220
|
return {
|
|
8858
|
-
forceMaterialization: args.fullFeatureMode && emergencyDropEligible,
|
|
8859
9221
|
emergencyDropEligible,
|
|
8860
9222
|
forceRideWaitsOnLocalCount,
|
|
8861
|
-
forceBandConfirmed: emergencyDropEligible && !forceRideWaitsOnLocalCount
|
|
8862
|
-
|
|
9223
|
+
forceBandConfirmed: emergencyDropEligible && !forceRideWaitsOnLocalCount
|
|
9224
|
+
};
|
|
9225
|
+
}
|
|
9226
|
+
function forceBandConfirmed(args) {
|
|
9227
|
+
return forceBandOf(args).forceBandConfirmed;
|
|
9228
|
+
}
|
|
9229
|
+
function pressureBands(args) {
|
|
9230
|
+
const band = forceBandOf(args);
|
|
9231
|
+
return {
|
|
9232
|
+
forceMaterialization: args.fullFeatureMode && band.emergencyDropEligible,
|
|
9233
|
+
emergencyDropEligible: band.emergencyDropEligible,
|
|
9234
|
+
forceRideWaitsOnLocalCount: band.forceRideWaitsOnLocalCount,
|
|
9235
|
+
forceBandConfirmed: band.forceBandConfirmed,
|
|
9236
|
+
executePressureEligible: args.schedulerDecision === "execute" || band.emergencyDropEligible
|
|
8863
9237
|
};
|
|
8864
9238
|
}
|
|
8865
9239
|
function forceRide(args) {
|
|
@@ -10370,7 +10744,7 @@ function applyRustModeThinkingStrips(args, hostEditBeforeNewestThinking) {
|
|
|
10370
10744
|
recoveryMessageIds.add(messageId);
|
|
10371
10745
|
}
|
|
10372
10746
|
const flagTarget = !args.activeThinkingTurn && args.thinkingBindingRecoveryEnabledForModel ? getThinkingBindingRecoveryTarget(args.db, args.sessionId) : null;
|
|
10373
|
-
if (flagTarget) {
|
|
10747
|
+
if (flagTarget && !isLatestThinkingRecoveryTarget(flagTarget)) {
|
|
10374
10748
|
thinkingBindingRecovery = freezeAllReasoningForBindingRecovery({
|
|
10375
10749
|
db: args.db,
|
|
10376
10750
|
sessionId: args.sessionId,
|
|
@@ -10701,6 +11075,9 @@ function legacyPublishedHeadChanged(args) {
|
|
|
10701
11075
|
const served = args.readLastServedMessages();
|
|
10702
11076
|
if (served === null)
|
|
10703
11077
|
return true;
|
|
11078
|
+
return legacyHeadDiffersFrom(args, served);
|
|
11079
|
+
}
|
|
11080
|
+
function legacyHeadDiffersFrom(args, served) {
|
|
10704
11081
|
const previous = served[0];
|
|
10705
11082
|
if (!Array.isArray(previous?.parts) || !args.pendingCompartmentInjection)
|
|
10706
11083
|
return false;
|
|
@@ -10714,6 +11091,17 @@ ${args.pendingCompartmentInjection.block}
|
|
|
10714
11091
|
|
|
10715
11092
|
`);
|
|
10716
11093
|
}
|
|
11094
|
+
function frozenRecoveryHeadDiffers(args, m0M1Enabled, frozen) {
|
|
11095
|
+
if (m0M1Enabled)
|
|
11096
|
+
return !servedPrefixMatches({
|
|
11097
|
+
messages: frozen,
|
|
11098
|
+
...servedHeadTexts(args.sessionMeta),
|
|
11099
|
+
muralDataUrl: args.sessionMeta.cachedM0MuralDataUrl ?? null
|
|
11100
|
+
});
|
|
11101
|
+
if ((args.pendingCompartmentInjection?.compartmentCount ?? 0) > 0)
|
|
11102
|
+
return frozen === null || legacyHeadDiffersFrom(args, frozen);
|
|
11103
|
+
return false;
|
|
11104
|
+
}
|
|
10717
11105
|
async function runPostTransformPhase(args) {
|
|
10718
11106
|
const tPostprocessSetup = performance.now();
|
|
10719
11107
|
const compactionOff = args.compactionOff === true;
|
|
@@ -10799,9 +11187,9 @@ async function runPostTransformPhase(args) {
|
|
|
10799
11187
|
let freezeM0M1 = args.freezeM0M1 === true || activeThinkingPrefixHold;
|
|
10800
11188
|
let rewritingSignedPrefix = false;
|
|
10801
11189
|
let thinkingReleasedForFit = false;
|
|
10802
|
-
const releaseThinkingForRewrite = (forFit = false, stripInCompactionOff = false) => {
|
|
11190
|
+
const releaseThinkingForRewrite = (forFit = false, stripInCompactionOff = false, saved) => {
|
|
10803
11191
|
const stripOffWire = compactionOff && stripInCompactionOff;
|
|
10804
|
-
const stripped = freezeReasoningOnBustingPass({
|
|
11192
|
+
const stripped = saved ?? freezeReasoningOnBustingPass({
|
|
10805
11193
|
db: args.db,
|
|
10806
11194
|
sessionId: args.sessionId,
|
|
10807
11195
|
messages: args.messages,
|
|
@@ -10892,9 +11280,37 @@ async function runPostTransformPhase(args) {
|
|
|
10892
11280
|
m1Bytes: args.sessionMeta.cachedM1Bytes ?? null,
|
|
10893
11281
|
muralDataUrl: args.sessionMeta.cachedM0MuralDataUrl ?? null
|
|
10894
11282
|
};
|
|
11283
|
+
const compareRenderedHead = (rendered) => {
|
|
11284
|
+
const servedMatches = () => servedPrefixMatches({
|
|
11285
|
+
messages: servedBeforeFirstRender,
|
|
11286
|
+
m0Text: rendered.m0Bytes.toString(),
|
|
11287
|
+
m1Text: rendered.m1Bytes.toString(),
|
|
11288
|
+
muralDataUrl: rendered.muralDataUrl
|
|
11289
|
+
});
|
|
11290
|
+
return {
|
|
11291
|
+
bustsPrefix: activeThinkingPrefixHold ? !servedMatches() : foldBustsServedPrefix(foldDueDecision.reason, servedPrefixBeforeFold, rendered),
|
|
11292
|
+
changesHead: firstRenderBust ? !servedMatches() : foldChangesServedPrefix(servedPrefixBeforeFold, rendered)
|
|
11293
|
+
};
|
|
11294
|
+
};
|
|
11295
|
+
const compactionOffRenderStrip = (db, head) => {
|
|
11296
|
+
const due = compactionOff && (activeThinkingPrefixHold ? firstRenderBust && head.bustsPrefix : args.thinkingBindingRecoveryEnabledForModel === true && head.changesHead);
|
|
11297
|
+
if (!due)
|
|
11298
|
+
return;
|
|
11299
|
+
const strip = freezeReasoningOnBustingPass({
|
|
11300
|
+
db,
|
|
11301
|
+
sessionId: args.sessionId,
|
|
11302
|
+
messages: args.messages,
|
|
11303
|
+
alreadyFrozen: bindingThinking,
|
|
11304
|
+
compactionOff: true
|
|
11305
|
+
});
|
|
11306
|
+
if (strip.persistenceFailed)
|
|
11307
|
+
throw new Error("Cannot persist signed thinking omission with the compaction-off fold");
|
|
11308
|
+
return strip;
|
|
11309
|
+
};
|
|
10895
11310
|
if ((foldDueDecision.value || softRefreshOpportunity || firstRenderBust && activeThinkingPrefixHold) && m0M1EnabledForFold && args.m0M1) {
|
|
10896
11311
|
let committedFoldBustsServedPrefix;
|
|
10897
11312
|
let committedFoldChangesHead;
|
|
11313
|
+
let compactionOffFoldStrip;
|
|
10898
11314
|
try {
|
|
10899
11315
|
const previousM1 = args.sessionMeta.cachedM1Bytes?.toString("utf8");
|
|
10900
11316
|
const foldResult = injectM0M1({
|
|
@@ -10918,18 +11334,9 @@ async function runPostTransformPhase(args) {
|
|
|
10918
11334
|
onFoldPrepare: () => {
|
|
10919
11335
|
const conversions = prepareLegacyToolSkeletonConversions(args.db, args.sessionId, args.targets);
|
|
10920
11336
|
return (db, rendered) => {
|
|
10921
|
-
const
|
|
10922
|
-
|
|
10923
|
-
|
|
10924
|
-
m1Text: rendered.m1Bytes.toString(),
|
|
10925
|
-
muralDataUrl: rendered.muralDataUrl
|
|
10926
|
-
}) : foldBustsServedPrefix(foldDueDecision.reason, servedPrefixBeforeFold, rendered);
|
|
10927
|
-
committedFoldChangesHead = firstRenderBust ? !servedPrefixMatches({
|
|
10928
|
-
messages: servedBeforeFirstRender,
|
|
10929
|
-
m0Text: rendered.m0Bytes.toString(),
|
|
10930
|
-
m1Text: rendered.m1Bytes.toString(),
|
|
10931
|
-
muralDataUrl: rendered.muralDataUrl
|
|
10932
|
-
}) : foldChangesServedPrefix(servedPrefixBeforeFold, rendered);
|
|
11337
|
+
const head = compareRenderedHead(rendered);
|
|
11338
|
+
const bustsPrefix = head.bustsPrefix;
|
|
11339
|
+
committedFoldChangesHead = head.changesHead;
|
|
10933
11340
|
if (bustsPrefix) {
|
|
10934
11341
|
if (!conversions.isCurrent(db)) {
|
|
10935
11342
|
throw new MaterializeContentionError({
|
|
@@ -10942,15 +11349,16 @@ async function runPostTransformPhase(args) {
|
|
|
10942
11349
|
}
|
|
10943
11350
|
}
|
|
10944
11351
|
committedFoldBustsServedPrefix = bustsPrefix;
|
|
11352
|
+
compactionOffFoldStrip = compactionOffRenderStrip(db, head);
|
|
10945
11353
|
};
|
|
10946
11354
|
}
|
|
10947
11355
|
});
|
|
10948
11356
|
preparedPrefix = foldResult;
|
|
10949
11357
|
if (activeThinkingPrefixHold && firstRenderBust && committedFoldBustsServedPrefix) {
|
|
10950
|
-
releaseThinkingForRewrite(false, true);
|
|
11358
|
+
releaseThinkingForRewrite(false, true, compactionOffFoldStrip);
|
|
10951
11359
|
} else if (compactionOff && !activeThinkingPrefixHold && args.thinkingBindingRecoveryEnabledForModel === true && committedFoldChangesHead) {
|
|
10952
11360
|
sessionLog2(args.sessionId, "compaction-off fold changed the head: stripping signed thinking");
|
|
10953
|
-
releaseThinkingForRewrite(false, true);
|
|
11361
|
+
releaseThinkingForRewrite(false, true, compactionOffFoldStrip);
|
|
10954
11362
|
}
|
|
10955
11363
|
prefixPreflightFailed = foldResult.materializationContentionRetryExhausted === true;
|
|
10956
11364
|
foldExecutedThisPass = foldExecutesThisPass(foldDueDecision.value || softRefreshOpportunity, foldResult.m0RematerializedThisPass);
|
|
@@ -10998,8 +11406,7 @@ async function runPostTransformPhase(args) {
|
|
|
10998
11406
|
}
|
|
10999
11407
|
logTransformTiming(args.sessionId, "pp.prefixPreflight", tPostprocessSetup, `foldExecuted=${foldExecutedThisPass} m1Refreshed=${publishedM1RefreshedThisPass}`);
|
|
11000
11408
|
const tPassDecisions = performance.now();
|
|
11001
|
-
|
|
11002
|
-
if (activeThinkingPrefixHold && (args.forceSignedRebuildForFit || args.contextUsage.percentage >= 95 && frontToolCandidates.length > 0 && frontToolCandidates.every((tag) => newTargets.get(tag.tagNumber)?.thinkingRewriteProtected === true))) {
|
|
11409
|
+
if (activeThinkingPrefixHold && args.forceSignedRebuildForFit) {
|
|
11003
11410
|
releaseThinkingForRewrite(true);
|
|
11004
11411
|
}
|
|
11005
11412
|
if (activeThinkingPrefixHold) {
|
|
@@ -11070,9 +11477,17 @@ async function runPostTransformPhase(args) {
|
|
|
11070
11477
|
if (servedShapeRepair.needsRebuild && !isCacheBustingPass)
|
|
11071
11478
|
throw new Error("Served-shape repair requires a rebuilding pass");
|
|
11072
11479
|
servedShapeRepair.apply(isCacheBustingPass);
|
|
11480
|
+
const releasedFrozenHeadChanged = isCacheBustingPass && !activeThinkingPrefixHold && args.frozenRecoveryRequest !== undefined && frozenRecoveryHeadDiffers(args, m0M1EnabledForFold, args.frozenRecoveryRequest());
|
|
11481
|
+
if (releasedFrozenHeadChanged)
|
|
11482
|
+
sessionLog2(args.sessionId, "frozen replay release: the history head differs from the replay's; counting it as a head change");
|
|
11483
|
+
const restartHeadChanged = !compactionOff && args.thinkingBindingRecoveryEnabledForModel === true && args.restartedLastServedRequest !== undefined && frozenRecoveryHeadDiffers(args, m0M1EnabledForFold, args.restartedLastServedRequest());
|
|
11484
|
+
if (restartHeadChanged) {
|
|
11485
|
+
sessionLog2(args.sessionId, "restart: the history head differs from the saved last-good request's; stripping signed thinking");
|
|
11486
|
+
releaseThinkingForRewrite();
|
|
11487
|
+
}
|
|
11073
11488
|
let unheldSignedTurnBust = false;
|
|
11074
11489
|
if (isCacheBustingPass && !activeThinkingPrefixHold && activeThinkingTurn && args.thinkingBindingRecoveryEnabledForModel === true) {
|
|
11075
|
-
if (foldBustsServedPrefixThisPass || firstRenderBust || publishedM1RefreshedThisPass || hostCheckpointRide)
|
|
11490
|
+
if (foldBustsServedPrefixThisPass || firstRenderBust || publishedM1RefreshedThisPass || hostCheckpointRide || releasedFrozenHeadChanged)
|
|
11076
11491
|
releaseThinkingForRewrite();
|
|
11077
11492
|
else {
|
|
11078
11493
|
unheldSignedTurnBust = true;
|
|
@@ -11087,6 +11502,15 @@ async function runPostTransformPhase(args) {
|
|
|
11087
11502
|
const recoveredShapeRewriteProof = recoveryHeadChangedThisPass ? "head_bytes" : recoveryExternalFoldCause ?? (recoveryHeadlessRebuild ? "headless_rebuild" : null);
|
|
11088
11503
|
const canNormalizeRecoveredShape = isCacheBustingPass && !activeThinkingPrefixHold && recoveredShapeRewriteProof !== null;
|
|
11089
11504
|
sessionLog2(args.sessionId, `rewrite permission: allowed=${isCacheBustingPass} ${reclaimRideLabel(rideSignals)} served_shape_repair=${servedShapeRepair.needsRebuild} signed_prefix_release=${rewritingSignedPrefix} fold_prefix_loss=${foldBustsServedPrefixThisPass} first_render=${firstRenderBust} cache_expired=${args.m0M1?.hardSignals?.cacheExpired === true} thinking_hold=${activeThinkingPrefixHold} recovery_has_head=${recoveryHasHistoryHead} recovery_head_changed=${recoveryHeadChangedThisPass} recovery_headless_rebuild=${recoveryHeadlessRebuild} proven_external_fold=${recoveryExternalFoldCause ?? "none"} recovered_shape_proof=${recoveredShapeRewriteProof ?? "none"}`);
|
|
11505
|
+
noteServedPassPermission(args.sessionId, {
|
|
11506
|
+
permitted: isCacheBustingPass,
|
|
11507
|
+
rides: reclaimRideLabel(rideSignals),
|
|
11508
|
+
signedThinkingHold: activeThinkingPrefixHold,
|
|
11509
|
+
firstRender: firstRenderBust,
|
|
11510
|
+
hostCheckpointHead: hostCheckpointRide,
|
|
11511
|
+
emergency: forceBandConfirmed,
|
|
11512
|
+
schedulerDecision: args.schedulerDecision
|
|
11513
|
+
});
|
|
11090
11514
|
let recoveryTailNormalizedThisPass = false;
|
|
11091
11515
|
if (args.normalizeRecoveryTail && canNormalizeRecoveredShape) {
|
|
11092
11516
|
args.normalizeRecoveryTail();
|
|
@@ -11622,6 +12046,7 @@ async function runPostTransformPhase(args) {
|
|
|
11622
12046
|
preparedPrefix = prepareCachedM0M1Replay(args.db, args.sessionId);
|
|
11623
12047
|
}
|
|
11624
12048
|
const tInjectM0M1 = performance.now();
|
|
12049
|
+
let finalRenderStrip;
|
|
11625
12050
|
try {
|
|
11626
12051
|
const messagesBeforeInjection = args.messages.slice();
|
|
11627
12052
|
const result = injectM0M1({
|
|
@@ -11643,8 +12068,17 @@ async function runPostTransformPhase(args) {
|
|
|
11643
12068
|
allowFreshContentionFallback: forceMaterialization || emergencyDropEligible,
|
|
11644
12069
|
hardSignals: args.m0M1.hardSignals,
|
|
11645
12070
|
muralEnabled: args.m0M1.muralEnabled,
|
|
11646
|
-
compactionOff
|
|
12071
|
+
compactionOff,
|
|
12072
|
+
...compactionOff ? {
|
|
12073
|
+
onFoldPrepare: () => (db, rendered) => {
|
|
12074
|
+
finalRenderStrip = compactionOffRenderStrip(db, compareRenderedHead(rendered));
|
|
12075
|
+
}
|
|
12076
|
+
} : {}
|
|
11647
12077
|
});
|
|
12078
|
+
if (finalRenderStrip?.strip) {
|
|
12079
|
+
sessionLog2(args.sessionId, "compaction-off render changed the head: stripping signed thinking");
|
|
12080
|
+
releaseThinkingForRewrite(false, true, finalRenderStrip);
|
|
12081
|
+
}
|
|
11648
12082
|
deliveredPrefix = result;
|
|
11649
12083
|
if (result.prefixTrimStatus === "applied") {
|
|
11650
12084
|
const retainedMessages = new Set(args.messages);
|
|
@@ -11747,10 +12181,12 @@ async function runPostTransformPhase(args) {
|
|
|
11747
12181
|
const historyWasConsumedThisPass = (!m0M1Enabled || deliveredPrefix?.injected === true && !deliveredPrefix.materializationContentionRetryExhausted) && args.historyRebuiltThisPass && (args.canConsumeDeferredLate || args.phaseJustAwaitedPublication || explicitRebuildHappened) && materializationSatisfied;
|
|
11748
12182
|
let suppressV12HistoryDrain = false;
|
|
11749
12183
|
let persistedCompactionMarkerState = replaySnapshot?.compactionMarker ?? null;
|
|
12184
|
+
let markerDrainChangedServedRow = false;
|
|
11750
12185
|
if (replaySnapshot?.pendingCompactionMarker && (args.compactionMarkerStrategy ?? defaultCompactionMarkerStrategy).applyDeferred === applyDeferredCompactionMarker)
|
|
11751
12186
|
startCompactionMarkerCandidatePreparation(args.sessionId);
|
|
11752
|
-
|
|
11753
|
-
|
|
12187
|
+
const servedHeadIsCurrent = !m0M1Enabled || deliveredPrefix?.injected === true && !deliveredPrefix.materializationContentionRetryExhausted;
|
|
12188
|
+
if (isCacheBustingPass || historyWasConsumedThisPass) {
|
|
12189
|
+
const pending = servedHeadIsCurrent ? replaySnapshot?.pendingCompactionMarker ?? null : null;
|
|
11754
12190
|
if (pending) {
|
|
11755
12191
|
const pendingCovered = pendingMarkerCoveredByConsumedBoundary(pending, args.pendingCompartmentInjection);
|
|
11756
12192
|
const trimWasProven = !m0M1Enabled || deliveredPrefixWasTrimmedThroughPendingBoundary(deliveredPrefix, args.prefixTrimSourceOrder, pending) || sourceAlreadyReflectsCoveringMarker(args.sessionId, args.prefixTrimSourceOrder, persistedCompactionMarkerState, pending);
|
|
@@ -11760,6 +12196,8 @@ async function runPostTransformPhase(args) {
|
|
|
11760
12196
|
} else if (!trimWasProven) {
|
|
11761
12197
|
suppressV12HistoryDrain = true;
|
|
11762
12198
|
sessionLog2(args.sessionId, `compaction-marker drain: refusing ordinal ${pending.ordinal} because prefix trim through ${args.pendingCompartmentInjection?.compartmentEndMessageId ?? "<none>"} was not proven; preserving deferred history refresh signal`);
|
|
12199
|
+
} else if (!isCacheBustingPass) {
|
|
12200
|
+
sessionLog2(args.sessionId, `compaction-marker drain: pass has no rewrite permission; ordinal ${pending.ordinal} waits for a pass with rewrite permission`);
|
|
11763
12201
|
} else {
|
|
11764
12202
|
const tMarkerDrain = performance.now();
|
|
11765
12203
|
const strategy = args.compactionMarkerStrategy ?? defaultCompactionMarkerStrategy;
|
|
@@ -11768,13 +12206,13 @@ async function runPostTransformPhase(args) {
|
|
|
11768
12206
|
logTransformTiming(args.sessionId, "pp.markerDrain", tMarkerDrain, `outcome=${outcome.kind}`);
|
|
11769
12207
|
switch (outcome.kind) {
|
|
11770
12208
|
case "deferred":
|
|
11771
|
-
|
|
11772
|
-
sessionLog2(args.sessionId, "compaction-marker drain: candidate preparation deferred; preserving deferred history refresh signal");
|
|
12209
|
+
sessionLog2(args.sessionId, "compaction-marker drain: candidate preparation deferred; pending marker kept for the next pass with rewrite permission");
|
|
11773
12210
|
break;
|
|
11774
12211
|
case "applied":
|
|
11775
12212
|
case "already-current":
|
|
11776
12213
|
case "stale-skip":
|
|
11777
12214
|
persistedCompactionMarkerState = getPersistedCompactionMarkerState(args.db, args.sessionId);
|
|
12215
|
+
markerDrainChangedServedRow = (persistedCompactionMarkerState?.summaryMessageId ?? null) !== (replaySnapshot?.compactionMarker?.summaryMessageId ?? null);
|
|
11778
12216
|
if (clearPendingCompactionMarkerAfterSuccessfulDrain({
|
|
11779
12217
|
db: args.db,
|
|
11780
12218
|
sessionId: args.sessionId,
|
|
@@ -11785,6 +12223,10 @@ async function runPostTransformPhase(args) {
|
|
|
11785
12223
|
}
|
|
11786
12224
|
break;
|
|
11787
12225
|
case "retryable-failure":
|
|
12226
|
+
if (outcome.cut === "definitely-no-cut") {
|
|
12227
|
+
sessionLog2(args.sessionId, `compaction-marker drain: marker unchanged (reason=${isSqliteLockContentionError(outcome.error) ? "busy-writer" : "left-unchanged"}); serving rebuilt history and keeping the pending marker for the next pass with rewrite permission:`, outcome.error);
|
|
12228
|
+
break;
|
|
12229
|
+
}
|
|
11788
12230
|
failPass("compaction-marker-drain-failure", outcome.error);
|
|
11789
12231
|
sessionLog2(args.sessionId, "compaction-marker drain: retryable failure; preserving deferred history refresh signal", outcome.error);
|
|
11790
12232
|
suppressV12HistoryDrain = true;
|
|
@@ -11955,7 +12397,7 @@ async function runPostTransformPhase(args) {
|
|
|
11955
12397
|
}
|
|
11956
12398
|
const materializeReason = m0MaterializeReason ?? (explicitMaterializedSuccessfully ? pendingOrigin : null);
|
|
11957
12399
|
const materialized = m0RematerializedThisPass || explicitMaterializedSuccessfully || deferredMaterializedSuccessfully;
|
|
11958
|
-
let bustedThisPass = firstApplicationEdits.any || firstRenderBust || hostCheckpointRide || pendingOpsDidMutate || heuristicOrReasoningDidMutate || autoReclaimDidMutateThisPass || convertedToolSkeletonsDidMutate || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass;
|
|
12400
|
+
let bustedThisPass = firstApplicationEdits.any || firstRenderBust || hostCheckpointRide || pendingOpsDidMutate || heuristicOrReasoningDidMutate || autoReclaimDidMutateThisPass || convertedToolSkeletonsDidMutate || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass || markerDrainChangedServedRow;
|
|
11959
12401
|
const proactiveThinkingStripPermitted = isCacheBustingPass && !activeThinkingPrefixHold;
|
|
11960
12402
|
const tFrozenDecisions = performance.now();
|
|
11961
12403
|
if (reasoningMutationTargetUnknown) {
|
|
@@ -11989,7 +12431,7 @@ async function runPostTransformPhase(args) {
|
|
|
11989
12431
|
}
|
|
11990
12432
|
}
|
|
11991
12433
|
const flagTarget = !activeThinkingTurn && args.thinkingBindingRecoveryEnabledForModel ? replaySnapshot?.thinkingBindingRecoveryTarget ?? null : null;
|
|
11992
|
-
if (flagTarget) {
|
|
12434
|
+
if (flagTarget && !isLatestThinkingRecoveryTarget(flagTarget) && flagTarget !== args.appliedBindingRecoveryTarget) {
|
|
11993
12435
|
thinkingBindingRecovery = freezeAllReasoningForBindingRecovery({
|
|
11994
12436
|
db: args.db,
|
|
11995
12437
|
sessionId: args.sessionId,
|
|
@@ -12161,7 +12603,7 @@ async function runPostTransformPhase(args) {
|
|
|
12161
12603
|
}
|
|
12162
12604
|
}
|
|
12163
12605
|
}
|
|
12164
|
-
const prefixEditBesidesReasoningTrim = firstRenderBust || materializationRequested || explicitMaterializedSuccessfully || deferredMaterializedSuccessfully || foldBustsServedPrefixThisPass || publishedM1RefreshedThisPass || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass || pendingOpsDidMutate || heuristicOrReasoningEditBesidesTrim || emergency || autoReclaimDidMutateThisPass || convertedToolSkeletonsDidMutate || deferredClearedMarkerRetires || noteNudgeAppendedThisPass || todoAnchorMovedThisPass || autoSearchHintAppendedThisPass || dropModeSwitchesThisPass || recoveryTailNormalizedThisPass || firstApplicationEdits.beforeNewerThinking;
|
|
12606
|
+
const prefixEditBesidesReasoningTrim = firstRenderBust || materializationRequested || explicitMaterializedSuccessfully || deferredMaterializedSuccessfully || foldBustsServedPrefixThisPass || publishedM1RefreshedThisPass || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass || markerDrainChangedServedRow || pendingOpsDidMutate || heuristicOrReasoningEditBesidesTrim || emergency || autoReclaimDidMutateThisPass || convertedToolSkeletonsDidMutate || deferredClearedMarkerRetires || noteNudgeAppendedThisPass || todoAnchorMovedThisPass || autoSearchHintAppendedThisPass || dropModeSwitchesThisPass || recoveryTailNormalizedThisPass || releasedFrozenHeadChanged || firstApplicationEdits.beforeNewerThinking;
|
|
12165
12607
|
let proactiveThinkingStrip = null;
|
|
12166
12608
|
if (!compactionOff && args.thinkingBindingRecoveryEnabledForModel === true && proactiveThinkingStripPermitted && prefixEditBesidesReasoningTrim) {
|
|
12167
12609
|
const outcome = freezeReasoningOnBustingPass({
|
|
@@ -12186,9 +12628,10 @@ async function runPostTransformPhase(args) {
|
|
|
12186
12628
|
failPass("proactive-thinking-strip-persistence-failure");
|
|
12187
12629
|
}
|
|
12188
12630
|
}
|
|
12189
|
-
hostRowReclaim
|
|
12190
|
-
|
|
12191
|
-
|
|
12631
|
+
const pendingHostInstructionDecisions = hostRowReclaim || retainCoveredInstructions && !coveredRetentionOn ? {
|
|
12632
|
+
reclaim: hostRowReclaim,
|
|
12633
|
+
retention: retainCoveredInstructions && !coveredRetentionOn
|
|
12634
|
+
} : undefined;
|
|
12192
12635
|
let settledDroppedReasoning = 0;
|
|
12193
12636
|
if (!canUseEmptySentinels) {
|
|
12194
12637
|
let mode = "legacy";
|
|
@@ -12373,9 +12816,12 @@ async function runPostTransformPhase(args) {
|
|
|
12373
12816
|
prefixMutationPermitted: isCacheBustingPass,
|
|
12374
12817
|
bustedThisPass,
|
|
12375
12818
|
prefixTrimStatus: deliveredPrefix?.prefixTrimStatus ?? null,
|
|
12819
|
+
prefixTrimRefusal: deliveredPrefix?.prefixTrimRefusal ?? null,
|
|
12376
12820
|
thinkingBindingRecovery,
|
|
12377
12821
|
proactiveThinkingStrip,
|
|
12378
|
-
thinkingReleasedForFit
|
|
12822
|
+
thinkingReleasedForFit,
|
|
12823
|
+
pendingHostInstructionDecisions,
|
|
12824
|
+
restartHeadChanged
|
|
12379
12825
|
};
|
|
12380
12826
|
}
|
|
12381
12827
|
function checkM0MutationDriftAndSignal(args) {
|
|
@@ -13052,6 +13498,47 @@ function recordCompartmentTriggerError(passOutcome, sessionId, error, log = sess
|
|
|
13052
13498
|
log(sessionId, "compartment trigger failed (non-fatal):", error);
|
|
13053
13499
|
}
|
|
13054
13500
|
|
|
13501
|
+
// src/hooks/magic-context/history-boundary-recovery.ts
|
|
13502
|
+
var exhaustedStateBySession = new BoundedSessionMap(512);
|
|
13503
|
+
function inputMessagesKey(messages) {
|
|
13504
|
+
let count = 0;
|
|
13505
|
+
let first = "";
|
|
13506
|
+
let last = "";
|
|
13507
|
+
for (const message of messages) {
|
|
13508
|
+
const id = message.info.id;
|
|
13509
|
+
if (typeof id !== "string" || id.length === 0)
|
|
13510
|
+
continue;
|
|
13511
|
+
if (count === 0)
|
|
13512
|
+
first = id;
|
|
13513
|
+
last = id;
|
|
13514
|
+
count += 1;
|
|
13515
|
+
}
|
|
13516
|
+
return `${count}:${first}:${last}`;
|
|
13517
|
+
}
|
|
13518
|
+
function historyBoundaryRecoveryStateKey(db, sessionId, inputKey) {
|
|
13519
|
+
try {
|
|
13520
|
+
const row = db.prepare(`SELECT
|
|
13521
|
+
(SELECT COUNT(*) FROM compartments WHERE session_id = ?) AS compartments,
|
|
13522
|
+
(SELECT COALESCE(MAX(sequence), -1) FROM compartments WHERE session_id = ?) AS newest,
|
|
13523
|
+
(SELECT COUNT(*) FROM tags WHERE session_id = ? AND status = 'dropped') AS dropped,
|
|
13524
|
+
(SELECT COALESCE(cached_m0_last_baseline_end_message_id, '') FROM session_meta WHERE session_id = ?) AS boundary`).get(sessionId, sessionId, sessionId, sessionId);
|
|
13525
|
+
if (!row)
|
|
13526
|
+
return null;
|
|
13527
|
+
return `${inputKey}|${row.compartments}:${row.newest}|${row.dropped}|${row.boundary ?? ""}`;
|
|
13528
|
+
} catch {
|
|
13529
|
+
return null;
|
|
13530
|
+
}
|
|
13531
|
+
}
|
|
13532
|
+
function markHistoryBoundaryRecoveryExhausted(sessionId, stateKey) {
|
|
13533
|
+
exhaustedStateBySession.set(sessionId, stateKey);
|
|
13534
|
+
}
|
|
13535
|
+
function isHistoryBoundaryRecoveryExhausted(sessionId, stateKey) {
|
|
13536
|
+
return stateKey !== null && exhaustedStateBySession.get(sessionId) === stateKey;
|
|
13537
|
+
}
|
|
13538
|
+
function forgetHistoryBoundaryRecovery(sessionId) {
|
|
13539
|
+
exhaustedStateBySession.delete(sessionId);
|
|
13540
|
+
}
|
|
13541
|
+
|
|
13055
13542
|
// src/hooks/magic-context/local-wire-reading.ts
|
|
13056
13543
|
function createLocalWireReadings() {
|
|
13057
13544
|
const readings = new Map;
|
|
@@ -13153,6 +13640,111 @@ function createPassOutcome() {
|
|
|
13153
13640
|
};
|
|
13154
13641
|
}
|
|
13155
13642
|
|
|
13643
|
+
// src/hooks/magic-context/signed-thinking-hold.ts
|
|
13644
|
+
var HEAVY_REASONING_TOKENS = 1500;
|
|
13645
|
+
var HEAVY_REASONING_WINDOW_STEPS = 15;
|
|
13646
|
+
var HOLD_CAP_POINTS = 10;
|
|
13647
|
+
var REASONING_TYPES = new Set(["reasoning", "thinking"]);
|
|
13648
|
+
function role2(message) {
|
|
13649
|
+
if (!isRecord(message))
|
|
13650
|
+
return;
|
|
13651
|
+
return isRecord(message.info) ? message.info.role : message.role;
|
|
13652
|
+
}
|
|
13653
|
+
function parts(message) {
|
|
13654
|
+
if (!isRecord(message))
|
|
13655
|
+
return [];
|
|
13656
|
+
if (Array.isArray(message.parts))
|
|
13657
|
+
return message.parts;
|
|
13658
|
+
return Array.isArray(message.content) ? message.content : [];
|
|
13659
|
+
}
|
|
13660
|
+
function recordedReasoningTokens(message) {
|
|
13661
|
+
if (!isRecord(message))
|
|
13662
|
+
return;
|
|
13663
|
+
const info = isRecord(message.info) ? message.info : undefined;
|
|
13664
|
+
const candidates = [];
|
|
13665
|
+
if (info && isRecord(info.tokens))
|
|
13666
|
+
candidates.push(info.tokens.reasoning);
|
|
13667
|
+
if (isRecord(message.usage)) {
|
|
13668
|
+
candidates.push(message.usage.reasoning, message.usage.reasoningTokens);
|
|
13669
|
+
}
|
|
13670
|
+
for (const value of candidates) {
|
|
13671
|
+
if (typeof value === "number" && Number.isFinite(value) && value > 0)
|
|
13672
|
+
return value;
|
|
13673
|
+
}
|
|
13674
|
+
return;
|
|
13675
|
+
}
|
|
13676
|
+
function stepReasoningTokens(message, estimateTextTokens) {
|
|
13677
|
+
let text = "";
|
|
13678
|
+
let opaque = false;
|
|
13679
|
+
for (const part of parts(message)) {
|
|
13680
|
+
if (!isRecord(part))
|
|
13681
|
+
continue;
|
|
13682
|
+
const type = String(part.type ?? part.kind);
|
|
13683
|
+
if (type === "redacted_thinking" || part.redacted === true) {
|
|
13684
|
+
opaque = true;
|
|
13685
|
+
continue;
|
|
13686
|
+
}
|
|
13687
|
+
if (!REASONING_TYPES.has(type))
|
|
13688
|
+
continue;
|
|
13689
|
+
const body = typeof part.thinking === "string" ? part.thinking : typeof part.text === "string" ? part.text : "";
|
|
13690
|
+
if (body.length > 0)
|
|
13691
|
+
text += body;
|
|
13692
|
+
else
|
|
13693
|
+
opaque = true;
|
|
13694
|
+
}
|
|
13695
|
+
if (!text && !opaque)
|
|
13696
|
+
return 0;
|
|
13697
|
+
return reasoningStepCost(recordedReasoningTokens(message), text ? estimateTextTokens(text) : 0, opaque);
|
|
13698
|
+
}
|
|
13699
|
+
function decideSignedThinkingHold(args) {
|
|
13700
|
+
const capPercentage = args.executeThresholdPercentage + HOLD_CAP_POINTS;
|
|
13701
|
+
let heavyStepsBack = null;
|
|
13702
|
+
let heavyStepTokens = 0;
|
|
13703
|
+
const start = latestAssistantTurnStart(args.messages);
|
|
13704
|
+
let stepsBack = 0;
|
|
13705
|
+
for (let index = args.messages.length - 1;index >= start; index--) {
|
|
13706
|
+
const message = args.messages[index];
|
|
13707
|
+
if (role2(message) !== "assistant" || parts(message).length === 0)
|
|
13708
|
+
continue;
|
|
13709
|
+
stepsBack++;
|
|
13710
|
+
if (stepsBack > HEAVY_REASONING_WINDOW_STEPS)
|
|
13711
|
+
break;
|
|
13712
|
+
const tokens = stepReasoningTokens(message, args.estimateTextTokens);
|
|
13713
|
+
if (tokens > HEAVY_REASONING_TOKENS) {
|
|
13714
|
+
heavyStepsBack = stepsBack;
|
|
13715
|
+
heavyStepTokens = tokens;
|
|
13716
|
+
break;
|
|
13717
|
+
}
|
|
13718
|
+
}
|
|
13719
|
+
if (heavyStepsBack === null)
|
|
13720
|
+
return {
|
|
13721
|
+
held: false,
|
|
13722
|
+
reason: "no_recent_heavy_reasoning",
|
|
13723
|
+
heavyStepsBack,
|
|
13724
|
+
heavyStepTokens,
|
|
13725
|
+
capPercentage
|
|
13726
|
+
};
|
|
13727
|
+
const ended = readingEndsHold({
|
|
13728
|
+
usagePercentage: args.usagePercentage,
|
|
13729
|
+
capPercentage,
|
|
13730
|
+
forceBandPressure: args.forceBandPressure
|
|
13731
|
+
});
|
|
13732
|
+
if (ended !== null)
|
|
13733
|
+
return { held: false, reason: ended, heavyStepsBack, heavyStepTokens, capPercentage };
|
|
13734
|
+
return {
|
|
13735
|
+
held: true,
|
|
13736
|
+
reason: "heavy_reasoning",
|
|
13737
|
+
heavyStepsBack,
|
|
13738
|
+
heavyStepTokens,
|
|
13739
|
+
capPercentage
|
|
13740
|
+
};
|
|
13741
|
+
}
|
|
13742
|
+
function readingEndsHold(args) {
|
|
13743
|
+
if (!(args.usagePercentage < args.capPercentage))
|
|
13744
|
+
return "above_cap";
|
|
13745
|
+
return args.forceBandPressure ? "force_band" : null;
|
|
13746
|
+
}
|
|
13747
|
+
|
|
13156
13748
|
// src/hooks/magic-context/priced-pass-sizing.ts
|
|
13157
13749
|
var REASONING_PART_TYPES = new Set(["reasoning", "thinking", "redacted_thinking"]);
|
|
13158
13750
|
var WIDEST_PRICED_PASS_PLAN = {
|
|
@@ -13169,6 +13761,11 @@ function planPricedPass(input, usage) {
|
|
|
13169
13761
|
schedulerDecision: input.schedulerDecision
|
|
13170
13762
|
});
|
|
13171
13763
|
const emergencySample = () => getEmergencyInputSample(input.db, input.sessionId);
|
|
13764
|
+
const signedThinkingHold = input.signedThinkingHold && (input.signedThinkingHoldCapPercentage === undefined ? !bands.forceBandConfirmed : readingEndsHold({
|
|
13765
|
+
usagePercentage: usage.percentage,
|
|
13766
|
+
capPercentage: input.signedThinkingHoldCapPercentage,
|
|
13767
|
+
forceBandPressure: bands.forceBandConfirmed
|
|
13768
|
+
}) === null);
|
|
13172
13769
|
const rides = {
|
|
13173
13770
|
hardFold: input.folds || input.firstRender,
|
|
13174
13771
|
force: forceRide({
|
|
@@ -13184,11 +13781,11 @@ function planPricedPass(input, usage) {
|
|
|
13184
13781
|
servedShapeRepair: false
|
|
13185
13782
|
};
|
|
13186
13783
|
const drainAllowed = !input.compactionOff && reclaimRidePermitted(rides, {
|
|
13187
|
-
signedThinkingHold
|
|
13784
|
+
signedThinkingHold,
|
|
13188
13785
|
firstRender: input.firstRender,
|
|
13189
13786
|
emergency: bands.forceBandConfirmed
|
|
13190
13787
|
});
|
|
13191
|
-
const materializationRequested = !
|
|
13788
|
+
const materializationRequested = !signedThinkingHold && input.materializationRequested;
|
|
13192
13789
|
const heuristics = heuristicsRunOnPass({
|
|
13193
13790
|
compactionOff: input.compactionOff,
|
|
13194
13791
|
drainAllowed,
|
|
@@ -13215,8 +13812,8 @@ function planPricedPass(input, usage) {
|
|
|
13215
13812
|
rewriteAlreadyPriced: input.folds || input.firstRender || input.historyRebuilt
|
|
13216
13813
|
});
|
|
13217
13814
|
return {
|
|
13218
|
-
editsWholePrefix: drainAllowed && !
|
|
13219
|
-
clearsReasoning: routine && !
|
|
13815
|
+
editsWholePrefix: drainAllowed && !signedThinkingHold,
|
|
13816
|
+
clearsReasoning: routine && !signedThinkingHold
|
|
13220
13817
|
};
|
|
13221
13818
|
}
|
|
13222
13819
|
function sameSizingPlan(input, a, b) {
|
|
@@ -17693,12 +18290,15 @@ function createRustModeTransform(deps, options) {
|
|
|
17693
18290
|
}
|
|
17694
18291
|
const inputCount = messages.length;
|
|
17695
18292
|
const inputHasActiveThinking = hasActiveAnthropicThinkingTurn(messages, "anthropic");
|
|
18293
|
+
const rustRecoveryModel = modelFromMessages(messages) ?? deps.liveModelBySession?.get(sessionId);
|
|
17696
18294
|
const thinkingRecovery = prepareLatestThinkingRecovery({
|
|
17697
18295
|
db: deps.db,
|
|
17698
18296
|
sessionId,
|
|
17699
18297
|
messages,
|
|
17700
18298
|
id: (message) => message?.info.id,
|
|
17701
|
-
parts: (message) => message?.parts ?? []
|
|
18299
|
+
parts: (message) => message?.parts ?? [],
|
|
18300
|
+
modelID: rustRecoveryModel?.modelID,
|
|
18301
|
+
providerID: rustRecoveryModel?.providerID
|
|
17702
18302
|
});
|
|
17703
18303
|
const restoreLatestTurnOriginals = thinkingRecovery.restore ? captureLatestTurnOriginals(messages) : undefined;
|
|
17704
18304
|
let requestInputTokens = 0;
|
|
@@ -17945,7 +18545,7 @@ function createRustModeTransform(deps, options) {
|
|
|
17945
18545
|
writeRustTransformDecision({
|
|
17946
18546
|
sessionId,
|
|
17947
18547
|
decision,
|
|
17948
|
-
materializeReason: materializeReason === "none" ?
|
|
18548
|
+
materializeReason: thinkingRecovery.removedThisPass && (materializeReason === "none" || materializeReason === "ttl_idle") ? LATEST_TURN_THINKING_REMOVED_REASON : materializeReason !== "none" ? materializeReason : null,
|
|
17949
18549
|
inputTokens: requestInputTokens,
|
|
17950
18550
|
tsMs: passObservedAtMs,
|
|
17951
18551
|
lkgFrozenReleaseReason: applied && served && frozenReleaseReason ? `${frozenReleaseReason};first_changed=${frozenReleaseFirstChanged}` : undefined
|
|
@@ -18849,7 +19449,7 @@ function createRustModeTransform(deps, options) {
|
|
|
18849
19449
|
const activeThinkingTurn = inputHasActiveThinking && isAnthropicFamilyRoute(model?.providerID, model?.modelID);
|
|
18850
19450
|
const postprocess = runRustModePostprocess({
|
|
18851
19451
|
activeThinkingTurn,
|
|
18852
|
-
protectedThinkingMessages: thinkingRecovery.restore ? protectedThinkingMessages : undefined,
|
|
19452
|
+
protectedThinkingMessages: thinkingRecovery.restore ? restoredTurnMessages(appliedMessages, protectedThinkingMessages) : undefined,
|
|
18853
19453
|
restoreLatestTurnOriginals: () => restoreLatestTurnOriginals?.(appliedMessages),
|
|
18854
19454
|
db: deps.db,
|
|
18855
19455
|
sessionId,
|
|
@@ -19009,7 +19609,7 @@ function createRustModeTransform(deps, options) {
|
|
|
19009
19609
|
}
|
|
19010
19610
|
}
|
|
19011
19611
|
const endRecoveryAfterResetCapture = () => {
|
|
19012
|
-
if (signedThinkingReset
|
|
19612
|
+
if (signedThinkingReset) {
|
|
19013
19613
|
endLatestThinkingRecoveryAfterReset(deps.db, sessionId);
|
|
19014
19614
|
}
|
|
19015
19615
|
};
|
|
@@ -19458,101 +20058,6 @@ function takeSignedThinkingFitSnapshot(args) {
|
|
|
19458
20058
|
}
|
|
19459
20059
|
var snapshotObserver;
|
|
19460
20060
|
|
|
19461
|
-
// src/hooks/magic-context/signed-thinking-hold.ts
|
|
19462
|
-
var HEAVY_REASONING_TOKENS = 1500;
|
|
19463
|
-
var HEAVY_REASONING_WINDOW_STEPS = 15;
|
|
19464
|
-
var HOLD_CAP_POINTS = 10;
|
|
19465
|
-
var REASONING_TYPES = new Set(["reasoning", "thinking"]);
|
|
19466
|
-
function role2(message) {
|
|
19467
|
-
if (!isRecord(message))
|
|
19468
|
-
return;
|
|
19469
|
-
return isRecord(message.info) ? message.info.role : message.role;
|
|
19470
|
-
}
|
|
19471
|
-
function parts(message) {
|
|
19472
|
-
if (!isRecord(message))
|
|
19473
|
-
return [];
|
|
19474
|
-
if (Array.isArray(message.parts))
|
|
19475
|
-
return message.parts;
|
|
19476
|
-
return Array.isArray(message.content) ? message.content : [];
|
|
19477
|
-
}
|
|
19478
|
-
function recordedReasoningTokens(message) {
|
|
19479
|
-
if (!isRecord(message))
|
|
19480
|
-
return;
|
|
19481
|
-
const info = isRecord(message.info) ? message.info : undefined;
|
|
19482
|
-
const candidates = [];
|
|
19483
|
-
if (info && isRecord(info.tokens))
|
|
19484
|
-
candidates.push(info.tokens.reasoning);
|
|
19485
|
-
if (isRecord(message.usage)) {
|
|
19486
|
-
candidates.push(message.usage.reasoning, message.usage.reasoningTokens);
|
|
19487
|
-
}
|
|
19488
|
-
for (const value of candidates) {
|
|
19489
|
-
if (typeof value === "number" && Number.isFinite(value) && value > 0)
|
|
19490
|
-
return value;
|
|
19491
|
-
}
|
|
19492
|
-
return;
|
|
19493
|
-
}
|
|
19494
|
-
function stepReasoningTokens(message, estimateTextTokens) {
|
|
19495
|
-
let text = "";
|
|
19496
|
-
let opaque = false;
|
|
19497
|
-
for (const part of parts(message)) {
|
|
19498
|
-
if (!isRecord(part))
|
|
19499
|
-
continue;
|
|
19500
|
-
const type = String(part.type ?? part.kind);
|
|
19501
|
-
if (type === "redacted_thinking" || part.redacted === true) {
|
|
19502
|
-
opaque = true;
|
|
19503
|
-
continue;
|
|
19504
|
-
}
|
|
19505
|
-
if (!REASONING_TYPES.has(type))
|
|
19506
|
-
continue;
|
|
19507
|
-
const body = typeof part.thinking === "string" ? part.thinking : typeof part.text === "string" ? part.text : "";
|
|
19508
|
-
if (body.length > 0)
|
|
19509
|
-
text += body;
|
|
19510
|
-
else
|
|
19511
|
-
opaque = true;
|
|
19512
|
-
}
|
|
19513
|
-
if (!text && !opaque)
|
|
19514
|
-
return 0;
|
|
19515
|
-
return reasoningStepCost(recordedReasoningTokens(message), text ? estimateTextTokens(text) : 0, opaque);
|
|
19516
|
-
}
|
|
19517
|
-
function decideSignedThinkingHold(args) {
|
|
19518
|
-
const capPercentage = args.executeThresholdPercentage + HOLD_CAP_POINTS;
|
|
19519
|
-
let heavyStepsBack = null;
|
|
19520
|
-
let heavyStepTokens = 0;
|
|
19521
|
-
const start = latestAssistantTurnStart(args.messages);
|
|
19522
|
-
let stepsBack = 0;
|
|
19523
|
-
for (let index = args.messages.length - 1;index >= start; index--) {
|
|
19524
|
-
const message = args.messages[index];
|
|
19525
|
-
if (role2(message) !== "assistant" || parts(message).length === 0)
|
|
19526
|
-
continue;
|
|
19527
|
-
stepsBack++;
|
|
19528
|
-
if (stepsBack > HEAVY_REASONING_WINDOW_STEPS)
|
|
19529
|
-
break;
|
|
19530
|
-
const tokens = stepReasoningTokens(message, args.estimateTextTokens);
|
|
19531
|
-
if (tokens > HEAVY_REASONING_TOKENS) {
|
|
19532
|
-
heavyStepsBack = stepsBack;
|
|
19533
|
-
heavyStepTokens = tokens;
|
|
19534
|
-
break;
|
|
19535
|
-
}
|
|
19536
|
-
}
|
|
19537
|
-
if (heavyStepsBack === null)
|
|
19538
|
-
return {
|
|
19539
|
-
held: false,
|
|
19540
|
-
reason: "no_recent_heavy_reasoning",
|
|
19541
|
-
heavyStepsBack,
|
|
19542
|
-
heavyStepTokens,
|
|
19543
|
-
capPercentage
|
|
19544
|
-
};
|
|
19545
|
-
if (!(args.usagePercentage < capPercentage))
|
|
19546
|
-
return { held: false, reason: "above_cap", heavyStepsBack, heavyStepTokens, capPercentage };
|
|
19547
|
-
return {
|
|
19548
|
-
held: true,
|
|
19549
|
-
reason: "heavy_reasoning",
|
|
19550
|
-
heavyStepsBack,
|
|
19551
|
-
heavyStepTokens,
|
|
19552
|
-
capPercentage
|
|
19553
|
-
};
|
|
19554
|
-
}
|
|
19555
|
-
|
|
19556
20061
|
// src/hooks/magic-context/temporal-served-projection.ts
|
|
19557
20062
|
function readLkgTemporalDecisions(db, sessionId, runtime) {
|
|
19558
20063
|
const slot = getInMemorySlot(sessionId) ?? loadPersistedLkgSlot(db, sessionId);
|
|
@@ -20048,23 +20553,46 @@ function storedHistoryBoundaryPresence(db, sessionId) {
|
|
|
20048
20553
|
return;
|
|
20049
20554
|
}
|
|
20050
20555
|
}
|
|
20556
|
+
var CAUSE_SENTENCES = {
|
|
20557
|
+
"boundary-not-in-request": "The message the history summary ends on is in the host's store but not in the loaded conversation, so Magic Context could not tell which loaded messages the summary already covers.",
|
|
20558
|
+
"boundary-unordered": "Magic Context could not place the message the history summary ends on in the loaded conversation: either it is not there and the host's store could not order it against the messages that are, or the conversation holds it more than once.",
|
|
20559
|
+
"boundary-missing-from-store": "The message the history summary ends on is no longer in the host's store."
|
|
20560
|
+
};
|
|
20561
|
+
function historyBoundaryRefusalText(cause, remedy) {
|
|
20562
|
+
const failure = renderUserFacingFailure(remedy === "send-again" ? "history_boundary_recovering" : "history_boundary_unresolved", "plain");
|
|
20563
|
+
return cause ? `${CAUSE_SENTENCES[cause]} ${failure}` : failure;
|
|
20564
|
+
}
|
|
20051
20565
|
|
|
20052
20566
|
class UnresolvedHistoryBoundaryError extends Error {
|
|
20053
20567
|
estimatedTokens;
|
|
20054
20568
|
contextLimitTokens;
|
|
20055
|
-
|
|
20569
|
+
refusalCause;
|
|
20570
|
+
remedy;
|
|
20056
20571
|
code = "UNRESOLVED_HISTORY_BOUNDARY";
|
|
20057
20572
|
recoverable = true;
|
|
20058
|
-
constructor(estimatedTokens, contextLimitTokens,
|
|
20059
|
-
|
|
20060
|
-
super(reason + renderUserFacingFailure("history_boundary_unresolved", "plain"));
|
|
20573
|
+
constructor(estimatedTokens, contextLimitTokens, refusalCause, remedy = "flush") {
|
|
20574
|
+
super(historyBoundaryRefusalText(refusalCause, remedy));
|
|
20061
20575
|
this.estimatedTokens = estimatedTokens;
|
|
20062
20576
|
this.contextLimitTokens = contextLimitTokens;
|
|
20063
|
-
this.
|
|
20577
|
+
this.refusalCause = refusalCause;
|
|
20578
|
+
this.remedy = remedy;
|
|
20064
20579
|
this.name = "UnresolvedHistoryBoundaryError";
|
|
20065
20580
|
}
|
|
20066
20581
|
}
|
|
20582
|
+
function historyBoundaryRefusalCause(trimRefusal, boundaryInStore) {
|
|
20583
|
+
if (boundaryInStore === false)
|
|
20584
|
+
return "boundary-missing-from-store";
|
|
20585
|
+
return trimRefusal ?? undefined;
|
|
20586
|
+
}
|
|
20067
20587
|
// src/hooks/magic-context/transform.ts
|
|
20588
|
+
function afterCapture(sessionId, statement, run) {
|
|
20589
|
+
try {
|
|
20590
|
+
return run();
|
|
20591
|
+
} catch (error) {
|
|
20592
|
+
sessionLog2(sessionId, `${statement} failed after the request was decided; serving the pass:`, error);
|
|
20593
|
+
return;
|
|
20594
|
+
}
|
|
20595
|
+
}
|
|
20068
20596
|
var MESSAGE_TOKENS_CACHE_MAX = 100;
|
|
20069
20597
|
var messageTokensBySession = new BoundedSessionMap(MESSAGE_TOKENS_CACHE_MAX);
|
|
20070
20598
|
function getMessageTokensCache(sessionId) {
|
|
@@ -20155,6 +20683,7 @@ function createTransform(deps) {
|
|
|
20155
20683
|
const clearSessionLogState = (sessionId) => {
|
|
20156
20684
|
prefixHoldLogTurnIds.delete(sessionId);
|
|
20157
20685
|
clearDiagnosticLogState(sessionId);
|
|
20686
|
+
forgetHistoryBoundaryRecovery(sessionId);
|
|
20158
20687
|
};
|
|
20159
20688
|
const unmanagedOverWindowSessions = new Set;
|
|
20160
20689
|
const localWireReadings = createLocalWireReadings();
|
|
@@ -20389,12 +20918,21 @@ function createTransform(deps) {
|
|
|
20389
20918
|
}
|
|
20390
20919
|
}
|
|
20391
20920
|
const activeThinkingModel = findLastAssistantModel(messages) ?? deps.liveModelBySession?.get(sessionId);
|
|
20921
|
+
const thinkingRecoveryModel = findNewestUserModel(messages) ?? deps.liveModelBySession?.get(sessionId);
|
|
20922
|
+
try {
|
|
20923
|
+
retryBindingRecoveryClear(db, sessionId);
|
|
20924
|
+
} catch (error) {
|
|
20925
|
+
sessionLog2(sessionId, "thinking binding recovery: retried clear failed:", error);
|
|
20926
|
+
}
|
|
20927
|
+
const appliedBindingRecoveryTarget = bindingRecoveryAwaitingClear(sessionId);
|
|
20392
20928
|
const thinkingRecovery = prepareLatestThinkingRecovery({
|
|
20393
20929
|
db,
|
|
20394
20930
|
sessionId,
|
|
20395
20931
|
messages,
|
|
20396
20932
|
id: (message) => message?.info.id,
|
|
20397
|
-
parts: (message) => message?.parts ?? []
|
|
20933
|
+
parts: (message) => message?.parts ?? [],
|
|
20934
|
+
modelID: thinkingRecoveryModel?.modelID,
|
|
20935
|
+
providerID: thinkingRecoveryModel?.providerID
|
|
20398
20936
|
});
|
|
20399
20937
|
if (thinkingRecovery.ended)
|
|
20400
20938
|
deps.pendingMaterializationSessions?.add(sessionId);
|
|
@@ -20447,6 +20985,7 @@ function createTransform(deps) {
|
|
|
20447
20985
|
} else {
|
|
20448
20986
|
clearDetectedContextLimit(db, sessionId);
|
|
20449
20987
|
clearEmergencyRecovery(db, sessionId);
|
|
20988
|
+
forgetHistoryBoundaryRecovery(sessionId);
|
|
20450
20989
|
}
|
|
20451
20990
|
deps.contextUsageMap.delete(sessionId);
|
|
20452
20991
|
sessionMeta = {
|
|
@@ -20490,6 +21029,8 @@ function createTransform(deps) {
|
|
|
20490
21029
|
let recoveryNoEligibleHeadCount = earlyStateSnapshot.protectedTail.recoveryNoEligibleHeadCount;
|
|
20491
21030
|
let emergencyRecoveryOrigin = null;
|
|
20492
21031
|
let usagePercentageSynthetic = false;
|
|
21032
|
+
const passInputKey = inputMessagesKey(messages);
|
|
21033
|
+
let recoveryStateKeyAtPassStart = null;
|
|
20493
21034
|
if (fullFeatureMode && !compactionOff) {
|
|
20494
21035
|
try {
|
|
20495
21036
|
const armModel = deps.liveModelBySession?.get(sessionId);
|
|
@@ -20507,22 +21048,29 @@ function createTransform(deps) {
|
|
|
20507
21048
|
overflowStateMutatedThisPass = true;
|
|
20508
21049
|
}
|
|
20509
21050
|
const overflowState = overflowStateMutatedThisPass ? getOverflowState(db, sessionId) : earlyStateSnapshot.overflow;
|
|
20510
|
-
|
|
20511
|
-
|
|
21051
|
+
if (overflowState.needsEmergencyRecovery) {
|
|
21052
|
+
recoveryStateKeyAtPassStart = historyBoundaryRecoveryStateKey(db, sessionId, passInputKey);
|
|
21053
|
+
}
|
|
21054
|
+
const recoveryIdle = overflowState.needsEmergencyRecovery && overflowState.emergencyRecoveryOrigin === "history_boundary_over_window" && isHistoryBoundaryRecoveryExhausted(sessionId, recoveryStateKeyAtPassStart);
|
|
21055
|
+
if (recoveryIdle) {
|
|
21056
|
+
sessionLog2(sessionId, "transform: recovery for an uncut history already ran on this exact state and made no room; idle until the conversation, its summaries or its dropped tool output change");
|
|
21057
|
+
}
|
|
21058
|
+
emergencyRecoveryArmed = overflowState.needsEmergencyRecovery && !recoveryIdle;
|
|
21059
|
+
emergencyRecoveryOrigin = recoveryIdle ? null : overflowState.emergencyRecoveryOrigin;
|
|
20512
21060
|
if (contextUsageEarly.percentage < 80 && !overflowState.needsEmergencyRecovery) {
|
|
20513
21061
|
resetProtectedTailNoEligibleHead(db, sessionId);
|
|
20514
21062
|
recoveryNoEligibleHeadCount = 0;
|
|
20515
21063
|
}
|
|
20516
21064
|
const noHeadEscape = overflowState.needsEmergencyRecovery && recoveryNoEligibleHeadCount >= RECOVERY_NO_HEAD_LIMIT;
|
|
20517
21065
|
recoveryNoHeadEscapeActive = noHeadEscape;
|
|
20518
|
-
if (overflowState.needsEmergencyRecovery && contextUsageEarly.percentage < 95 && !noHeadEscape) {
|
|
21066
|
+
if (overflowState.needsEmergencyRecovery && !recoveryIdle && contextUsageEarly.percentage < 95 && !noHeadEscape) {
|
|
20519
21067
|
sessionLog2(sessionId, `transform: bumping percentage to 95% due to overflow recovery flag (was ${contextUsageEarly.percentage.toFixed(1)}%, detectedLimit=${overflowState.detectedContextLimit || "unknown"})`);
|
|
20520
21068
|
contextUsageEarly = {
|
|
20521
21069
|
...contextUsageEarly,
|
|
20522
21070
|
percentage: 95
|
|
20523
21071
|
};
|
|
20524
21072
|
usagePercentageSynthetic = true;
|
|
20525
|
-
} else if (recoveryNoHeadEscapeActive && deps.client) {
|
|
21073
|
+
} else if (recoveryNoHeadEscapeActive && !recoveryIdle && deps.client) {
|
|
20526
21074
|
withoutSqliteTransformPass2(() => sendStatusNotification2(deps.client, sessionId, "Magic Context can't compact yet — the recent history is a single in-progress block. Continuing; it will compact once the block completes. Run `/ctx-recomp` if this persists.", runNotificationParams(sessionId) ?? {}));
|
|
20527
21075
|
}
|
|
20528
21076
|
} catch (error) {
|
|
@@ -20538,6 +21086,7 @@ function createTransform(deps) {
|
|
|
20538
21086
|
deps.liveModelBySession?.set(sessionId, recovered);
|
|
20539
21087
|
}
|
|
20540
21088
|
}
|
|
21089
|
+
noteServedModel(sessionId, modelForBudget);
|
|
20541
21090
|
const resolvedProviderID = modelForBudget?.providerID;
|
|
20542
21091
|
activeThinkingTurn ||= hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID);
|
|
20543
21092
|
const signedThinkingPrefixBound = activeThinkingTurn && (isPrefixBoundThinkingModel(activeThinkingModel?.providerID, activeThinkingModel?.modelID) || isPrefixBoundThinkingModel(resolvedProviderID, modelForBudget?.modelID));
|
|
@@ -20610,6 +21159,12 @@ function createTransform(deps) {
|
|
|
20610
21159
|
messages,
|
|
20611
21160
|
usagePercentage: contextUsageEarly.percentage,
|
|
20612
21161
|
executeThresholdPercentage: effectiveExecuteThresholdPercentage,
|
|
21162
|
+
forceBandPressure: forceBandConfirmed({
|
|
21163
|
+
percentage: contextUsageEarly.percentage,
|
|
21164
|
+
fromEstimate: hostOverWindow,
|
|
21165
|
+
forceMaterializationPercentage,
|
|
21166
|
+
compactionOff
|
|
21167
|
+
}),
|
|
20613
21168
|
estimateTextTokens: (text) => {
|
|
20614
21169
|
holdProseRatio ??= sessionDecisionCalibration(db, sessionId).proseRatio;
|
|
20615
21170
|
return estimateTokens(text) * holdProseRatio;
|
|
@@ -21262,6 +21817,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21262
21817
|
schedulerDecision,
|
|
21263
21818
|
forceMaterializationPercentage,
|
|
21264
21819
|
signedThinkingHold: activeThinkingPrefixHold,
|
|
21820
|
+
signedThinkingHoldCapPercentage: !compactionOff && signedThinkingHold?.held === true ? signedThinkingHold.capPercentage : undefined,
|
|
21265
21821
|
firstRender: servesHead && !(sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) && !hasCompleteCachedM0M1(db, sessionId),
|
|
21266
21822
|
folds: protectionFoldWillBust,
|
|
21267
21823
|
explicitFlush: hasPendingMaterializationOrigin(deps.pendingMaterializationSessions, sessionId, "user_flush"),
|
|
@@ -21376,6 +21932,20 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21376
21932
|
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}`);
|
|
21377
21933
|
}
|
|
21378
21934
|
}
|
|
21935
|
+
const sizedHoldEnd = activeThinkingPrefixHold && !compactionOff && signedThinkingHold?.held === true ? readingEndsHold({
|
|
21936
|
+
usagePercentage: contextUsage.percentage,
|
|
21937
|
+
capPercentage: signedThinkingHold.capPercentage,
|
|
21938
|
+
forceBandPressure: forceBandConfirmed({
|
|
21939
|
+
percentage: contextUsage.percentage,
|
|
21940
|
+
fromEstimate: contextUsageFromEstimate,
|
|
21941
|
+
forceMaterializationPercentage,
|
|
21942
|
+
compactionOff
|
|
21943
|
+
})
|
|
21944
|
+
}) : null;
|
|
21945
|
+
if (sizedHoldEnd !== null && signedThinkingHold) {
|
|
21946
|
+
activeThinkingPrefixHold = false;
|
|
21947
|
+
sessionLog2(sessionId, `signed thinking hold: held=false reason=${sizedHoldEnd} heavyStepsBack=${signedThinkingHold.heavyStepsBack ?? "none"} heavyStepTokens=${signedThinkingHold.heavyStepTokens} usage=${contextUsage.percentage.toFixed(1)}% cap=${signedThinkingHold.capPercentage}% (sized reading${contextUsageFromEstimate ? ", local count" : ""})`);
|
|
21948
|
+
}
|
|
21379
21949
|
const protectionUsableSoft = windowGeometry?.usableSoft ?? boundaryContextLimit;
|
|
21380
21950
|
const protectionFloor = resolveEpochFloorForPass(db, sessionId, {
|
|
21381
21951
|
configuredOverride: deps.protectedTokens,
|
|
@@ -21400,6 +21970,22 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21400
21970
|
opencode2: deps.storeGeneration === "v2",
|
|
21401
21971
|
structuralSentinelUpgradeFailed,
|
|
21402
21972
|
releaseRecoveryPrefix: releaseRecoveryReplay,
|
|
21973
|
+
frozenRecoveryRequest: recovery.prefix ? () => {
|
|
21974
|
+
try {
|
|
21975
|
+
const frozen = JSON.parse(recovery.prefix?.json ?? "null");
|
|
21976
|
+
return Array.isArray(frozen) ? frozen : null;
|
|
21977
|
+
} catch {
|
|
21978
|
+
return null;
|
|
21979
|
+
}
|
|
21980
|
+
} : undefined,
|
|
21981
|
+
restartedLastServedRequest: recovery.restartedSlotJson !== undefined ? () => {
|
|
21982
|
+
try {
|
|
21983
|
+
const saved = JSON.parse(recovery.restartedSlotJson ?? "");
|
|
21984
|
+
return Array.isArray(saved) ? saved : null;
|
|
21985
|
+
} catch {
|
|
21986
|
+
return null;
|
|
21987
|
+
}
|
|
21988
|
+
} : undefined,
|
|
21403
21989
|
normalizeRecoveryTail,
|
|
21404
21990
|
compactionMarkerStrategy: deps.compactionMarkerStrategy ?? defaultCompactionMarkerStrategy,
|
|
21405
21991
|
sessionId,
|
|
@@ -21481,10 +22067,11 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21481
22067
|
protectedTools: deps.protectedTools,
|
|
21482
22068
|
resolvedProviderID,
|
|
21483
22069
|
activeThinkingTurn,
|
|
21484
|
-
protectedThinkingMessages: thinkingRecovery.restore ? protectedThinkingMessages : undefined,
|
|
21485
|
-
restoreThinkingMessageIds: thinkingRecovery.restore ? new Set([...protectedThinkingMessages].flatMap((message) => typeof message.info.id === "string" ? [message.info.id] : [])) : undefined,
|
|
22070
|
+
protectedThinkingMessages: thinkingRecovery.restore ? restoredTurnMessages(messages, protectedThinkingMessages) : undefined,
|
|
22071
|
+
restoreThinkingMessageIds: thinkingRecovery.restore ? new Set([...restoredTurnMessages(messages, protectedThinkingMessages)].flatMap((message) => typeof message.info.id === "string" ? [message.info.id] : [])) : undefined,
|
|
21486
22072
|
restoreLatestTurnOriginals,
|
|
21487
22073
|
resolvedModelID: modelForBudget?.modelID,
|
|
22074
|
+
appliedBindingRecoveryTarget,
|
|
21488
22075
|
thinkingBindingRecoveryEnabledForModel: isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID),
|
|
21489
22076
|
trailingBlankSourceDecisions,
|
|
21490
22077
|
passOutcome,
|
|
@@ -21519,7 +22106,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21519
22106
|
const suffix = recoveryTailSources.flatMap(({ identity, pristineSystem }) => pristineSystem ? [pristineSystem] : renderedById.get(identity) ?? []);
|
|
21520
22107
|
messages.splice(0, messages.length, ...JSON.parse(recovery.prefix.json), ...suffix);
|
|
21521
22108
|
}
|
|
21522
|
-
const recoveryReleaseReason = recovery.rebuildReason ?? (recoveryNormalized ? "recovery_tail_normalized" : recoveryReleased ? "recovery_prefix_released" : undefined);
|
|
22109
|
+
const recoveryReleaseReason = recovery.rebuildReason ?? (recoveryNormalized ? "recovery_tail_normalized" : recoveryReleased ? "recovery_prefix_released" : postTransformResult.restartHeadChanged ? "lkg_restart_head_changed" : undefined);
|
|
21523
22110
|
if (recoveryReleaseReason)
|
|
21524
22111
|
postTransformResult.bustedThisPass = true;
|
|
21525
22112
|
passOutcome.markFinalized();
|
|
@@ -21606,6 +22193,21 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21606
22193
|
throw contextRefusalError("The request remains over the model window after stripping signed thinking and reclaiming context");
|
|
21607
22194
|
}
|
|
21608
22195
|
}
|
|
22196
|
+
const currentModelKeyForRecovery = deps.getModelKey?.(sessionId);
|
|
22197
|
+
const keepRecoveryArmed = () => {
|
|
22198
|
+
if (!emergencyRecoveryArmed || emergencyRecoveryOrigin === null)
|
|
22199
|
+
return;
|
|
22200
|
+
try {
|
|
22201
|
+
if (getOverflowState(db, sessionId).needsEmergencyRecovery)
|
|
22202
|
+
return;
|
|
22203
|
+
recordOverflowDetected(db, sessionId, undefined, currentModelKeyForRecovery, emergencyRecoveryOrigin);
|
|
22204
|
+
} catch (error) {
|
|
22205
|
+
throw new EmergencyFailClosedError("Emergency recovery re-arm failed", {
|
|
22206
|
+
cause: error
|
|
22207
|
+
});
|
|
22208
|
+
}
|
|
22209
|
+
sessionLog2(sessionId, `transform: recovery was cleared during a pass that is not sent; armed again (${emergencyRecoveryOrigin}) for the next turn`);
|
|
22210
|
+
};
|
|
21609
22211
|
if (postTransformResult.prefixTrimStatus === "refused") {
|
|
21610
22212
|
const untrimmed = finalWireEstimate ?? estimateFinalWireInputTokens({
|
|
21611
22213
|
messages,
|
|
@@ -21616,8 +22218,35 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21616
22218
|
sessionId
|
|
21617
22219
|
});
|
|
21618
22220
|
if (untrimmed.tokens > boundaryContextLimit) {
|
|
21619
|
-
|
|
21620
|
-
|
|
22221
|
+
const stateKey = historyBoundaryRecoveryStateKey(db, sessionId, passInputKey);
|
|
22222
|
+
let remedy = "flush";
|
|
22223
|
+
let recovery;
|
|
22224
|
+
if (emergencyRecoveryArmed && emergencyRecoveryOrigin !== null) {
|
|
22225
|
+
const madeRoom = compartmentPhase.published || postTransformResult.droppedCount > 0 || postTransformResult.emergencyReclaimedTokens > 0 || stateKey !== null && recoveryStateKeyAtPassStart !== null && stateKey !== recoveryStateKeyAtPassStart;
|
|
22226
|
+
if (madeRoom) {
|
|
22227
|
+
keepRecoveryArmed();
|
|
22228
|
+
remedy = "send-again";
|
|
22229
|
+
recovery = `${emergencyRecoveryOrigin} recovery made room this pass but not enough; it stays armed for the next turn`;
|
|
22230
|
+
} else {
|
|
22231
|
+
if (stateKey !== null)
|
|
22232
|
+
markHistoryBoundaryRecoveryExhausted(sessionId, stateKey);
|
|
22233
|
+
recovery = `${emergencyRecoveryOrigin} recovery ran this pass and made no room; it stays idle on this state`;
|
|
22234
|
+
}
|
|
22235
|
+
} else if (!untrimmed.trusted) {
|
|
22236
|
+
recovery = "the estimate is not calibrated, so recovery is not armed";
|
|
22237
|
+
} else if (isHistoryBoundaryRecoveryExhausted(sessionId, stateKey)) {
|
|
22238
|
+
recovery = "recovery already ran on this exact state and made no room";
|
|
22239
|
+
} else {
|
|
22240
|
+
try {
|
|
22241
|
+
recordOverflowDetected(db, sessionId, undefined, currentModelKeyForRecovery, "history_boundary_over_window");
|
|
22242
|
+
remedy = "send-again";
|
|
22243
|
+
recovery = "overflow recovery armed (history_boundary_over_window) for the next pass";
|
|
22244
|
+
} catch (error) {
|
|
22245
|
+
recovery = `arming overflow recovery failed: ${getErrorMessage(error)}`;
|
|
22246
|
+
}
|
|
22247
|
+
}
|
|
22248
|
+
sessionLog2(sessionId, `history boundary unresolved: prefix trim refused (${postTransformResult.prefixTrimRefusal ?? "no reason recorded"}) and the untrimmed request estimate ${untrimmed.tokens} (trusted=${untrimmed.trusted}) exceeds the context limit ${boundaryContextLimit}; not sending it; ${recovery}`);
|
|
22249
|
+
throw new UnresolvedHistoryBoundaryError(untrimmed.tokens, boundaryContextLimit, historyBoundaryRefusalCause(postTransformResult.prefixTrimRefusal, storedHistoryBoundaryPresence(db, sessionId)), remedy);
|
|
21621
22250
|
}
|
|
21622
22251
|
}
|
|
21623
22252
|
if (unmanagedOverWindowPass) {
|
|
@@ -21637,21 +22266,6 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21637
22266
|
unmanagedOverWindowSessions.delete(sessionId);
|
|
21638
22267
|
sessionLog2(sessionId, `over-window first pass reduced: the request is about ${servedTokens} tokens (history started at ${unmanagedOverWindowPass.tokens}), under the ${unmanagedOverWindowPass.limit}-token window`);
|
|
21639
22268
|
}
|
|
21640
|
-
const currentModelKeyForRecovery = deps.getModelKey?.(sessionId);
|
|
21641
|
-
const keepRecoveryArmed = () => {
|
|
21642
|
-
if (!emergencyRecoveryArmed || emergencyRecoveryOrigin === null)
|
|
21643
|
-
return;
|
|
21644
|
-
try {
|
|
21645
|
-
if (getOverflowState(db, sessionId).needsEmergencyRecovery)
|
|
21646
|
-
return;
|
|
21647
|
-
recordOverflowDetected(db, sessionId, undefined, currentModelKeyForRecovery, emergencyRecoveryOrigin);
|
|
21648
|
-
} catch (error) {
|
|
21649
|
-
throw new EmergencyFailClosedError("Emergency recovery re-arm failed", {
|
|
21650
|
-
cause: error
|
|
21651
|
-
});
|
|
21652
|
-
}
|
|
21653
|
-
sessionLog2(sessionId, `transform: recovery was cleared during a pass that is not sent; armed again (${emergencyRecoveryOrigin}) for the next turn`);
|
|
21654
|
-
};
|
|
21655
22269
|
const timedOutHistorianFailure = compartmentPhase.historianJoinTimedOut ? historianJoinFailClosedMessage({
|
|
21656
22270
|
timedOut: true,
|
|
21657
22271
|
budgetMs: compartmentPhase.historianJoinBudgetMs,
|
|
@@ -21689,9 +22303,11 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21689
22303
|
});
|
|
21690
22304
|
if (emergencyFailClosed.disarm) {
|
|
21691
22305
|
clearEmergencyRecovery(db, sessionId);
|
|
22306
|
+
forgetHistoryBoundaryRecovery(sessionId);
|
|
21692
22307
|
sessionLog2(sessionId, `emergency disarm: trusted final-wire ${emergencyFailClosed.disarm.finalWireTokens} under limit ${emergencyFailClosed.disarm.provenLimitTokens}`);
|
|
21693
22308
|
} else if (recoveryAdmissionPass && !emergencyFailClosed.shouldAbort && recoveryServedRequest !== undefined) {
|
|
21694
22309
|
clearEmergencyRecovery(db, sessionId);
|
|
22310
|
+
forgetHistoryBoundaryRecovery(sessionId);
|
|
21695
22311
|
sessionLog2(sessionId, `transform: recovery request admitted: about ${recoveryServedRequest.tokens} tokens, within ${recoveryServedRequest.lineTokens} of ${recoveryWindowTokens}; ${emergencyRecoveryOrigin} recovery ends`);
|
|
21696
22312
|
}
|
|
21697
22313
|
if (emergencyFailClosed.shouldAbort) {
|
|
@@ -21756,11 +22372,25 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21756
22372
|
if (!finalWireEstimate) {
|
|
21757
22373
|
sessionLog2(sessionId, `transform: final-wire telemetry estimate=unavailable trusted=false conversation=unknown tools=unknown system=unknown toolDefinitions=unknown tail=${finalWireTail}`);
|
|
21758
22374
|
}
|
|
22375
|
+
const instructionDecisions = postTransformResult.pendingHostInstructionDecisions;
|
|
22376
|
+
const reclaim = instructionDecisions?.reclaim;
|
|
22377
|
+
const decisionsDue = instructionDecisions !== undefined && (instructionDecisions.retention || reclaim?.hasDecisions === true);
|
|
21759
22378
|
if (!compactionOff) {
|
|
21760
22379
|
const stillUntagged = untaggedReplayTailServed && !recoveryNormalized ? [...untaggedReplayIds] : [];
|
|
21761
|
-
|
|
22380
|
+
const untaggedChanged = JSON.stringify([...new Set(stillUntagged)].sort()) !== JSON.stringify([...new Set(persistedUntaggedInputIds)].sort());
|
|
22381
|
+
if ((untaggedChanged || decisionsDue) && !persistLkgUntaggedInputIds(db, sessionId, untaggedChanged ? stillUntagged : undefined, decisionsDue ? (doc) => recordHostInstructionDecisions(doc, {
|
|
22382
|
+
retention: instructionDecisions?.retention === true,
|
|
22383
|
+
record: reclaim ? (target) => reclaim.record(target) : undefined
|
|
22384
|
+
}) : undefined)) {
|
|
22385
|
+
if (decisionsDue) {
|
|
22386
|
+
const failure = new Error("Cannot persist the last-good records with this pass's instruction-row decisions");
|
|
22387
|
+
sessionLog2(sessionId, "transform refused degraded pass site=host-instruction-retention-persistence-failure:", failure);
|
|
22388
|
+
failPass("host-instruction-retention-persistence-failure", failure);
|
|
22389
|
+
}
|
|
21762
22390
|
throw new Error("Cannot persist the last-good untagged-message record");
|
|
22391
|
+
}
|
|
21763
22392
|
}
|
|
22393
|
+
reclaim?.markRetired();
|
|
21764
22394
|
const signedThinkingServed = isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID) && servesThinkingBlock(messages, modelForBudget?.providerID, modelForBudget?.modelID);
|
|
21765
22395
|
finishSystemDateRefresh(deps.historyRefreshSessions, dateRequest, postTransformResult.bustedThisPass && !activeThinkingPrefixHold && !signedThinkingServed || postTransformResult.thinkingReleasedForFit === true, signedThinkingServed);
|
|
21766
22396
|
if (activeThinkingPrefixHold && !postTransformResult.thinkingReleasedForFit && sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) {
|
|
@@ -21781,8 +22411,10 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21781
22411
|
agentName: notificationParams?.agent
|
|
21782
22412
|
});
|
|
21783
22413
|
if (captured) {
|
|
21784
|
-
|
|
21785
|
-
|
|
22414
|
+
afterCapture(sessionId, "deferred last-good save", () => {
|
|
22415
|
+
const capturedSlot = getInMemorySlot(sessionId);
|
|
22416
|
+
if (!capturedSlot)
|
|
22417
|
+
return;
|
|
21786
22418
|
const revision = lkgDirtyRevision(sessionId) ?? dirtyLkgRecoveryRevision(sessionId, capturedSlot);
|
|
21787
22419
|
const fence = {
|
|
21788
22420
|
ownDirtyRevision: revision,
|
|
@@ -21802,7 +22434,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21802
22434
|
sessionLog2(sessionId, "Last-good deferred publication remains uncertified:", error);
|
|
21803
22435
|
}
|
|
21804
22436
|
}));
|
|
21805
|
-
}
|
|
22437
|
+
});
|
|
21806
22438
|
noteLkgHealthyPrefix(sessionId, lkgInput, messages, !!recoveryReleaseReason);
|
|
21807
22439
|
}
|
|
21808
22440
|
if (!captured) {
|
|
@@ -21816,94 +22448,98 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21816
22448
|
}
|
|
21817
22449
|
sessionLog2(sessionId, `lkg_capture_declined degradations=${passOutcome.degradations.map((item) => item.site).join(",")}`);
|
|
21818
22450
|
}
|
|
21819
|
-
|
|
21820
|
-
|
|
21821
|
-
|
|
21822
|
-
|
|
21823
|
-
|
|
21824
|
-
|
|
21825
|
-
|
|
21826
|
-
|
|
21827
|
-
|
|
21828
|
-
|
|
21829
|
-
|
|
21830
|
-
|
|
21831
|
-
|
|
21832
|
-
|
|
21833
|
-
|
|
21834
|
-
|
|
21835
|
-
|
|
21836
|
-
|
|
21837
|
-
|
|
21838
|
-
|
|
21839
|
-
|
|
21840
|
-
|
|
21841
|
-
|
|
21842
|
-
|
|
21843
|
-
|
|
21844
|
-
|
|
21845
|
-
|
|
21846
|
-
|
|
21847
|
-
|
|
21848
|
-
|
|
21849
|
-
|
|
21850
|
-
|
|
21851
|
-
|
|
21852
|
-
|
|
21853
|
-
|
|
21854
|
-
|
|
21855
|
-
|
|
21856
|
-
|
|
21857
|
-
|
|
21858
|
-
const msgTokens = getMessageTokensCache(sessionId);
|
|
21859
|
-
let storedByMessage = new Map;
|
|
21860
|
-
const uncachedMessageIds = messages.flatMap((message) => {
|
|
21861
|
-
const messageId = message.info.id;
|
|
21862
|
-
return messageId !== undefined && !msgTokens.has(messageId) ? [messageId] : [];
|
|
22451
|
+
afterCapture(sessionId, "transform decision record", () => {
|
|
22452
|
+
if (postTransformResult.bustedThisPass || hardCacheExpired || thinkingRecovery.removedThisPass) {
|
|
22453
|
+
recordPendingTransformDecision(sessionId, {
|
|
22454
|
+
tsMs: Date.now(),
|
|
22455
|
+
decision: schedulerDecision,
|
|
22456
|
+
materialized: postTransformResult.materialized,
|
|
22457
|
+
materializeReason: normalizeMaterializeReason("opencode", postTransformResult.materializeReason ?? (thinkingRecovery.removedThisPass ? LATEST_TURN_THINKING_REMOVED_REASON : hardCacheExpired ? "ttl_idle" : null), postTransformResult.materialized),
|
|
22458
|
+
systemHashPrev: postTransformResult.systemHashPrev,
|
|
22459
|
+
systemHashNew: postTransformResult.systemHashNew,
|
|
22460
|
+
m0ToolSetHashPrev: postTransformResult.m0ToolSetHashPrev,
|
|
22461
|
+
m0ToolSetHashNew: postTransformResult.m0ToolSetHashNew,
|
|
22462
|
+
m0ModelKeyPrev: postTransformResult.m0ModelKeyPrev,
|
|
22463
|
+
m0ModelKeyNew: postTransformResult.m0ModelKeyNew,
|
|
22464
|
+
emergency: postTransformResult.emergency,
|
|
22465
|
+
droppedTokens: postTransformResult.droppedTokens,
|
|
22466
|
+
droppedCount: postTransformResult.droppedCount,
|
|
22467
|
+
inputTokens: contextUsage.inputTokens,
|
|
22468
|
+
bustedThisPass: true,
|
|
22469
|
+
lkgFrozenReleaseReason: recoveryReleaseReason
|
|
22470
|
+
});
|
|
22471
|
+
} else {
|
|
22472
|
+
noteOpenCodeUnbustedPass(sessionId, {
|
|
22473
|
+
tsMs: Date.now(),
|
|
22474
|
+
decision: schedulerDecision,
|
|
22475
|
+
materialized: postTransformResult.materialized,
|
|
22476
|
+
materializeReason: normalizeMaterializeReason("opencode", postTransformResult.materializeReason, postTransformResult.materialized),
|
|
22477
|
+
systemHashPrev: postTransformResult.systemHashPrev,
|
|
22478
|
+
systemHashNew: postTransformResult.systemHashNew,
|
|
22479
|
+
m0ToolSetHashPrev: postTransformResult.m0ToolSetHashPrev,
|
|
22480
|
+
m0ToolSetHashNew: postTransformResult.m0ToolSetHashNew,
|
|
22481
|
+
m0ModelKeyPrev: postTransformResult.m0ModelKeyPrev,
|
|
22482
|
+
m0ModelKeyNew: postTransformResult.m0ModelKeyNew,
|
|
22483
|
+
emergency: postTransformResult.emergency,
|
|
22484
|
+
droppedTokens: postTransformResult.droppedTokens,
|
|
22485
|
+
droppedCount: postTransformResult.droppedCount,
|
|
22486
|
+
inputTokens: contextUsage.inputTokens,
|
|
22487
|
+
bustedThisPass: false
|
|
22488
|
+
});
|
|
22489
|
+
}
|
|
21863
22490
|
});
|
|
21864
|
-
|
|
21865
|
-
|
|
21866
|
-
|
|
21867
|
-
|
|
21868
|
-
|
|
21869
|
-
|
|
21870
|
-
|
|
21871
|
-
|
|
21872
|
-
|
|
21873
|
-
|
|
21874
|
-
|
|
21875
|
-
|
|
21876
|
-
|
|
21877
|
-
if (cached) {
|
|
21878
|
-
conversationTokens += cached.conversation;
|
|
21879
|
-
toolCallTokens += cached.toolCall;
|
|
21880
|
-
continue;
|
|
22491
|
+
logTransformTiming(sessionId, "postTransformPhase", tPostProcess);
|
|
22492
|
+
afterCapture(sessionId, "conversation token estimate", () => {
|
|
22493
|
+
const msgTokens = getMessageTokensCache(sessionId);
|
|
22494
|
+
let storedByMessage = new Map;
|
|
22495
|
+
const uncachedMessageIds = messages.flatMap((message) => {
|
|
22496
|
+
const messageId = message.info.id;
|
|
22497
|
+
return messageId !== undefined && !msgTokens.has(messageId) ? [messageId] : [];
|
|
22498
|
+
});
|
|
22499
|
+
if (uncachedMessageIds.length > 0) {
|
|
22500
|
+
try {
|
|
22501
|
+
storedByMessage = omitIncompleteFileTokenTotals(db, sessionId, messages.flatMap((message) => message.info.id ? [{ id: message.info.id, parts: message.parts }] : []), getActiveTagTokenTotalsByMessage2(db, sessionId, uncachedMessageIds));
|
|
22502
|
+
} catch {
|
|
22503
|
+
storedByMessage = new Map;
|
|
21881
22504
|
}
|
|
21882
|
-
|
|
21883
|
-
|
|
21884
|
-
|
|
21885
|
-
|
|
21886
|
-
|
|
21887
|
-
|
|
21888
|
-
|
|
21889
|
-
|
|
21890
|
-
|
|
22505
|
+
}
|
|
22506
|
+
let conversationTokens = 0;
|
|
22507
|
+
let toolCallTokens = 0;
|
|
22508
|
+
for (const message of messages) {
|
|
22509
|
+
const mid = message.info.id;
|
|
22510
|
+
if (mid) {
|
|
22511
|
+
const cached = msgTokens.get(mid);
|
|
22512
|
+
if (cached) {
|
|
22513
|
+
conversationTokens += cached.conversation;
|
|
22514
|
+
toolCallTokens += cached.toolCall;
|
|
22515
|
+
continue;
|
|
22516
|
+
}
|
|
22517
|
+
const stored = storedByMessage.get(mid);
|
|
22518
|
+
if (stored && !stored.hasNull) {
|
|
22519
|
+
conversationTokens += stored.conversation;
|
|
22520
|
+
toolCallTokens += stored.toolCall;
|
|
22521
|
+
msgTokens.set(mid, {
|
|
22522
|
+
conversation: stored.conversation,
|
|
22523
|
+
toolCall: stored.toolCall
|
|
22524
|
+
});
|
|
22525
|
+
continue;
|
|
22526
|
+
}
|
|
21891
22527
|
}
|
|
22528
|
+
const estimated = estimateMessageTokens(message);
|
|
22529
|
+
if (mid)
|
|
22530
|
+
msgTokens.set(mid, estimated);
|
|
22531
|
+
conversationTokens += estimated.conversation;
|
|
22532
|
+
toolCallTokens += estimated.toolCall;
|
|
21892
22533
|
}
|
|
21893
|
-
|
|
21894
|
-
|
|
21895
|
-
|
|
21896
|
-
|
|
21897
|
-
|
|
21898
|
-
|
|
21899
|
-
|
|
21900
|
-
updateSessionMeta(db, sessionId, { conversationTokens, toolCallTokens });
|
|
21901
|
-
} catch (error) {
|
|
21902
|
-
const code = error?.code;
|
|
21903
|
-
if (code !== "SQLITE_BUSY") {
|
|
21904
|
-
sessionLog2(sessionId, "conversation_tokens UPDATE failed:", error);
|
|
22534
|
+
try {
|
|
22535
|
+
updateSessionMeta(db, sessionId, { conversationTokens, toolCallTokens });
|
|
22536
|
+
} catch (error) {
|
|
22537
|
+
const code = error?.code;
|
|
22538
|
+
if (code !== "SQLITE_BUSY") {
|
|
22539
|
+
sessionLog2(sessionId, "conversation_tokens UPDATE failed:", error);
|
|
22540
|
+
}
|
|
21905
22541
|
}
|
|
21906
|
-
}
|
|
22542
|
+
});
|
|
21907
22543
|
const channelBaseline = deps.channel1StateBySession?.get(sessionId);
|
|
21908
22544
|
if (ctxReduceCallable && !compactionOff && channelBaseline) {
|
|
21909
22545
|
try {
|
|
@@ -21942,14 +22578,16 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21942
22578
|
}
|
|
21943
22579
|
const elapsed = (performance.now() - startTime).toFixed(1);
|
|
21944
22580
|
sessionLog2(sessionId, `transform completed in ${elapsed}ms (${messages.length} messages, ${targets.size} targets, watermark: ${watermark})`);
|
|
21945
|
-
withoutSqliteTransformPass2(() => deps.maybeAutoEmbedSession?.(sessionId));
|
|
22581
|
+
afterCapture(sessionId, "auto-embed scheduling", () => withoutSqliteTransformPass2(() => deps.maybeAutoEmbedSession?.(sessionId)));
|
|
21946
22582
|
const bindingRecovery = postTransformResult.thinkingBindingRecovery;
|
|
21947
22583
|
if (bindingRecovery) {
|
|
21948
|
-
const cleared = clearThinkingBindingRecoveryIf(db, sessionId, bindingRecovery.flagTarget);
|
|
21949
|
-
|
|
22584
|
+
const cleared = afterCapture(sessionId, "thinking binding recovery clear", () => clearThinkingBindingRecoveryIf(db, sessionId, bindingRecovery.flagTarget));
|
|
22585
|
+
if (cleared === undefined)
|
|
22586
|
+
noteBindingRecoveryAwaitingClear(sessionId, bindingRecovery.flagTarget);
|
|
22587
|
+
sessionLog2(sessionId, `thinking binding recovery: stripped bound reasoning from ${bindingRecovery.messageIds.length} assistant(s) [${bindingRecovery.messageIds.join(",")}]; flag=${cleared === undefined ? "kept" : cleared ? "cleared" : "rearmed"}`);
|
|
21950
22588
|
}
|
|
21951
22589
|
if (passOutcome.captureEligible)
|
|
21952
|
-
finalWireUsage.capture(sessionId, {
|
|
22590
|
+
afterCapture(sessionId, "final wire usage capture", () => finalWireUsage.capture(sessionId, {
|
|
21953
22591
|
messages,
|
|
21954
22592
|
systemPromptTokens: sessionMeta.systemPromptTokens,
|
|
21955
22593
|
providerID: modelForBudget?.providerID,
|
|
@@ -21957,8 +22595,8 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21957
22595
|
agentName: notificationParams.agent,
|
|
21958
22596
|
sessionId,
|
|
21959
22597
|
systemPromptHash: sessionMeta.systemPromptHash
|
|
21960
|
-
});
|
|
21961
|
-
deps.onPassPermission?.(sessionId, postTransformResult.prefixMutationPermitted);
|
|
22598
|
+
}));
|
|
22599
|
+
afterCapture(sessionId, "pass permission report", () => deps.onPassPermission?.(sessionId, postTransformResult.prefixMutationPermitted));
|
|
21962
22600
|
};
|
|
21963
22601
|
const timedTransform = (input, output) => withTransformTimingSummary(async () => {
|
|
21964
22602
|
const sessionId = findSessionId(output.messages);
|
|
@@ -22265,6 +22903,7 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
22265
22903
|
} else {
|
|
22266
22904
|
const inputMessages = output.messages;
|
|
22267
22905
|
const keys = resolveLkgModelKeys(inputMessages);
|
|
22906
|
+
const hostTailDigests = rust ? [] : entry.pristineTail.map(lkgContentDigest);
|
|
22268
22907
|
const replay = replayLkg({
|
|
22269
22908
|
sessionId,
|
|
22270
22909
|
messages: inputMessages,
|
|
@@ -22331,6 +22970,7 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
22331
22970
|
entry,
|
|
22332
22971
|
messages: replay.messages,
|
|
22333
22972
|
...keys,
|
|
22973
|
+
hostTailDigests,
|
|
22334
22974
|
db
|
|
22335
22975
|
}))
|
|
22336
22976
|
return false;
|
|
@@ -22338,6 +22978,7 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
22338
22978
|
args.onLkgReplay?.();
|
|
22339
22979
|
noteExternalLkgReplay(rust, sessionId, inputMessages, replay.messages);
|
|
22340
22980
|
replaceMessagesInPlace2(output, replay.messages);
|
|
22981
|
+
noteServedReplay(sessionId);
|
|
22341
22982
|
sessionLog2(sessionId, "lkg_replay_served");
|
|
22342
22983
|
return true;
|
|
22343
22984
|
} else {
|
|
@@ -22364,6 +23005,8 @@ function createMessagesTransformHandler(args) {
|
|
|
22364
23005
|
const isInternalChild = typeof sessionId === "string" && sessionId.length > 0 && args.internalChildSessions?.has(sessionId) === true;
|
|
22365
23006
|
const compactionOffInputSnapshot = args.compactionOff ? [...output.messages] : null;
|
|
22366
23007
|
const restoreCompactionOffInput = () => {
|
|
23008
|
+
if (compactionOffInputSnapshot && sessionId)
|
|
23009
|
+
noteServedHostInput(sessionId);
|
|
22367
23010
|
if (compactionOffInputSnapshot && output.messages !== compactionOffInputSnapshot) {
|
|
22368
23011
|
output.messages.splice(0, output.messages.length, ...compactionOffInputSnapshot);
|
|
22369
23012
|
}
|
|
@@ -22444,6 +23087,8 @@ function createMessagesTransformHandler(args) {
|
|
|
22444
23087
|
tryReopen: args.tryReopenStorage
|
|
22445
23088
|
});
|
|
22446
23089
|
}
|
|
23090
|
+
if (sessionId)
|
|
23091
|
+
noteServedHostInput(sessionId);
|
|
22447
23092
|
return output.messages;
|
|
22448
23093
|
}
|
|
22449
23094
|
}
|
|
@@ -22530,7 +23175,42 @@ function createMessagesTransformHandler(args) {
|
|
|
22530
23175
|
restoreCompactionOffInput();
|
|
22531
23176
|
return output.messages;
|
|
22532
23177
|
};
|
|
23178
|
+
const finishServedRequest = (sessionId, output, returned) => {
|
|
23179
|
+
try {
|
|
23180
|
+
if (!returned)
|
|
23181
|
+
countServedRefusal(sessionId);
|
|
23182
|
+
else if (resolveRust(sessionId))
|
|
23183
|
+
forgetServedRecord(sessionId);
|
|
23184
|
+
else {
|
|
23185
|
+
const keys = resolveLkgModelKeys(output.messages);
|
|
23186
|
+
commitServedRequest({
|
|
23187
|
+
sessionId,
|
|
23188
|
+
host: "opencode",
|
|
23189
|
+
messages: output.messages,
|
|
23190
|
+
providerID: keys.providerKey,
|
|
23191
|
+
modelID: keys.modelKey && keys.providerKey ? keys.modelKey.slice(keys.providerKey.length + 1) : keys.modelKey,
|
|
23192
|
+
compactionOff: args.compactionOff === true
|
|
23193
|
+
});
|
|
23194
|
+
}
|
|
23195
|
+
} catch (error) {
|
|
23196
|
+
sessionLog2(sessionId, "served check skipped:", error);
|
|
23197
|
+
}
|
|
23198
|
+
};
|
|
22533
23199
|
return (input, output) => withSqliteTransformPass2(async () => {
|
|
23200
|
+
const servedSessionId = args.recordServed === false ? null : resolveSessionId2(output);
|
|
23201
|
+
if (servedSessionId)
|
|
23202
|
+
beginServedRequest(servedSessionId);
|
|
23203
|
+
let returned = false;
|
|
23204
|
+
try {
|
|
23205
|
+
const served = await servePass(input, output);
|
|
23206
|
+
returned = true;
|
|
23207
|
+
return served;
|
|
23208
|
+
} finally {
|
|
23209
|
+
if (servedSessionId)
|
|
23210
|
+
finishServedRequest(servedSessionId, output, returned);
|
|
23211
|
+
}
|
|
23212
|
+
});
|
|
23213
|
+
async function servePass(input, output) {
|
|
22534
23214
|
const tail = output.messages.at(-1);
|
|
22535
23215
|
if (tail?.info.role === "user" && tail.info.id && !tail.info.summary && tail.parts.length === 0) {
|
|
22536
23216
|
throw new IncompleteUserMessageError;
|
|
@@ -22544,7 +23224,7 @@ function createMessagesTransformHandler(args) {
|
|
|
22544
23224
|
preserveUserTerminatedTail(output.messages, inputMessages);
|
|
22545
23225
|
reportAssistantTerminatedTail(output.messages, inputTailRole, resolveSessionId2(output));
|
|
22546
23226
|
}
|
|
22547
|
-
}
|
|
23227
|
+
}
|
|
22548
23228
|
}
|
|
22549
23229
|
function resolveSessionId2(output) {
|
|
22550
23230
|
for (const message of output.messages) {
|
|
@@ -23682,7 +24362,7 @@ var storedCarry = object({
|
|
|
23682
24362
|
})
|
|
23683
24363
|
]))
|
|
23684
24364
|
});
|
|
23685
|
-
function
|
|
24365
|
+
function readState3(db, sessionId) {
|
|
23686
24366
|
const row = db.prepare("SELECT deferred_execute_state, new_work_tokens, total_input_tokens FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
23687
24367
|
let root = {};
|
|
23688
24368
|
try {
|
|
@@ -23705,7 +24385,7 @@ function matchesStoredState(state, source, carry, metrics) {
|
|
|
23705
24385
|
});
|
|
23706
24386
|
}
|
|
23707
24387
|
function readSessionWorkMetricsCarry(db, sessionId, source) {
|
|
23708
|
-
const parsed = storedCarry.safeParse(
|
|
24388
|
+
const parsed = storedCarry.safeParse(readState3(db, sessionId).root[STATE_KEY]);
|
|
23709
24389
|
if (!parsed.success || parsed.data.source !== source)
|
|
23710
24390
|
return;
|
|
23711
24391
|
return {
|
|
@@ -23720,10 +24400,10 @@ function setSessionWorkMetricsCarry(db, sessionId, source, carry, metrics) {
|
|
|
23720
24400
|
newWorkTokens: Math.max(0, Math.floor(metrics.newWorkTokens)),
|
|
23721
24401
|
totalInputTokens: Math.max(0, Math.floor(metrics.totalInputTokens))
|
|
23722
24402
|
};
|
|
23723
|
-
if (matchesStoredState(
|
|
24403
|
+
if (matchesStoredState(readState3(db, sessionId), source, carry, normalized))
|
|
23724
24404
|
return;
|
|
23725
24405
|
db.transaction(() => {
|
|
23726
|
-
const state =
|
|
24406
|
+
const state = readState3(db, sessionId);
|
|
23727
24407
|
if (matchesStoredState(state, source, carry, normalized))
|
|
23728
24408
|
return;
|
|
23729
24409
|
ensureSessionMetaRow(db, sessionId);
|
|
@@ -25306,7 +25986,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
25306
25986
|
const db = readDatabase();
|
|
25307
25987
|
if (!db)
|
|
25308
25988
|
return { ok: false, error: "db unavailable" };
|
|
25309
|
-
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-
|
|
25989
|
+
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-e560ryjm.js"));
|
|
25310
25990
|
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-95p89k7q.js"));
|
|
25311
25991
|
log2(`[rpc] recomp requested for session ${sessionId}`);
|
|
25312
25992
|
if (!args.client && !args.hiddenCompletionExecutor) {
|
|
@@ -25391,7 +26071,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
25391
26071
|
const db = readDatabase();
|
|
25392
26072
|
if (!db)
|
|
25393
26073
|
return { ok: false, error: "db unavailable" };
|
|
25394
|
-
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-
|
|
26074
|
+
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-ckpj1yvj.js"));
|
|
25395
26075
|
const model = liveSessionState.liveModelBySession.get(sessionId);
|
|
25396
26076
|
const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
|
|
25397
26077
|
const ctx = {
|
|
@@ -26766,22 +27446,24 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
|
|
|
26766
27446
|
}
|
|
26767
27447
|
return {
|
|
26768
27448
|
edits,
|
|
26769
|
-
|
|
26770
|
-
|
|
26771
|
-
|
|
26772
|
-
|
|
26773
|
-
|
|
26774
|
-
|
|
26775
|
-
|
|
26776
|
-
|
|
26777
|
-
|
|
26778
|
-
|
|
26779
|
-
|
|
26780
|
-
|
|
26781
|
-
|
|
26782
|
-
|
|
26783
|
-
|
|
26784
|
-
|
|
27449
|
+
hasDecisions: newlyRetired.size > 0 || switchCovered,
|
|
27450
|
+
record(doc) {
|
|
27451
|
+
if (newlyRetired.size === 0 && !switchCovered)
|
|
27452
|
+
return false;
|
|
27453
|
+
const current = decode(doc[namespace]);
|
|
27454
|
+
if ([...newlyRetired].every((id) => current.has(id)) && (!switchCovered || coveredOn(doc[coveredNamespace])))
|
|
27455
|
+
return false;
|
|
27456
|
+
for (const id of folded)
|
|
27457
|
+
current.delete(id);
|
|
27458
|
+
for (const id of newlyRetired)
|
|
27459
|
+
current.add(id);
|
|
27460
|
+
doc.version = 2;
|
|
27461
|
+
doc[namespace] = [...current];
|
|
27462
|
+
if (switchCovered)
|
|
27463
|
+
doc[coveredNamespace] = { on: true };
|
|
27464
|
+
return true;
|
|
27465
|
+
},
|
|
27466
|
+
markRetired() {
|
|
26785
27467
|
for (const { message, row } of rows) {
|
|
26786
27468
|
if (omits(message, row.id))
|
|
26787
27469
|
markRetiredInstructionRow(message.info);
|
|
@@ -55739,6 +56421,7 @@ async function cacheV2SessionDirectory(session, sessionID, directories) {
|
|
|
55739
56421
|
function refuseBeforeProvider(session, sessionID, arm, cause) {
|
|
55740
56422
|
const detail = cause instanceof Error ? `${cause.name}: ${cause.message}` : cause === undefined ? "" : String(cause);
|
|
55741
56423
|
sessionLog2(sessionID, `v2 refusal: interrupting the turn before the provider request arm=${arm}${detail ? ` cause=${JSON.stringify(detail.slice(0, 500))}` : ""}`);
|
|
56424
|
+
noteServedRefusal(sessionID);
|
|
55742
56425
|
return interruptBeforeProvider(session, sessionID);
|
|
55743
56426
|
}
|
|
55744
56427
|
function createHostSeams(context, readAllForConversion, reconciliationSource, liveModels) {
|
|
@@ -56412,6 +57095,23 @@ async function registerContext(context) {
|
|
|
56412
57095
|
log2("[magic-context] v2 thinking binding recovery arm failed", armError);
|
|
56413
57096
|
}
|
|
56414
57097
|
};
|
|
57098
|
+
const armLatestThinkingFromEvent = (sessionID, error) => {
|
|
57099
|
+
if (error === undefined || !db || compactionOff)
|
|
57100
|
+
return false;
|
|
57101
|
+
const model = liveModels.get(sessionID);
|
|
57102
|
+
try {
|
|
57103
|
+
return armLatestThinkingRecoveryFromError({
|
|
57104
|
+
db,
|
|
57105
|
+
sessionId: sessionID,
|
|
57106
|
+
error,
|
|
57107
|
+
providerID: model?.providerID,
|
|
57108
|
+
modelID: model?.modelID
|
|
57109
|
+
});
|
|
57110
|
+
} catch (armError) {
|
|
57111
|
+
log2("[magic-context] v2 latest-thinking recovery arm failed", armError);
|
|
57112
|
+
return false;
|
|
57113
|
+
}
|
|
57114
|
+
};
|
|
56415
57115
|
const usageController = new AbortController;
|
|
56416
57116
|
const usageDone = (async () => {
|
|
56417
57117
|
let retry = 0;
|
|
@@ -56464,7 +57164,7 @@ async function registerContext(context) {
|
|
|
56464
57164
|
if (typeof messageID === "string")
|
|
56465
57165
|
messageTimesCache.deleteMessage(sessionID, messageID);
|
|
56466
57166
|
}
|
|
56467
|
-
if (event.type === "session.step.failed")
|
|
57167
|
+
if (event.type === "session.step.failed" && !armLatestThinkingFromEvent(sessionID, event.data.error))
|
|
56468
57168
|
armBindingRecoveryFromEvent(sessionID, event.data.error, "session.step.failed");
|
|
56469
57169
|
if (event.type === "session.error" || event.type === "session.execution.failed") {
|
|
56470
57170
|
hostFoldIdle?.active(sessionID);
|
|
@@ -56472,20 +57172,7 @@ async function registerContext(context) {
|
|
|
56472
57172
|
if (error !== undefined)
|
|
56473
57173
|
hiddenSessionErrors.set(sessionID, error);
|
|
56474
57174
|
if (error !== undefined && db && !compactionOff) {
|
|
56475
|
-
|
|
56476
|
-
let latestTurnRejection = false;
|
|
56477
|
-
try {
|
|
56478
|
-
latestTurnRejection = armLatestThinkingRecoveryFromError({
|
|
56479
|
-
db,
|
|
56480
|
-
sessionId: sessionID,
|
|
56481
|
-
error,
|
|
56482
|
-
providerID: model?.providerID,
|
|
56483
|
-
modelID: model?.modelID
|
|
56484
|
-
});
|
|
56485
|
-
} catch (armError) {
|
|
56486
|
-
log2("[magic-context] v2 latest-thinking recovery arm failed", armError);
|
|
56487
|
-
}
|
|
56488
|
-
if (!latestTurnRejection)
|
|
57175
|
+
if (!armLatestThinkingFromEvent(sessionID, error))
|
|
56489
57176
|
armBindingRecoveryFromEvent(sessionID, error, event.type);
|
|
56490
57177
|
}
|
|
56491
57178
|
continue;
|
|
@@ -56494,6 +57181,7 @@ async function registerContext(context) {
|
|
|
56494
57181
|
overflowRecovery.forget(sessionID);
|
|
56495
57182
|
hostFoldIdle?.active(sessionID);
|
|
56496
57183
|
clearLkgMeasuredRequest(sessionID);
|
|
57184
|
+
dropServedRecord(sessionID, "session_deleted");
|
|
56497
57185
|
deletedSessions.add(sessionID);
|
|
56498
57186
|
const failures = [];
|
|
56499
57187
|
try {
|
|
@@ -57269,6 +57957,7 @@ async function registerContext(context) {
|
|
|
57269
57957
|
await createMessagesTransformHandler({
|
|
57270
57958
|
magicContext: { "experimental.chat.messages.transform": transform },
|
|
57271
57959
|
compactionOff,
|
|
57960
|
+
recordServed: false,
|
|
57272
57961
|
replayFits,
|
|
57273
57962
|
onLkgReplay: restoreLkgSystem,
|
|
57274
57963
|
rustReplayParticipant: () => transform?.getRustReplayParticipant() ?? null
|
|
@@ -57344,6 +58033,7 @@ async function registerContext(context) {
|
|
|
57344
58033
|
throw new StorageBusyRefusalError(error, "v2-context");
|
|
57345
58034
|
const { mapped } = input;
|
|
57346
58035
|
await createMessagesTransformHandler({
|
|
58036
|
+
recordServed: false,
|
|
57347
58037
|
replayFits,
|
|
57348
58038
|
onLkgReplay: restoreLkgSystem,
|
|
57349
58039
|
rustReplayParticipant: () => transform?.getRustReplayParticipant() ?? null,
|
|
@@ -57387,6 +58077,26 @@ async function registerContext(context) {
|
|
|
57387
58077
|
}
|
|
57388
58078
|
}
|
|
57389
58079
|
};
|
|
58080
|
+
const finishServedRequest = (draft, returned) => {
|
|
58081
|
+
try {
|
|
58082
|
+
const sessionID = draft.sessionID;
|
|
58083
|
+
if (!returned)
|
|
58084
|
+
countServedRefusal(sessionID);
|
|
58085
|
+
else if (rustModeModuleClient || deletedSessions.has(sessionID) || hiddenChildHook.owns(sessionID))
|
|
58086
|
+
forgetServedRecord(sessionID);
|
|
58087
|
+
else
|
|
58088
|
+
commitServedRequest({
|
|
58089
|
+
sessionId: sessionID,
|
|
58090
|
+
host: "opencode2",
|
|
58091
|
+
messages: draft.messages,
|
|
58092
|
+
providerID: draft.model.providerID,
|
|
58093
|
+
modelID: draft.model.id,
|
|
58094
|
+
compactionOff
|
|
58095
|
+
});
|
|
58096
|
+
} catch (error) {
|
|
58097
|
+
sessionLog2(draft.sessionID, "served check skipped:", error);
|
|
58098
|
+
}
|
|
58099
|
+
};
|
|
57390
58100
|
const refuseOversizedCheckpoint = async (draft) => {
|
|
57391
58101
|
const hasCheckpoint = draft.messages.some((message) => message.content.some((part) => part.type === "text" && typeof part.text === "string" && part.text.startsWith("<conversation-checkpoint>")));
|
|
57392
58102
|
const limit = draft.model.limit?.input ?? draft.model.limit?.context;
|
|
@@ -57409,6 +58119,8 @@ async function registerContext(context) {
|
|
|
57409
58119
|
await context.session.hook("context", (draft) => withSqliteTransformPass2(async () => {
|
|
57410
58120
|
hostFoldIdle?.active(draft.sessionID);
|
|
57411
58121
|
const anchor = generateReplayAnchor(draft.messages);
|
|
58122
|
+
beginServedRequest(draft.sessionID);
|
|
58123
|
+
let returned = false;
|
|
57412
58124
|
try {
|
|
57413
58125
|
await runManagedContext(draft);
|
|
57414
58126
|
if (!compactionOff)
|
|
@@ -57422,6 +58134,7 @@ async function registerContext(context) {
|
|
|
57422
58134
|
hostFoldIdle.idle(draft.sessionID, meta.cacheTtl, meta.lastResponseTime);
|
|
57423
58135
|
}
|
|
57424
58136
|
}
|
|
58137
|
+
returned = true;
|
|
57425
58138
|
} finally {
|
|
57426
58139
|
admissionRebuildPasses.delete(draft.sessionID);
|
|
57427
58140
|
nativeFoldReplay?.cancelLegacyUpgrade(draft.sessionID);
|
|
@@ -57429,6 +58142,7 @@ async function registerContext(context) {
|
|
|
57429
58142
|
checkpointInputEstimates.delete(draft.sessionID);
|
|
57430
58143
|
checkpointPassPermissions.delete(draft.sessionID);
|
|
57431
58144
|
foldedInstructionIDs.delete(draft.sessionID);
|
|
58145
|
+
finishServedRequest(draft, returned);
|
|
57432
58146
|
}
|
|
57433
58147
|
if (!compactionOff)
|
|
57434
58148
|
generateReplay.capture(draft, anchor);
|