@cortexkit/opencode-magic-context 0.49.52 → 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-bkkd7br4.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 +19 -0
- 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/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 +10 -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/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.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 +33 -0
- 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/{index-x7jcqpy6.js → index-2ctn7q09.js} +531 -17
- package/dist/{index-bamnjp2t.js → index-2m54t4g1.js} +9 -5
- package/dist/{index-qbda6a8k.js → index-3b5k5vma.js} +27 -16
- package/dist/{index-0jc25yjf.js → index-3h0wyv22.js} +3 -3
- package/dist/{index-x4h461yf.js → index-3hhq18q0.js} +1 -1
- package/dist/{index-kaqs6h31.js → index-52x68mj4.js} +1 -1
- package/dist/{index-4xpff2m1.js → index-5684dzbv.js} +647 -69
- package/dist/{index-g3j49m95.js → index-7wasafnb.js} +1 -1
- package/dist/{index-8d7gkgjs.js → index-85chg6fw.js} +1 -1
- package/dist/{index-a4zmmhxs.js → index-a6bxwv4a.js} +1 -1
- package/dist/{index-42n4fhxy.js → index-chjsdqg6.js} +17 -10
- package/dist/{index-fxgaaptn.js → index-esm4farg.js} +8 -7
- package/dist/{index-qtpkkzan.js → index-fbs0f5ch.js} +4 -4
- package/dist/{index-xqhejxmd.js → index-kwpweqzs.js} +1 -1
- package/dist/{index-9gs34125.js → index-n3rxwtwt.js} +47 -14
- package/dist/{index-kanfby7e.js → index-p7ssfv6p.js} +381 -369
- package/dist/{index-k2efzh9r.js → index-pgbmbtdq.js} +4 -4
- package/dist/{index-q9m97m5g.js → index-wpab17w4.js} +1 -1
- package/dist/index.js +53 -32
- package/dist/{message-index-bounded-71b75npz.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-bfv831yx.js → read-session-chunk-cyks9yx4.js} +1 -1
- package/dist/{recomp-orchestrator-8gj1b7pz.js → recomp-orchestrator-d4nks9da.js} +9 -9
- package/dist/{render-b3zcz9x4.js → render-gc1fn4nz.js} +5 -5
- package/dist/{search-y3w590tn.js → search-1bjy7yhc.js} +8 -8
- package/dist/{search-archive-dp9afcv1.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/tools/ctx-expand/search-archive.d.ts.map +1 -1
- package/dist/{transform-postprocess-phase-8awze16a.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-99v7x7fm.js → context-1p22880w.js} +961 -344
- 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-2pev910h.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-a454a4d2.js → read-session-chunk-cxk2kssy.js} +1 -1
- package/dist/v2/{recomp-orchestrator-03fskpsa.js → recomp-orchestrator-e560ryjm.js} +8 -8
- package/dist/v2/{render-cryx4xsj.js → render-rk17pvy0.js} +5 -5
- package/dist/v2/{search-archive-xw2rsq81.js → search-archive-a51g9sp7.js} +4 -4
- package/dist/v2/{search-2qj4w7rw.js → search-kvzyj2mf.js} +7 -7
- package/dist/v2/{server-kreheyw5.js → server-28g1b00j.js} +1 -1
- package/dist/v2/{server-kaqs6h31.js → server-52x68mj4.js} +1 -1
- package/dist/v2/{server-cpstyzvy.js → server-71bg2psk.js} +3 -3
- package/dist/v2/{server-qsvm6w79.js → server-77rvx3wn.js} +33 -14
- package/dist/v2/{server-txdsx71h.js → server-ah1j996f.js} +1 -1
- package/dist/v2/{server-dkfs58nq.js → server-bjsmb6zs.js} +1 -1
- package/dist/v2/{server-kfw4m268.js → server-bzh1fkvd.js} +1 -1
- package/dist/v2/{server-vjadwb3j.js → server-d5zgah57.js} +1 -1
- package/dist/v2/{server-y5cma2j1.js → server-e37d2zt4.js} +8 -7
- package/dist/v2/{server-wq9y9a03.js → server-fh6dhx8c.js} +17 -10
- package/dist/v2/{server-xjzx27w2.js → server-jmrd7vwc.js} +26 -15
- package/dist/v2/{server-4h4acntc.js → server-k3vtc89v.js} +9 -5
- package/dist/v2/{server-b3h8vqa6.js → server-zq704789.js} +531 -17
- package/dist/v2/server.js +2 -2
- package/dist/v2/{v2-archive-reader-3575hw8s.js → v2-archive-reader-hsvddme0.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-shzv6t4v.js → wrapup-orchestrator-ckpj1yvj.js} +8 -8
- package/dist/{v2-archive-reader-75fdm0te.js → v2-archive-reader-qgqrxgrq.js} +1 -1
- package/dist/{wrapup-orchestrator-e0z7nvnx.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
|
@@ -194,7 +194,7 @@ import {
|
|
|
194
194
|
snapRangeToCompartments,
|
|
195
195
|
getActiveCompartmentRun,
|
|
196
196
|
startCompartmentAgent
|
|
197
|
-
} from "./index-
|
|
197
|
+
} from "./index-chjsdqg6.js";
|
|
198
198
|
import {
|
|
199
199
|
hasTrustedAbsoluteWall,
|
|
200
200
|
applyProvenInputFloor,
|
|
@@ -307,7 +307,6 @@ import {
|
|
|
307
307
|
DreamTokenBudgetExceeded,
|
|
308
308
|
isEditTool,
|
|
309
309
|
createFinalWireIncompleteLogger,
|
|
310
|
-
decodeMergedReasoningParts,
|
|
311
310
|
MAX_EXECUTE_THRESHOLD,
|
|
312
311
|
escalationBands,
|
|
313
312
|
sessionDecisionCalibration,
|
|
@@ -365,8 +364,9 @@ import {
|
|
|
365
364
|
getStrippedPlaceholderIds,
|
|
366
365
|
THINKING_BINDING_RECOVERY_FROZEN_PREFIX,
|
|
367
366
|
thinkingBindingRecoveryFrozenId,
|
|
368
|
-
|
|
369
|
-
|
|
367
|
+
noteBindingRecoveryAwaitingClear,
|
|
368
|
+
bindingRecoveryAwaitingClear,
|
|
369
|
+
retryBindingRecoveryClear,
|
|
370
370
|
clearThinkingBindingRecoveryIf,
|
|
371
371
|
getMergedReasoningStrippedIds,
|
|
372
372
|
addMergedReasoningStrippedIds,
|
|
@@ -378,8 +378,6 @@ import {
|
|
|
378
378
|
getObservedEpochFloor,
|
|
379
379
|
resolveEpochFloorForPass,
|
|
380
380
|
getReasoningRemovalState,
|
|
381
|
-
detectThinkingBindingMismatch,
|
|
382
|
-
detectLatestTurnThinkingMismatch,
|
|
383
381
|
isPrefixBoundThinkingModel,
|
|
384
382
|
detectOverflow,
|
|
385
383
|
modelAcceptsEmptyContent,
|
|
@@ -426,7 +424,7 @@ import {
|
|
|
426
424
|
readRawSessionMessageById2,
|
|
427
425
|
readSessionChunk2,
|
|
428
426
|
readRawSessionSeedTail2
|
|
429
|
-
} from "./index-
|
|
427
|
+
} from "./index-n3rxwtwt.js";
|
|
430
428
|
import {
|
|
431
429
|
BoundedSessionMap,
|
|
432
430
|
getMeasuredToolDefinitionTokens
|
|
@@ -456,7 +454,7 @@ import {
|
|
|
456
454
|
runSqliteOptimize,
|
|
457
455
|
openDatabase,
|
|
458
456
|
openCurrentDatabase
|
|
459
|
-
} from "./index-
|
|
457
|
+
} from "./index-a6bxwv4a.js";
|
|
460
458
|
import {
|
|
461
459
|
unescapeXml,
|
|
462
460
|
resolveWorkspaceShareCategories,
|
|
@@ -541,6 +539,13 @@ import {
|
|
|
541
539
|
noteLkgHealthyPrefix,
|
|
542
540
|
lkgRecoveryReplayUnproven,
|
|
543
541
|
lkgRecoveryEntryUnproven,
|
|
542
|
+
beginServedRequest,
|
|
543
|
+
noteServedModel,
|
|
544
|
+
noteServedReplay,
|
|
545
|
+
noteServedHostInput,
|
|
546
|
+
countServedRefusal,
|
|
547
|
+
forgetServedRecord,
|
|
548
|
+
commitServedRequest,
|
|
544
549
|
lkgInputIdentity,
|
|
545
550
|
beginLkgPass,
|
|
546
551
|
visitMessageContentFields,
|
|
@@ -549,6 +554,7 @@ import {
|
|
|
549
554
|
signatureForFields,
|
|
550
555
|
exactReusablePrefix,
|
|
551
556
|
incrementalLkgContentDigests,
|
|
557
|
+
lkgContentDigest,
|
|
552
558
|
lkgSlotRejection,
|
|
553
559
|
captureSlot,
|
|
554
560
|
getInMemorySlot,
|
|
@@ -557,7 +563,6 @@ import {
|
|
|
557
563
|
dropSlot,
|
|
558
564
|
noteEntry,
|
|
559
565
|
getLkgSlotHeapStats,
|
|
560
|
-
TOOL_SWEEP_SCOPED_MARKER,
|
|
561
566
|
useScopedToolSweep,
|
|
562
567
|
createPreAdoptionToolSweepResolver,
|
|
563
568
|
queueMemoryMutation,
|
|
@@ -565,10 +570,10 @@ import {
|
|
|
565
570
|
GLOBAL_USER_PROFILE_PROJECT_PATH,
|
|
566
571
|
getProjectState,
|
|
567
572
|
bumpProjectUserProfileVersion
|
|
568
|
-
} from "./index-
|
|
573
|
+
} from "./index-2ctn7q09.js";
|
|
569
574
|
import {
|
|
570
575
|
getLastIndexedOrdinal
|
|
571
|
-
} from "./index-
|
|
576
|
+
} from "./index-3hhq18q0.js";
|
|
572
577
|
import {
|
|
573
578
|
SESSION_NOTE_CONDITION_ERROR,
|
|
574
579
|
getNoteByIdInScope,
|
|
@@ -627,7 +632,7 @@ import {
|
|
|
627
632
|
embedSessionCompartmentChunks2,
|
|
628
633
|
getEmbeddingCoverageStatus2,
|
|
629
634
|
getAutoEmbeddingSessionCoverage2
|
|
630
|
-
} from "./index-
|
|
635
|
+
} from "./index-2m54t4g1.js";
|
|
631
636
|
import {
|
|
632
637
|
saveEmbeddingIfHashMatches,
|
|
633
638
|
invalidateProject2,
|
|
@@ -635,7 +640,7 @@ import {
|
|
|
635
640
|
} from "./index-4dhv7mqz.js";
|
|
636
641
|
import {
|
|
637
642
|
cosineSimilarity
|
|
638
|
-
} from "./index-
|
|
643
|
+
} from "./index-85chg6fw.js";
|
|
639
644
|
import {
|
|
640
645
|
computeCueContentHash,
|
|
641
646
|
hasMuralCueColumns,
|
|
@@ -681,7 +686,7 @@ import {
|
|
|
681
686
|
readGitFileChangeTimesSince,
|
|
682
687
|
verificationFileExists,
|
|
683
688
|
normalizeVerificationFiles
|
|
684
|
-
} from "./index-
|
|
689
|
+
} from "./index-kwpweqzs.js";
|
|
685
690
|
import {
|
|
686
691
|
renderSingleStoreMigrationRequiredRefusal,
|
|
687
692
|
SingleStoreMigrationRequiredError,
|
|
@@ -702,13 +707,13 @@ import {
|
|
|
702
707
|
resolveMemoriesByIdsForSearch2,
|
|
703
708
|
unifiedSearch2,
|
|
704
709
|
formatSearchResults2
|
|
705
|
-
} from "./index-
|
|
710
|
+
} from "./index-3b5k5vma.js";
|
|
706
711
|
import {
|
|
707
712
|
scheduleReconciliation,
|
|
708
713
|
scheduleIncrementalIndex,
|
|
709
714
|
getMessageIndexQueueHeapStats,
|
|
710
715
|
clearSessionTracking
|
|
711
|
-
} from "./index-
|
|
716
|
+
} from "./index-7wasafnb.js";
|
|
712
717
|
import {
|
|
713
718
|
flushIgnoredMessages2,
|
|
714
719
|
clearIgnoredMessages2,
|
|
@@ -718,7 +723,7 @@ import {
|
|
|
718
723
|
import {
|
|
719
724
|
setRecompStarting2,
|
|
720
725
|
setRecompTerminal2
|
|
721
|
-
} from "./index-
|
|
726
|
+
} from "./index-fbs0f5ch.js";
|
|
722
727
|
import {
|
|
723
728
|
makeToolCompositeKey,
|
|
724
729
|
searchMessageHistoryOffThread,
|
|
@@ -761,13 +766,20 @@ import {
|
|
|
761
766
|
latestAssistantTurnMessages,
|
|
762
767
|
hasActiveAnthropicThinkingTurn,
|
|
763
768
|
retainedActiveThinkingParts,
|
|
769
|
+
LATEST_TURN_THINKING_REMOVED_REASON,
|
|
770
|
+
prepareLatestThinkingRecovery,
|
|
771
|
+
endLatestThinkingRecoveryAfterReset,
|
|
772
|
+
restoredTurnMessages,
|
|
773
|
+
captureLatestTurnOriginals,
|
|
774
|
+
hostInstructionRetentionEnabled,
|
|
775
|
+
isHostInstructionRetentionOn,
|
|
776
|
+
recordHostInstructionDecisions,
|
|
764
777
|
replayCavemanCompression,
|
|
765
778
|
DegradedPassRefusalError,
|
|
766
779
|
degradedPassError,
|
|
767
780
|
revertHostCheckpointPass,
|
|
768
781
|
forgetHostCheckpointPass,
|
|
769
|
-
|
|
770
|
-
isHostInstructionRetentionOn,
|
|
782
|
+
forceBandConfirmed,
|
|
771
783
|
pressureBands,
|
|
772
784
|
forceRide,
|
|
773
785
|
heuristicsRunOnPass,
|
|
@@ -796,7 +808,7 @@ import {
|
|
|
796
808
|
abortSessionFailClosed2,
|
|
797
809
|
evaluateEmergencyFailClosed2,
|
|
798
810
|
runPostTransformPhase2
|
|
799
|
-
} from "./index-
|
|
811
|
+
} from "./index-5684dzbv.js";
|
|
800
812
|
import {
|
|
801
813
|
ANNOUNCEMENT_VERSION2,
|
|
802
814
|
ANNOUNCEMENT_FEATURES2,
|
|
@@ -811,13 +823,13 @@ import {
|
|
|
811
823
|
renderMessageByOrdinal2,
|
|
812
824
|
renderVerboseRangeForTool2,
|
|
813
825
|
renderItemByTag2
|
|
814
|
-
} from "./index-
|
|
826
|
+
} from "./index-wpab17w4.js";
|
|
815
827
|
import {
|
|
816
828
|
readV2ArchiveOffThread2
|
|
817
|
-
} from "./index-
|
|
829
|
+
} from "./index-3h0wyv22.js";
|
|
818
830
|
import {
|
|
819
831
|
renderSearchArchiveOffThread2
|
|
820
|
-
} from "./index-
|
|
832
|
+
} from "./index-esm4farg.js";
|
|
821
833
|
import {
|
|
822
834
|
COMPACTION_ENABLED_PATH,
|
|
823
835
|
isDreamerRunnable,
|
|
@@ -16436,7 +16448,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
16436
16448
|
const db = readDatabase();
|
|
16437
16449
|
if (!db)
|
|
16438
16450
|
return { ok: false, error: "db unavailable" };
|
|
16439
|
-
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-
|
|
16451
|
+
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-d4nks9da.js"));
|
|
16440
16452
|
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-gamjee2f.js"));
|
|
16441
16453
|
log2(`[rpc] recomp requested for session ${sessionId}`);
|
|
16442
16454
|
if (!args.client && !args.hiddenCompletionExecutor) {
|
|
@@ -16521,7 +16533,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
16521
16533
|
const db = readDatabase();
|
|
16522
16534
|
if (!db)
|
|
16523
16535
|
return { ok: false, error: "db unavailable" };
|
|
16524
|
-
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-
|
|
16536
|
+
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-6189f37j.js"));
|
|
16525
16537
|
const model = liveSessionState.liveModelBySession.get(sessionId);
|
|
16526
16538
|
const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
|
|
16527
16539
|
const ctx = {
|
|
@@ -16719,7 +16731,8 @@ var canonicalReasons = new Set([
|
|
|
16719
16731
|
"coverage_fold",
|
|
16720
16732
|
"profile_transition",
|
|
16721
16733
|
"host_compaction",
|
|
16722
|
-
"tag_identity_repair"
|
|
16734
|
+
"tag_identity_repair",
|
|
16735
|
+
"latest_turn_thinking_removed"
|
|
16723
16736
|
]);
|
|
16724
16737
|
var piReasonAliases = {
|
|
16725
16738
|
project_memory_change: "project_memory_epoch",
|
|
@@ -16759,11 +16772,12 @@ function normalizeMaterializeReason(harness, reason, rematerialized) {
|
|
|
16759
16772
|
function writeRustTransformDecision(args) {
|
|
16760
16773
|
const rawDecision = args.decision.trim();
|
|
16761
16774
|
const decisionUpper = rawDecision.toUpperCase();
|
|
16762
|
-
const
|
|
16775
|
+
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 } : {
|
|
16763
16776
|
decision: rawDecision.toLowerCase() || "unknown",
|
|
16764
16777
|
materialized: false,
|
|
16765
16778
|
bustedThisPass: false
|
|
16766
16779
|
};
|
|
16780
|
+
const mapped = args.materializeReason === "latest_turn_thinking_removed" ? { ...scheduled, bustedThisPass: true } : scheduled;
|
|
16767
16781
|
pendingDecisionBySession.set(args.sessionId, {
|
|
16768
16782
|
tsMs: args.tsMs ?? Date.now(),
|
|
16769
16783
|
decision: mapped.decision,
|
|
@@ -17151,146 +17165,6 @@ async function maybeDeliverChannel2(sessionId, deps) {
|
|
|
17151
17165
|
}
|
|
17152
17166
|
}
|
|
17153
17167
|
|
|
17154
|
-
// src/hooks/magic-context/latest-thinking-recovery.ts
|
|
17155
|
-
var LATEST_THINKING_RESTORE = "latest_thinking_original";
|
|
17156
|
-
var knownRejectedSessions = new Set;
|
|
17157
|
-
var lastPassTurnAnchor = new Map;
|
|
17158
|
-
var ACTIVE = `${LATEST_THINKING_RESTORE}:`;
|
|
17159
|
-
var ARMED = `${LATEST_THINKING_RESTORE}_armed:`;
|
|
17160
|
-
var UNRECOVERABLE = `${LATEST_THINKING_RESTORE}_unavailable`;
|
|
17161
|
-
var LATEST_THINKING_UNSAFE = "ANTHROPIC_LATEST_TURN_EDIT_UNSAFE: The provider rejected edits to this thinking turn and its original context cannot be safely replayed. Send a new user message or /clear to continue.";
|
|
17162
|
-
function armLatestThinkingRecovery(db, sessionId) {
|
|
17163
|
-
knownRejectedSessions.add(sessionId);
|
|
17164
|
-
ensureSessionMetaRow(db, sessionId);
|
|
17165
|
-
const current = getThinkingBindingRecoveryTarget(db, sessionId);
|
|
17166
|
-
const anchor = lastPassTurnAnchor.get(sessionId);
|
|
17167
|
-
const next = current?.startsWith(ACTIVE) ? UNRECOVERABLE + ":" + current.slice(ACTIVE.length) : current?.startsWith(UNRECOVERABLE) || current?.startsWith(ARMED) ? current : anchor !== undefined ? ARMED + anchor : LATEST_THINKING_RESTORE;
|
|
17168
|
-
db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ?").run(next, sessionId);
|
|
17169
|
-
}
|
|
17170
|
-
function clone(value) {
|
|
17171
|
-
if (Array.isArray(value))
|
|
17172
|
-
return value.map(clone);
|
|
17173
|
-
if (!isRecord(value))
|
|
17174
|
-
return value;
|
|
17175
|
-
const proto = Object.getPrototypeOf(value);
|
|
17176
|
-
if (proto !== Object.prototype && proto !== null)
|
|
17177
|
-
return value;
|
|
17178
|
-
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clone(item)]));
|
|
17179
|
-
}
|
|
17180
|
-
function isThinkingPart2(part) {
|
|
17181
|
-
return isRecord(part) && ["thinking", "reasoning", "redacted_thinking"].includes(String(part.type));
|
|
17182
|
-
}
|
|
17183
|
-
function replayableOriginal(part) {
|
|
17184
|
-
if (!isThinkingPart2(part) || !isRecord(part))
|
|
17185
|
-
return false;
|
|
17186
|
-
const metadata = isRecord(part.metadata) && isRecord(part.metadata.anthropic) ? part.metadata.anthropic : {};
|
|
17187
|
-
const signature = part.signature ?? part.thinkingSignature ?? metadata.signature ?? part.data ?? metadata.redactedData;
|
|
17188
|
-
return typeof signature === "string" && signature.length > 0 && part.text !== "[cleared]" && part.thinking !== "[cleared]";
|
|
17189
|
-
}
|
|
17190
|
-
function prepareLatestThinkingRecovery(args) {
|
|
17191
|
-
const start = latestAssistantTurnStart(args.messages);
|
|
17192
|
-
const anchor = start > 0 ? args.id(args.messages[start - 1], start - 1) : undefined;
|
|
17193
|
-
if (anchor === undefined)
|
|
17194
|
-
lastPassTurnAnchor.delete(args.sessionId);
|
|
17195
|
-
else
|
|
17196
|
-
lastPassTurnAnchor.set(args.sessionId, anchor);
|
|
17197
|
-
let target;
|
|
17198
|
-
try {
|
|
17199
|
-
target = getThinkingBindingRecoveryTarget(args.db, args.sessionId);
|
|
17200
|
-
} catch (error) {
|
|
17201
|
-
if (knownRejectedSessions.has(args.sessionId))
|
|
17202
|
-
throw contextRefusalError(LATEST_THINKING_UNSAFE);
|
|
17203
|
-
return { restore: false, ended: false };
|
|
17204
|
-
}
|
|
17205
|
-
if (!target || !target.startsWith(LATEST_THINKING_RESTORE)) {
|
|
17206
|
-
knownRejectedSessions.delete(args.sessionId);
|
|
17207
|
-
return { restore: false, ended: false };
|
|
17208
|
-
}
|
|
17209
|
-
const armedAnchor = target.startsWith(ARMED) ? target.slice(ARMED.length) : undefined;
|
|
17210
|
-
if (target === LATEST_THINKING_RESTORE || armedAnchor !== undefined && armedAnchor !== anchor) {
|
|
17211
|
-
args.db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(args.sessionId, target);
|
|
17212
|
-
knownRejectedSessions.delete(args.sessionId);
|
|
17213
|
-
return { restore: false, ended: false };
|
|
17214
|
-
}
|
|
17215
|
-
knownRejectedSessions.add(args.sessionId);
|
|
17216
|
-
const savedAnchor = target.startsWith(ACTIVE) ? target.slice(ACTIVE.length) : target.startsWith(UNRECOVERABLE + ":") ? target.slice(UNRECOVERABLE.length + 1) : undefined;
|
|
17217
|
-
if (savedAnchor !== undefined && savedAnchor !== anchor) {
|
|
17218
|
-
args.db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(args.sessionId, target);
|
|
17219
|
-
knownRejectedSessions.delete(args.sessionId);
|
|
17220
|
-
return { restore: false, ended: true };
|
|
17221
|
-
}
|
|
17222
|
-
if (target.startsWith(UNRECOVERABLE) || !anchor)
|
|
17223
|
-
throw contextRefusalError(LATEST_THINKING_UNSAFE);
|
|
17224
|
-
if (armedAnchor !== undefined) {
|
|
17225
|
-
args.db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(ACTIVE + anchor, args.sessionId, target);
|
|
17226
|
-
}
|
|
17227
|
-
const active = args.messages.slice(start);
|
|
17228
|
-
if (!active.some((message) => args.parts(message).some(replayableOriginal)))
|
|
17229
|
-
throw contextRefusalError(LATEST_THINKING_UNSAFE + " [missing-thinking-original]");
|
|
17230
|
-
const ids = new Map(args.messages.map((message, index) => [args.id(message, index), index]));
|
|
17231
|
-
for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
17232
|
-
if (decision === "binding_mismatch_order:end" || decision === TOOL_SWEEP_SCOPED_MARKER)
|
|
17233
|
-
continue;
|
|
17234
|
-
const id = decodeMergedReasoningParts(decision)?.[0] ?? (decision.startsWith("binding_mismatch:") ? decision.slice("binding_mismatch:".length) : decision);
|
|
17235
|
-
const index = ids.get(id);
|
|
17236
|
-
if (index === undefined || index >= start && !args.parts(args.messages[index]).some(replayableOriginal))
|
|
17237
|
-
throw contextRefusalError(LATEST_THINKING_UNSAFE + ` [missing-original:${id}]`);
|
|
17238
|
-
}
|
|
17239
|
-
return { restore: true, ended: false };
|
|
17240
|
-
}
|
|
17241
|
-
function endLatestThinkingRecoveryAfterReset(db, sessionId) {
|
|
17242
|
-
const target = getThinkingBindingRecoveryTarget(db, sessionId);
|
|
17243
|
-
if (target?.startsWith(LATEST_THINKING_RESTORE)) {
|
|
17244
|
-
db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(sessionId, target);
|
|
17245
|
-
}
|
|
17246
|
-
knownRejectedSessions.delete(sessionId);
|
|
17247
|
-
}
|
|
17248
|
-
function captureOriginalTurn(messages, parts, setParts) {
|
|
17249
|
-
const start = Math.max(0, latestAssistantTurnStart(messages) - 1);
|
|
17250
|
-
const originals = messages.slice(start).map((message) => ({ message, parts: clone(parts(message)) }));
|
|
17251
|
-
const before = messages.slice(0, start);
|
|
17252
|
-
return (target = messages) => {
|
|
17253
|
-
const first = target.findIndex((message) => originals.some((original) => original.message === message || isRecord(message) && isRecord(original.message) && (isRecord(message.info) && isRecord(original.message.info) && message.info.id === original.message.info.id || message.role === original.message.role && message.timestamp !== undefined && message.timestamp === original.message.timestamp)));
|
|
17254
|
-
const prefix = first >= 0 ? target.slice(0, first) : target === messages ? before : target.slice();
|
|
17255
|
-
for (const original of originals) {
|
|
17256
|
-
setParts(original.message, clone(original.parts));
|
|
17257
|
-
}
|
|
17258
|
-
target.length = 0;
|
|
17259
|
-
target.push(...prefix, ...originals.map((original) => original.message));
|
|
17260
|
-
};
|
|
17261
|
-
}
|
|
17262
|
-
function captureLatestTurnOriginals(messages) {
|
|
17263
|
-
return captureOriginalTurn(messages, (message) => message.parts, (message, parts) => {
|
|
17264
|
-
message.parts = parts;
|
|
17265
|
-
});
|
|
17266
|
-
}
|
|
17267
|
-
function armBindingRecoverySafely(db, sessionId) {
|
|
17268
|
-
if (getThinkingBindingRecoveryTarget(db, sessionId)?.startsWith(LATEST_THINKING_RESTORE))
|
|
17269
|
-
armLatestThinkingRecovery(db, sessionId);
|
|
17270
|
-
else
|
|
17271
|
-
armThinkingBindingRecovery(db, sessionId);
|
|
17272
|
-
}
|
|
17273
|
-
function armLatestThinkingRecoveryFromError(args) {
|
|
17274
|
-
if (!detectLatestTurnThinkingMismatch(args.error))
|
|
17275
|
-
return false;
|
|
17276
|
-
if (!isAnthropicFamilyRoute(args.providerID, args.modelID))
|
|
17277
|
-
return true;
|
|
17278
|
-
armLatestThinkingRecovery(args.db, args.sessionId);
|
|
17279
|
-
dropSlot(args.sessionId, "latest-thinking-recovery-arm");
|
|
17280
|
-
return true;
|
|
17281
|
-
}
|
|
17282
|
-
function armThinkingBindingRecoveryFromError(args) {
|
|
17283
|
-
const mismatch = detectThinkingBindingMismatch(args.error);
|
|
17284
|
-
if (!mismatch.isBindingMismatch)
|
|
17285
|
-
return false;
|
|
17286
|
-
if (!isPrefixBoundThinkingModel(args.providerID, args.modelID))
|
|
17287
|
-
return true;
|
|
17288
|
-
armBindingRecoverySafely(args.db, args.sessionId);
|
|
17289
|
-
sessionLog2(args.sessionId, `thinking binding recovery armed from ${args.source} (provider paths: failing=${mismatch.failingBlockPath ?? "?"} firstChanged=${mismatch.firstChangedPath ?? "?"})`);
|
|
17290
|
-
dropSlot(args.sessionId, "thinking-binding-recovery-arm");
|
|
17291
|
-
return true;
|
|
17292
|
-
}
|
|
17293
|
-
|
|
17294
17168
|
// src/hooks/magic-context/compaction-off-transition.ts
|
|
17295
17169
|
import { existsSync as existsSync7 } from "node:fs";
|
|
17296
17170
|
var loggedUnverifiedMarkerCleanupRetry = false;
|
|
@@ -17589,6 +17463,111 @@ function createPassOutcome() {
|
|
|
17589
17463
|
};
|
|
17590
17464
|
}
|
|
17591
17465
|
|
|
17466
|
+
// src/hooks/magic-context/signed-thinking-hold.ts
|
|
17467
|
+
var HEAVY_REASONING_TOKENS = 1500;
|
|
17468
|
+
var HEAVY_REASONING_WINDOW_STEPS = 15;
|
|
17469
|
+
var HOLD_CAP_POINTS = 10;
|
|
17470
|
+
var REASONING_TYPES = new Set(["reasoning", "thinking"]);
|
|
17471
|
+
function role(message) {
|
|
17472
|
+
if (!isRecord(message))
|
|
17473
|
+
return;
|
|
17474
|
+
return isRecord(message.info) ? message.info.role : message.role;
|
|
17475
|
+
}
|
|
17476
|
+
function parts(message) {
|
|
17477
|
+
if (!isRecord(message))
|
|
17478
|
+
return [];
|
|
17479
|
+
if (Array.isArray(message.parts))
|
|
17480
|
+
return message.parts;
|
|
17481
|
+
return Array.isArray(message.content) ? message.content : [];
|
|
17482
|
+
}
|
|
17483
|
+
function recordedReasoningTokens(message) {
|
|
17484
|
+
if (!isRecord(message))
|
|
17485
|
+
return;
|
|
17486
|
+
const info = isRecord(message.info) ? message.info : undefined;
|
|
17487
|
+
const candidates = [];
|
|
17488
|
+
if (info && isRecord(info.tokens))
|
|
17489
|
+
candidates.push(info.tokens.reasoning);
|
|
17490
|
+
if (isRecord(message.usage)) {
|
|
17491
|
+
candidates.push(message.usage.reasoning, message.usage.reasoningTokens);
|
|
17492
|
+
}
|
|
17493
|
+
for (const value of candidates) {
|
|
17494
|
+
if (typeof value === "number" && Number.isFinite(value) && value > 0)
|
|
17495
|
+
return value;
|
|
17496
|
+
}
|
|
17497
|
+
return;
|
|
17498
|
+
}
|
|
17499
|
+
function stepReasoningTokens(message, estimateTextTokens) {
|
|
17500
|
+
let text = "";
|
|
17501
|
+
let opaque = false;
|
|
17502
|
+
for (const part of parts(message)) {
|
|
17503
|
+
if (!isRecord(part))
|
|
17504
|
+
continue;
|
|
17505
|
+
const type = String(part.type ?? part.kind);
|
|
17506
|
+
if (type === "redacted_thinking" || part.redacted === true) {
|
|
17507
|
+
opaque = true;
|
|
17508
|
+
continue;
|
|
17509
|
+
}
|
|
17510
|
+
if (!REASONING_TYPES.has(type))
|
|
17511
|
+
continue;
|
|
17512
|
+
const body = typeof part.thinking === "string" ? part.thinking : typeof part.text === "string" ? part.text : "";
|
|
17513
|
+
if (body.length > 0)
|
|
17514
|
+
text += body;
|
|
17515
|
+
else
|
|
17516
|
+
opaque = true;
|
|
17517
|
+
}
|
|
17518
|
+
if (!text && !opaque)
|
|
17519
|
+
return 0;
|
|
17520
|
+
return reasoningStepCost(recordedReasoningTokens(message), text ? estimateTextTokens(text) : 0, opaque);
|
|
17521
|
+
}
|
|
17522
|
+
function decideSignedThinkingHold(args) {
|
|
17523
|
+
const capPercentage = args.executeThresholdPercentage + HOLD_CAP_POINTS;
|
|
17524
|
+
let heavyStepsBack = null;
|
|
17525
|
+
let heavyStepTokens = 0;
|
|
17526
|
+
const start = latestAssistantTurnStart(args.messages);
|
|
17527
|
+
let stepsBack = 0;
|
|
17528
|
+
for (let index = args.messages.length - 1;index >= start; index--) {
|
|
17529
|
+
const message = args.messages[index];
|
|
17530
|
+
if (role(message) !== "assistant" || parts(message).length === 0)
|
|
17531
|
+
continue;
|
|
17532
|
+
stepsBack++;
|
|
17533
|
+
if (stepsBack > HEAVY_REASONING_WINDOW_STEPS)
|
|
17534
|
+
break;
|
|
17535
|
+
const tokens = stepReasoningTokens(message, args.estimateTextTokens);
|
|
17536
|
+
if (tokens > HEAVY_REASONING_TOKENS) {
|
|
17537
|
+
heavyStepsBack = stepsBack;
|
|
17538
|
+
heavyStepTokens = tokens;
|
|
17539
|
+
break;
|
|
17540
|
+
}
|
|
17541
|
+
}
|
|
17542
|
+
if (heavyStepsBack === null)
|
|
17543
|
+
return {
|
|
17544
|
+
held: false,
|
|
17545
|
+
reason: "no_recent_heavy_reasoning",
|
|
17546
|
+
heavyStepsBack,
|
|
17547
|
+
heavyStepTokens,
|
|
17548
|
+
capPercentage
|
|
17549
|
+
};
|
|
17550
|
+
const ended = readingEndsHold({
|
|
17551
|
+
usagePercentage: args.usagePercentage,
|
|
17552
|
+
capPercentage,
|
|
17553
|
+
forceBandPressure: args.forceBandPressure
|
|
17554
|
+
});
|
|
17555
|
+
if (ended !== null)
|
|
17556
|
+
return { held: false, reason: ended, heavyStepsBack, heavyStepTokens, capPercentage };
|
|
17557
|
+
return {
|
|
17558
|
+
held: true,
|
|
17559
|
+
reason: "heavy_reasoning",
|
|
17560
|
+
heavyStepsBack,
|
|
17561
|
+
heavyStepTokens,
|
|
17562
|
+
capPercentage
|
|
17563
|
+
};
|
|
17564
|
+
}
|
|
17565
|
+
function readingEndsHold(args) {
|
|
17566
|
+
if (!(args.usagePercentage < args.capPercentage))
|
|
17567
|
+
return "above_cap";
|
|
17568
|
+
return args.forceBandPressure ? "force_band" : null;
|
|
17569
|
+
}
|
|
17570
|
+
|
|
17592
17571
|
// src/hooks/magic-context/priced-pass-sizing.ts
|
|
17593
17572
|
var REASONING_PART_TYPES = new Set(["reasoning", "thinking", "redacted_thinking"]);
|
|
17594
17573
|
var WIDEST_PRICED_PASS_PLAN = {
|
|
@@ -17605,6 +17584,11 @@ function planPricedPass(input, usage) {
|
|
|
17605
17584
|
schedulerDecision: input.schedulerDecision
|
|
17606
17585
|
});
|
|
17607
17586
|
const emergencySample = () => getEmergencyInputSample(input.db, input.sessionId);
|
|
17587
|
+
const signedThinkingHold = input.signedThinkingHold && (input.signedThinkingHoldCapPercentage === undefined ? !bands.forceBandConfirmed : readingEndsHold({
|
|
17588
|
+
usagePercentage: usage.percentage,
|
|
17589
|
+
capPercentage: input.signedThinkingHoldCapPercentage,
|
|
17590
|
+
forceBandPressure: bands.forceBandConfirmed
|
|
17591
|
+
}) === null);
|
|
17608
17592
|
const rides = {
|
|
17609
17593
|
hardFold: input.folds || input.firstRender,
|
|
17610
17594
|
force: forceRide({
|
|
@@ -17620,11 +17604,11 @@ function planPricedPass(input, usage) {
|
|
|
17620
17604
|
servedShapeRepair: false
|
|
17621
17605
|
};
|
|
17622
17606
|
const drainAllowed = !input.compactionOff && reclaimRidePermitted(rides, {
|
|
17623
|
-
signedThinkingHold
|
|
17607
|
+
signedThinkingHold,
|
|
17624
17608
|
firstRender: input.firstRender,
|
|
17625
17609
|
emergency: bands.forceBandConfirmed
|
|
17626
17610
|
});
|
|
17627
|
-
const materializationRequested = !
|
|
17611
|
+
const materializationRequested = !signedThinkingHold && input.materializationRequested;
|
|
17628
17612
|
const heuristics = heuristicsRunOnPass({
|
|
17629
17613
|
compactionOff: input.compactionOff,
|
|
17630
17614
|
drainAllowed,
|
|
@@ -17651,8 +17635,8 @@ function planPricedPass(input, usage) {
|
|
|
17651
17635
|
rewriteAlreadyPriced: input.folds || input.firstRender || input.historyRebuilt
|
|
17652
17636
|
});
|
|
17653
17637
|
return {
|
|
17654
|
-
editsWholePrefix: drainAllowed && !
|
|
17655
|
-
clearsReasoning: routine && !
|
|
17638
|
+
editsWholePrefix: drainAllowed && !signedThinkingHold,
|
|
17639
|
+
clearsReasoning: routine && !signedThinkingHold
|
|
17656
17640
|
};
|
|
17657
17641
|
}
|
|
17658
17642
|
function sameSizingPlan(input, a, b) {
|
|
@@ -22422,12 +22406,15 @@ function createRustModeTransform(deps, options) {
|
|
|
22422
22406
|
}
|
|
22423
22407
|
const inputCount = messages.length;
|
|
22424
22408
|
const inputHasActiveThinking = hasActiveAnthropicThinkingTurn(messages, "anthropic");
|
|
22409
|
+
const rustRecoveryModel = modelFromMessages(messages) ?? deps.liveModelBySession?.get(sessionId);
|
|
22425
22410
|
const thinkingRecovery = prepareLatestThinkingRecovery({
|
|
22426
22411
|
db: deps.db,
|
|
22427
22412
|
sessionId,
|
|
22428
22413
|
messages,
|
|
22429
22414
|
id: (message) => message?.info.id,
|
|
22430
|
-
parts: (message) => message?.parts ?? []
|
|
22415
|
+
parts: (message) => message?.parts ?? [],
|
|
22416
|
+
modelID: rustRecoveryModel?.modelID,
|
|
22417
|
+
providerID: rustRecoveryModel?.providerID
|
|
22431
22418
|
});
|
|
22432
22419
|
const restoreLatestTurnOriginals = thinkingRecovery.restore ? captureLatestTurnOriginals(messages) : undefined;
|
|
22433
22420
|
let requestInputTokens = 0;
|
|
@@ -22674,7 +22661,7 @@ function createRustModeTransform(deps, options) {
|
|
|
22674
22661
|
writeRustTransformDecision({
|
|
22675
22662
|
sessionId,
|
|
22676
22663
|
decision,
|
|
22677
|
-
materializeReason: materializeReason === "none" ?
|
|
22664
|
+
materializeReason: thinkingRecovery.removedThisPass && (materializeReason === "none" || materializeReason === "ttl_idle") ? LATEST_TURN_THINKING_REMOVED_REASON : materializeReason !== "none" ? materializeReason : null,
|
|
22678
22665
|
inputTokens: requestInputTokens,
|
|
22679
22666
|
tsMs: passObservedAtMs,
|
|
22680
22667
|
lkgFrozenReleaseReason: applied && served && frozenReleaseReason ? `${frozenReleaseReason};first_changed=${frozenReleaseFirstChanged}` : undefined
|
|
@@ -23578,7 +23565,7 @@ function createRustModeTransform(deps, options) {
|
|
|
23578
23565
|
const activeThinkingTurn = inputHasActiveThinking && isAnthropicFamilyRoute(model?.providerID, model?.modelID);
|
|
23579
23566
|
const postprocess = runRustModePostprocess2({
|
|
23580
23567
|
activeThinkingTurn,
|
|
23581
|
-
protectedThinkingMessages: thinkingRecovery.restore ? protectedThinkingMessages : undefined,
|
|
23568
|
+
protectedThinkingMessages: thinkingRecovery.restore ? restoredTurnMessages(appliedMessages, protectedThinkingMessages) : undefined,
|
|
23582
23569
|
restoreLatestTurnOriginals: () => restoreLatestTurnOriginals?.(appliedMessages),
|
|
23583
23570
|
db: deps.db,
|
|
23584
23571
|
sessionId,
|
|
@@ -23738,7 +23725,7 @@ function createRustModeTransform(deps, options) {
|
|
|
23738
23725
|
}
|
|
23739
23726
|
}
|
|
23740
23727
|
const endRecoveryAfterResetCapture = () => {
|
|
23741
|
-
if (signedThinkingReset
|
|
23728
|
+
if (signedThinkingReset) {
|
|
23742
23729
|
endLatestThinkingRecoveryAfterReset(deps.db, sessionId);
|
|
23743
23730
|
}
|
|
23744
23731
|
};
|
|
@@ -24187,101 +24174,6 @@ function takeSignedThinkingFitSnapshot(args) {
|
|
|
24187
24174
|
}
|
|
24188
24175
|
var snapshotObserver;
|
|
24189
24176
|
|
|
24190
|
-
// src/hooks/magic-context/signed-thinking-hold.ts
|
|
24191
|
-
var HEAVY_REASONING_TOKENS = 1500;
|
|
24192
|
-
var HEAVY_REASONING_WINDOW_STEPS = 15;
|
|
24193
|
-
var HOLD_CAP_POINTS = 10;
|
|
24194
|
-
var REASONING_TYPES = new Set(["reasoning", "thinking"]);
|
|
24195
|
-
function role(message) {
|
|
24196
|
-
if (!isRecord(message))
|
|
24197
|
-
return;
|
|
24198
|
-
return isRecord(message.info) ? message.info.role : message.role;
|
|
24199
|
-
}
|
|
24200
|
-
function parts(message) {
|
|
24201
|
-
if (!isRecord(message))
|
|
24202
|
-
return [];
|
|
24203
|
-
if (Array.isArray(message.parts))
|
|
24204
|
-
return message.parts;
|
|
24205
|
-
return Array.isArray(message.content) ? message.content : [];
|
|
24206
|
-
}
|
|
24207
|
-
function recordedReasoningTokens(message) {
|
|
24208
|
-
if (!isRecord(message))
|
|
24209
|
-
return;
|
|
24210
|
-
const info = isRecord(message.info) ? message.info : undefined;
|
|
24211
|
-
const candidates = [];
|
|
24212
|
-
if (info && isRecord(info.tokens))
|
|
24213
|
-
candidates.push(info.tokens.reasoning);
|
|
24214
|
-
if (isRecord(message.usage)) {
|
|
24215
|
-
candidates.push(message.usage.reasoning, message.usage.reasoningTokens);
|
|
24216
|
-
}
|
|
24217
|
-
for (const value of candidates) {
|
|
24218
|
-
if (typeof value === "number" && Number.isFinite(value) && value > 0)
|
|
24219
|
-
return value;
|
|
24220
|
-
}
|
|
24221
|
-
return;
|
|
24222
|
-
}
|
|
24223
|
-
function stepReasoningTokens(message, estimateTextTokens) {
|
|
24224
|
-
let text = "";
|
|
24225
|
-
let opaque = false;
|
|
24226
|
-
for (const part of parts(message)) {
|
|
24227
|
-
if (!isRecord(part))
|
|
24228
|
-
continue;
|
|
24229
|
-
const type = String(part.type ?? part.kind);
|
|
24230
|
-
if (type === "redacted_thinking" || part.redacted === true) {
|
|
24231
|
-
opaque = true;
|
|
24232
|
-
continue;
|
|
24233
|
-
}
|
|
24234
|
-
if (!REASONING_TYPES.has(type))
|
|
24235
|
-
continue;
|
|
24236
|
-
const body = typeof part.thinking === "string" ? part.thinking : typeof part.text === "string" ? part.text : "";
|
|
24237
|
-
if (body.length > 0)
|
|
24238
|
-
text += body;
|
|
24239
|
-
else
|
|
24240
|
-
opaque = true;
|
|
24241
|
-
}
|
|
24242
|
-
if (!text && !opaque)
|
|
24243
|
-
return 0;
|
|
24244
|
-
return reasoningStepCost(recordedReasoningTokens(message), text ? estimateTextTokens(text) : 0, opaque);
|
|
24245
|
-
}
|
|
24246
|
-
function decideSignedThinkingHold(args) {
|
|
24247
|
-
const capPercentage = args.executeThresholdPercentage + HOLD_CAP_POINTS;
|
|
24248
|
-
let heavyStepsBack = null;
|
|
24249
|
-
let heavyStepTokens = 0;
|
|
24250
|
-
const start = latestAssistantTurnStart(args.messages);
|
|
24251
|
-
let stepsBack = 0;
|
|
24252
|
-
for (let index = args.messages.length - 1;index >= start; index--) {
|
|
24253
|
-
const message = args.messages[index];
|
|
24254
|
-
if (role(message) !== "assistant" || parts(message).length === 0)
|
|
24255
|
-
continue;
|
|
24256
|
-
stepsBack++;
|
|
24257
|
-
if (stepsBack > HEAVY_REASONING_WINDOW_STEPS)
|
|
24258
|
-
break;
|
|
24259
|
-
const tokens = stepReasoningTokens(message, args.estimateTextTokens);
|
|
24260
|
-
if (tokens > HEAVY_REASONING_TOKENS) {
|
|
24261
|
-
heavyStepsBack = stepsBack;
|
|
24262
|
-
heavyStepTokens = tokens;
|
|
24263
|
-
break;
|
|
24264
|
-
}
|
|
24265
|
-
}
|
|
24266
|
-
if (heavyStepsBack === null)
|
|
24267
|
-
return {
|
|
24268
|
-
held: false,
|
|
24269
|
-
reason: "no_recent_heavy_reasoning",
|
|
24270
|
-
heavyStepsBack,
|
|
24271
|
-
heavyStepTokens,
|
|
24272
|
-
capPercentage
|
|
24273
|
-
};
|
|
24274
|
-
if (!(args.usagePercentage < capPercentage))
|
|
24275
|
-
return { held: false, reason: "above_cap", heavyStepsBack, heavyStepTokens, capPercentage };
|
|
24276
|
-
return {
|
|
24277
|
-
held: true,
|
|
24278
|
-
reason: "heavy_reasoning",
|
|
24279
|
-
heavyStepsBack,
|
|
24280
|
-
heavyStepTokens,
|
|
24281
|
-
capPercentage
|
|
24282
|
-
};
|
|
24283
|
-
}
|
|
24284
|
-
|
|
24285
24177
|
// src/hooks/magic-context/temporal-served-projection.ts
|
|
24286
24178
|
function readLkgTemporalDecisions(db, sessionId, runtime) {
|
|
24287
24179
|
const slot = getInMemorySlot(sessionId) ?? loadPersistedLkgSlot(db, sessionId);
|
|
@@ -24809,6 +24701,14 @@ function historyBoundaryRefusalCause(trimRefusal, boundaryInStore) {
|
|
|
24809
24701
|
return trimRefusal ?? undefined;
|
|
24810
24702
|
}
|
|
24811
24703
|
// src/hooks/magic-context/transform.ts
|
|
24704
|
+
function afterCapture(sessionId, statement, run) {
|
|
24705
|
+
try {
|
|
24706
|
+
return run();
|
|
24707
|
+
} catch (error) {
|
|
24708
|
+
sessionLog2(sessionId, `${statement} failed after the request was decided; serving the pass:`, error);
|
|
24709
|
+
return;
|
|
24710
|
+
}
|
|
24711
|
+
}
|
|
24812
24712
|
var MESSAGE_TOKENS_CACHE_MAX = 100;
|
|
24813
24713
|
var messageTokensBySession = new BoundedSessionMap(MESSAGE_TOKENS_CACHE_MAX);
|
|
24814
24714
|
function getMessageTokensCache(sessionId) {
|
|
@@ -25143,12 +25043,21 @@ function createTransform(deps) {
|
|
|
25143
25043
|
}
|
|
25144
25044
|
}
|
|
25145
25045
|
const activeThinkingModel = findLastAssistantModel(messages) ?? deps.liveModelBySession?.get(sessionId);
|
|
25046
|
+
const thinkingRecoveryModel = findNewestUserModel(messages) ?? deps.liveModelBySession?.get(sessionId);
|
|
25047
|
+
try {
|
|
25048
|
+
retryBindingRecoveryClear(db, sessionId);
|
|
25049
|
+
} catch (error) {
|
|
25050
|
+
sessionLog2(sessionId, "thinking binding recovery: retried clear failed:", error);
|
|
25051
|
+
}
|
|
25052
|
+
const appliedBindingRecoveryTarget = bindingRecoveryAwaitingClear(sessionId);
|
|
25146
25053
|
const thinkingRecovery = prepareLatestThinkingRecovery({
|
|
25147
25054
|
db,
|
|
25148
25055
|
sessionId,
|
|
25149
25056
|
messages,
|
|
25150
25057
|
id: (message) => message?.info.id,
|
|
25151
|
-
parts: (message) => message?.parts ?? []
|
|
25058
|
+
parts: (message) => message?.parts ?? [],
|
|
25059
|
+
modelID: thinkingRecoveryModel?.modelID,
|
|
25060
|
+
providerID: thinkingRecoveryModel?.providerID
|
|
25152
25061
|
});
|
|
25153
25062
|
if (thinkingRecovery.ended)
|
|
25154
25063
|
deps.pendingMaterializationSessions?.add(sessionId);
|
|
@@ -25302,6 +25211,7 @@ function createTransform(deps) {
|
|
|
25302
25211
|
deps.liveModelBySession?.set(sessionId, recovered);
|
|
25303
25212
|
}
|
|
25304
25213
|
}
|
|
25214
|
+
noteServedModel(sessionId, modelForBudget);
|
|
25305
25215
|
const resolvedProviderID = modelForBudget?.providerID;
|
|
25306
25216
|
activeThinkingTurn ||= hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID);
|
|
25307
25217
|
const signedThinkingPrefixBound = activeThinkingTurn && (isPrefixBoundThinkingModel(activeThinkingModel?.providerID, activeThinkingModel?.modelID) || isPrefixBoundThinkingModel(resolvedProviderID, modelForBudget?.modelID));
|
|
@@ -25374,6 +25284,12 @@ function createTransform(deps) {
|
|
|
25374
25284
|
messages,
|
|
25375
25285
|
usagePercentage: contextUsageEarly.percentage,
|
|
25376
25286
|
executeThresholdPercentage: effectiveExecuteThresholdPercentage,
|
|
25287
|
+
forceBandPressure: forceBandConfirmed({
|
|
25288
|
+
percentage: contextUsageEarly.percentage,
|
|
25289
|
+
fromEstimate: hostOverWindow,
|
|
25290
|
+
forceMaterializationPercentage,
|
|
25291
|
+
compactionOff
|
|
25292
|
+
}),
|
|
25377
25293
|
estimateTextTokens: (text) => {
|
|
25378
25294
|
holdProseRatio ??= sessionDecisionCalibration(db, sessionId).proseRatio;
|
|
25379
25295
|
return estimateTokens(text) * holdProseRatio;
|
|
@@ -26026,6 +25942,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
26026
25942
|
schedulerDecision,
|
|
26027
25943
|
forceMaterializationPercentage,
|
|
26028
25944
|
signedThinkingHold: activeThinkingPrefixHold,
|
|
25945
|
+
signedThinkingHoldCapPercentage: !compactionOff && signedThinkingHold?.held === true ? signedThinkingHold.capPercentage : undefined,
|
|
26029
25946
|
firstRender: servesHead && !(sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) && !hasCompleteCachedM0M1(db, sessionId),
|
|
26030
25947
|
folds: protectionFoldWillBust,
|
|
26031
25948
|
explicitFlush: hasPendingMaterializationOrigin(deps.pendingMaterializationSessions, sessionId, "user_flush"),
|
|
@@ -26140,6 +26057,20 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
26140
26057
|
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}`);
|
|
26141
26058
|
}
|
|
26142
26059
|
}
|
|
26060
|
+
const sizedHoldEnd = activeThinkingPrefixHold && !compactionOff && signedThinkingHold?.held === true ? readingEndsHold({
|
|
26061
|
+
usagePercentage: contextUsage.percentage,
|
|
26062
|
+
capPercentage: signedThinkingHold.capPercentage,
|
|
26063
|
+
forceBandPressure: forceBandConfirmed({
|
|
26064
|
+
percentage: contextUsage.percentage,
|
|
26065
|
+
fromEstimate: contextUsageFromEstimate,
|
|
26066
|
+
forceMaterializationPercentage,
|
|
26067
|
+
compactionOff
|
|
26068
|
+
})
|
|
26069
|
+
}) : null;
|
|
26070
|
+
if (sizedHoldEnd !== null && signedThinkingHold) {
|
|
26071
|
+
activeThinkingPrefixHold = false;
|
|
26072
|
+
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" : ""})`);
|
|
26073
|
+
}
|
|
26143
26074
|
const protectionUsableSoft = windowGeometry?.usableSoft ?? boundaryContextLimit;
|
|
26144
26075
|
const protectionFloor = resolveEpochFloorForPass(db, sessionId, {
|
|
26145
26076
|
configuredOverride: deps.protectedTokens,
|
|
@@ -26164,6 +26095,22 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
26164
26095
|
opencode2: deps.storeGeneration === "v2",
|
|
26165
26096
|
structuralSentinelUpgradeFailed,
|
|
26166
26097
|
releaseRecoveryPrefix: releaseRecoveryReplay,
|
|
26098
|
+
frozenRecoveryRequest: recovery.prefix ? () => {
|
|
26099
|
+
try {
|
|
26100
|
+
const frozen = JSON.parse(recovery.prefix?.json ?? "null");
|
|
26101
|
+
return Array.isArray(frozen) ? frozen : null;
|
|
26102
|
+
} catch {
|
|
26103
|
+
return null;
|
|
26104
|
+
}
|
|
26105
|
+
} : undefined,
|
|
26106
|
+
restartedLastServedRequest: recovery.restartedSlotJson !== undefined ? () => {
|
|
26107
|
+
try {
|
|
26108
|
+
const saved = JSON.parse(recovery.restartedSlotJson ?? "");
|
|
26109
|
+
return Array.isArray(saved) ? saved : null;
|
|
26110
|
+
} catch {
|
|
26111
|
+
return null;
|
|
26112
|
+
}
|
|
26113
|
+
} : undefined,
|
|
26167
26114
|
normalizeRecoveryTail,
|
|
26168
26115
|
compactionMarkerStrategy: deps.compactionMarkerStrategy ?? defaultCompactionMarkerStrategy2,
|
|
26169
26116
|
sessionId,
|
|
@@ -26245,10 +26192,11 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
26245
26192
|
protectedTools: deps.protectedTools,
|
|
26246
26193
|
resolvedProviderID,
|
|
26247
26194
|
activeThinkingTurn,
|
|
26248
|
-
protectedThinkingMessages: thinkingRecovery.restore ? protectedThinkingMessages : undefined,
|
|
26249
|
-
restoreThinkingMessageIds: thinkingRecovery.restore ? new Set([...protectedThinkingMessages].flatMap((message) => typeof message.info.id === "string" ? [message.info.id] : [])) : undefined,
|
|
26195
|
+
protectedThinkingMessages: thinkingRecovery.restore ? restoredTurnMessages(messages, protectedThinkingMessages) : undefined,
|
|
26196
|
+
restoreThinkingMessageIds: thinkingRecovery.restore ? new Set([...restoredTurnMessages(messages, protectedThinkingMessages)].flatMap((message) => typeof message.info.id === "string" ? [message.info.id] : [])) : undefined,
|
|
26250
26197
|
restoreLatestTurnOriginals,
|
|
26251
26198
|
resolvedModelID: modelForBudget?.modelID,
|
|
26199
|
+
appliedBindingRecoveryTarget,
|
|
26252
26200
|
thinkingBindingRecoveryEnabledForModel: isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID),
|
|
26253
26201
|
trailingBlankSourceDecisions,
|
|
26254
26202
|
passOutcome,
|
|
@@ -26283,7 +26231,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
26283
26231
|
const suffix = recoveryTailSources.flatMap(({ identity, pristineSystem }) => pristineSystem ? [pristineSystem] : renderedById.get(identity) ?? []);
|
|
26284
26232
|
messages.splice(0, messages.length, ...JSON.parse(recovery.prefix.json), ...suffix);
|
|
26285
26233
|
}
|
|
26286
|
-
const recoveryReleaseReason = recovery.rebuildReason ?? (recoveryNormalized ? "recovery_tail_normalized" : recoveryReleased ? "recovery_prefix_released" : undefined);
|
|
26234
|
+
const recoveryReleaseReason = recovery.rebuildReason ?? (recoveryNormalized ? "recovery_tail_normalized" : recoveryReleased ? "recovery_prefix_released" : postTransformResult.restartHeadChanged ? "lkg_restart_head_changed" : undefined);
|
|
26287
26235
|
if (recoveryReleaseReason)
|
|
26288
26236
|
postTransformResult.bustedThisPass = true;
|
|
26289
26237
|
passOutcome.markFinalized();
|
|
@@ -26549,11 +26497,25 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
26549
26497
|
if (!finalWireEstimate) {
|
|
26550
26498
|
sessionLog2(sessionId, `transform: final-wire telemetry estimate=unavailable trusted=false conversation=unknown tools=unknown system=unknown toolDefinitions=unknown tail=${finalWireTail}`);
|
|
26551
26499
|
}
|
|
26500
|
+
const instructionDecisions = postTransformResult.pendingHostInstructionDecisions;
|
|
26501
|
+
const reclaim = instructionDecisions?.reclaim;
|
|
26502
|
+
const decisionsDue = instructionDecisions !== undefined && (instructionDecisions.retention || reclaim?.hasDecisions === true);
|
|
26552
26503
|
if (!compactionOff) {
|
|
26553
26504
|
const stillUntagged = untaggedReplayTailServed && !recoveryNormalized ? [...untaggedReplayIds] : [];
|
|
26554
|
-
|
|
26505
|
+
const untaggedChanged = JSON.stringify([...new Set(stillUntagged)].sort()) !== JSON.stringify([...new Set(persistedUntaggedInputIds)].sort());
|
|
26506
|
+
if ((untaggedChanged || decisionsDue) && !persistLkgUntaggedInputIds(db, sessionId, untaggedChanged ? stillUntagged : undefined, decisionsDue ? (doc) => recordHostInstructionDecisions(doc, {
|
|
26507
|
+
retention: instructionDecisions?.retention === true,
|
|
26508
|
+
record: reclaim ? (target) => reclaim.record(target) : undefined
|
|
26509
|
+
}) : undefined)) {
|
|
26510
|
+
if (decisionsDue) {
|
|
26511
|
+
const failure = new Error("Cannot persist the last-good records with this pass's instruction-row decisions");
|
|
26512
|
+
sessionLog2(sessionId, "transform refused degraded pass site=host-instruction-retention-persistence-failure:", failure);
|
|
26513
|
+
failPass("host-instruction-retention-persistence-failure", failure);
|
|
26514
|
+
}
|
|
26555
26515
|
throw new Error("Cannot persist the last-good untagged-message record");
|
|
26516
|
+
}
|
|
26556
26517
|
}
|
|
26518
|
+
reclaim?.markRetired();
|
|
26557
26519
|
const signedThinkingServed = isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID) && servesThinkingBlock2(messages, modelForBudget?.providerID, modelForBudget?.modelID);
|
|
26558
26520
|
finishSystemDateRefresh(deps.historyRefreshSessions, dateRequest, postTransformResult.bustedThisPass && !activeThinkingPrefixHold && !signedThinkingServed || postTransformResult.thinkingReleasedForFit === true, signedThinkingServed);
|
|
26559
26521
|
if (activeThinkingPrefixHold && !postTransformResult.thinkingReleasedForFit && sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) {
|
|
@@ -26574,8 +26536,10 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
26574
26536
|
agentName: notificationParams?.agent
|
|
26575
26537
|
});
|
|
26576
26538
|
if (captured) {
|
|
26577
|
-
|
|
26578
|
-
|
|
26539
|
+
afterCapture(sessionId, "deferred last-good save", () => {
|
|
26540
|
+
const capturedSlot = getInMemorySlot(sessionId);
|
|
26541
|
+
if (!capturedSlot)
|
|
26542
|
+
return;
|
|
26579
26543
|
const revision = lkgDirtyRevision(sessionId) ?? dirtyLkgRecoveryRevision(sessionId, capturedSlot);
|
|
26580
26544
|
const fence = {
|
|
26581
26545
|
ownDirtyRevision: revision,
|
|
@@ -26595,7 +26559,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
26595
26559
|
sessionLog2(sessionId, "Last-good deferred publication remains uncertified:", error);
|
|
26596
26560
|
}
|
|
26597
26561
|
}));
|
|
26598
|
-
}
|
|
26562
|
+
});
|
|
26599
26563
|
noteLkgHealthyPrefix(sessionId, lkgInput, messages, !!recoveryReleaseReason);
|
|
26600
26564
|
}
|
|
26601
26565
|
if (!captured) {
|
|
@@ -26609,94 +26573,98 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
26609
26573
|
}
|
|
26610
26574
|
sessionLog2(sessionId, `lkg_capture_declined degradations=${passOutcome.degradations.map((item) => item.site).join(",")}`);
|
|
26611
26575
|
}
|
|
26612
|
-
|
|
26613
|
-
|
|
26614
|
-
|
|
26615
|
-
|
|
26616
|
-
|
|
26617
|
-
|
|
26618
|
-
|
|
26619
|
-
|
|
26620
|
-
|
|
26621
|
-
|
|
26622
|
-
|
|
26623
|
-
|
|
26624
|
-
|
|
26625
|
-
|
|
26626
|
-
|
|
26627
|
-
|
|
26628
|
-
|
|
26629
|
-
|
|
26630
|
-
|
|
26631
|
-
|
|
26632
|
-
|
|
26633
|
-
|
|
26634
|
-
|
|
26635
|
-
|
|
26636
|
-
|
|
26637
|
-
|
|
26638
|
-
|
|
26639
|
-
|
|
26640
|
-
|
|
26641
|
-
|
|
26642
|
-
|
|
26643
|
-
|
|
26644
|
-
|
|
26645
|
-
|
|
26646
|
-
|
|
26647
|
-
|
|
26648
|
-
|
|
26649
|
-
|
|
26650
|
-
|
|
26651
|
-
const msgTokens = getMessageTokensCache(sessionId);
|
|
26652
|
-
let storedByMessage = new Map;
|
|
26653
|
-
const uncachedMessageIds = messages.flatMap((message) => {
|
|
26654
|
-
const messageId = message.info.id;
|
|
26655
|
-
return messageId !== undefined && !msgTokens.has(messageId) ? [messageId] : [];
|
|
26576
|
+
afterCapture(sessionId, "transform decision record", () => {
|
|
26577
|
+
if (postTransformResult.bustedThisPass || hardCacheExpired || thinkingRecovery.removedThisPass) {
|
|
26578
|
+
recordPendingTransformDecision(sessionId, {
|
|
26579
|
+
tsMs: Date.now(),
|
|
26580
|
+
decision: schedulerDecision,
|
|
26581
|
+
materialized: postTransformResult.materialized,
|
|
26582
|
+
materializeReason: normalizeMaterializeReason("opencode", postTransformResult.materializeReason ?? (thinkingRecovery.removedThisPass ? LATEST_TURN_THINKING_REMOVED_REASON : hardCacheExpired ? "ttl_idle" : null), postTransformResult.materialized),
|
|
26583
|
+
systemHashPrev: postTransformResult.systemHashPrev,
|
|
26584
|
+
systemHashNew: postTransformResult.systemHashNew,
|
|
26585
|
+
m0ToolSetHashPrev: postTransformResult.m0ToolSetHashPrev,
|
|
26586
|
+
m0ToolSetHashNew: postTransformResult.m0ToolSetHashNew,
|
|
26587
|
+
m0ModelKeyPrev: postTransformResult.m0ModelKeyPrev,
|
|
26588
|
+
m0ModelKeyNew: postTransformResult.m0ModelKeyNew,
|
|
26589
|
+
emergency: postTransformResult.emergency,
|
|
26590
|
+
droppedTokens: postTransformResult.droppedTokens,
|
|
26591
|
+
droppedCount: postTransformResult.droppedCount,
|
|
26592
|
+
inputTokens: contextUsage.inputTokens,
|
|
26593
|
+
bustedThisPass: true,
|
|
26594
|
+
lkgFrozenReleaseReason: recoveryReleaseReason
|
|
26595
|
+
});
|
|
26596
|
+
} else {
|
|
26597
|
+
noteOpenCodeUnbustedPass(sessionId, {
|
|
26598
|
+
tsMs: Date.now(),
|
|
26599
|
+
decision: schedulerDecision,
|
|
26600
|
+
materialized: postTransformResult.materialized,
|
|
26601
|
+
materializeReason: normalizeMaterializeReason("opencode", postTransformResult.materializeReason, postTransformResult.materialized),
|
|
26602
|
+
systemHashPrev: postTransformResult.systemHashPrev,
|
|
26603
|
+
systemHashNew: postTransformResult.systemHashNew,
|
|
26604
|
+
m0ToolSetHashPrev: postTransformResult.m0ToolSetHashPrev,
|
|
26605
|
+
m0ToolSetHashNew: postTransformResult.m0ToolSetHashNew,
|
|
26606
|
+
m0ModelKeyPrev: postTransformResult.m0ModelKeyPrev,
|
|
26607
|
+
m0ModelKeyNew: postTransformResult.m0ModelKeyNew,
|
|
26608
|
+
emergency: postTransformResult.emergency,
|
|
26609
|
+
droppedTokens: postTransformResult.droppedTokens,
|
|
26610
|
+
droppedCount: postTransformResult.droppedCount,
|
|
26611
|
+
inputTokens: contextUsage.inputTokens,
|
|
26612
|
+
bustedThisPass: false
|
|
26613
|
+
});
|
|
26614
|
+
}
|
|
26656
26615
|
});
|
|
26657
|
-
|
|
26658
|
-
|
|
26659
|
-
|
|
26660
|
-
|
|
26661
|
-
|
|
26662
|
-
|
|
26663
|
-
|
|
26664
|
-
|
|
26665
|
-
|
|
26666
|
-
|
|
26667
|
-
|
|
26668
|
-
|
|
26669
|
-
|
|
26670
|
-
if (cached) {
|
|
26671
|
-
conversationTokens += cached.conversation;
|
|
26672
|
-
toolCallTokens += cached.toolCall;
|
|
26673
|
-
continue;
|
|
26616
|
+
logTransformTiming(sessionId, "postTransformPhase", tPostProcess);
|
|
26617
|
+
afterCapture(sessionId, "conversation token estimate", () => {
|
|
26618
|
+
const msgTokens = getMessageTokensCache(sessionId);
|
|
26619
|
+
let storedByMessage = new Map;
|
|
26620
|
+
const uncachedMessageIds = messages.flatMap((message) => {
|
|
26621
|
+
const messageId = message.info.id;
|
|
26622
|
+
return messageId !== undefined && !msgTokens.has(messageId) ? [messageId] : [];
|
|
26623
|
+
});
|
|
26624
|
+
if (uncachedMessageIds.length > 0) {
|
|
26625
|
+
try {
|
|
26626
|
+
storedByMessage = omitIncompleteFileTokenTotals(db, sessionId, messages.flatMap((message) => message.info.id ? [{ id: message.info.id, parts: message.parts }] : []), getActiveTagTokenTotalsByMessage2(db, sessionId, uncachedMessageIds));
|
|
26627
|
+
} catch {
|
|
26628
|
+
storedByMessage = new Map;
|
|
26674
26629
|
}
|
|
26675
|
-
|
|
26676
|
-
|
|
26677
|
-
|
|
26678
|
-
|
|
26679
|
-
|
|
26680
|
-
|
|
26681
|
-
|
|
26682
|
-
|
|
26683
|
-
|
|
26630
|
+
}
|
|
26631
|
+
let conversationTokens = 0;
|
|
26632
|
+
let toolCallTokens = 0;
|
|
26633
|
+
for (const message of messages) {
|
|
26634
|
+
const mid = message.info.id;
|
|
26635
|
+
if (mid) {
|
|
26636
|
+
const cached = msgTokens.get(mid);
|
|
26637
|
+
if (cached) {
|
|
26638
|
+
conversationTokens += cached.conversation;
|
|
26639
|
+
toolCallTokens += cached.toolCall;
|
|
26640
|
+
continue;
|
|
26641
|
+
}
|
|
26642
|
+
const stored = storedByMessage.get(mid);
|
|
26643
|
+
if (stored && !stored.hasNull) {
|
|
26644
|
+
conversationTokens += stored.conversation;
|
|
26645
|
+
toolCallTokens += stored.toolCall;
|
|
26646
|
+
msgTokens.set(mid, {
|
|
26647
|
+
conversation: stored.conversation,
|
|
26648
|
+
toolCall: stored.toolCall
|
|
26649
|
+
});
|
|
26650
|
+
continue;
|
|
26651
|
+
}
|
|
26684
26652
|
}
|
|
26653
|
+
const estimated = estimateMessageTokens(message);
|
|
26654
|
+
if (mid)
|
|
26655
|
+
msgTokens.set(mid, estimated);
|
|
26656
|
+
conversationTokens += estimated.conversation;
|
|
26657
|
+
toolCallTokens += estimated.toolCall;
|
|
26685
26658
|
}
|
|
26686
|
-
|
|
26687
|
-
|
|
26688
|
-
|
|
26689
|
-
|
|
26690
|
-
|
|
26691
|
-
|
|
26692
|
-
|
|
26693
|
-
updateSessionMeta(db, sessionId, { conversationTokens, toolCallTokens });
|
|
26694
|
-
} catch (error) {
|
|
26695
|
-
const code = error?.code;
|
|
26696
|
-
if (code !== "SQLITE_BUSY") {
|
|
26697
|
-
sessionLog2(sessionId, "conversation_tokens UPDATE failed:", error);
|
|
26659
|
+
try {
|
|
26660
|
+
updateSessionMeta(db, sessionId, { conversationTokens, toolCallTokens });
|
|
26661
|
+
} catch (error) {
|
|
26662
|
+
const code = error?.code;
|
|
26663
|
+
if (code !== "SQLITE_BUSY") {
|
|
26664
|
+
sessionLog2(sessionId, "conversation_tokens UPDATE failed:", error);
|
|
26665
|
+
}
|
|
26698
26666
|
}
|
|
26699
|
-
}
|
|
26667
|
+
});
|
|
26700
26668
|
const channelBaseline = deps.channel1StateBySession?.get(sessionId);
|
|
26701
26669
|
if (ctxReduceCallable && !compactionOff && channelBaseline) {
|
|
26702
26670
|
try {
|
|
@@ -26735,14 +26703,16 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
26735
26703
|
}
|
|
26736
26704
|
const elapsed = (performance.now() - startTime).toFixed(1);
|
|
26737
26705
|
sessionLog2(sessionId, `transform completed in ${elapsed}ms (${messages.length} messages, ${targets.size} targets, watermark: ${watermark})`);
|
|
26738
|
-
withoutSqliteTransformPass2(() => deps.maybeAutoEmbedSession?.(sessionId));
|
|
26706
|
+
afterCapture(sessionId, "auto-embed scheduling", () => withoutSqliteTransformPass2(() => deps.maybeAutoEmbedSession?.(sessionId)));
|
|
26739
26707
|
const bindingRecovery = postTransformResult.thinkingBindingRecovery;
|
|
26740
26708
|
if (bindingRecovery) {
|
|
26741
|
-
const cleared = clearThinkingBindingRecoveryIf(db, sessionId, bindingRecovery.flagTarget);
|
|
26742
|
-
|
|
26709
|
+
const cleared = afterCapture(sessionId, "thinking binding recovery clear", () => clearThinkingBindingRecoveryIf(db, sessionId, bindingRecovery.flagTarget));
|
|
26710
|
+
if (cleared === undefined)
|
|
26711
|
+
noteBindingRecoveryAwaitingClear(sessionId, bindingRecovery.flagTarget);
|
|
26712
|
+
sessionLog2(sessionId, `thinking binding recovery: stripped bound reasoning from ${bindingRecovery.messageIds.length} assistant(s) [${bindingRecovery.messageIds.join(",")}]; flag=${cleared === undefined ? "kept" : cleared ? "cleared" : "rearmed"}`);
|
|
26743
26713
|
}
|
|
26744
26714
|
if (passOutcome.captureEligible)
|
|
26745
|
-
finalWireUsage.capture(sessionId, {
|
|
26715
|
+
afterCapture(sessionId, "final wire usage capture", () => finalWireUsage.capture(sessionId, {
|
|
26746
26716
|
messages,
|
|
26747
26717
|
systemPromptTokens: sessionMeta.systemPromptTokens,
|
|
26748
26718
|
providerID: modelForBudget?.providerID,
|
|
@@ -26750,8 +26720,8 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
26750
26720
|
agentName: notificationParams.agent,
|
|
26751
26721
|
sessionId,
|
|
26752
26722
|
systemPromptHash: sessionMeta.systemPromptHash
|
|
26753
|
-
});
|
|
26754
|
-
deps.onPassPermission?.(sessionId, postTransformResult.prefixMutationPermitted);
|
|
26723
|
+
}));
|
|
26724
|
+
afterCapture(sessionId, "pass permission report", () => deps.onPassPermission?.(sessionId, postTransformResult.prefixMutationPermitted));
|
|
26755
26725
|
};
|
|
26756
26726
|
const timedTransform = (input, output) => withTransformTimingSummary(async () => {
|
|
26757
26727
|
const sessionId = findSessionId(output.messages);
|
|
@@ -27544,6 +27514,7 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
27544
27514
|
} else {
|
|
27545
27515
|
const inputMessages = output.messages;
|
|
27546
27516
|
const keys = resolveLkgModelKeys(inputMessages);
|
|
27517
|
+
const hostTailDigests = rust ? [] : entry.pristineTail.map(lkgContentDigest);
|
|
27547
27518
|
const replay = replayLkg({
|
|
27548
27519
|
sessionId,
|
|
27549
27520
|
messages: inputMessages,
|
|
@@ -27610,6 +27581,7 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
27610
27581
|
entry,
|
|
27611
27582
|
messages: replay.messages,
|
|
27612
27583
|
...keys,
|
|
27584
|
+
hostTailDigests,
|
|
27613
27585
|
db
|
|
27614
27586
|
}))
|
|
27615
27587
|
return false;
|
|
@@ -27617,6 +27589,7 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
27617
27589
|
args.onLkgReplay?.();
|
|
27618
27590
|
noteExternalLkgReplay(rust, sessionId, inputMessages, replay.messages);
|
|
27619
27591
|
replaceMessagesInPlace2(output, replay.messages);
|
|
27592
|
+
noteServedReplay(sessionId);
|
|
27620
27593
|
sessionLog2(sessionId, "lkg_replay_served");
|
|
27621
27594
|
return true;
|
|
27622
27595
|
} else {
|
|
@@ -27643,6 +27616,8 @@ function createMessagesTransformHandler(args) {
|
|
|
27643
27616
|
const isInternalChild = typeof sessionId === "string" && sessionId.length > 0 && args.internalChildSessions?.has(sessionId) === true;
|
|
27644
27617
|
const compactionOffInputSnapshot = args.compactionOff ? [...output.messages] : null;
|
|
27645
27618
|
const restoreCompactionOffInput = () => {
|
|
27619
|
+
if (compactionOffInputSnapshot && sessionId)
|
|
27620
|
+
noteServedHostInput(sessionId);
|
|
27646
27621
|
if (compactionOffInputSnapshot && output.messages !== compactionOffInputSnapshot) {
|
|
27647
27622
|
output.messages.splice(0, output.messages.length, ...compactionOffInputSnapshot);
|
|
27648
27623
|
}
|
|
@@ -27723,6 +27698,8 @@ function createMessagesTransformHandler(args) {
|
|
|
27723
27698
|
tryReopen: args.tryReopenStorage
|
|
27724
27699
|
});
|
|
27725
27700
|
}
|
|
27701
|
+
if (sessionId)
|
|
27702
|
+
noteServedHostInput(sessionId);
|
|
27726
27703
|
return output.messages;
|
|
27727
27704
|
}
|
|
27728
27705
|
}
|
|
@@ -27809,7 +27786,42 @@ function createMessagesTransformHandler(args) {
|
|
|
27809
27786
|
restoreCompactionOffInput();
|
|
27810
27787
|
return output.messages;
|
|
27811
27788
|
};
|
|
27789
|
+
const finishServedRequest = (sessionId, output, returned) => {
|
|
27790
|
+
try {
|
|
27791
|
+
if (!returned)
|
|
27792
|
+
countServedRefusal(sessionId);
|
|
27793
|
+
else if (resolveRust(sessionId))
|
|
27794
|
+
forgetServedRecord(sessionId);
|
|
27795
|
+
else {
|
|
27796
|
+
const keys = resolveLkgModelKeys(output.messages);
|
|
27797
|
+
commitServedRequest({
|
|
27798
|
+
sessionId,
|
|
27799
|
+
host: "opencode",
|
|
27800
|
+
messages: output.messages,
|
|
27801
|
+
providerID: keys.providerKey,
|
|
27802
|
+
modelID: keys.modelKey && keys.providerKey ? keys.modelKey.slice(keys.providerKey.length + 1) : keys.modelKey,
|
|
27803
|
+
compactionOff: args.compactionOff === true
|
|
27804
|
+
});
|
|
27805
|
+
}
|
|
27806
|
+
} catch (error) {
|
|
27807
|
+
sessionLog2(sessionId, "served check skipped:", error);
|
|
27808
|
+
}
|
|
27809
|
+
};
|
|
27812
27810
|
return (input, output) => withSqliteTransformPass2(async () => {
|
|
27811
|
+
const servedSessionId = args.recordServed === false ? null : resolveSessionId2(output);
|
|
27812
|
+
if (servedSessionId)
|
|
27813
|
+
beginServedRequest(servedSessionId);
|
|
27814
|
+
let returned = false;
|
|
27815
|
+
try {
|
|
27816
|
+
const served = await servePass(input, output);
|
|
27817
|
+
returned = true;
|
|
27818
|
+
return served;
|
|
27819
|
+
} finally {
|
|
27820
|
+
if (servedSessionId)
|
|
27821
|
+
finishServedRequest(servedSessionId, output, returned);
|
|
27822
|
+
}
|
|
27823
|
+
});
|
|
27824
|
+
async function servePass(input, output) {
|
|
27813
27825
|
const tail = output.messages.at(-1);
|
|
27814
27826
|
if (tail?.info.role === "user" && tail.info.id && !tail.info.summary && tail.parts.length === 0) {
|
|
27815
27827
|
throw new IncompleteUserMessageError;
|
|
@@ -27823,7 +27835,7 @@ function createMessagesTransformHandler(args) {
|
|
|
27823
27835
|
preserveUserTerminatedTail(output.messages, inputMessages);
|
|
27824
27836
|
reportAssistantTerminatedTail(output.messages, inputTailRole, resolveSessionId2(output));
|
|
27825
27837
|
}
|
|
27826
|
-
}
|
|
27838
|
+
}
|
|
27827
27839
|
}
|
|
27828
27840
|
function resolveSessionId2(output) {
|
|
27829
27841
|
for (const message of output.messages) {
|
|
@@ -30524,4 +30536,4 @@ function applyHiddenSubagentTemperature(input, output, log) {
|
|
|
30524
30536
|
output.temperature = temperature;
|
|
30525
30537
|
}
|
|
30526
30538
|
|
|
30527
|
-
export { logConfigDependencyNotesOnce, openOpenCodeDb, DREAMER_SYSTEM_PROMPT, runSessionProjectBackfill, SMART_NOTE_COMPILER_SYSTEM_PROMPT, createLiveSessionState, RETROSPECTIVE_MAX_USER_MESSAGE_CHARS, RETROSPECTIVE_MESSAGE_TRUNCATION_MARKER, OpenCodeRetrospectiveRawProvider, createDreamTaskExecutor, runManualDream, runDueTasksForProject, startDreamScheduleTimer, createDreamTimerModuleClient, ensureProjectRegisteredFromOpenCodeDirectory, recordOpenCodeProvenInputFloor, resolveOpenCodeProvenInputFloor, resolveContextWindowGeometry, resolveContextLimit, resolveExecuteThresholdDetail, resolveModelKey, resolveSessionId, parseCacheTtl, createScheduler, computeHardCacheExpired, describeStorageUnavailability, resolveSessionCacheTtl, runEmbedHistoryDrain, pauseEmbedHistoryDrain, formatEmbedStatusText, getSessionProperties, getSessionCreatedInfo, getMessageUpdatedAssistantInfo, getMessageUpdatedInfo, getSessionErrorInfo, getMessageRemovedInfo, summarizeManualDream, createMagicContextCommandHandler, getLiveNotificationParams, createChatMessageHook, createEventHook, createCommandExecuteBeforeHook, createToolExecuteAfterHook, recordHiddenVariantWarning, buildStatusDetail, isDebugRpcEnabled, registerRpcHandlers, maybeAutoEmbedSessionBackfill, clearTransformDecisionSession, scheduleOpenCodeTransformDecisionWrite, stageOpenCodeV2TransformDecision, bindOpenCodeV2TransformDecision, maybeDeliverChannel2,
|
|
30539
|
+
export { logConfigDependencyNotesOnce, openOpenCodeDb, DREAMER_SYSTEM_PROMPT, runSessionProjectBackfill, SMART_NOTE_COMPILER_SYSTEM_PROMPT, createLiveSessionState, RETROSPECTIVE_MAX_USER_MESSAGE_CHARS, RETROSPECTIVE_MESSAGE_TRUNCATION_MARKER, OpenCodeRetrospectiveRawProvider, createDreamTaskExecutor, runManualDream, runDueTasksForProject, startDreamScheduleTimer, createDreamTimerModuleClient, ensureProjectRegisteredFromOpenCodeDirectory, recordOpenCodeProvenInputFloor, resolveOpenCodeProvenInputFloor, resolveContextWindowGeometry, resolveContextLimit, resolveExecuteThresholdDetail, resolveModelKey, resolveSessionId, parseCacheTtl, createScheduler, computeHardCacheExpired, describeStorageUnavailability, resolveSessionCacheTtl, runEmbedHistoryDrain, pauseEmbedHistoryDrain, formatEmbedStatusText, getSessionProperties, getSessionCreatedInfo, getMessageUpdatedAssistantInfo, getMessageUpdatedInfo, getSessionErrorInfo, getMessageRemovedInfo, summarizeManualDream, createMagicContextCommandHandler, getLiveNotificationParams, createChatMessageHook, createEventHook, createCommandExecuteBeforeHook, createToolExecuteAfterHook, recordHiddenVariantWarning, buildStatusDetail, isDebugRpcEnabled, registerRpcHandlers, maybeAutoEmbedSessionBackfill, clearTransformDecisionSession, scheduleOpenCodeTransformDecisionWrite, stageOpenCodeV2TransformDecision, bindOpenCodeV2TransformDecision, maybeDeliverChannel2, createM0RenderOptions, lkgReplayLimit, measureLkgReplay, STORAGE_BUSY_MESSAGE, StorageBusyRefusalError, bindSystemDateRequestIdentity, bindSystemDateOutput, registerSystemDateRefresh, rustWrapupHistorianFields, UnmanagedOverWindowError, UnresolvedHistoryBoundaryError, clearMessageTokensCache, createTransform, createSubcModuleClient, createModuleToolBackends, createRustRefusalRecovery, createSystemPromptHashHandler, tryMessagesTransformLkgReplay, createMessagesTransformHandler, primaryOnlyToolIds, subagentToolRefusal, guardSubagentTools, hideSubagentTools, removePrimaryOnlyTools, storedSubagentMode, createCtxExpandTools, CTX_MEMORY_LIST_TOOL_NAME, CTX_MEMORY_ACTIONS, createCtxMemoryTools, createCtxMemoryListTools, CTX_NOTE_DESCRIPTION, withoutSmartNoteText, createCtxNoteTools, createCtxReduceTools, createCtxSearchTools, parameterDescriptionsFor, applyJsonSchemaParameterDescriptions, MagicContextRpcServer, subagentTemperature, applyHiddenSubagentTemperature };
|