@cortexkit/opencode-magic-context 0.49.0 → 0.49.1
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/{announcement-fp14dw0n.js → announcement-hdbkt8v5.js} +1 -1
- package/dist/auto-search-worker.js +3 -3
- package/dist/config/{mural-model-deprecation.d.ts → deprecated-config.d.ts} +4 -1
- package/dist/config/deprecated-config.d.ts.map +1 -0
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/project-security.d.ts +2 -2
- package/dist/config/schema/magic-context.d.ts +4 -4
- package/dist/config/schema/magic-context.d.ts.map +1 -1
- package/dist/{conflict-warning-hook-kzx4dmk1.js → conflict-warning-hook-asnt6hfc.js} +3 -3
- package/dist/{context-nj5f293n.js → context-tfyhtdcs.js} +111 -45
- package/dist/{derive-budgets-qz5rrr08.js → derive-budgets-j4ry8j8n.js} +1 -1
- package/dist/{embedding-backfill-aetxv1vt.js → embedding-backfill-wyc3ykyf.js} +7 -7
- package/dist/embedding-worker-process.js +30 -0
- package/dist/embedding-worker.js +5 -5
- package/dist/features/magic-context/dreamer/task-registry.d.ts +2 -3
- package/dist/features/magic-context/dreamer/task-registry.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-worker-client.d.ts +8 -1
- package/dist/features/magic-context/memory/embedding-worker-client.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-worker-process.d.ts +2 -0
- package/dist/features/magic-context/memory/embedding-worker-process.d.ts.map +1 -0
- package/dist/features/magic-context/memory/onnx-telemetry.d.ts +3 -0
- package/dist/features/magic-context/memory/onnx-telemetry.d.ts.map +1 -0
- package/dist/features/magic-context/overflow-detection.d.ts +1 -2
- package/dist/features/magic-context/overflow-detection.d.ts.map +1 -1
- package/dist/features/magic-context/storage-session-tables.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/features/magic-context/user-memory/storage-user-memory.d.ts +1 -0
- package/dist/features/magic-context/user-memory/storage-user-memory.d.ts.map +1 -1
- package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
- package/dist/hooks/magic-context/final-wire-token-estimate.d.ts +1 -0
- package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook-handlers.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook.d.ts +1 -0
- package/dist/hooks/magic-context/hook.d.ts.map +1 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-measured-request.d.ts +3 -1
- package/dist/hooks/magic-context/lkg-measured-request.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-persist.d.ts +8 -14
- package/dist/hooks/magic-context/lkg-persist.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-recovery-fence.d.ts +62 -0
- package/dist/hooks/magic-context/lkg-recovery-fence.d.ts.map +1 -0
- package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts +38 -0
- package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts.map +1 -0
- package/dist/hooks/magic-context/lkg-replay.d.ts +3 -1
- package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
- package/dist/hooks/magic-context/opaque-thinking.d.ts +12 -0
- package/dist/hooks/magic-context/opaque-thinking.d.ts.map +1 -0
- package/dist/hooks/magic-context/pass-outcome.d.ts +2 -2
- package/dist/hooks/magic-context/pending-materialization.d.ts +8 -0
- package/dist/hooks/magic-context/pending-materialization.d.ts.map +1 -0
- package/dist/hooks/magic-context/read-session-db.d.ts +3 -0
- package/dist/hooks/magic-context/read-session-db.d.ts.map +1 -1
- package/dist/hooks/magic-context/recomp-orchestrator.d.ts.map +1 -1
- package/dist/hooks/magic-context/rust-mode-transform.d.ts +1 -0
- package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
- package/dist/hooks/magic-context/strip-content.d.ts +5 -2
- package/dist/hooks/magic-context/strip-content.d.ts.map +1 -1
- package/dist/hooks/magic-context/system-date-refresh.d.ts +29 -0
- package/dist/hooks/magic-context/system-date-refresh.d.ts.map +1 -0
- package/dist/hooks/magic-context/system-prompt-dates.d.ts +6 -0
- package/dist/hooks/magic-context/system-prompt-dates.d.ts.map +1 -0
- package/dist/hooks/magic-context/system-prompt-delivery.d.ts +47 -0
- package/dist/hooks/magic-context/system-prompt-delivery.d.ts.map +1 -0
- package/dist/hooks/magic-context/system-prompt-hash.d.ts +4 -0
- package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
- package/dist/hooks/magic-context/tag-messages.d.ts +8 -0
- package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +2 -0
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts +6 -0
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/{index-9qjqq45k.js → index-0pjvpfkf.js} +21 -1
- package/dist/index-6m7rdv7y.js +733 -0
- package/dist/{index-1r0k9js3.js → index-6tfxmc4n.js} +10 -10
- package/dist/{index-gzcmtmar.js → index-7w18gg78.js} +25 -1
- package/dist/{index-nm6a8xpd.js → index-att4bfan.js} +1 -1
- package/dist/{index-ezmszwbd.js → index-eypn4ba6.js} +7 -4
- package/dist/{index-ha87j7a8.js → index-fdtkt5r1.js} +6 -6
- package/dist/{index-kp5qe690.js → index-fg00p1cg.js} +38 -36
- package/dist/{index-1bc61ans.js → index-fvnzcnww.js} +44 -1
- package/dist/index-gbmqa9x9.js +1170 -0
- package/dist/{index-pxwp2hjk.js → index-gzky5rva.js} +30 -53
- package/dist/{index-kq57tdf0.js → index-k6xvbj2e.js} +255 -1075
- package/dist/{index-0w56v4fm.js → index-mw7c950g.js} +1 -1
- package/dist/{index-1g30axtz.js → index-p0n5ryq8.js} +82 -900
- package/dist/{index-b7mv1jx3.js → index-p1hnwfd8.js} +1 -1
- package/dist/{index-peshmj6h.js → index-r2zcs71c.js} +6 -4
- package/dist/{index-kmpvemph.js → index-rafsaxac.js} +2 -2
- package/dist/{index-stbr4ce6.js → index-s7fc0fkn.js} +1 -1
- package/dist/{index-hj2q50k0.js → index-sfhndpcb.js} +463 -6
- package/dist/index-sv0bb7vg.js +6972 -0
- package/dist/{index-57mrqed8.js → index-w23dh319.js} +17 -258
- package/dist/{index-9rt53q79.js → index-xgrwmj82.js} +1 -1
- package/dist/{index-h2py7207.js → index-xnanvj3w.js} +765 -1255
- package/dist/{index-2jcbj7r1.js → index-zfzdpeq2.js} +2269 -3802
- package/dist/{index-s4j7t92z.js → index-zg8yq4ya.js} +29 -744
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +209 -61
- package/dist/{message-index-bounded-h0mrd4pr.js → message-index-bounded-hqktkhdy.js} +7 -6
- package/dist/migration-worker.js +6 -5
- package/dist/plugin/hooks/create-session-hooks.d.ts +3 -1
- package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
- package/dist/plugin/messages-transform.d.ts.map +1 -1
- package/dist/plugin/rpc-handlers.d.ts.map +1 -1
- package/dist/{project-embedding-registry-rtt0djyb.js → project-embedding-registry-0gv3h6y8.js} +6 -6
- package/dist/raw-ordinal-warmup-worker.js +1 -1
- package/dist/{read-session-chunk-ty89v75e.js → read-session-chunk-5mh0bh8y.js} +5 -4
- package/dist/{recomp-orchestrator-4f1yyd1q.js → recomp-orchestrator-kpkhkjhq.js} +20 -19
- package/dist/{search-pz4f4wge.js → search-p9w39qv4.js} +15 -14
- package/dist/{send-session-notification-38cd5dqt.js → send-session-notification-xffh3bbe.js} +2 -2
- package/dist/shared/models-dev-cache.d.ts.map +1 -1
- package/dist/shared/storage-file-mutex.d.ts +9 -0
- package/dist/shared/storage-file-mutex.d.ts.map +1 -0
- package/dist/shared/storage-permissions.d.ts +6 -0
- package/dist/shared/storage-permissions.d.ts.map +1 -1
- package/dist/shared/window-geometry.d.ts +9 -66
- package/dist/shared/window-geometry.d.ts.map +1 -1
- package/dist/standalone-plugin-marker.d.ts +8 -0
- package/dist/standalone-plugin-marker.d.ts.map +1 -0
- package/dist/tools/ctx-reduce/constants.d.ts +1 -2
- package/dist/tools/ctx-reduce/constants.d.ts.map +1 -1
- package/dist/tools/ctx-reduce/tools.d.ts +1 -1
- package/dist/tools/ctx-reduce/tools.d.ts.map +1 -1
- package/dist/{transform-postprocess-phase-tck4g20s.js → transform-postprocess-phase-481j5a7z.js} +20 -19
- package/dist/v2/auto-search-worker.js +3 -3
- package/dist/v2/{context-crbt6p1y.js → context-gsdtha5v.js} +873 -2122
- package/dist/v2/{derive-budgets-fgej9j46.js → derive-budgets-enckmg7y.js} +2 -2
- package/dist/v2/{embedding-backfill-ph1qfyn3.js → embedding-backfill-dbvjbcmm.js} +8 -9
- package/dist/v2/embedding-worker-process.js +29 -0
- package/dist/v2/embedding-worker.js +3 -4
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/copied-tag-notation.d.ts +19 -0
- package/dist/v2/hooks/copied-tag-notation.d.ts.map +1 -0
- package/dist/v2/hooks/payload.d.ts.map +1 -1
- package/dist/v2/hooks/system-prompt-response.d.ts +5 -0
- package/dist/v2/hooks/system-prompt-response.d.ts.map +1 -0
- package/dist/v2/{message-index-bounded-xwqdywxg.js → message-index-bounded-p6v0n8qh.js} +8 -7
- package/dist/v2/migration-worker.js +6 -5
- package/dist/v2/{project-embedding-registry-d6m7tyxr.js → project-embedding-registry-nyq7z8y6.js} +7 -8
- package/dist/v2/raw-ordinal-warmup-worker.js +2 -2
- package/dist/v2/{read-session-chunk-8p5mdryx.js → read-session-chunk-fhyfe4qa.js} +6 -5
- package/dist/v2/{recomp-orchestrator-ckfgt6wq.js → recomp-orchestrator-5xy7w136.js} +22 -22
- package/dist/v2/{search-ym8rehhz.js → search-j7bakcwa.js} +17 -17
- package/dist/v2/{send-session-notification-5m0yapqx.js → send-session-notification-f6v698r5.js} +2 -2
- package/dist/v2/{server-jvxzm1jy.js → server-1fszbabv.js} +28 -28
- package/dist/v2/{server-3j4d00kf.js → server-2htmbqbv.js} +25 -1
- package/dist/v2/{server-c5rrgrcd.js → server-4c7jt8gq.js} +25 -1
- package/dist/v2/{server-ycw9qqcy.js → server-4enr7s6x.js} +1 -1
- package/dist/v2/{server-v4mewb78.js → server-6tcrjfw8.js} +1 -1
- package/dist/v2/{server-x4hscabv.js → server-7spkq1y6.js} +2257 -3746
- package/dist/v2/{server-sa8jvrfc.js → server-7vkj6zhb.js} +29 -744
- package/dist/v2/{server-xwz4dqh9.js → server-8xmq9h3f.js} +30 -53
- package/dist/v2/{server-1tk82krw.js → server-bgzy0phk.js} +463 -6
- package/dist/v2/server-c7n2ftng.js +6860 -0
- package/dist/v2/server-cvgn49tr.js +733 -0
- package/dist/v2/{server-zm570tr2.js → server-cw6521wn.js} +232 -7
- package/dist/v2/{server-pj4pjv02.js → server-czb2rkpk.js} +21 -1
- package/dist/v2/{server-19zjmn02.js → server-d6g4whc2.js} +20 -14
- package/dist/v2/{server-1bc61ans.js → server-fvnzcnww.js} +44 -1
- package/dist/v2/{server-w32kmdez.js → server-kh958yj8.js} +3 -3
- package/dist/v2/{server-q4ph9bwn.js → server-mqvtz7wz.js} +7 -7
- package/dist/v2/{server-2s6ayq3t.js → server-ras2sxnc.js} +133 -13
- package/dist/v2/{server-ss95ky04.js → server-s2st631p.js} +1 -1
- package/dist/v2/{server-2s9qz6n7.js → server-t528t8qm.js} +1 -1
- package/dist/v2/{server-8k2agx29.js → server-vb7pbd9p.js} +17 -258
- package/dist/v2/{server-zp53y8js.js → server-zbxjj2mz.js} +2 -2
- package/dist/v2/server.d.ts.map +1 -1
- package/dist/v2/server.js +149 -5
- package/dist/v2/{storage-tags-8vw924zn.js → storage-tags-5yxrvkaf.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-a7efxaax.js → wrapup-orchestrator-yem5422s.js} +28 -28
- package/dist/{wrapup-orchestrator-barbc6h9.js → wrapup-orchestrator-xvrr27ws.js} +21 -20
- package/package.json +4 -4
- package/src/config/{mural-model-deprecation.ts → deprecated-config.ts} +19 -0
- package/src/config/index.test.ts +15 -37
- package/src/config/index.ts +2 -3
- package/src/config/project-security.ts +3 -3
- package/src/config/schema/magic-context.ts +11 -7
- package/src/features/magic-context/dreamer/task-registry.ts +2 -3
- package/src/shared/models-dev-cache.ts +1 -7
- package/src/shared/sqlite-640-review.test.ts +5 -1
- package/src/shared/storage-file-mutex-review.test.ts +162 -0
- package/src/shared/storage-file-mutex.ts +130 -0
- package/src/shared/storage-permissions.ts +46 -0
- package/src/shared/window-geometry.test.ts +102 -236
- package/src/shared/window-geometry.ts +23 -413
- package/dist/config/mural-model-deprecation.d.ts.map +0 -1
- package/dist/index-2jgwttpt.js +0 -3269
- package/dist/index-mfkzp7qj.js +0 -229
- package/dist/v2/server-4ez8mntn.js +0 -3213
- package/dist/v2/server-mfkzp7qj.js +0 -229
- package/src/shared/__fixtures__/window-overlay.v1.json +0 -337
- /package/dist/{index-2pp04pmg.js → index-69vas84q.js} +0 -0
- /package/dist/v2/{index-2pp04pmg.js → index-69vas84q.js} +0 -0
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
resolveLegacyConfigSources,
|
|
10
10
|
getProtectedTokensTierOverrides,
|
|
11
11
|
loadPluginConfigDetailed
|
|
12
|
-
} from "./server-
|
|
12
|
+
} from "./server-d6g4whc2.js";
|
|
13
13
|
import {
|
|
14
14
|
getHarness2,
|
|
15
15
|
harnessOwnsOpenCodeStore2
|
|
@@ -36,7 +36,7 @@ import {
|
|
|
36
36
|
getSdkContextLimit,
|
|
37
37
|
getSdkOutputLimit,
|
|
38
38
|
getModelsDevCacheState
|
|
39
|
-
} from "./server-
|
|
39
|
+
} from "./server-vb7pbd9p.js";
|
|
40
40
|
import {
|
|
41
41
|
withContentLanguageDirective,
|
|
42
42
|
parseCron,
|
|
@@ -48,10 +48,8 @@ import {
|
|
|
48
48
|
DEFAULT_HISTORIAN_TIMEOUT_MS,
|
|
49
49
|
DEFAULT_LOCAL_EMBEDDING_MODEL,
|
|
50
50
|
DREAM_TASK_PROMOTION_DEFAULTS
|
|
51
|
-
} from "./server-
|
|
52
|
-
import"./server-mfkzp7qj.js";
|
|
51
|
+
} from "./server-cw6521wn.js";
|
|
53
52
|
import {
|
|
54
|
-
BoundedSessionMap,
|
|
55
53
|
historianRunConfig,
|
|
56
54
|
dreamerRunConfig,
|
|
57
55
|
pluginConfigReader,
|
|
@@ -66,117 +64,70 @@ import {
|
|
|
66
64
|
isCompartmentLeaseHeld,
|
|
67
65
|
queueM0Mutation,
|
|
68
66
|
getMaxM0MutationId,
|
|
69
|
-
ensureSessionMetaRow,
|
|
70
|
-
clearCachedM0M1,
|
|
71
67
|
getCompartments,
|
|
72
68
|
getLastCompartmentEndMessage,
|
|
73
69
|
getLastCompartmentEndMessageId,
|
|
74
70
|
getUncoveredCompartmentEndsThrough,
|
|
75
|
-
MAX_EXECUTE_THRESHOLD,
|
|
76
|
-
escalationBands,
|
|
77
|
-
MERGED_REASONING_PARTS_PREFIX,
|
|
78
|
-
decodeMergedReasoningParts,
|
|
79
|
-
readFrozenMergedReasoningParts,
|
|
80
|
-
HYGIENE_PROVIDER_UNITS_VERSION,
|
|
81
|
-
sessionDecisionCalibration,
|
|
82
|
-
transitionSessionHygieneUnits,
|
|
83
|
-
getProtectionWindowForSession,
|
|
84
|
-
isRustMarkerAdmissionFenced,
|
|
85
|
-
setRustMarkerAdmissionFence,
|
|
86
|
-
ReplayDocumentError,
|
|
87
|
-
readReplayEnvelope,
|
|
88
|
-
updateReplayDocument,
|
|
89
|
-
isEmergencyRecoveryArmed,
|
|
90
|
-
isProviderOverflowReconfirmed,
|
|
91
|
-
isProviderOverflowFailClosedProven,
|
|
92
|
-
getEmergencyRecoveryArmedAt,
|
|
93
|
-
loadPersistedUsage,
|
|
94
|
-
loadProtectedTailMeta,
|
|
95
|
-
resetProtectedTailNoEligibleHead,
|
|
96
|
-
resolveCompactionModeRecord,
|
|
97
|
-
getCompactionModeRecord,
|
|
98
|
-
setCompactionModeRecord,
|
|
99
|
-
getProtectedTailDrainBudgetSkip,
|
|
100
|
-
clearPersistedReasoningWatermark,
|
|
101
|
-
getEmergencyInputSample,
|
|
102
|
-
setEmergencyDropSample,
|
|
103
|
-
clearEmergencyDropSample,
|
|
104
|
-
getLastNudgeUndropped,
|
|
105
|
-
setLastNudgeUndropped,
|
|
106
|
-
getChannel1NudgeState,
|
|
107
|
-
setChannel1NudgeState,
|
|
108
|
-
markChannel1PostReduceGracePending,
|
|
109
|
-
captureChannel1PostReduceGraceBaseline,
|
|
110
|
-
getChannel2NudgeState,
|
|
111
|
-
setChannel2NudgeState,
|
|
112
|
-
casChannel2NudgeState,
|
|
113
|
-
claimChannel2NudgeState,
|
|
114
|
-
casChannel2NudgeClaim,
|
|
115
|
-
setPersistedNoteNudgeTrigger,
|
|
116
|
-
getNoteNudgeAnchors,
|
|
117
|
-
getAutoSearchHintDecisions,
|
|
118
|
-
appendAutoSearchHintDecision,
|
|
119
|
-
pruneNoteNudgeAnchors,
|
|
120
|
-
flushAutoSearchHintDecisionRetirement,
|
|
121
|
-
getPersistedTodoPermissionDenied,
|
|
122
|
-
setPersistedTodoPermissionDenied,
|
|
123
|
-
getPersistedTodoSyntheticAnchor,
|
|
124
|
-
setPersistedTodoSyntheticAnchor,
|
|
125
|
-
clearPersistedTodoSyntheticAnchor,
|
|
126
|
-
setNoteLastReadAt,
|
|
127
|
-
getHistorianFailureState,
|
|
128
|
-
clearHistorianFailureState,
|
|
129
|
-
getOverflowState,
|
|
130
|
-
loadTransformPassStateSnapshot,
|
|
131
|
-
recordOverflowDetected,
|
|
132
|
-
recordDetectedContextLimit,
|
|
133
|
-
clearEmergencyRecovery,
|
|
134
|
-
clearDetectedContextLimit,
|
|
135
|
-
getPersistedCompactionMarkerState,
|
|
136
|
-
setPersistedCompactionMarkerState,
|
|
137
|
-
getDeferredClearedCompactionMarkerState,
|
|
138
|
-
retireDeferredClearedCompactionMarkerState,
|
|
139
|
-
getStrippedPlaceholderIds,
|
|
140
|
-
applyStrippedPlaceholderDelta,
|
|
141
|
-
THINKING_BINDING_RECOVERY_FROZEN_PREFIX,
|
|
142
|
-
thinkingBindingRecoveryFrozenId,
|
|
143
|
-
getThinkingBindingRecoveryTarget,
|
|
144
|
-
clearThinkingBindingRecoveryIf,
|
|
145
|
-
getMergedReasoningStrippedIds,
|
|
146
|
-
addMergedReasoningStrippedIds,
|
|
147
|
-
getTrailingBlankDecisions,
|
|
148
|
-
addTrailingBlankDecisions,
|
|
149
|
-
demoteTrailingBlankKeepDecisions,
|
|
150
|
-
getStaleReduceStrippedIds,
|
|
151
|
-
addStaleReduceStrippedIds,
|
|
152
|
-
getProcessedImageStrippedIds,
|
|
153
|
-
addProcessedImageStrippedIds,
|
|
154
|
-
getPendingCompactionMarkerState,
|
|
155
|
-
getCompactionMarkerHealth,
|
|
156
|
-
loadPostprocessReplaySnapshot,
|
|
157
|
-
setPendingCompactionMarkerState,
|
|
158
|
-
replacePendingCompactionMarkerStateIf,
|
|
159
|
-
clearPendingCompactionMarkerStateIf,
|
|
160
|
-
setSessionWorkMetrics,
|
|
161
|
-
getObservedEpochFloor,
|
|
162
|
-
resolveEpochFloorForPass,
|
|
163
71
|
providerResponseFailed,
|
|
164
72
|
isSuccessfulProviderCompletion,
|
|
73
|
+
rememberUnpublishedAutoSearchNoHint,
|
|
74
|
+
getUnpublishedAutoSearchNoHint,
|
|
75
|
+
forgetUnpublishedAutoSearchNoHint,
|
|
76
|
+
registerAutoSearchWork,
|
|
77
|
+
gaDatabasePath,
|
|
78
|
+
RAW_MESSAGE_TYPES,
|
|
79
|
+
V2StoreReaderPool,
|
|
80
|
+
V2StoreReader,
|
|
81
|
+
getOrCreateSessionMeta,
|
|
82
|
+
updateSessionMeta,
|
|
83
|
+
advanceToolReclaimWatermark,
|
|
84
|
+
markSessionCleanupPending,
|
|
85
|
+
retryPendingSessionCleanups,
|
|
86
|
+
retryPendingRustSessionCleanupsForProject,
|
|
87
|
+
clearSession,
|
|
88
|
+
requestPendingMaterialization,
|
|
89
|
+
pendingMaterializationOrigin,
|
|
90
|
+
clearPendingMaterialization,
|
|
91
|
+
recordSystemPromptForRequest,
|
|
92
|
+
recordHeldHeadForRequest,
|
|
93
|
+
bindSystemPromptResponse,
|
|
94
|
+
isHeldHeadForRequest,
|
|
95
|
+
deferDeliveredSystemRefresh,
|
|
96
|
+
retirePendingSystemPromptDelivery,
|
|
165
97
|
lkgProviderInputTotal,
|
|
166
98
|
beginV2LkgRequest,
|
|
167
99
|
claimLkgRequestIdentity,
|
|
100
|
+
currentLkgRequestIdentity,
|
|
168
101
|
noteCapturedLkgRequest,
|
|
169
102
|
noteLkgProviderResponse,
|
|
170
103
|
measuredLkgPrefix,
|
|
104
|
+
clearLkgMeasuredRequest,
|
|
105
|
+
saveLkgSlotToDb,
|
|
106
|
+
clearPersistedLkgSlotStrict,
|
|
107
|
+
loadPersistedLkgSlot,
|
|
108
|
+
drainStaleLkgSlots,
|
|
109
|
+
resolveLkgModelKeys,
|
|
110
|
+
createLkgEntryProjector,
|
|
111
|
+
captureLkgSlot,
|
|
112
|
+
replayLkg,
|
|
113
|
+
coldStartRawServedIndex,
|
|
114
|
+
coldStartUncapturedReplay,
|
|
115
|
+
noteUncertifiedNormalLkg,
|
|
116
|
+
hasProcessLocalLkgProof,
|
|
117
|
+
lkgDirtyRevision,
|
|
118
|
+
rememberLkgDirtyRevision,
|
|
119
|
+
noteLkgRecoveryPrefix,
|
|
120
|
+
readLkgRecoveryPrefix,
|
|
121
|
+
noteLkgHealthyPrefix,
|
|
122
|
+
lkgRecoveryReplayUnproven,
|
|
123
|
+
lkgRecoveryEntryUnproven,
|
|
171
124
|
beginLkgPass,
|
|
172
125
|
visitMessageContentFields,
|
|
173
126
|
contentSnapshotValue,
|
|
174
127
|
messageContentFields,
|
|
175
128
|
signatureForFields,
|
|
176
|
-
isLegacyLkgDigest,
|
|
177
129
|
exactReusablePrefix,
|
|
178
130
|
incrementalLkgContentDigests,
|
|
179
|
-
lkgContentDigest,
|
|
180
131
|
lkgSlotRejection,
|
|
181
132
|
captureSlot,
|
|
182
133
|
getInMemorySlot,
|
|
@@ -184,8 +135,6 @@ import {
|
|
|
184
135
|
forgetInMemorySlot,
|
|
185
136
|
dropSlot,
|
|
186
137
|
noteEntry,
|
|
187
|
-
LkgEntryDigestCache,
|
|
188
|
-
sharedLkgEntryDigests,
|
|
189
138
|
getLkgSlotHeapStats,
|
|
190
139
|
TOOL_SWEEP_SCOPED_MARKER,
|
|
191
140
|
useScopedToolSweep,
|
|
@@ -193,21 +142,6 @@ import {
|
|
|
193
142
|
copySessionStateForClone,
|
|
194
143
|
queueMemoryMutation,
|
|
195
144
|
getMaxMemoryMutationIdForProjects,
|
|
196
|
-
rememberUnpublishedAutoSearchNoHint,
|
|
197
|
-
getUnpublishedAutoSearchNoHint,
|
|
198
|
-
forgetUnpublishedAutoSearchNoHint,
|
|
199
|
-
registerAutoSearchWork,
|
|
200
|
-
gaDatabasePath,
|
|
201
|
-
RAW_MESSAGE_TYPES,
|
|
202
|
-
V2StoreReaderPool,
|
|
203
|
-
V2StoreReader,
|
|
204
|
-
getOrCreateSessionMeta,
|
|
205
|
-
updateSessionMeta,
|
|
206
|
-
advanceToolReclaimWatermark,
|
|
207
|
-
markSessionCleanupPending,
|
|
208
|
-
retryPendingSessionCleanups,
|
|
209
|
-
retryPendingRustSessionCleanupsForProject,
|
|
210
|
-
clearSession,
|
|
211
145
|
GLOBAL_USER_PROFILE_PROJECT_PATH,
|
|
212
146
|
getProjectState,
|
|
213
147
|
bumpProjectUserProfileVersion,
|
|
@@ -328,7 +262,7 @@ import {
|
|
|
328
262
|
startCompartmentAgent,
|
|
329
263
|
setRecompStarting2,
|
|
330
264
|
setRecompTerminal2
|
|
331
|
-
} from "./server-
|
|
265
|
+
} from "./server-7spkq1y6.js";
|
|
332
266
|
import {
|
|
333
267
|
CANONICAL_DREAM_TASKS,
|
|
334
268
|
DREAM_TASK_CAPABILITIES,
|
|
@@ -353,11 +287,6 @@ import {
|
|
|
353
287
|
isFailClosedBlockingError,
|
|
354
288
|
shouldBypassFailClosedBlock,
|
|
355
289
|
resolveAgentNameFromMessages,
|
|
356
|
-
registerOwnRpcServerInstance,
|
|
357
|
-
rpcPortDir,
|
|
358
|
-
rpcPortFilePath,
|
|
359
|
-
parseRpcPortFile,
|
|
360
|
-
inspectProcessesAsync,
|
|
361
290
|
startBootDeadline,
|
|
362
291
|
getUnconfirmedMigrationHolders,
|
|
363
292
|
getSchemaFenceRejection,
|
|
@@ -371,10 +300,8 @@ import {
|
|
|
371
300
|
openDatabaseAsync,
|
|
372
301
|
isDatabasePersisted,
|
|
373
302
|
getDatabasePersistenceError
|
|
374
|
-
} from "./server-
|
|
303
|
+
} from "./server-7vkj6zhb.js";
|
|
375
304
|
import {
|
|
376
|
-
sameProjectDirectory,
|
|
377
|
-
canonicalProjectDirectory,
|
|
378
305
|
setHomeProjectPermission,
|
|
379
306
|
shouldSkipHomeProjectMemory,
|
|
380
307
|
ProjectIdentityError,
|
|
@@ -389,11 +316,13 @@ import {
|
|
|
389
316
|
storedPathBelongsToIdentity,
|
|
390
317
|
beginBootQuietPeriod,
|
|
391
318
|
scheduleAfterBootQuiet
|
|
392
|
-
} from "./server-
|
|
319
|
+
} from "./server-8xmq9h3f.js";
|
|
393
320
|
import {
|
|
394
321
|
detectLatestTurnThinkingMismatch,
|
|
395
322
|
isPrefixBoundThinkingModel,
|
|
396
323
|
detectOverflow,
|
|
324
|
+
ensureSessionMetaRow,
|
|
325
|
+
clearCachedM0M1,
|
|
397
326
|
expandToolPart,
|
|
398
327
|
markHostUnservedRow,
|
|
399
328
|
estimateTrueRawMessageTokens,
|
|
@@ -409,24 +338,136 @@ import {
|
|
|
409
338
|
createDroppedInputGuard,
|
|
410
339
|
assertExecutableToolInput,
|
|
411
340
|
isEditTool,
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
341
|
+
decodeMergedReasoningParts,
|
|
342
|
+
MAX_EXECUTE_THRESHOLD,
|
|
343
|
+
escalationBands,
|
|
344
|
+
HYGIENE_PROVIDER_UNITS_VERSION,
|
|
345
|
+
sessionDecisionCalibration,
|
|
346
|
+
transitionSessionHygieneUnits,
|
|
347
|
+
getProtectionWindowForSession,
|
|
348
|
+
isRustMarkerAdmissionFenced,
|
|
349
|
+
setRustMarkerAdmissionFence,
|
|
350
|
+
ReplayDocumentError,
|
|
351
|
+
readReplayEnvelope,
|
|
352
|
+
updateReplayDocument,
|
|
353
|
+
isEmergencyRecoveryArmed,
|
|
354
|
+
isProviderOverflowReconfirmed,
|
|
355
|
+
isProviderOverflowFailClosedProven,
|
|
356
|
+
getEmergencyRecoveryArmedAt,
|
|
357
|
+
loadPersistedUsage,
|
|
358
|
+
loadProtectedTailMeta,
|
|
359
|
+
resetProtectedTailNoEligibleHead,
|
|
360
|
+
resolveCompactionModeRecord,
|
|
361
|
+
getCompactionModeRecord,
|
|
362
|
+
setCompactionModeRecord,
|
|
363
|
+
getProtectedTailDrainBudgetSkip,
|
|
364
|
+
clearPersistedReasoningWatermark,
|
|
365
|
+
getEmergencyInputSample,
|
|
366
|
+
setEmergencyDropSample,
|
|
367
|
+
clearEmergencyDropSample,
|
|
368
|
+
getLastNudgeUndropped,
|
|
369
|
+
setLastNudgeUndropped,
|
|
370
|
+
getChannel1NudgeState,
|
|
371
|
+
setChannel1NudgeState,
|
|
372
|
+
markChannel1PostReduceGracePending,
|
|
373
|
+
captureChannel1PostReduceGraceBaseline,
|
|
374
|
+
getChannel2NudgeState,
|
|
375
|
+
setChannel2NudgeState,
|
|
376
|
+
casChannel2NudgeState,
|
|
377
|
+
claimChannel2NudgeState,
|
|
378
|
+
casChannel2NudgeClaim,
|
|
379
|
+
setPersistedNoteNudgeTrigger,
|
|
380
|
+
getNoteNudgeAnchors,
|
|
381
|
+
getAutoSearchHintDecisions,
|
|
382
|
+
appendAutoSearchHintDecision,
|
|
383
|
+
pruneNoteNudgeAnchors,
|
|
384
|
+
flushAutoSearchHintDecisionRetirement,
|
|
385
|
+
getPersistedTodoPermissionDenied,
|
|
386
|
+
setPersistedTodoPermissionDenied,
|
|
387
|
+
getPersistedTodoSyntheticAnchor,
|
|
388
|
+
setPersistedTodoSyntheticAnchor,
|
|
389
|
+
clearPersistedTodoSyntheticAnchor,
|
|
390
|
+
setNoteLastReadAt,
|
|
391
|
+
getHistorianFailureState,
|
|
392
|
+
clearHistorianFailureState,
|
|
393
|
+
getOverflowState,
|
|
394
|
+
loadTransformPassStateSnapshot,
|
|
395
|
+
recordOverflowDetected,
|
|
396
|
+
recordDetectedContextLimit,
|
|
397
|
+
clearEmergencyRecovery,
|
|
398
|
+
clearDetectedContextLimit,
|
|
399
|
+
getPersistedCompactionMarkerState,
|
|
400
|
+
setPersistedCompactionMarkerState,
|
|
401
|
+
getDeferredClearedCompactionMarkerState,
|
|
402
|
+
retireDeferredClearedCompactionMarkerState,
|
|
403
|
+
getStrippedPlaceholderIds,
|
|
404
|
+
applyStrippedPlaceholderDelta,
|
|
405
|
+
THINKING_BINDING_RECOVERY_FROZEN_PREFIX,
|
|
406
|
+
thinkingBindingRecoveryFrozenId,
|
|
407
|
+
getThinkingBindingRecoveryTarget,
|
|
408
|
+
clearThinkingBindingRecoveryIf,
|
|
409
|
+
getMergedReasoningStrippedIds,
|
|
410
|
+
addMergedReasoningStrippedIds,
|
|
411
|
+
getTrailingBlankDecisions,
|
|
412
|
+
addTrailingBlankDecisions,
|
|
413
|
+
demoteTrailingBlankKeepDecisions,
|
|
414
|
+
getStaleReduceStrippedIds,
|
|
415
|
+
addStaleReduceStrippedIds,
|
|
416
|
+
getProcessedImageStrippedIds,
|
|
417
|
+
addProcessedImageStrippedIds,
|
|
418
|
+
getPendingCompactionMarkerState,
|
|
419
|
+
getCompactionMarkerHealth,
|
|
420
|
+
loadPostprocessReplaySnapshot,
|
|
421
|
+
setPendingCompactionMarkerState,
|
|
422
|
+
replacePendingCompactionMarkerStateIf,
|
|
423
|
+
clearPendingCompactionMarkerStateIf,
|
|
424
|
+
setSessionWorkMetrics,
|
|
425
|
+
getObservedEpochFloor,
|
|
426
|
+
resolveEpochFloorForPass,
|
|
427
|
+
getReasoningRemovalState,
|
|
428
|
+
addRemovedReasoningIds,
|
|
429
|
+
markDropLeavesReasoning,
|
|
418
430
|
modelAcceptsEmptyContent,
|
|
419
431
|
isAnthropicFamilyRoute,
|
|
420
432
|
neutralizeDroppedReasoningPart,
|
|
421
433
|
restoreNeutralizedReasoningPart,
|
|
422
434
|
isNeutralizedReasoningPart,
|
|
423
|
-
neutralizedReasoningSource,
|
|
424
435
|
variantChangeBustsProviderCache,
|
|
425
436
|
makeSentinel,
|
|
426
437
|
makeWholeMessageSentinel,
|
|
427
|
-
neutralizeWholeMessage,
|
|
428
438
|
isSentinel,
|
|
429
439
|
replaySentinelByMessageIds,
|
|
440
|
+
isInActiveAnthropicTurn,
|
|
441
|
+
activeAnthropicTurnStart,
|
|
442
|
+
hasAnthropicReasoning,
|
|
443
|
+
stripSystemInjectedMessages,
|
|
444
|
+
stripDroppedPlaceholderMessages,
|
|
445
|
+
replayClearedReasoning,
|
|
446
|
+
replayStrippedInlineThinking,
|
|
447
|
+
clearOldReasoning,
|
|
448
|
+
stripClearedReasoning,
|
|
449
|
+
stripInlineThinking,
|
|
450
|
+
findReasoningBearingAssistantIds,
|
|
451
|
+
findLatestAssistantReasoningMutationExemptMessage,
|
|
452
|
+
snapshotTrailingBlankSourceDecisions,
|
|
453
|
+
findTrailingBlankDecisionCandidates,
|
|
454
|
+
applyFrozenTrailingBlankDecisions,
|
|
455
|
+
stripReasoningFromAssistantIds,
|
|
456
|
+
findMergedReasoningStripDecisions,
|
|
457
|
+
stripReasoningFromMergedAssistants,
|
|
458
|
+
stripProcessedImages,
|
|
459
|
+
projectOpencodeReasoningBudgetCutoff,
|
|
460
|
+
DEFAULT_KEEP_REASONING_TOKENS,
|
|
461
|
+
resolveKeepReasoningTokens,
|
|
462
|
+
reasoningBudgetCutoff,
|
|
463
|
+
reasoningTextAndOpaque,
|
|
464
|
+
opencodeReasoningBudgetCutoff,
|
|
465
|
+
describeFinalWireTail,
|
|
466
|
+
estimateMessageTokens,
|
|
467
|
+
wireContentBytes,
|
|
468
|
+
createFinalWireUsageTracker,
|
|
469
|
+
estimateFinalWireInputTokens,
|
|
470
|
+
estimateAppendedWireTokens,
|
|
430
471
|
SKELETON_REAL_INPUT_MAX_BYTES,
|
|
431
472
|
partHasCompletedResult,
|
|
432
473
|
extractToolCallObservation,
|
|
@@ -451,7 +492,7 @@ import {
|
|
|
451
492
|
readRawSessionMessageById2,
|
|
452
493
|
readSessionChunk2,
|
|
453
494
|
readRawSessionSeedTail2
|
|
454
|
-
} from "./server-
|
|
495
|
+
} from "./server-c7n2ftng.js";
|
|
455
496
|
import {
|
|
456
497
|
textMentionsRecentCommit,
|
|
457
498
|
hasMeaningfulUserText2,
|
|
@@ -484,11 +525,31 @@ import {
|
|
|
484
525
|
SqliteAcquisitionBusyError2,
|
|
485
526
|
withAsyncPrivilegedWriter2
|
|
486
527
|
} from "./server-kb9nn0a0.js";
|
|
487
|
-
import
|
|
528
|
+
import {
|
|
529
|
+
sameProjectDirectory,
|
|
530
|
+
canonicalProjectDirectory
|
|
531
|
+
} from "./server-2htmbqbv.js";
|
|
488
532
|
import {
|
|
489
533
|
deleteChunkEmbedBackoffForSession
|
|
490
|
-
} from "./server-
|
|
534
|
+
} from "./server-s2st631p.js";
|
|
491
535
|
import {
|
|
536
|
+
registerOwnRpcServerInstance,
|
|
537
|
+
rpcPortDir,
|
|
538
|
+
rpcPortFilePath,
|
|
539
|
+
parseRpcPortFile,
|
|
540
|
+
inspectProcessesAsync
|
|
541
|
+
} from "./server-cvgn49tr.js";
|
|
542
|
+
import {
|
|
543
|
+
BoundedSessionMap,
|
|
544
|
+
LkgRecoveryFenceError,
|
|
545
|
+
lkgServedArrayDigest,
|
|
546
|
+
hasCleanLkgRecoveryFence,
|
|
547
|
+
dirtyLkgRecoveryRevision,
|
|
548
|
+
ownsLkgDirtyFence,
|
|
549
|
+
invalidateCleanLkgRecoveryFence,
|
|
550
|
+
prepareLkgCaptureFence,
|
|
551
|
+
certifyCommittedLkgCapture,
|
|
552
|
+
markLkgRecoveryDirty,
|
|
492
553
|
advanceSessionActivity,
|
|
493
554
|
backfillSessionActivity,
|
|
494
555
|
getLastIndexedOrdinal,
|
|
@@ -496,7 +557,7 @@ import {
|
|
|
496
557
|
isMessageIndexReconciledThrough,
|
|
497
558
|
indexMessagesAfterOrdinal,
|
|
498
559
|
sweepOrphanedOpenCodeMessageIndexes
|
|
499
|
-
} from "./server-
|
|
560
|
+
} from "./server-bgzy0phk.js";
|
|
500
561
|
import {
|
|
501
562
|
stableStringify,
|
|
502
563
|
getTemporalDecisions,
|
|
@@ -512,7 +573,7 @@ import {
|
|
|
512
573
|
import {
|
|
513
574
|
protectedToolTagNumbers,
|
|
514
575
|
protectedToolTokenCount,
|
|
515
|
-
|
|
576
|
+
stripPersistedAssistantText,
|
|
516
577
|
byteSize,
|
|
517
578
|
stripTagPrefix,
|
|
518
579
|
peelLeadingMcTagNotation,
|
|
@@ -523,7 +584,6 @@ import {
|
|
|
523
584
|
estimateImageTokensFromDataUrl,
|
|
524
585
|
estimateToolAttachmentImageTokens,
|
|
525
586
|
providerVisiblePart,
|
|
526
|
-
providerVisibleMessage,
|
|
527
587
|
normalizeTodoStateJson,
|
|
528
588
|
buildSyntheticTodoPart,
|
|
529
589
|
computeSyntheticCallId,
|
|
@@ -561,9 +621,7 @@ import {
|
|
|
561
621
|
getActiveToolTagsForAgeReclaim2,
|
|
562
622
|
getTriggerTagTokenUpperBound2,
|
|
563
623
|
getActiveTagTokenTotalsByMessage2,
|
|
564
|
-
getReasoningTokenEstimatesByMessage2,
|
|
565
624
|
tryGetReasoningTokenEstimatesByMessage2,
|
|
566
|
-
getMaxTagNumberByOwnerMessage2,
|
|
567
625
|
cachedTagOwnerRatios2,
|
|
568
626
|
tagOwnerWarmupState2,
|
|
569
627
|
installTagOwnerDelta2,
|
|
@@ -584,6 +642,7 @@ import {
|
|
|
584
642
|
getTagNumberByMessageId2,
|
|
585
643
|
getAssignableTagNumberByMessageId2,
|
|
586
644
|
deriveTagLoadFloor2,
|
|
645
|
+
getTagsBySession2,
|
|
587
646
|
getActiveTagsBySession2,
|
|
588
647
|
getTailHygieneTags2,
|
|
589
648
|
getDroppedTagsBySession2,
|
|
@@ -597,7 +656,7 @@ import {
|
|
|
597
656
|
adoptNullOwnerToolTag2,
|
|
598
657
|
getCandidateToolOwners2,
|
|
599
658
|
pickNearestPriorOwner2
|
|
600
|
-
} from "./server-
|
|
659
|
+
} from "./server-4c7jt8gq.js";
|
|
601
660
|
import {
|
|
602
661
|
isRawCompactionSummaryInfo2,
|
|
603
662
|
extractInMemoryMessageViews2,
|
|
@@ -616,9 +675,10 @@ import {
|
|
|
616
675
|
openCodeDbExists,
|
|
617
676
|
withReadOnlySessionDb,
|
|
618
677
|
latestPersistedMessageForRecovery,
|
|
678
|
+
latestRealUserTurnIdFromOpenCodeDb,
|
|
619
679
|
getMessageTimesFromOpenCodeDb,
|
|
620
680
|
findLastAssistantModelFromOpenCodeDb
|
|
621
|
-
} from "./server-
|
|
681
|
+
} from "./server-czb2rkpk.js";
|
|
622
682
|
import {
|
|
623
683
|
getCurrentToolSetHash,
|
|
624
684
|
recordToolDefinition,
|
|
@@ -630,18 +690,14 @@ import {
|
|
|
630
690
|
} from "./server-fr0wbhdn.js";
|
|
631
691
|
import {
|
|
632
692
|
unescapeXml,
|
|
633
|
-
layoutLkgPrefix,
|
|
634
|
-
assembleLkgPrefix,
|
|
635
693
|
resolveWorkspaceShareCategories,
|
|
636
694
|
resolveWorkspaceIdentitySet,
|
|
637
695
|
expandWorkspaceIdentitySetWithAliases,
|
|
638
696
|
resolveStoredPathWorkspaceIdentity,
|
|
639
697
|
storedPathBelongsToWorkspace,
|
|
640
698
|
computeWorkspaceEpochFingerprint
|
|
641
|
-
} from "./server-
|
|
642
|
-
import"./server-fb3zxn06.js";
|
|
699
|
+
} from "./server-6tcrjfw8.js";
|
|
643
700
|
import {
|
|
644
|
-
drainBackgroundBatches,
|
|
645
701
|
GIT_SWEEP_LEASE_RENEWAL_MS,
|
|
646
702
|
acquireGitSweepLease,
|
|
647
703
|
renewGitSweepLease,
|
|
@@ -667,7 +723,8 @@ import {
|
|
|
667
723
|
drainCommitBacklogForProject2,
|
|
668
724
|
embedSessionCompartmentChunks2,
|
|
669
725
|
getEmbeddingCoverageStatus2
|
|
670
|
-
} from "./server-
|
|
726
|
+
} from "./server-1fszbabv.js";
|
|
727
|
+
import"./server-fb3zxn06.js";
|
|
671
728
|
import {
|
|
672
729
|
SESSION_NOTE_CONDITION_ERROR,
|
|
673
730
|
getNoteByIdInScope,
|
|
@@ -710,14 +767,14 @@ import {
|
|
|
710
767
|
readGitFileChangeTimesSince,
|
|
711
768
|
verificationFileExists,
|
|
712
769
|
normalizeVerificationFiles
|
|
713
|
-
} from "./server-
|
|
770
|
+
} from "./server-zbxjj2mz.js";
|
|
714
771
|
import {
|
|
715
772
|
deriveTriggerBudget2,
|
|
716
773
|
deriveHistorianChunkTokens2,
|
|
717
774
|
resolveKnownHistorianContextLimit2,
|
|
718
775
|
resolveHistorianProducerLimits2,
|
|
719
776
|
resolveHistorianContextLimit2
|
|
720
|
-
} from "./server-
|
|
777
|
+
} from "./server-t528t8qm.js";
|
|
721
778
|
import {
|
|
722
779
|
isEmbeddingHostBusy2
|
|
723
780
|
} from "./server-qt1qqasc.js";
|
|
@@ -728,10 +785,10 @@ import {
|
|
|
728
785
|
} from "./server-4dhv7mqz.js";
|
|
729
786
|
import {
|
|
730
787
|
getLocalEmbeddingNativeMemoryStats
|
|
731
|
-
} from "./server-
|
|
788
|
+
} from "./server-ras2sxnc.js";
|
|
732
789
|
import {
|
|
733
790
|
cosineSimilarity
|
|
734
|
-
} from "./server-
|
|
791
|
+
} from "./server-kh958yj8.js";
|
|
735
792
|
import {
|
|
736
793
|
computeCueContentHash,
|
|
737
794
|
hasMuralCueColumns,
|
|
@@ -768,7 +825,7 @@ import"./server-676xw7at.js";
|
|
|
768
825
|
import {
|
|
769
826
|
flushIgnoredMessages2,
|
|
770
827
|
sendStatusNotification2
|
|
771
|
-
} from "./server-
|
|
828
|
+
} from "./server-4enr7s6x.js";
|
|
772
829
|
import {
|
|
773
830
|
renderSingleStoreMigrationRequiredRefusal,
|
|
774
831
|
SingleStoreMigrationRequiredError,
|
|
@@ -788,13 +845,17 @@ import {
|
|
|
788
845
|
resolveMemoriesByIdsForSearch2,
|
|
789
846
|
unifiedSearch2,
|
|
790
847
|
formatSearchResults2
|
|
791
|
-
} from "./server-
|
|
848
|
+
} from "./server-mqvtz7wz.js";
|
|
792
849
|
import {
|
|
793
850
|
resolvePromptContext2
|
|
794
851
|
} from "./server-fmsr7v69.js";
|
|
795
852
|
import {
|
|
796
853
|
compareSemverCore
|
|
797
854
|
} from "./server-84w6rvvf.js";
|
|
855
|
+
import {
|
|
856
|
+
__toESM,
|
|
857
|
+
__export
|
|
858
|
+
} from "./server-syahy8j8.js";
|
|
798
859
|
import {
|
|
799
860
|
computeNormalizedHash
|
|
800
861
|
} from "./server-2bvekkfy.js";
|
|
@@ -808,7 +869,7 @@ import {
|
|
|
808
869
|
writeStorageFileAtomicSync,
|
|
809
870
|
writeStorageFileAsync,
|
|
810
871
|
createStorageWriteStream
|
|
811
|
-
} from "./server-
|
|
872
|
+
} from "./server-fvnzcnww.js";
|
|
812
873
|
import {
|
|
813
874
|
normalizeProtectedToolName,
|
|
814
875
|
mergeProtectedTools
|
|
@@ -825,10 +886,6 @@ import {
|
|
|
825
886
|
import {
|
|
826
887
|
logSlowWriteTransaction
|
|
827
888
|
} from "./server-3t0q2cqx.js";
|
|
828
|
-
import {
|
|
829
|
-
__toESM,
|
|
830
|
-
__export
|
|
831
|
-
} from "./server-syahy8j8.js";
|
|
832
889
|
|
|
833
890
|
// ../../node_modules/.bun/zod@4.1.8/node_modules/zod/v4/classic/external.js
|
|
834
891
|
var exports_external = {};
|
|
@@ -5205,851 +5262,6 @@ function isHistorianDrainBudgetSpent(args) {
|
|
|
5205
5262
|
return true;
|
|
5206
5263
|
}
|
|
5207
5264
|
|
|
5208
|
-
// src/features/magic-context/storage-reasoning-removal.ts
|
|
5209
|
-
var NAMESPACE = "reasoningRemoval";
|
|
5210
|
-
var BACKUP_NAMESPACE = "reasoningRemovalBackup";
|
|
5211
|
-
function invalidState(sessionId) {
|
|
5212
|
-
return new Error(`invalid persisted reasoning removal state for session ${sessionId}`);
|
|
5213
|
-
}
|
|
5214
|
-
function parseState(doc, sessionId, namespace = NAMESPACE) {
|
|
5215
|
-
const lane = doc[namespace];
|
|
5216
|
-
if (lane === undefined)
|
|
5217
|
-
return { messageIds: new Set, dropLeavesReasoning: false };
|
|
5218
|
-
if (!isRecord(lane) || !Array.isArray(lane.messageIds))
|
|
5219
|
-
throw invalidState(sessionId);
|
|
5220
|
-
const ids = new Set;
|
|
5221
|
-
for (const id of lane.messageIds) {
|
|
5222
|
-
if (typeof id !== "string" || id.length === 0)
|
|
5223
|
-
throw invalidState(sessionId);
|
|
5224
|
-
ids.add(id);
|
|
5225
|
-
}
|
|
5226
|
-
if (lane.dropLeavesReasoning !== undefined && typeof lane.dropLeavesReasoning !== "boolean") {
|
|
5227
|
-
throw invalidState(sessionId);
|
|
5228
|
-
}
|
|
5229
|
-
return { messageIds: ids, dropLeavesReasoning: lane.dropLeavesReasoning === true };
|
|
5230
|
-
}
|
|
5231
|
-
function writeState(doc, state) {
|
|
5232
|
-
doc.version = 2;
|
|
5233
|
-
const lane = {
|
|
5234
|
-
messageIds: [...state.messageIds],
|
|
5235
|
-
...state.dropLeavesReasoning ? { dropLeavesReasoning: true } : {}
|
|
5236
|
-
};
|
|
5237
|
-
doc[NAMESPACE] = lane;
|
|
5238
|
-
doc[BACKUP_NAMESPACE] = { ...lane, messageIds: [...lane.messageIds] };
|
|
5239
|
-
}
|
|
5240
|
-
function getReasoningRemovalState(db, sessionId) {
|
|
5241
|
-
const doc = readReplayEnvelope(db, sessionId);
|
|
5242
|
-
try {
|
|
5243
|
-
return parseState(doc, sessionId);
|
|
5244
|
-
} catch (error) {
|
|
5245
|
-
if (doc[BACKUP_NAMESPACE] === undefined)
|
|
5246
|
-
throw error;
|
|
5247
|
-
return parseState(doc, sessionId, BACKUP_NAMESPACE);
|
|
5248
|
-
}
|
|
5249
|
-
}
|
|
5250
|
-
function addRemovedReasoningIds(db, sessionId, ids) {
|
|
5251
|
-
const requested = [...ids].filter((id) => typeof id === "string" && id.length > 0);
|
|
5252
|
-
if (requested.length === 0)
|
|
5253
|
-
return true;
|
|
5254
|
-
return updateReplayDocument(db, sessionId, (doc) => {
|
|
5255
|
-
const current = parseState(doc, sessionId);
|
|
5256
|
-
let changed = false;
|
|
5257
|
-
for (const id of requested) {
|
|
5258
|
-
if (current.messageIds.has(id))
|
|
5259
|
-
continue;
|
|
5260
|
-
current.messageIds.add(id);
|
|
5261
|
-
changed = true;
|
|
5262
|
-
}
|
|
5263
|
-
if (!changed)
|
|
5264
|
-
return false;
|
|
5265
|
-
writeState(doc, current);
|
|
5266
|
-
return true;
|
|
5267
|
-
});
|
|
5268
|
-
}
|
|
5269
|
-
function markDropLeavesReasoning(db, sessionId) {
|
|
5270
|
-
return updateReplayDocument(db, sessionId, (doc) => {
|
|
5271
|
-
const current = parseState(doc, sessionId);
|
|
5272
|
-
if (current.dropLeavesReasoning)
|
|
5273
|
-
return false;
|
|
5274
|
-
current.dropLeavesReasoning = true;
|
|
5275
|
-
writeState(doc, current);
|
|
5276
|
-
return true;
|
|
5277
|
-
});
|
|
5278
|
-
}
|
|
5279
|
-
|
|
5280
|
-
// src/hooks/magic-context/active-anthropic-turn.ts
|
|
5281
|
-
function isInActiveAnthropicTurn(messages, index, anthropic) {
|
|
5282
|
-
const start = activeAnthropicTurnStart(messages, anthropic);
|
|
5283
|
-
return start !== undefined && index >= start;
|
|
5284
|
-
}
|
|
5285
|
-
function activeAnthropicTurnStart(messages, anthropic) {
|
|
5286
|
-
if (!anthropic)
|
|
5287
|
-
return;
|
|
5288
|
-
for (let user = messages.length - 1;user >= 0; user--) {
|
|
5289
|
-
const message = messages[user];
|
|
5290
|
-
if (!isRecord(message))
|
|
5291
|
-
continue;
|
|
5292
|
-
const info = isRecord(message.info) ? message.info : message;
|
|
5293
|
-
if (info.role !== "user" || info.synthetic === true || message.synthetic === true)
|
|
5294
|
-
continue;
|
|
5295
|
-
const id = typeof info.id === "string" ? info.id : "";
|
|
5296
|
-
if (id.startsWith("synth-user-"))
|
|
5297
|
-
continue;
|
|
5298
|
-
const parts = Array.isArray(message.parts) ? message.parts : Array.isArray(message.content) ? message.content : [];
|
|
5299
|
-
if (parts.length > 0 && parts.every((part) => isRecord(part) && (part.synthetic === true || part.ignored === true || ["tool_result", "toolResult", "tool-result"].includes(String(part.type)))))
|
|
5300
|
-
continue;
|
|
5301
|
-
return user + 1;
|
|
5302
|
-
}
|
|
5303
|
-
return;
|
|
5304
|
-
}
|
|
5305
|
-
function hasAnthropicReasoning(messages) {
|
|
5306
|
-
return messages.some((message) => {
|
|
5307
|
-
if (!isRecord(message))
|
|
5308
|
-
return false;
|
|
5309
|
-
const info = isRecord(message.info) ? message.info : message;
|
|
5310
|
-
if (isAnthropicFamilyRoute(typeof info.providerID === "string" ? info.providerID : typeof info.provider === "string" ? info.provider : undefined, typeof info.modelID === "string" ? info.modelID : typeof info.model === "string" ? info.model : undefined))
|
|
5311
|
-
return true;
|
|
5312
|
-
const parts = Array.isArray(message.parts) ? message.parts : [];
|
|
5313
|
-
return parts.some((part) => isRecord(part) && isRecord(part.metadata) && isRecord(part.metadata.anthropic));
|
|
5314
|
-
});
|
|
5315
|
-
}
|
|
5316
|
-
|
|
5317
|
-
// src/hooks/magic-context/strip-content.ts
|
|
5318
|
-
var MARKER_ONLY_PATTERN = /^(?:(?:§\d+§|\[dropped(?: §\d+§)?\]|\[cleared\])\s*)+$/;
|
|
5319
|
-
function isMarkerOnlyText(text) {
|
|
5320
|
-
const trimmed = text.trim();
|
|
5321
|
-
return trimmed.length > 0 && MARKER_ONLY_PATTERN.test(trimmed);
|
|
5322
|
-
}
|
|
5323
|
-
var TAG_PREFIX_PATTERN = /^§\d+§\s*/;
|
|
5324
|
-
var SYSTEM_INJECTION_PATTERNS = [
|
|
5325
|
-
/^<!-- OMO_INTERNAL_INITIATOR -->$/,
|
|
5326
|
-
/^<system-reminder>[\s\S]*<\/system-reminder>$/,
|
|
5327
|
-
/^\[SYSTEM DIRECTIVE:/,
|
|
5328
|
-
/^\[Category\+Skill Reminder\]/,
|
|
5329
|
-
/^\[EDIT ERROR - IMMEDIATE ACTION REQUIRED\]/,
|
|
5330
|
-
/^\[task CALL FAILED/,
|
|
5331
|
-
/^\[EMERGENCY CONTEXT WINDOW WARNING\]/
|
|
5332
|
-
];
|
|
5333
|
-
function isSystemInjectedText(text) {
|
|
5334
|
-
const stripped = text.trim().replace(TAG_PREFIX_PATTERN, "").trim();
|
|
5335
|
-
if (stripped.length === 0)
|
|
5336
|
-
return false;
|
|
5337
|
-
return SYSTEM_INJECTION_PATTERNS.some((pattern) => pattern.test(stripped));
|
|
5338
|
-
}
|
|
5339
|
-
function stripSystemInjectedMessages(messages, protectedTailStart, providerID, onFirstApplication) {
|
|
5340
|
-
let stripped = 0;
|
|
5341
|
-
const sentineledIds = [];
|
|
5342
|
-
for (let i = 0;i < messages.length; i++) {
|
|
5343
|
-
if (i >= protectedTailStart)
|
|
5344
|
-
continue;
|
|
5345
|
-
const msg = messages[i];
|
|
5346
|
-
if (msg.parts.length === 0)
|
|
5347
|
-
continue;
|
|
5348
|
-
if (msg.info.role === "user")
|
|
5349
|
-
continue;
|
|
5350
|
-
if (msg.parts.length === 1 && isSentinel(msg.parts[0]))
|
|
5351
|
-
continue;
|
|
5352
|
-
let hasContentPart = false;
|
|
5353
|
-
let allContentIsSystemInjection = true;
|
|
5354
|
-
for (const part of msg.parts) {
|
|
5355
|
-
if (!isRecord(part))
|
|
5356
|
-
continue;
|
|
5357
|
-
const partType = part.type;
|
|
5358
|
-
if (METADATA_PART_TYPES.has(partType))
|
|
5359
|
-
continue;
|
|
5360
|
-
if (part.ignored === true)
|
|
5361
|
-
continue;
|
|
5362
|
-
if (partType === "tool") {
|
|
5363
|
-
allContentIsSystemInjection = false;
|
|
5364
|
-
break;
|
|
5365
|
-
}
|
|
5366
|
-
if (partType === "text" && typeof part.text === "string") {
|
|
5367
|
-
hasContentPart = true;
|
|
5368
|
-
if (!isSystemInjectedText(part.text)) {
|
|
5369
|
-
allContentIsSystemInjection = false;
|
|
5370
|
-
break;
|
|
5371
|
-
}
|
|
5372
|
-
continue;
|
|
5373
|
-
}
|
|
5374
|
-
allContentIsSystemInjection = false;
|
|
5375
|
-
break;
|
|
5376
|
-
}
|
|
5377
|
-
if (hasContentPart && allContentIsSystemInjection) {
|
|
5378
|
-
onFirstApplication?.(msg, 0);
|
|
5379
|
-
neutralizeWholeMessage(msg, providerID);
|
|
5380
|
-
stripped++;
|
|
5381
|
-
if (typeof msg.info.id === "string")
|
|
5382
|
-
sentineledIds.push(msg.info.id);
|
|
5383
|
-
}
|
|
5384
|
-
}
|
|
5385
|
-
return { stripped, sentineledIds };
|
|
5386
|
-
}
|
|
5387
|
-
var METADATA_PART_TYPES = new Set([
|
|
5388
|
-
"step-start",
|
|
5389
|
-
"step-finish",
|
|
5390
|
-
"snapshot",
|
|
5391
|
-
"patch",
|
|
5392
|
-
"agent",
|
|
5393
|
-
"retry",
|
|
5394
|
-
"subtask",
|
|
5395
|
-
"compaction"
|
|
5396
|
-
]);
|
|
5397
|
-
function stripDroppedPlaceholderMessages(messages, providerID, onFirstApplication) {
|
|
5398
|
-
let stripped = 0;
|
|
5399
|
-
const sentineledIds = [];
|
|
5400
|
-
for (let i = 0;i < messages.length; i++) {
|
|
5401
|
-
const msg = messages[i];
|
|
5402
|
-
if (msg.parts.length === 0)
|
|
5403
|
-
continue;
|
|
5404
|
-
if (msg.info.role === "user")
|
|
5405
|
-
continue;
|
|
5406
|
-
if (msg.parts.length === 1 && isSentinel(msg.parts[0]))
|
|
5407
|
-
continue;
|
|
5408
|
-
let hasContentPart = false;
|
|
5409
|
-
let hasNonDroppedContent = false;
|
|
5410
|
-
for (const part of msg.parts) {
|
|
5411
|
-
if (!isRecord(part)) {
|
|
5412
|
-
hasNonDroppedContent = true;
|
|
5413
|
-
break;
|
|
5414
|
-
}
|
|
5415
|
-
const partType = part.type;
|
|
5416
|
-
if (METADATA_PART_TYPES.has(partType))
|
|
5417
|
-
continue;
|
|
5418
|
-
if (partType === "tool") {
|
|
5419
|
-
hasNonDroppedContent = true;
|
|
5420
|
-
break;
|
|
5421
|
-
}
|
|
5422
|
-
if ((partType === "text" || partType === "reasoning") && typeof part.text === "string") {
|
|
5423
|
-
hasContentPart = true;
|
|
5424
|
-
if (part.text.trim().length === 0)
|
|
5425
|
-
continue;
|
|
5426
|
-
if (!isMarkerOnlyText(part.text)) {
|
|
5427
|
-
hasNonDroppedContent = true;
|
|
5428
|
-
break;
|
|
5429
|
-
}
|
|
5430
|
-
continue;
|
|
5431
|
-
}
|
|
5432
|
-
hasNonDroppedContent = true;
|
|
5433
|
-
break;
|
|
5434
|
-
}
|
|
5435
|
-
if (hasContentPart && !hasNonDroppedContent) {
|
|
5436
|
-
onFirstApplication?.(msg, 0);
|
|
5437
|
-
neutralizeWholeMessage(msg, providerID);
|
|
5438
|
-
stripped++;
|
|
5439
|
-
if (typeof msg.info.id === "string")
|
|
5440
|
-
sentineledIds.push(msg.info.id);
|
|
5441
|
-
}
|
|
5442
|
-
}
|
|
5443
|
-
return { stripped, sentineledIds };
|
|
5444
|
-
}
|
|
5445
|
-
function replayClearedReasoning(messages, reasoningByMessage, messageTagNumbers, persistedWatermark) {
|
|
5446
|
-
if (persistedWatermark <= 0)
|
|
5447
|
-
return 0;
|
|
5448
|
-
let cleared = 0;
|
|
5449
|
-
for (const message of messages) {
|
|
5450
|
-
const msgTag = messageTagNumbers.get(message) ?? 0;
|
|
5451
|
-
if (msgTag === 0 || msgTag > persistedWatermark)
|
|
5452
|
-
continue;
|
|
5453
|
-
const parts = reasoningByMessage.get(message);
|
|
5454
|
-
if (!parts)
|
|
5455
|
-
continue;
|
|
5456
|
-
for (const tp of parts) {
|
|
5457
|
-
if (tp.type === "text")
|
|
5458
|
-
continue;
|
|
5459
|
-
if (tp.thinking !== undefined && tp.thinking !== "[cleared]") {
|
|
5460
|
-
tp.thinking = "[cleared]";
|
|
5461
|
-
cleared++;
|
|
5462
|
-
}
|
|
5463
|
-
if (tp.text !== undefined && tp.text !== "[cleared]") {
|
|
5464
|
-
tp.text = "[cleared]";
|
|
5465
|
-
cleared++;
|
|
5466
|
-
}
|
|
5467
|
-
}
|
|
5468
|
-
}
|
|
5469
|
-
return cleared;
|
|
5470
|
-
}
|
|
5471
|
-
function replayStrippedInlineThinking(messages, messageTagNumbers, persistedWatermark) {
|
|
5472
|
-
if (persistedWatermark <= 0)
|
|
5473
|
-
return 0;
|
|
5474
|
-
let stripped = 0;
|
|
5475
|
-
for (const message of messages) {
|
|
5476
|
-
if (message.info.role !== "assistant")
|
|
5477
|
-
continue;
|
|
5478
|
-
const msgTag = messageTagNumbers.get(message) ?? 0;
|
|
5479
|
-
if (msgTag === 0 || msgTag > persistedWatermark)
|
|
5480
|
-
continue;
|
|
5481
|
-
for (const part of message.parts) {
|
|
5482
|
-
if (!isRecord(part) || part.type !== "text" || typeof part.text !== "string")
|
|
5483
|
-
continue;
|
|
5484
|
-
if (!part.text.includes("<think"))
|
|
5485
|
-
continue;
|
|
5486
|
-
const cleaned = part.text.replace(INLINE_THINKING_PATTERN, "");
|
|
5487
|
-
if (cleaned !== part.text) {
|
|
5488
|
-
part.text = cleaned;
|
|
5489
|
-
stripped++;
|
|
5490
|
-
}
|
|
5491
|
-
}
|
|
5492
|
-
}
|
|
5493
|
-
return stripped;
|
|
5494
|
-
}
|
|
5495
|
-
function clearOldReasoning(messages, reasoningByMessage, messageTagNumbers, cutoff) {
|
|
5496
|
-
const ageCutoff = cutoff;
|
|
5497
|
-
let cleared = 0;
|
|
5498
|
-
for (const message of messages) {
|
|
5499
|
-
const msgTag = messageTagNumbers.get(message) ?? 0;
|
|
5500
|
-
if (msgTag === 0 || msgTag > ageCutoff)
|
|
5501
|
-
continue;
|
|
5502
|
-
const parts = reasoningByMessage.get(message);
|
|
5503
|
-
if (!parts)
|
|
5504
|
-
continue;
|
|
5505
|
-
for (const tp of parts) {
|
|
5506
|
-
if (tp.type === "text")
|
|
5507
|
-
continue;
|
|
5508
|
-
if (tp.thinking !== undefined && tp.thinking !== "[cleared]") {
|
|
5509
|
-
tp.thinking = "[cleared]";
|
|
5510
|
-
cleared++;
|
|
5511
|
-
}
|
|
5512
|
-
if (tp.text !== undefined && tp.text !== "[cleared]") {
|
|
5513
|
-
tp.text = "[cleared]";
|
|
5514
|
-
cleared++;
|
|
5515
|
-
}
|
|
5516
|
-
}
|
|
5517
|
-
}
|
|
5518
|
-
return cleared;
|
|
5519
|
-
}
|
|
5520
|
-
var CLEARED_REASONING_TYPES = new Set(["thinking", "reasoning"]);
|
|
5521
|
-
function stripClearedReasoning(messages) {
|
|
5522
|
-
let stripped = 0;
|
|
5523
|
-
for (const message of messages) {
|
|
5524
|
-
if (message.info.role !== "assistant")
|
|
5525
|
-
continue;
|
|
5526
|
-
for (let i = 0;i < message.parts.length; i++) {
|
|
5527
|
-
const part = message.parts[i];
|
|
5528
|
-
if (!isRecord(part))
|
|
5529
|
-
continue;
|
|
5530
|
-
const partType = part.type;
|
|
5531
|
-
if (!CLEARED_REASONING_TYPES.has(partType))
|
|
5532
|
-
continue;
|
|
5533
|
-
if (!("thinking" in part) && !("text" in part))
|
|
5534
|
-
continue;
|
|
5535
|
-
const thinking = "thinking" in part ? part.thinking : undefined;
|
|
5536
|
-
const text = "text" in part ? part.text : undefined;
|
|
5537
|
-
const isCleared = (thinking === undefined || thinking === "[cleared]") && (text === undefined || text === "[cleared]");
|
|
5538
|
-
if (!isCleared)
|
|
5539
|
-
continue;
|
|
5540
|
-
message.parts[i] = makeSentinel(part);
|
|
5541
|
-
stripped++;
|
|
5542
|
-
}
|
|
5543
|
-
}
|
|
5544
|
-
return stripped;
|
|
5545
|
-
}
|
|
5546
|
-
var INLINE_THINKING_PATTERN = /<(?:thinking|think)>[\s\S]*?<\/(?:thinking|think)>\s*/g;
|
|
5547
|
-
function stripInlineThinking(messages, messageTagNumbers, cutoff) {
|
|
5548
|
-
const ageCutoff = cutoff;
|
|
5549
|
-
let stripped = 0;
|
|
5550
|
-
for (const message of messages) {
|
|
5551
|
-
if (message.info.role !== "assistant")
|
|
5552
|
-
continue;
|
|
5553
|
-
const msgTag = messageTagNumbers.get(message) ?? 0;
|
|
5554
|
-
if (msgTag === 0 || msgTag > ageCutoff)
|
|
5555
|
-
continue;
|
|
5556
|
-
for (const part of message.parts) {
|
|
5557
|
-
if (!isRecord(part) || part.type !== "text" || typeof part.text !== "string")
|
|
5558
|
-
continue;
|
|
5559
|
-
const cleaned = part.text.replace(INLINE_THINKING_PATTERN, "");
|
|
5560
|
-
if (cleaned !== part.text) {
|
|
5561
|
-
part.text = cleaned;
|
|
5562
|
-
stripped++;
|
|
5563
|
-
}
|
|
5564
|
-
}
|
|
5565
|
-
}
|
|
5566
|
-
return stripped;
|
|
5567
|
-
}
|
|
5568
|
-
var REASONING_IGNORED_PART_TYPES = new Set([
|
|
5569
|
-
"step-start",
|
|
5570
|
-
"step-finish",
|
|
5571
|
-
"snapshot",
|
|
5572
|
-
"patch",
|
|
5573
|
-
"agent",
|
|
5574
|
-
"retry",
|
|
5575
|
-
"subtask",
|
|
5576
|
-
"compaction"
|
|
5577
|
-
]);
|
|
5578
|
-
var REASONING_PART_TYPES = new Set(["reasoning", "thinking", "redacted_thinking"]);
|
|
5579
|
-
function hasReasoningReplayContent(message) {
|
|
5580
|
-
return message.parts.some((part) => {
|
|
5581
|
-
if (!isRecord(part) || part.ignored === true)
|
|
5582
|
-
return false;
|
|
5583
|
-
const type = typeof part.type === "string" ? part.type : "";
|
|
5584
|
-
if (REASONING_IGNORED_PART_TYPES.has(type))
|
|
5585
|
-
return false;
|
|
5586
|
-
return type !== "text" || typeof part.text !== "string" || part.text.trim().length > 0;
|
|
5587
|
-
});
|
|
5588
|
-
}
|
|
5589
|
-
function findReasoningBearingAssistantIds(messages) {
|
|
5590
|
-
const ids = new Set;
|
|
5591
|
-
for (const message of messages) {
|
|
5592
|
-
if (message.info.role !== "assistant")
|
|
5593
|
-
continue;
|
|
5594
|
-
const id = message.info.id;
|
|
5595
|
-
if (typeof id !== "string" || id.length === 0)
|
|
5596
|
-
continue;
|
|
5597
|
-
if (message.parts.some((part) => isRecord(part) && REASONING_PART_TYPES.has(String(part.type)))) {
|
|
5598
|
-
ids.add(id);
|
|
5599
|
-
}
|
|
5600
|
-
}
|
|
5601
|
-
return [...ids];
|
|
5602
|
-
}
|
|
5603
|
-
function findLatestAssistantReasoningMutationExemptMessage(messages) {
|
|
5604
|
-
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
5605
|
-
const message = messages[index];
|
|
5606
|
-
if (message.info.role === "assistant" && hasReasoningReplayContent(message))
|
|
5607
|
-
return message;
|
|
5608
|
-
}
|
|
5609
|
-
return;
|
|
5610
|
-
}
|
|
5611
|
-
function planMergedAssistantReasoningStrip(messages, mutationExemptMessage, frozenMessageIds, protectedMessages) {
|
|
5612
|
-
const plan = [];
|
|
5613
|
-
let prevRole;
|
|
5614
|
-
let keptReasoningInRun = false;
|
|
5615
|
-
for (const message of messages) {
|
|
5616
|
-
const role = message.info.role;
|
|
5617
|
-
if (role !== "assistant") {
|
|
5618
|
-
prevRole = role;
|
|
5619
|
-
keptReasoningInRun = false;
|
|
5620
|
-
continue;
|
|
5621
|
-
}
|
|
5622
|
-
const firstInRun = prevRole !== "assistant";
|
|
5623
|
-
if (firstInRun)
|
|
5624
|
-
keptReasoningInRun = false;
|
|
5625
|
-
if (protectedMessages?.has(message) || message === mutationExemptMessage || frozenMessageIds?.has(message.info.id ?? "")) {
|
|
5626
|
-
prevRole = role;
|
|
5627
|
-
continue;
|
|
5628
|
-
}
|
|
5629
|
-
let keepIndex = -1;
|
|
5630
|
-
if (firstInRun && !keptReasoningInRun) {
|
|
5631
|
-
for (let i = 0;i < message.parts.length; i++) {
|
|
5632
|
-
const part = message.parts[i];
|
|
5633
|
-
if (!isRecord(part))
|
|
5634
|
-
continue;
|
|
5635
|
-
const partType = part.type;
|
|
5636
|
-
if (REASONING_IGNORED_PART_TYPES.has(partType))
|
|
5637
|
-
continue;
|
|
5638
|
-
if (part.ignored === true)
|
|
5639
|
-
continue;
|
|
5640
|
-
if (isSentinel(part))
|
|
5641
|
-
continue;
|
|
5642
|
-
if (partType === "text" && typeof part.text === "string" && part.text.trim() === "") {
|
|
5643
|
-
continue;
|
|
5644
|
-
}
|
|
5645
|
-
if (REASONING_PART_TYPES.has(partType)) {
|
|
5646
|
-
keepIndex = i;
|
|
5647
|
-
}
|
|
5648
|
-
break;
|
|
5649
|
-
}
|
|
5650
|
-
}
|
|
5651
|
-
const stripIndices = [];
|
|
5652
|
-
for (let i = 0;i < message.parts.length; i++) {
|
|
5653
|
-
const part = message.parts[i];
|
|
5654
|
-
if (!isRecord(part))
|
|
5655
|
-
continue;
|
|
5656
|
-
if (!REASONING_PART_TYPES.has(part.type))
|
|
5657
|
-
continue;
|
|
5658
|
-
if (part.cache_control !== undefined)
|
|
5659
|
-
continue;
|
|
5660
|
-
if (i === keepIndex) {
|
|
5661
|
-
keptReasoningInRun = true;
|
|
5662
|
-
continue;
|
|
5663
|
-
}
|
|
5664
|
-
stripIndices.push(i);
|
|
5665
|
-
}
|
|
5666
|
-
if (stripIndices.length > 0)
|
|
5667
|
-
plan.push({ message, stripIndices });
|
|
5668
|
-
prevRole = role;
|
|
5669
|
-
}
|
|
5670
|
-
return plan;
|
|
5671
|
-
}
|
|
5672
|
-
var MAX_FROZEN_TRAILING_BLANKS = 1e4;
|
|
5673
|
-
var CANONICAL_BLANK_PART = { type: "text", text: "" };
|
|
5674
|
-
function isSentinelInvisibleTextPart(part) {
|
|
5675
|
-
return isRecord(part) && part.type === "text" && typeof part.text === "string" && stripWellFormedLeadingTagPrefix(part.text).trim() === "";
|
|
5676
|
-
}
|
|
5677
|
-
function isCanonicalBlankPart(part) {
|
|
5678
|
-
return isRecord(part) && Object.keys(part).length === 2 && part.type === "text" && part.text === "";
|
|
5679
|
-
}
|
|
5680
|
-
function trailingBlankKeepCount(decision) {
|
|
5681
|
-
if (decision === "keep")
|
|
5682
|
-
return 1;
|
|
5683
|
-
if (!decision.startsWith("keep:"))
|
|
5684
|
-
return;
|
|
5685
|
-
const countText = decision.slice("keep:".length);
|
|
5686
|
-
if (!/^[1-9]\d*$/.test(countText))
|
|
5687
|
-
return;
|
|
5688
|
-
const count = Number(countText);
|
|
5689
|
-
return Number.isSafeInteger(count) && count > 0 && count <= MAX_FROZEN_TRAILING_BLANKS ? count : undefined;
|
|
5690
|
-
}
|
|
5691
|
-
function trailingBlankDecisionForMessage(message) {
|
|
5692
|
-
const id = message.info.id;
|
|
5693
|
-
if (message.info.role !== "assistant" || typeof id !== "string" || id.length === 0) {
|
|
5694
|
-
return;
|
|
5695
|
-
}
|
|
5696
|
-
let trailingCount = 0;
|
|
5697
|
-
while (trailingCount < message.parts.length && isSentinelInvisibleTextPart(message.parts[message.parts.length - trailingCount - 1])) {
|
|
5698
|
-
trailingCount += 1;
|
|
5699
|
-
}
|
|
5700
|
-
if (trailingCount > MAX_FROZEN_TRAILING_BLANKS && trailingCount < message.parts.length) {
|
|
5701
|
-
return;
|
|
5702
|
-
}
|
|
5703
|
-
const decision = message.parts.length === 0 || trailingCount === message.parts.length ? "keep" : trailingCount === 0 ? "strip" : trailingCount === 1 ? "keep" : `keep:${trailingCount}`;
|
|
5704
|
-
return [id, decision];
|
|
5705
|
-
}
|
|
5706
|
-
function snapshotTrailingBlankSourceDecisions(messages) {
|
|
5707
|
-
const decisions = new Map;
|
|
5708
|
-
for (const message of messages) {
|
|
5709
|
-
const observed = trailingBlankDecisionForMessage(message);
|
|
5710
|
-
if (observed)
|
|
5711
|
-
decisions.set(...observed);
|
|
5712
|
-
}
|
|
5713
|
-
return decisions;
|
|
5714
|
-
}
|
|
5715
|
-
function findTrailingBlankDecisionCandidates(messages, frozenDecisions, options) {
|
|
5716
|
-
const observedDecisions = options?.sourceDecisions ?? snapshotTrailingBlankSourceDecisions(messages);
|
|
5717
|
-
const visibleIds = new Set(messages.flatMap((message) => typeof message.info.id === "string" ? [message.info.id] : []));
|
|
5718
|
-
const decisions = [];
|
|
5719
|
-
for (const [id, decision] of observedDecisions) {
|
|
5720
|
-
if (!visibleIds.has(id))
|
|
5721
|
-
continue;
|
|
5722
|
-
const frozen = frozenDecisions.get(id);
|
|
5723
|
-
if (frozen !== undefined && (id !== options?.refreshMessageId || frozen === decision || frozen === "strip")) {
|
|
5724
|
-
continue;
|
|
5725
|
-
}
|
|
5726
|
-
decisions.push([id, decision]);
|
|
5727
|
-
}
|
|
5728
|
-
return decisions;
|
|
5729
|
-
}
|
|
5730
|
-
function applyFrozenTrailingBlankDecisions(messages, frozenDecisions) {
|
|
5731
|
-
let mutations = 0;
|
|
5732
|
-
for (let messageIndex = 0;messageIndex < messages.length; messageIndex += 1) {
|
|
5733
|
-
let message = messages[messageIndex];
|
|
5734
|
-
const id = message.info.id;
|
|
5735
|
-
if (message.info.role !== "assistant" || typeof id !== "string")
|
|
5736
|
-
continue;
|
|
5737
|
-
const decision = frozenDecisions.get(id);
|
|
5738
|
-
if (!decision)
|
|
5739
|
-
continue;
|
|
5740
|
-
let lastMeaningfulIndex = message.parts.length - 1;
|
|
5741
|
-
while (lastMeaningfulIndex >= 0 && isSentinelInvisibleTextPart(message.parts[lastMeaningfulIndex])) {
|
|
5742
|
-
lastMeaningfulIndex -= 1;
|
|
5743
|
-
}
|
|
5744
|
-
const replaceParts = (start, deleteCount, insertBlankCount) => {
|
|
5745
|
-
message = { ...message, parts: [...message.parts] };
|
|
5746
|
-
messages[messageIndex] = message;
|
|
5747
|
-
message.parts.splice(start, deleteCount, ...Array.from({ length: insertBlankCount }, () => ({ ...CANONICAL_BLANK_PART })));
|
|
5748
|
-
};
|
|
5749
|
-
if (lastMeaningfulIndex < 0) {
|
|
5750
|
-
if (message.parts.length === 0)
|
|
5751
|
-
continue;
|
|
5752
|
-
if (message.parts.length !== 1 || !isCanonicalBlankPart(message.parts[0])) {
|
|
5753
|
-
mutations += Math.max(1, message.parts.length);
|
|
5754
|
-
replaceParts(0, message.parts.length, 1);
|
|
5755
|
-
}
|
|
5756
|
-
continue;
|
|
5757
|
-
}
|
|
5758
|
-
const trailingCount = message.parts.length - lastMeaningfulIndex - 1;
|
|
5759
|
-
const keepCount = trailingBlankKeepCount(decision);
|
|
5760
|
-
if (keepCount !== undefined) {
|
|
5761
|
-
if (trailingCount === 0)
|
|
5762
|
-
continue;
|
|
5763
|
-
const blankIndex = lastMeaningfulIndex + 1;
|
|
5764
|
-
const suffixIsCanonical = trailingCount === keepCount && message.parts.slice(blankIndex).every(isCanonicalBlankPart);
|
|
5765
|
-
if (!suffixIsCanonical) {
|
|
5766
|
-
mutations += Math.max(1, trailingCount, keepCount);
|
|
5767
|
-
replaceParts(blankIndex, trailingCount, keepCount);
|
|
5768
|
-
}
|
|
5769
|
-
continue;
|
|
5770
|
-
}
|
|
5771
|
-
if (trailingCount === 0)
|
|
5772
|
-
continue;
|
|
5773
|
-
const lastMeaningfulPart = message.parts[lastMeaningfulIndex];
|
|
5774
|
-
if (isRecord(lastMeaningfulPart) && REASONING_PART_TYPES.has(lastMeaningfulPart.type)) {
|
|
5775
|
-
const blankIndex = lastMeaningfulIndex + 1;
|
|
5776
|
-
if (trailingCount !== 1 || !isCanonicalBlankPart(message.parts[blankIndex])) {
|
|
5777
|
-
mutations += Math.max(1, trailingCount);
|
|
5778
|
-
replaceParts(blankIndex, trailingCount, 1);
|
|
5779
|
-
}
|
|
5780
|
-
continue;
|
|
5781
|
-
}
|
|
5782
|
-
mutations += trailingCount;
|
|
5783
|
-
replaceParts(lastMeaningfulIndex + 1, trailingCount, 0);
|
|
5784
|
-
}
|
|
5785
|
-
return mutations;
|
|
5786
|
-
}
|
|
5787
|
-
function stripReasoningFromAssistantIds(messages, providerID, messageIds, protectedMessages) {
|
|
5788
|
-
if (messageIds.size === 0)
|
|
5789
|
-
return 0;
|
|
5790
|
-
const emptySentinels = modelAcceptsEmptyContent(providerID);
|
|
5791
|
-
let stripped = 0;
|
|
5792
|
-
for (const message of messages) {
|
|
5793
|
-
if (protectedMessages?.has(message))
|
|
5794
|
-
continue;
|
|
5795
|
-
const id = message.info.id;
|
|
5796
|
-
if (typeof id !== "string" || !messageIds.has(id))
|
|
5797
|
-
continue;
|
|
5798
|
-
for (let index = 0;index < message.parts.length; index += 1) {
|
|
5799
|
-
const part = message.parts[index];
|
|
5800
|
-
if (!isRecord(part) || !REASONING_PART_TYPES.has(String(part.type)))
|
|
5801
|
-
continue;
|
|
5802
|
-
if (emptySentinels) {
|
|
5803
|
-
message.parts[index] = makeSentinel(part);
|
|
5804
|
-
} else {
|
|
5805
|
-
message.parts.splice(index, 1);
|
|
5806
|
-
index -= 1;
|
|
5807
|
-
}
|
|
5808
|
-
stripped += 1;
|
|
5809
|
-
}
|
|
5810
|
-
if (message.parts.length === 0)
|
|
5811
|
-
message.parts.push(makeWholeMessageSentinel(providerID));
|
|
5812
|
-
}
|
|
5813
|
-
return stripped;
|
|
5814
|
-
}
|
|
5815
|
-
function findMergedReasoningStripDecisions(messages, providerID, frozenIds, options) {
|
|
5816
|
-
if (providerID !== "anthropic")
|
|
5817
|
-
return [];
|
|
5818
|
-
const frozenParts = readFrozenMergedReasoningParts(frozenIds);
|
|
5819
|
-
const decisions = [];
|
|
5820
|
-
for (const entry of planMergedAssistantReasoningStrip(messages, options?.mutationExemptMessage, new Set(frozenParts.keys()), options?.protectedMessages)) {
|
|
5821
|
-
const id = entry.message.info.id;
|
|
5822
|
-
if (typeof id !== "string" || id.length === 0 || frozenParts.has(id))
|
|
5823
|
-
continue;
|
|
5824
|
-
const parts = entry.stripIndices.map((index) => {
|
|
5825
|
-
const part = entry.message.parts[index];
|
|
5826
|
-
return isRecord(part) && typeof part.id === "string" ? part.id : index;
|
|
5827
|
-
});
|
|
5828
|
-
decisions.push(id, MERGED_REASONING_PARTS_PREFIX + JSON.stringify([id, parts]));
|
|
5829
|
-
}
|
|
5830
|
-
return decisions;
|
|
5831
|
-
}
|
|
5832
|
-
function stripReasoningFromMergedAssistants(messages, providerID, options) {
|
|
5833
|
-
if (providerID !== "anthropic")
|
|
5834
|
-
return 0;
|
|
5835
|
-
let stripped = 0;
|
|
5836
|
-
const frozenParts = options?.frozenParts ?? readFrozenMergedReasoningParts(options?.frozenMessageIds ?? new Set);
|
|
5837
|
-
for (const message of messages) {
|
|
5838
|
-
if (message.info.role !== "assistant" || options?.restoreMessages?.has(message))
|
|
5839
|
-
continue;
|
|
5840
|
-
const parts = frozenParts.get(message.info.id ?? "");
|
|
5841
|
-
if (!parts)
|
|
5842
|
-
continue;
|
|
5843
|
-
for (let index = 0;index < message.parts.length; index += 1) {
|
|
5844
|
-
const part = message.parts[index];
|
|
5845
|
-
if (!isRecord(part) || !REASONING_PART_TYPES.has(String(part.type)))
|
|
5846
|
-
continue;
|
|
5847
|
-
if (!parts.includes(index) && !(typeof part.id === "string" && parts.includes(part.id)))
|
|
5848
|
-
continue;
|
|
5849
|
-
message.parts[index] = makeSentinel(part);
|
|
5850
|
-
stripped++;
|
|
5851
|
-
}
|
|
5852
|
-
}
|
|
5853
|
-
for (const entry of planMergedAssistantReasoningStrip(messages, options?.mutationExemptMessage, options?.frozenPartMessageIds ?? new Set(frozenParts.keys()), options?.frozenMessageIds ? options.restoreMessages : options?.protectedMessages)) {
|
|
5854
|
-
if (options?.frozenMessageIds) {
|
|
5855
|
-
const id = entry.message.info.id;
|
|
5856
|
-
if (typeof id !== "string" || !options.frozenMessageIds.has(id))
|
|
5857
|
-
continue;
|
|
5858
|
-
}
|
|
5859
|
-
for (const index of entry.stripIndices) {
|
|
5860
|
-
entry.message.parts[index] = makeSentinel(entry.message.parts[index]);
|
|
5861
|
-
stripped++;
|
|
5862
|
-
}
|
|
5863
|
-
}
|
|
5864
|
-
return stripped;
|
|
5865
|
-
}
|
|
5866
|
-
function stripProcessedImages(messages, frozenIds, options) {
|
|
5867
|
-
const { detect, watermark, messageTagNumbers } = options;
|
|
5868
|
-
let stripped = 0;
|
|
5869
|
-
const newlyStrippedIds = [];
|
|
5870
|
-
let hasAssistantResponse = false;
|
|
5871
|
-
for (let i = messages.length - 1;i >= 0; i--) {
|
|
5872
|
-
const msg = messages[i];
|
|
5873
|
-
if (msg.info.role === "assistant") {
|
|
5874
|
-
hasAssistantResponse = true;
|
|
5875
|
-
continue;
|
|
5876
|
-
}
|
|
5877
|
-
if (msg.info.role !== "user") {
|
|
5878
|
-
continue;
|
|
5879
|
-
}
|
|
5880
|
-
const id = typeof msg.info.id === "string" ? msg.info.id : undefined;
|
|
5881
|
-
const inFrozen = id !== undefined && frozenIds.has(id);
|
|
5882
|
-
const maxTag = messageTagNumbers.get(msg) ?? 0;
|
|
5883
|
-
const isNewDetection = !inFrozen && detect && hasAssistantResponse && id !== undefined && maxTag <= watermark;
|
|
5884
|
-
if (!inFrozen && !isNewDetection) {
|
|
5885
|
-
continue;
|
|
5886
|
-
}
|
|
5887
|
-
let touchedThisMsg = false;
|
|
5888
|
-
for (let j = 0;j < msg.parts.length; j++) {
|
|
5889
|
-
const part = msg.parts[j];
|
|
5890
|
-
if (!isRecord(part) || part.type !== "file") {
|
|
5891
|
-
continue;
|
|
5892
|
-
}
|
|
5893
|
-
if (typeof part.mime !== "string" || !part.mime.startsWith("image/")) {
|
|
5894
|
-
continue;
|
|
5895
|
-
}
|
|
5896
|
-
if (typeof part.url === "string" && part.url.startsWith("data:") && part.url.length > 200) {
|
|
5897
|
-
if (isNewDetection)
|
|
5898
|
-
options.onFirstApplication?.(msg, j);
|
|
5899
|
-
msg.parts[j] = makeSentinel(part);
|
|
5900
|
-
stripped++;
|
|
5901
|
-
touchedThisMsg = true;
|
|
5902
|
-
}
|
|
5903
|
-
}
|
|
5904
|
-
if (touchedThisMsg && isNewDetection && id !== undefined) {
|
|
5905
|
-
newlyStrippedIds.push(id);
|
|
5906
|
-
}
|
|
5907
|
-
}
|
|
5908
|
-
return { stripped, newlyStrippedIds };
|
|
5909
|
-
}
|
|
5910
|
-
|
|
5911
|
-
// src/hooks/magic-context/reasoning-budget.ts
|
|
5912
|
-
function projectOpencodeReasoningBudgetCutoff(db, sessionId, messages, budget, watermark, proseRatio) {
|
|
5913
|
-
const textEstimateByMessageId = getReasoningTokenEstimatesByMessage2(db, sessionId, proseRatio);
|
|
5914
|
-
const maxTags = getMaxTagNumberByOwnerMessage2(db, sessionId);
|
|
5915
|
-
const messageTags = new Map;
|
|
5916
|
-
const gone = new Set(getReasoningRemovalState(db, sessionId).messageIds);
|
|
5917
|
-
for (const message of messages) {
|
|
5918
|
-
if (typeof message.info.id !== "string")
|
|
5919
|
-
continue;
|
|
5920
|
-
const tag = maxTags.get(message.info.id) ?? 0;
|
|
5921
|
-
messageTags.set(message, tag);
|
|
5922
|
-
if (tag > 0 && tag <= watermark)
|
|
5923
|
-
gone.add(message.info.id);
|
|
5924
|
-
}
|
|
5925
|
-
const frozenMergedIds = getMergedReasoningStrippedIds(db, sessionId);
|
|
5926
|
-
return opencodeReasoningBudgetCutoff({
|
|
5927
|
-
messages,
|
|
5928
|
-
messageTagNumbers: messageTags,
|
|
5929
|
-
budget,
|
|
5930
|
-
alreadyRemoved: gone,
|
|
5931
|
-
textEstimateByMessageId,
|
|
5932
|
-
proseRatio,
|
|
5933
|
-
frozenMergedIds,
|
|
5934
|
-
alsoGone: new Set([...frozenMergedIds].filter((id) => id.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX)).map((id) => id.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length)))
|
|
5935
|
-
});
|
|
5936
|
-
}
|
|
5937
|
-
var DEFAULT_KEEP_REASONING_TOKENS = 1e4;
|
|
5938
|
-
var UNKNOWN_REASONING_STEP_TOKENS = 1000;
|
|
5939
|
-
function resolveKeepReasoningTokens(config, modelKey) {
|
|
5940
|
-
const values = config && typeof config === "object" ? Object.assign(Object.create(null), config) : undefined;
|
|
5941
|
-
return typeof config === "number" ? config : resolveModelConfigValue(values, modelKey)?.value ?? values?.default ?? DEFAULT_KEEP_REASONING_TOKENS;
|
|
5942
|
-
}
|
|
5943
|
-
function reasoningStepCost(reported, textEstimate, opaque) {
|
|
5944
|
-
if (reported !== undefined && Number.isFinite(reported) && reported > 0)
|
|
5945
|
-
return reported;
|
|
5946
|
-
if (textEstimate > 0)
|
|
5947
|
-
return Math.ceil(textEstimate);
|
|
5948
|
-
return opaque ? UNKNOWN_REASONING_STEP_TOKENS : 0;
|
|
5949
|
-
}
|
|
5950
|
-
function reasoningBudgetCutoff(steps, budget) {
|
|
5951
|
-
const cost = (step) => step.alreadyRemoved ? 0 : typeof step.cost === "function" ? step.cost() : step.cost;
|
|
5952
|
-
let kept = 0;
|
|
5953
|
-
let upperBound = Number.POSITIVE_INFINITY;
|
|
5954
|
-
for (const step of steps) {
|
|
5955
|
-
if (!step.exempt)
|
|
5956
|
-
continue;
|
|
5957
|
-
kept += cost(step);
|
|
5958
|
-
if (step.tag > 0)
|
|
5959
|
-
upperBound = Math.min(upperBound, step.tag - 1);
|
|
5960
|
-
}
|
|
5961
|
-
for (let index = steps.length - 1;index >= 0; index--) {
|
|
5962
|
-
const step = steps[index];
|
|
5963
|
-
if (step.exempt || step.alreadyRemoved)
|
|
5964
|
-
continue;
|
|
5965
|
-
const tokens = cost(step);
|
|
5966
|
-
if (kept + tokens <= budget) {
|
|
5967
|
-
kept += tokens;
|
|
5968
|
-
if (step.tag > 0)
|
|
5969
|
-
upperBound = Math.min(upperBound, step.tag - 1);
|
|
5970
|
-
continue;
|
|
5971
|
-
}
|
|
5972
|
-
let tag = step.tag;
|
|
5973
|
-
for (let older = index - 1;tag <= 0 && older >= 0; older--)
|
|
5974
|
-
tag = steps[older].tag;
|
|
5975
|
-
return Math.max(0, Math.min(tag, upperBound));
|
|
5976
|
-
}
|
|
5977
|
-
return 0;
|
|
5978
|
-
}
|
|
5979
|
-
function reasoningTextAndOpaque(parts) {
|
|
5980
|
-
let text = "";
|
|
5981
|
-
let inlineText = "";
|
|
5982
|
-
let opaque = false;
|
|
5983
|
-
let hasReasoning = false;
|
|
5984
|
-
const detailText = new Set;
|
|
5985
|
-
for (const part of parts) {
|
|
5986
|
-
if (!isRecord(part))
|
|
5987
|
-
continue;
|
|
5988
|
-
if (part.ignored === true)
|
|
5989
|
-
continue;
|
|
5990
|
-
if (isRecord(part.metadata)) {
|
|
5991
|
-
const router = part.metadata.openrouter;
|
|
5992
|
-
if (isRecord(router) && Array.isArray(router.reasoning_details) && router.reasoning_details.length > 0) {
|
|
5993
|
-
hasReasoning = true;
|
|
5994
|
-
opaque = true;
|
|
5995
|
-
for (const detail of router.reasoning_details) {
|
|
5996
|
-
if (!isRecord(detail))
|
|
5997
|
-
continue;
|
|
5998
|
-
if (detail.type === "reasoning.text" && typeof detail.text === "string")
|
|
5999
|
-
detailText.add(detail.text);
|
|
6000
|
-
if (detail.type === "reasoning.summary" && typeof detail.summary === "string")
|
|
6001
|
-
detailText.add(detail.summary);
|
|
6002
|
-
}
|
|
6003
|
-
}
|
|
6004
|
-
}
|
|
6005
|
-
if (["reasoning", "thinking", "redacted_thinking"].includes(String(part.type))) {
|
|
6006
|
-
hasReasoning = true;
|
|
6007
|
-
const visible = part.type === "redacted_thinking" || part.redacted === true ? "" : typeof part.thinking === "string" ? part.thinking : typeof part.text === "string" ? part.text : "";
|
|
6008
|
-
if (visible !== "[cleared]")
|
|
6009
|
-
text += visible;
|
|
6010
|
-
opaque ||= part.type === "redacted_thinking" || part.redacted === true || visible === "" && (part.metadata !== undefined || part.signature !== undefined || part.thinkingSignature !== undefined);
|
|
6011
|
-
} else if (part.type === "text" && typeof part.text === "string") {
|
|
6012
|
-
for (const match of part.text.matchAll(/<(?:thinking|think)>([\s\S]*?)<\/(?:thinking|think)>/gi))
|
|
6013
|
-
inlineText += match[1];
|
|
6014
|
-
}
|
|
6015
|
-
}
|
|
6016
|
-
return { text: text || [...detailText].join(""), inlineText, opaque, hasReasoning };
|
|
6017
|
-
}
|
|
6018
|
-
function opencodeReasoningBudgetCutoff(args) {
|
|
6019
|
-
const assistants = args.messages.filter((message) => message.info.role === "assistant");
|
|
6020
|
-
const newest = assistants.at(-1);
|
|
6021
|
-
const exempt = findLatestAssistantReasoningMutationExemptMessage(args.messages);
|
|
6022
|
-
const anthropic = args.anthropic ?? hasAnthropicReasoning(args.messages);
|
|
6023
|
-
const indexOfMessage = new Map;
|
|
6024
|
-
args.messages.forEach((message, index) => {
|
|
6025
|
-
if (!indexOfMessage.has(message))
|
|
6026
|
-
indexOfMessage.set(message, index);
|
|
6027
|
-
});
|
|
6028
|
-
const frozenParts = args.frozenMergedIds ? readFrozenMergedReasoningParts(args.frozenMergedIds) : undefined;
|
|
6029
|
-
const frozenPartMessageIds = frozenParts ? new Set(frozenParts.keys()) : undefined;
|
|
6030
|
-
return reasoningBudgetCutoff(assistants.map((message) => ({
|
|
6031
|
-
tag: args.messageTagNumbers.get(message) ?? 0,
|
|
6032
|
-
exempt: message === newest || message === exempt || isInActiveAnthropicTurn(args.messages, indexOfMessage.get(message) ?? -1, anthropic),
|
|
6033
|
-
cost: () => {
|
|
6034
|
-
const costMessage = { ...message, parts: [...message.parts] };
|
|
6035
|
-
const id = message.info.id ?? "";
|
|
6036
|
-
if (args.frozenMergedIds && (frozenParts?.has(id) || args.frozenMergedIds.has(id)))
|
|
6037
|
-
stripReasoningFromMergedAssistants([costMessage], "anthropic", {
|
|
6038
|
-
frozenMessageIds: args.frozenMergedIds,
|
|
6039
|
-
frozenParts,
|
|
6040
|
-
frozenPartMessageIds
|
|
6041
|
-
});
|
|
6042
|
-
const visible = reasoningTextAndOpaque(args.countNeutralized ? costMessage.parts.map(neutralizedReasoningSource) : costMessage.parts);
|
|
6043
|
-
if (!visible.hasReasoning && !visible.inlineText)
|
|
6044
|
-
return 0;
|
|
6045
|
-
const info = message.info;
|
|
6046
|
-
const tokens = isRecord(info.tokens) ? info.tokens.reasoning : undefined;
|
|
6047
|
-
const typedGone = typeof message.info.id === "string" && (args.alreadyRemoved?.has(message.info.id) === true || args.alsoGone?.has(message.info.id) === true);
|
|
6048
|
-
return (visible.hasReasoning && !typedGone ? reasoningStepCost(typeof tokens === "number" ? tokens : undefined, estimateTokens(visible.text) * (args.proseRatio ?? 1), visible.opaque) : 0) + Math.ceil(estimateTokens(visible.inlineText) * (args.proseRatio ?? 1));
|
|
6049
|
-
}
|
|
6050
|
-
})), args.budget);
|
|
6051
|
-
}
|
|
6052
|
-
|
|
6053
5265
|
// src/hooks/magic-context/compartment-trigger.ts
|
|
6054
5266
|
var PROACTIVE_TRIGGER_OFFSET_PERCENTAGE = 2;
|
|
6055
5267
|
var POST_DROP_TARGET_RATIO = 0.75;
|
|
@@ -6595,7 +5807,7 @@ function createChatMessageHook(args) {
|
|
|
6595
5807
|
sessionLog2(sessionId, `variant changed (${previousVariant} -> ${input.variant}), triggering flush`);
|
|
6596
5808
|
args.historyRefreshSessions.add(sessionId);
|
|
6597
5809
|
args.systemPromptRefreshSessions.add(sessionId);
|
|
6598
|
-
args.pendingMaterializationSessions
|
|
5810
|
+
requestPendingMaterialization(args.pendingMaterializationSessions, sessionId, "variant_change");
|
|
6599
5811
|
args.lastHeuristicsTurnId.delete(sessionId);
|
|
6600
5812
|
} else {
|
|
6601
5813
|
sessionLog2(sessionId, `variant changed (${previousVariant} -> ${input.variant}) on ${providerID ?? "unknown"}/${modelID ?? "unknown"} without a proven natural cache bust; deferring flush to next natural bust`);
|
|
@@ -7668,14 +6880,14 @@ function foldExecutesThisPass(foldDue, materialized) {
|
|
|
7668
6880
|
}
|
|
7669
6881
|
|
|
7670
6882
|
// src/features/magic-context/storage-caveman-rules.ts
|
|
7671
|
-
var
|
|
6883
|
+
var NAMESPACE = "caveman";
|
|
7672
6884
|
var CURRENT_RULES_VERSION = 2;
|
|
7673
6885
|
var ORIGINAL_RULES = {
|
|
7674
6886
|
currentRules: false,
|
|
7675
6887
|
englishWordRules: true,
|
|
7676
6888
|
legacyReasoningTags: new Set
|
|
7677
6889
|
};
|
|
7678
|
-
function
|
|
6890
|
+
function parseState(lane) {
|
|
7679
6891
|
if (!isRecord(lane) || lane.rules !== CURRENT_RULES_VERSION)
|
|
7680
6892
|
return ORIGINAL_RULES;
|
|
7681
6893
|
const tags = Array.isArray(lane.legacyReasoningTags) ? lane.legacyReasoningTags : [];
|
|
@@ -7687,7 +6899,7 @@ function parseState2(lane) {
|
|
|
7687
6899
|
}
|
|
7688
6900
|
function getCavemanReplayState(db, sessionId) {
|
|
7689
6901
|
try {
|
|
7690
|
-
return
|
|
6902
|
+
return parseState(readReplayEnvelope(db, sessionId)[NAMESPACE]);
|
|
7691
6903
|
} catch (error) {
|
|
7692
6904
|
if (error instanceof ReplayDocumentError)
|
|
7693
6905
|
return ORIGINAL_RULES;
|
|
@@ -7697,11 +6909,11 @@ function getCavemanReplayState(db, sessionId) {
|
|
|
7697
6909
|
function recordCavemanCurrentRules(db, sessionId, englishWordRules, legacyReasoningTags) {
|
|
7698
6910
|
const tags = [...new Set(legacyReasoningTags)].sort((a, b) => a - b);
|
|
7699
6911
|
const persisted = updateReplayDocument(db, sessionId, (doc) => {
|
|
7700
|
-
const current =
|
|
6912
|
+
const current = parseState(doc[NAMESPACE]);
|
|
7701
6913
|
if (current.currentRules && current.englishWordRules === englishWordRules)
|
|
7702
6914
|
return false;
|
|
7703
6915
|
doc.version = 2;
|
|
7704
|
-
doc[
|
|
6916
|
+
doc[NAMESPACE] = {
|
|
7705
6917
|
rules: CURRENT_RULES_VERSION,
|
|
7706
6918
|
legacyReasoningTags: current.currentRules ? [...current.legacyReasoningTags].sort((a, b) => a - b) : tags,
|
|
7707
6919
|
...englishWordRules ? {} : { englishWordRules: false }
|
|
@@ -8956,7 +8168,7 @@ function tagMessages(sessionId, messages, tagger, db, options = {}) {
|
|
|
8956
8168
|
accAssignTag += performance.now() - _tAssignText;
|
|
8957
8169
|
const persistedSource = sourceContents.get(tagId);
|
|
8958
8170
|
if (persistedSource !== undefined) {
|
|
8959
|
-
textPart.text = persistedSource;
|
|
8171
|
+
textPart.text = options.normalizeRestoredAssistantText && message.info.role === "assistant" ? options.normalizeRestoredAssistantText(persistedSource) : persistedSource;
|
|
8960
8172
|
} else {
|
|
8961
8173
|
const sourceContent = stripTagPrefix(textPart.text);
|
|
8962
8174
|
if (sourceContent.trim().length > 0) {
|
|
@@ -9807,6 +9019,7 @@ async function runPostTransformPhase(args) {
|
|
|
9807
9019
|
}
|
|
9808
9020
|
const reasoningMutationExemptMessage = findLatestAssistantReasoningMutationExemptMessage(args.messages);
|
|
9809
9021
|
const pendingMaterializationAtPassStart = args.pendingMaterializationSessions.has(args.sessionId);
|
|
9022
|
+
const pendingOrigin = pendingMaterializationOrigin(args.pendingMaterializationSessions, args.sessionId);
|
|
9810
9023
|
const deferredMaterializationAtPassStart = args.deferredMaterializationSessions.has(args.sessionId);
|
|
9811
9024
|
let isExplicitFlush = pendingMaterializationAtPassStart;
|
|
9812
9025
|
const deferredMaterializationWasPending = deferredMaterializationAtPassStart;
|
|
@@ -9992,6 +9205,11 @@ async function runPostTransformPhase(args) {
|
|
|
9992
9205
|
}
|
|
9993
9206
|
sessionLog2(args.sessionId, `m[0] HARD fold decision: reason=${m0MaterializeReason ?? foldDueDecision.reason ?? (foldExecutedThisPass ? "drift" : "soft_refresh")} executed=${foldExecutedThisPass} bustsServedPrefix=${foldBustsServedPrefixThisPass}`);
|
|
9994
9207
|
}
|
|
9208
|
+
if (args.normalizeRecoveryTail && (foldBustsServedPrefixThisPass || firstRenderBust)) {
|
|
9209
|
+
args.normalizeRecoveryTail();
|
|
9210
|
+
args.tags = getTagsBySession2(args.db, args.sessionId);
|
|
9211
|
+
newTargets = protectNewTagMutations(args.messages, args.targets, retainedThinking, args.thinkingBindingRecoveryEnabledForModel === true);
|
|
9212
|
+
}
|
|
9995
9213
|
logTransformTiming(args.sessionId, "pp.prefixPreflight", tPostprocessSetup, `foldExecuted=${foldExecutedThisPass} m1Refreshed=${publishedM1RefreshedThisPass}`);
|
|
9996
9214
|
const tPassDecisions = performance.now();
|
|
9997
9215
|
const frontToolCandidates = args.tags.filter((tag) => tag.type === "tool" && tag.status === "active" && args.targets.get(tag.tagNumber)?.canDrop?.());
|
|
@@ -10007,7 +9225,7 @@ async function runPostTransformPhase(args) {
|
|
|
10007
9225
|
const pendingOps = shouldReadPendingOps ? getPendingOps(args.db, args.sessionId) : [];
|
|
10008
9226
|
const hasPendingUserOps = pendingOps.length > 0;
|
|
10009
9227
|
if (args.schedulerDecision === "execute" && pendingOps.some((op) => newTargets.get(op.tagId)?.thinkingDropProtected))
|
|
10010
|
-
args.pendingMaterializationSessions
|
|
9228
|
+
requestPendingMaterialization(args.pendingMaterializationSessions, args.sessionId, "thinking_hold");
|
|
10011
9229
|
const formatPendingOpsDepth = () => {
|
|
10012
9230
|
const depth = getPendingOpsCount(args.db, args.sessionId);
|
|
10013
9231
|
return depth === null ? "not loaded (deferred pass)" : String(depth);
|
|
@@ -10098,7 +9316,7 @@ async function runPostTransformPhase(args) {
|
|
|
10098
9316
|
}
|
|
10099
9317
|
if (shouldRunHeuristics) {
|
|
10100
9318
|
const subagentRerun = !args.fullFeatureMode && alreadyRanThisTurn && args.schedulerDecision === "execute" && !isExplicitFlush && !forceMaterialization;
|
|
10101
|
-
const reason = isExplicitFlush ?
|
|
9319
|
+
const reason = isExplicitFlush ? `pending_materialization origin=${pendingOrigin}` : deferredMaterialize ? "deferred_materialization" : forceMaterialization ? `force_materialization (${args.contextUsage.percentage.toFixed(1)}% >= ${args.forceMaterializationPercentage}%)` : foldBustsServedPrefixThisPass && args.schedulerDecision !== "execute" ? `m0_hard_fold (drain folded into executed m[0] bust, scheduler=${args.schedulerDecision})` : subagentRerun ? `${reclaimRideLabel(rideSignals)} subagent_rerun (pendingOps=${pendingOps.length}, scheduler=${args.schedulerDecision})` : `${reclaimRideLabel(rideSignals)} (pendingOps=${pendingOps.length}, scheduler=${args.schedulerDecision})`;
|
|
10102
9320
|
sessionLog2(args.sessionId, `heuristics WILL RUN — reason=${reason}, context=${args.contextUsage.percentage.toFixed(1)}%, turn=${args.currentTurnId}`);
|
|
10103
9321
|
} else if (args.schedulerDeferReason !== undefined && args.schedulerDeferReason !== null) {
|
|
10104
9322
|
sessionLog2(args.sessionId, `heuristics WILL NOT RUN — reason=${args.schedulerDeferReason}`);
|
|
@@ -10161,7 +9379,7 @@ async function runPostTransformPhase(args) {
|
|
|
10161
9379
|
logTransformTiming(args.sessionId, "pp.passDecisions", tPassDecisions, `pendingOps=${pendingOps.length}`);
|
|
10162
9380
|
try {
|
|
10163
9381
|
if (shouldApplyPendingOps) {
|
|
10164
|
-
const applyReason = isExplicitFlush ?
|
|
9382
|
+
const applyReason = isExplicitFlush ? `pending_materialization origin=${pendingOrigin}` : deferredMaterialize ? "deferred_materialization" : foldBustsServedPrefixThisPass && args.schedulerDecision !== "execute" ? `m0_hard_fold (drain folded into executed m[0] bust, scheduler=${args.schedulerDecision})` : `${reclaimRideLabel(rideSignals)} (scheduler=${args.schedulerDecision})`;
|
|
10165
9383
|
sessionLog2(args.sessionId, `pending ops WILL APPLY — reason=${applyReason}, pendingOps=${formatPendingOpsDepth()}, context=${args.contextUsage.percentage.toFixed(1)}%`);
|
|
10166
9384
|
const tApply = performance.now();
|
|
10167
9385
|
pendingOpsDidMutate = applyPendingOperations(args.sessionId, args.db, newTargets, new Set([
|
|
@@ -10326,7 +9544,7 @@ async function runPostTransformPhase(args) {
|
|
|
10326
9544
|
heuristicOrReasoningEditBesidesTrim = heuristicMutationCount + clearedReasoning + strippedInline > 0;
|
|
10327
9545
|
droppedCount += clearedReasoning + strippedInline + removedReasoningMessages;
|
|
10328
9546
|
if (pendingMaterializationAtPassStart && !freezeM0M1 && !pendingOps.some((op) => newTargets.get(op.tagId)?.thinkingDropProtected)) {
|
|
10329
|
-
args.pendingMaterializationSessions
|
|
9547
|
+
clearPendingMaterialization(args.pendingMaterializationSessions, args.sessionId);
|
|
10330
9548
|
}
|
|
10331
9549
|
if (args.currentTurnId) {
|
|
10332
9550
|
args.lastHeuristicsTurnId.set(args.sessionId, args.currentTurnId);
|
|
@@ -10459,15 +9677,13 @@ async function runPostTransformPhase(args) {
|
|
|
10459
9677
|
try {
|
|
10460
9678
|
const tImg = performance.now();
|
|
10461
9679
|
const frozenImageIds = replaySnapshot.processedImageStrippedIds;
|
|
10462
|
-
|
|
9680
|
+
stripProcessedImages(args.messages, frozenImageIds, {
|
|
10463
9681
|
detect: canEditWholePrefix && args.watermark > 0,
|
|
10464
9682
|
watermark: args.watermark,
|
|
10465
9683
|
messageTagNumbers: args.messageTagNumbers,
|
|
9684
|
+
persistNewIds: (ids) => addProcessedImageStrippedIds(args.db, args.sessionId, ids),
|
|
10466
9685
|
onFirstApplication: recordFirstApplicationAt
|
|
10467
9686
|
});
|
|
10468
|
-
if (isCacheBustingPass && imageResult.newlyStrippedIds.length > 0) {
|
|
10469
|
-
addProcessedImageStrippedIds(args.db, args.sessionId, imageResult.newlyStrippedIds);
|
|
10470
|
-
}
|
|
10471
9687
|
logTransformTiming(args.sessionId, "stripProcessedImages", tImg);
|
|
10472
9688
|
} catch (error) {
|
|
10473
9689
|
failPass("image-strip-exception", error);
|
|
@@ -10784,7 +10000,7 @@ async function runPostTransformPhase(args) {
|
|
|
10784
10000
|
sessionLog2(args.sessionId, `sticky-injection GC: pruned ${prunedAnchors} note-nudge anchor(s)`);
|
|
10785
10001
|
}
|
|
10786
10002
|
}
|
|
10787
|
-
const materializeReason = m0MaterializeReason ?? (explicitMaterializedSuccessfully ?
|
|
10003
|
+
const materializeReason = m0MaterializeReason ?? (explicitMaterializedSuccessfully ? pendingOrigin : null);
|
|
10788
10004
|
const materialized = m0RematerializedThisPass || explicitMaterializedSuccessfully || deferredMaterializedSuccessfully;
|
|
10789
10005
|
let bustedThisPass = firstApplicationEdits.any || firstRenderBust || pendingOpsDidMutate || heuristicOrReasoningDidMutate || autoReclaimDidMutateThisPass || convertedToolSkeletonsDidMutate || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass;
|
|
10790
10006
|
const proactiveThinkingStripPermitted = isCacheBustingPass && !activeThinkingPrefixHold;
|
|
@@ -11170,7 +10386,7 @@ function checkM0MutationDriftAndSignal(args) {
|
|
|
11170
10386
|
const currentMaxMutationId = getMaxM0MutationId(args.db, args.sessionId) ?? 0;
|
|
11171
10387
|
const cachedMaxMutationId = args.cachedM0MaxMutationId ?? 0;
|
|
11172
10388
|
if (currentMaxMutationId !== cachedMaxMutationId) {
|
|
11173
|
-
args.pendingMaterializationSessions
|
|
10389
|
+
requestPendingMaterialization(args.pendingMaterializationSessions, args.sessionId, "mutation_drift");
|
|
11174
10390
|
args.historyRefreshSessions?.add(args.sessionId);
|
|
11175
10391
|
sessionLog2(args.sessionId, `m[0] drift watcher: mutation id changed ${cachedMaxMutationId} → ${currentMaxMutationId}; scheduling next-pass materialization`);
|
|
11176
10392
|
return true;
|
|
@@ -11228,6 +10444,160 @@ class StorageBusyRefusalError extends Error {
|
|
|
11228
10444
|
|
|
11229
10445
|
// src/hooks/magic-context/system-prompt-hash.ts
|
|
11230
10446
|
import { createHash } from "node:crypto";
|
|
10447
|
+
|
|
10448
|
+
// src/hooks/magic-context/system-prompt-dates.ts
|
|
10449
|
+
function replaceHostDates(prompt, replace) {
|
|
10450
|
+
const fields = /<(plugin-env|environment|env)>[\s\S]*?<\/\1>|Today's date: [^\r\n<]+/g;
|
|
10451
|
+
return prompt.replace(fields, (block) => block.replace(/(^[\t ]*(?:Date|Today's date):[\t ]*)([^\r\n<]+)/gm, (_line, label, date) => `${label}${replace(date)}`));
|
|
10452
|
+
}
|
|
10453
|
+
function systemPromptDates(prompt, sticky) {
|
|
10454
|
+
const values = [];
|
|
10455
|
+
replaceHostDates(prompt, (date) => {
|
|
10456
|
+
values.push(date);
|
|
10457
|
+
return date;
|
|
10458
|
+
});
|
|
10459
|
+
const prior = sticky ? JSON.parse(sticky) : [];
|
|
10460
|
+
let index = 0;
|
|
10461
|
+
const stable = replaceHostDates(prompt, (date) => prior[index++] ?? date);
|
|
10462
|
+
return { live: values.length ? JSON.stringify(values) : undefined, stable };
|
|
10463
|
+
}
|
|
10464
|
+
|
|
10465
|
+
// src/hooks/magic-context/system-date-refresh.ts
|
|
10466
|
+
var channels = new WeakMap;
|
|
10467
|
+
var outputUpdates = new WeakMap;
|
|
10468
|
+
var outputIdentities = new WeakMap;
|
|
10469
|
+
var outputRequests = new WeakMap;
|
|
10470
|
+
function systemDateTurnId(messages) {
|
|
10471
|
+
const start = activeAnthropicTurnStart(messages, true);
|
|
10472
|
+
if (start === undefined)
|
|
10473
|
+
return;
|
|
10474
|
+
const message = messages[start - 1];
|
|
10475
|
+
const id = message.info?.id ?? message.id;
|
|
10476
|
+
return typeof id === "string" && id.length > 0 ? id : undefined;
|
|
10477
|
+
}
|
|
10478
|
+
function bindSystemDateRequestIdentity(output, identity) {
|
|
10479
|
+
outputIdentities.set(output, identity);
|
|
10480
|
+
}
|
|
10481
|
+
function systemDateRequestIdentity(output) {
|
|
10482
|
+
return outputIdentities.get(output);
|
|
10483
|
+
}
|
|
10484
|
+
function bindSystemDateRequest(output, request) {
|
|
10485
|
+
if (request)
|
|
10486
|
+
outputRequests.set(output, request);
|
|
10487
|
+
}
|
|
10488
|
+
function systemDateRequestForOutput(history, output) {
|
|
10489
|
+
const request = outputRequests.get(output);
|
|
10490
|
+
return state(history, request);
|
|
10491
|
+
}
|
|
10492
|
+
function bindSystemDateOutput(system, update) {
|
|
10493
|
+
outputUpdates.set(system, update);
|
|
10494
|
+
}
|
|
10495
|
+
function publishSystemDateOutput(system) {
|
|
10496
|
+
outputUpdates.get(system)?.();
|
|
10497
|
+
outputUpdates.delete(system);
|
|
10498
|
+
}
|
|
10499
|
+
function registerSystemDateRefresh(history) {
|
|
10500
|
+
if (!channels.has(history))
|
|
10501
|
+
channels.set(history, new Map);
|
|
10502
|
+
}
|
|
10503
|
+
function hasSystemDateRefresh(history) {
|
|
10504
|
+
return channels.has(history);
|
|
10505
|
+
}
|
|
10506
|
+
function beginSystemDateRequest(history, sessionId, stage, turnId, identity) {
|
|
10507
|
+
const channel = channels.get(history);
|
|
10508
|
+
if (!channel)
|
|
10509
|
+
return;
|
|
10510
|
+
let requests = channel.get(sessionId);
|
|
10511
|
+
if (!requests)
|
|
10512
|
+
channel.set(sessionId, requests = new Map);
|
|
10513
|
+
let request = identity === undefined ? undefined : requests.get(identity);
|
|
10514
|
+
if (identity === undefined) {
|
|
10515
|
+
const candidates = [...requests.values()].filter((candidate) => !candidate.explicit && !(candidate.systemSeen && candidate.messagesSeen) && (stage === "system-after-messages" || candidate.turnId === turnId));
|
|
10516
|
+
const matching = candidates.filter((candidate) => !candidate.ambiguous && (stage === "messages" ? candidate.systemSeen && !candidate.messagesSeen : candidate.messagesSeen && !candidate.systemSeen));
|
|
10517
|
+
if (turnId !== undefined && candidates.length === 1 && matching.length === 1) {
|
|
10518
|
+
request = matching[0];
|
|
10519
|
+
} else if (candidates.length > 0) {
|
|
10520
|
+
for (const candidate of candidates)
|
|
10521
|
+
candidate.ambiguous = true;
|
|
10522
|
+
}
|
|
10523
|
+
}
|
|
10524
|
+
if (!request) {
|
|
10525
|
+
const sameTurn = [...requests.values()].some((candidate) => !candidate.explicit && !(candidate.systemSeen && candidate.messagesSeen) && (stage === "system-after-messages" || candidate.turnId === turnId));
|
|
10526
|
+
request = {
|
|
10527
|
+
sessionId,
|
|
10528
|
+
identity: identity ?? {},
|
|
10529
|
+
turnId,
|
|
10530
|
+
explicit: identity !== undefined,
|
|
10531
|
+
systemSeen: false,
|
|
10532
|
+
systemDone: false,
|
|
10533
|
+
messagesSeen: false,
|
|
10534
|
+
permitted: undefined,
|
|
10535
|
+
ambiguous: identity === undefined && (turnId === undefined || sameTurn)
|
|
10536
|
+
};
|
|
10537
|
+
const blocked = [...requests.values()].filter((candidate) => !candidate.explicit && candidate.ambiguous && !(candidate.systemSeen && candidate.messagesSeen) && candidate.turnId === turnId).length;
|
|
10538
|
+
if (request.explicit || !request.ambiguous || blocked < 2)
|
|
10539
|
+
requests.set(request.identity, request);
|
|
10540
|
+
}
|
|
10541
|
+
if (stage === "messages")
|
|
10542
|
+
request.messagesSeen = true;
|
|
10543
|
+
else
|
|
10544
|
+
request.systemSeen = true;
|
|
10545
|
+
return request;
|
|
10546
|
+
}
|
|
10547
|
+
function state(history, request) {
|
|
10548
|
+
if (!request)
|
|
10549
|
+
return;
|
|
10550
|
+
const current = channels.get(history)?.get(request.sessionId)?.get(request.identity);
|
|
10551
|
+
return current === request ? current : undefined;
|
|
10552
|
+
}
|
|
10553
|
+
function systemDateRefreshPermission(history, request) {
|
|
10554
|
+
const current = state(history, request);
|
|
10555
|
+
return current?.ambiguous ? undefined : current?.permitted;
|
|
10556
|
+
}
|
|
10557
|
+
function waitForSystemDateRefresh(history, request, apply) {
|
|
10558
|
+
const current = state(history, request);
|
|
10559
|
+
if (!current)
|
|
10560
|
+
return false;
|
|
10561
|
+
current.waiting = apply;
|
|
10562
|
+
return true;
|
|
10563
|
+
}
|
|
10564
|
+
function retire(history, current) {
|
|
10565
|
+
const unpairable = !current.explicit && current.turnId === undefined;
|
|
10566
|
+
if (!unpairable && (!current.systemDone || current.permitted === undefined))
|
|
10567
|
+
return;
|
|
10568
|
+
if (unpairable) {
|
|
10569
|
+
const apply = current.waiting;
|
|
10570
|
+
current.waiting = undefined;
|
|
10571
|
+
apply?.(false);
|
|
10572
|
+
}
|
|
10573
|
+
const channel = channels.get(history);
|
|
10574
|
+
const requests = channel?.get(current.sessionId);
|
|
10575
|
+
requests?.delete(current.identity);
|
|
10576
|
+
if (requests?.size === 0)
|
|
10577
|
+
channel?.delete(current.sessionId);
|
|
10578
|
+
}
|
|
10579
|
+
function finishSystemDateRefresh(history, request, permitted) {
|
|
10580
|
+
const current = state(history, request);
|
|
10581
|
+
if (!current)
|
|
10582
|
+
return;
|
|
10583
|
+
current.permitted = current.ambiguous ? false : permitted;
|
|
10584
|
+
const apply = current.waiting;
|
|
10585
|
+
current.waiting = undefined;
|
|
10586
|
+
apply?.(current.permitted);
|
|
10587
|
+
retire(history, current);
|
|
10588
|
+
}
|
|
10589
|
+
function finishSystemDateHook(history, request) {
|
|
10590
|
+
const current = state(history, request);
|
|
10591
|
+
if (!current)
|
|
10592
|
+
return;
|
|
10593
|
+
current.systemDone = true;
|
|
10594
|
+
retire(history, current);
|
|
10595
|
+
}
|
|
10596
|
+
function clearSystemDateRefresh(history, sessionId) {
|
|
10597
|
+
channels.get(history)?.delete(sessionId);
|
|
10598
|
+
}
|
|
10599
|
+
|
|
10600
|
+
// src/hooks/magic-context/system-prompt-hash.ts
|
|
11231
10601
|
var MAGIC_CONTEXT_MARKER = "## Magic Context";
|
|
11232
10602
|
var SYSTEM_PROMPT_GUIDANCE_SEPARATOR = `
|
|
11233
10603
|
|
|
@@ -11249,7 +10619,7 @@ function createSystemPromptHashHandler(deps) {
|
|
|
11249
10619
|
});
|
|
11250
10620
|
const guidanceEpochs = createPromptSurfaceGuidanceEpochCache(promptSurfaceRuntime);
|
|
11251
10621
|
const stickyDateBySession = new Map;
|
|
11252
|
-
const
|
|
10622
|
+
const processSystemPrompt = async (input, output) => {
|
|
11253
10623
|
const sessionId = input.sessionID;
|
|
11254
10624
|
if (!sessionId)
|
|
11255
10625
|
return;
|
|
@@ -11273,7 +10643,10 @@ function createSystemPromptHashHandler(deps) {
|
|
|
11273
10643
|
sessionLog2(sessionId, "system-prompt-hash skipped (matched system_prompt_injection.skip_signatures)");
|
|
11274
10644
|
return;
|
|
11275
10645
|
}
|
|
11276
|
-
const
|
|
10646
|
+
const messagesPrepared = deps.consumeMessagesPrepared?.(sessionId) ?? false;
|
|
10647
|
+
const dateRequest = beginSystemDateRequest(deps.historyRefreshSessions, sessionId, messagesPrepared ? "system-after-messages" : "system", input.dateRefreshRequest === undefined && hasSystemDateRefresh(deps.historyRefreshSessions) ? (deps.resolveDateTurnId ?? latestRealUserTurnIdFromOpenCodeDb)(sessionId) : undefined, input.dateRefreshRequest);
|
|
10648
|
+
bindSystemDateRequest(output, dateRequest);
|
|
10649
|
+
const requestMessagesFinal = messagesPrepared || systemDateRefreshPermission(deps.historyRefreshSessions, dateRequest) !== undefined;
|
|
11277
10650
|
let sessionMetaEarly;
|
|
11278
10651
|
try {
|
|
11279
10652
|
sessionMetaEarly = getOrCreateSessionMeta(deps.db, sessionId);
|
|
@@ -11305,9 +10678,7 @@ function createSystemPromptHashHandler(deps) {
|
|
|
11305
10678
|
}
|
|
11306
10679
|
const isCacheBusting = deps.systemPromptRefreshSessions.has(sessionId);
|
|
11307
10680
|
const idleCacheExpired = sessionMetaEarly !== undefined && computeHardCacheExpired(sessionMetaEarly.cacheTtl, sessionMetaEarly.lastResponseTime, Date.now());
|
|
11308
|
-
const adoptSystemChange = idleCacheExpired || requestMessagesFinal;
|
|
11309
|
-
const DATE_PATTERN = /Today's date: .+/;
|
|
11310
|
-
const DATE_PATTERN_ALL = /Today's date: .+/g;
|
|
10681
|
+
const adoptSystemChange = idleCacheExpired || requestMessagesFinal && !isHeldHeadForRequest(sessionId, currentLkgRequestIdentity(sessionId));
|
|
11311
10682
|
const liveSystemContent = output.system.join(`
|
|
11312
10683
|
`);
|
|
11313
10684
|
if (liveSystemContent.length === 0)
|
|
@@ -11316,29 +10687,56 @@ function createSystemPromptHashHandler(deps) {
|
|
|
11316
10687
|
const hasPersistedHash = previousHash !== "" && previousHash !== "0";
|
|
11317
10688
|
if (!hasPersistedHash)
|
|
11318
10689
|
stickyDateBySession.delete(sessionId);
|
|
11319
|
-
const dateElementIndexes = [];
|
|
11320
|
-
let currentDate;
|
|
11321
|
-
for (let i = 0;i < output.system.length; i++) {
|
|
11322
|
-
const match = output.system[i].match(DATE_PATTERN);
|
|
11323
|
-
if (!match)
|
|
11324
|
-
continue;
|
|
11325
|
-
dateElementIndexes.push(i);
|
|
11326
|
-
currentDate ??= match[0];
|
|
11327
|
-
}
|
|
11328
10690
|
const stickyDate = stickyDateBySession.get(sessionId);
|
|
11329
|
-
const
|
|
10691
|
+
const dates = systemPromptDates(liveSystemContent, stickyDate);
|
|
10692
|
+
const currentDate = dates.live;
|
|
10693
|
+
const stableCandidate = dates.stable;
|
|
11330
10694
|
const stableCandidateHash = createHash("md5").update(promptSurfaceHashMaterial(stableCandidate, promptSurface.preset)).digest("hex");
|
|
11331
10695
|
const contentOrPresetChanged = hasPersistedHash && stableCandidateHash !== previousHash;
|
|
11332
|
-
const
|
|
10696
|
+
const rewritePermission = systemDateRefreshPermission(deps.historyRefreshSessions, dateRequest);
|
|
10697
|
+
let deferredDateRefresh = false;
|
|
10698
|
+
if (currentDate && stickyDate && currentDate !== stickyDate && isCacheBusting && !idleCacheExpired && !contentOrPresetChanged && !requestMessagesFinal) {
|
|
10699
|
+
const liveElements = [...output.system];
|
|
10700
|
+
deferredDateRefresh = waitForSystemDateRefresh(deps.historyRefreshSessions, dateRequest, (permitted) => {
|
|
10701
|
+
if (!permitted) {
|
|
10702
|
+
deps.systemPromptRefreshSessions.add(sessionId);
|
|
10703
|
+
return;
|
|
10704
|
+
}
|
|
10705
|
+
try {
|
|
10706
|
+
const content = liveElements.join(`
|
|
10707
|
+
`);
|
|
10708
|
+
const hash = createHash("md5").update(promptSurfaceHashMaterial(content, promptSurface.preset)).digest("hex");
|
|
10709
|
+
updateSessionMeta(deps.db, sessionId, {
|
|
10710
|
+
systemPromptHash: hash,
|
|
10711
|
+
cachedM0SystemHash: hash,
|
|
10712
|
+
systemPromptTokens: estimateTokens(content)
|
|
10713
|
+
});
|
|
10714
|
+
stickyDateBySession.set(sessionId, currentDate);
|
|
10715
|
+
output.system.splice(0, output.system.length, ...liveElements);
|
|
10716
|
+
publishSystemDateOutput(output.system);
|
|
10717
|
+
deps.systemPromptRefreshSessions.delete(sessionId);
|
|
10718
|
+
sessionLog2(sessionId, `system prompt date updated after prefix rewrite: ${stickyDate} → ${currentDate}`);
|
|
10719
|
+
} catch (error) {
|
|
10720
|
+
deps.systemPromptRefreshSessions.add(sessionId);
|
|
10721
|
+
sessionLog2(sessionId, "system prompt date refresh failed (keeping frozen date):", error);
|
|
10722
|
+
}
|
|
10723
|
+
});
|
|
10724
|
+
}
|
|
10725
|
+
const dateMayAdvance = idleCacheExpired || contentOrPresetChanged || isCacheBusting && !deferredDateRefresh && (dateRequest ? rewritePermission === true : rewritePermission !== false);
|
|
11333
10726
|
if (currentDate && !stickyDate) {
|
|
11334
10727
|
stickyDateBySession.set(sessionId, currentDate);
|
|
11335
10728
|
} else if (currentDate && stickyDate && currentDate !== stickyDate) {
|
|
11336
10729
|
if (dateMayAdvance) {
|
|
11337
10730
|
stickyDateBySession.set(sessionId, currentDate);
|
|
11338
10731
|
sessionLog2(sessionId, `system prompt date updated: ${stickyDate} → ${currentDate} (cache-busting pass)`);
|
|
11339
|
-
} else
|
|
11340
|
-
|
|
11341
|
-
|
|
10732
|
+
} else {
|
|
10733
|
+
let offset = 0;
|
|
10734
|
+
const prior = JSON.parse(stickyDate);
|
|
10735
|
+
for (let index = 0;index < output.system.length; index++) {
|
|
10736
|
+
const element = systemPromptDates(output.system[index]);
|
|
10737
|
+
const count = element.live ? JSON.parse(element.live).length : 0;
|
|
10738
|
+
output.system[index] = systemPromptDates(output.system[index], JSON.stringify(prior.slice(offset, offset + count))).stable;
|
|
10739
|
+
offset += count;
|
|
11342
10740
|
}
|
|
11343
10741
|
sessionLog2(sessionId, `system prompt date frozen: real=${currentDate}, using=${stickyDate} (defer pass)`);
|
|
11344
10742
|
}
|
|
@@ -11348,6 +10746,7 @@ function createSystemPromptHashHandler(deps) {
|
|
|
11348
10746
|
if (!availability.frozen || !modelKey)
|
|
11349
10747
|
return;
|
|
11350
10748
|
const currentHash = createHash("md5").update(promptSurfaceHashMaterial(systemContent, promptSurface.preset)).digest("hex");
|
|
10749
|
+
recordSystemPromptForRequest(sessionId, currentLkgRequestIdentity(sessionId), currentHash, deps.db, previousHash !== currentHash ? !deps.historyRefreshSessions.has(sessionId) : undefined, deps.historyRefreshSessions, deps.pendingMaterializationSessions);
|
|
11351
10750
|
if (!sessionMetaEarly) {
|
|
11352
10751
|
return;
|
|
11353
10752
|
}
|
|
@@ -11357,7 +10756,9 @@ function createSystemPromptHashHandler(deps) {
|
|
|
11357
10756
|
if (!adoptSystemChange) {
|
|
11358
10757
|
deps.historyRefreshSessions.add(sessionId);
|
|
11359
10758
|
deps.systemPromptRefreshSessions.add(sessionId);
|
|
11360
|
-
deps.pendingMaterializationSessions.
|
|
10759
|
+
if (!deps.pendingMaterializationSessions.has(sessionId)) {
|
|
10760
|
+
requestPendingMaterialization(deps.pendingMaterializationSessions, sessionId, "system_hash");
|
|
10761
|
+
}
|
|
11361
10762
|
deps.lastHeuristicsTurnId.delete(sessionId);
|
|
11362
10763
|
}
|
|
11363
10764
|
} else if (previousHash === "" || previousHash === "0") {
|
|
@@ -11380,13 +10781,21 @@ function createSystemPromptHashHandler(deps) {
|
|
|
11380
10781
|
sessionLog2(sessionId, "system prompt meta persist failed (fail-open):", error);
|
|
11381
10782
|
}
|
|
11382
10783
|
}
|
|
11383
|
-
if (isCacheBusting) {
|
|
10784
|
+
if (isCacheBusting && !deferredDateRefresh && (contentOrPresetChanged || !currentDate || currentDate === stickyDate || !dateRequest || rewritePermission === true)) {
|
|
11384
10785
|
deps.systemPromptRefreshSessions.delete(sessionId);
|
|
11385
10786
|
}
|
|
11386
10787
|
};
|
|
10788
|
+
const handler = async (input, output) => {
|
|
10789
|
+
try {
|
|
10790
|
+
await processSystemPrompt(input, output);
|
|
10791
|
+
} finally {
|
|
10792
|
+
finishSystemDateHook(deps.historyRefreshSessions, systemDateRequestForOutput(deps.historyRefreshSessions, output));
|
|
10793
|
+
}
|
|
10794
|
+
};
|
|
11387
10795
|
return {
|
|
11388
10796
|
handler,
|
|
11389
10797
|
clearSession: (sessionId) => {
|
|
10798
|
+
clearSystemDateRefresh(deps.historyRefreshSessions, sessionId);
|
|
11390
10799
|
guidanceEpochs.clear(sessionId);
|
|
11391
10800
|
clearSystemPromptHashSession(sessionId, {
|
|
11392
10801
|
stickyDateBySession,
|
|
@@ -11403,6 +10812,15 @@ var canonicalReasons = new Set([
|
|
|
11403
10812
|
"project_memory_epoch",
|
|
11404
10813
|
"ttl_idle",
|
|
11405
10814
|
"explicit_flush",
|
|
10815
|
+
"user_flush",
|
|
10816
|
+
"fit_retry",
|
|
10817
|
+
"pending_materialization",
|
|
10818
|
+
"variant_change",
|
|
10819
|
+
"recomp",
|
|
10820
|
+
"boundary_repair",
|
|
10821
|
+
"host_history_change",
|
|
10822
|
+
"thinking_hold",
|
|
10823
|
+
"mutation_drift",
|
|
11406
10824
|
"max_mutation_id",
|
|
11407
10825
|
"first_render",
|
|
11408
10826
|
"pressure_refold",
|
|
@@ -11629,911 +11047,6 @@ function commitCompactionModeRecord(db, sessionId, record) {
|
|
|
11629
11047
|
setCompactionModeRecord(db, sessionId, record);
|
|
11630
11048
|
}
|
|
11631
11049
|
|
|
11632
|
-
// src/hooks/magic-context/lkg-persist.ts
|
|
11633
|
-
import { createHash as createHash2 } from "node:crypto";
|
|
11634
|
-
function parseStringArray(value) {
|
|
11635
|
-
if (typeof value !== "string")
|
|
11636
|
-
return null;
|
|
11637
|
-
let parsed;
|
|
11638
|
-
try {
|
|
11639
|
-
parsed = JSON.parse(value);
|
|
11640
|
-
} catch {
|
|
11641
|
-
return null;
|
|
11642
|
-
}
|
|
11643
|
-
if (!Array.isArray(parsed))
|
|
11644
|
-
return null;
|
|
11645
|
-
const result = [];
|
|
11646
|
-
for (const entry of parsed) {
|
|
11647
|
-
if (typeof entry !== "string" || entry.length === 0)
|
|
11648
|
-
return null;
|
|
11649
|
-
result.push(entry);
|
|
11650
|
-
}
|
|
11651
|
-
return result;
|
|
11652
|
-
}
|
|
11653
|
-
function parseNullableString(value) {
|
|
11654
|
-
if (value === null || value === undefined)
|
|
11655
|
-
return null;
|
|
11656
|
-
return typeof value === "string" ? value : undefined;
|
|
11657
|
-
}
|
|
11658
|
-
function parseNullableInteger(value) {
|
|
11659
|
-
if (value === null || value === undefined)
|
|
11660
|
-
return;
|
|
11661
|
-
return typeof value === "number" && Number.isSafeInteger(value) ? value : undefined;
|
|
11662
|
-
}
|
|
11663
|
-
function parsePersistedLkgSlot(row) {
|
|
11664
|
-
if (!row || typeof row !== "object")
|
|
11665
|
-
return;
|
|
11666
|
-
const record = row;
|
|
11667
|
-
const jsonPrefix = record.json_prefix;
|
|
11668
|
-
const lastInputMessageId = record.last_input_message_id;
|
|
11669
|
-
const capturedAt = record.captured_at;
|
|
11670
|
-
let inputIdsRaw = record.input_id_seq;
|
|
11671
|
-
let piOutputEntryIds;
|
|
11672
|
-
if (typeof inputIdsRaw === "string") {
|
|
11673
|
-
try {
|
|
11674
|
-
const metadata = JSON.parse(inputIdsRaw);
|
|
11675
|
-
if (metadata && !Array.isArray(metadata) && metadata.version === 1 && Array.isArray(metadata.piOutputEntryIds)) {
|
|
11676
|
-
if (!metadata.piOutputEntryIds.every((id) => id === null || typeof id === "string" && id.length > 0))
|
|
11677
|
-
return;
|
|
11678
|
-
piOutputEntryIds = metadata.piOutputEntryIds;
|
|
11679
|
-
inputIdsRaw = JSON.stringify(metadata.inputIds);
|
|
11680
|
-
}
|
|
11681
|
-
} catch {
|
|
11682
|
-
return;
|
|
11683
|
-
}
|
|
11684
|
-
}
|
|
11685
|
-
const inputIdSeq = parseStringArray(inputIdsRaw);
|
|
11686
|
-
const inputContentDigests = parseStringArray(record.input_content_digests);
|
|
11687
|
-
const modelKey = parseNullableString(record.model_key);
|
|
11688
|
-
const providerKey = parseNullableString(record.provider_key);
|
|
11689
|
-
if (typeof jsonPrefix !== "string" || typeof lastInputMessageId !== "string" || lastInputMessageId.length === 0 || typeof capturedAt !== "number" || !Number.isFinite(capturedAt) || inputIdSeq === null || inputContentDigests === null || inputContentDigests.length !== inputIdSeq.length || modelKey === undefined || providerKey === undefined) {
|
|
11690
|
-
return;
|
|
11691
|
-
}
|
|
11692
|
-
if (piOutputEntryIds) {
|
|
11693
|
-
try {
|
|
11694
|
-
const output = JSON.parse(jsonPrefix);
|
|
11695
|
-
const inputs = new Set(inputIdSeq);
|
|
11696
|
-
if (!Array.isArray(output) || output.length !== piOutputEntryIds.length || piOutputEntryIds.some((id) => id !== null && !inputs.has(id)))
|
|
11697
|
-
return;
|
|
11698
|
-
} catch {
|
|
11699
|
-
return;
|
|
11700
|
-
}
|
|
11701
|
-
}
|
|
11702
|
-
let inputContentSignatures;
|
|
11703
|
-
if (record.input_content_signatures !== null && record.input_content_signatures !== undefined) {
|
|
11704
|
-
const parsed = parseStringArray(record.input_content_signatures);
|
|
11705
|
-
if (parsed === null || parsed.length !== inputIdSeq.length)
|
|
11706
|
-
return;
|
|
11707
|
-
inputContentSignatures = parsed;
|
|
11708
|
-
}
|
|
11709
|
-
const slot = {
|
|
11710
|
-
jsonPrefix,
|
|
11711
|
-
inputIdSeq,
|
|
11712
|
-
inputContentDigests,
|
|
11713
|
-
lastInputMessageId,
|
|
11714
|
-
modelKey,
|
|
11715
|
-
providerKey,
|
|
11716
|
-
capturedAt
|
|
11717
|
-
};
|
|
11718
|
-
if (inputContentSignatures)
|
|
11719
|
-
slot.inputContentSignatures = inputContentSignatures;
|
|
11720
|
-
if (piOutputEntryIds)
|
|
11721
|
-
slot.piOutputEntryIds = piOutputEntryIds;
|
|
11722
|
-
const rowVersion = parseNullableInteger(record.row_version);
|
|
11723
|
-
if (rowVersion !== undefined)
|
|
11724
|
-
slot.rowVersion = rowVersion;
|
|
11725
|
-
const captureSequence = parseNullableInteger(record.capture_sequence);
|
|
11726
|
-
if (captureSequence !== undefined)
|
|
11727
|
-
slot.captureSequence = captureSequence;
|
|
11728
|
-
return slot;
|
|
11729
|
-
}
|
|
11730
|
-
var persistedFingerprints = new WeakMap;
|
|
11731
|
-
var PERSISTED_FINGERPRINT_MAX_SESSIONS = 1000;
|
|
11732
|
-
function rememberFingerprint(db, sessionId, fingerprint) {
|
|
11733
|
-
let saved = persistedFingerprints.get(db);
|
|
11734
|
-
if (!saved) {
|
|
11735
|
-
saved = new Map;
|
|
11736
|
-
persistedFingerprints.set(db, saved);
|
|
11737
|
-
}
|
|
11738
|
-
saved.delete(sessionId);
|
|
11739
|
-
if (saved.size >= PERSISTED_FINGERPRINT_MAX_SESSIONS) {
|
|
11740
|
-
const oldest = saved.keys().next().value;
|
|
11741
|
-
if (oldest !== undefined)
|
|
11742
|
-
saved.delete(oldest);
|
|
11743
|
-
}
|
|
11744
|
-
saved.set(sessionId, fingerprint);
|
|
11745
|
-
}
|
|
11746
|
-
function slotFingerprint(slot) {
|
|
11747
|
-
return createHash2("sha256").update(JSON.stringify([
|
|
11748
|
-
slot.jsonPrefix,
|
|
11749
|
-
slot.inputIdSeq,
|
|
11750
|
-
slot.inputContentDigests,
|
|
11751
|
-
slot.inputContentSignatures,
|
|
11752
|
-
slot.piOutputEntryIds,
|
|
11753
|
-
slot.lastInputMessageId,
|
|
11754
|
-
slot.modelKey,
|
|
11755
|
-
slot.providerKey,
|
|
11756
|
-
slot.rowVersion,
|
|
11757
|
-
slot.captureSequence
|
|
11758
|
-
])).digest("hex");
|
|
11759
|
-
}
|
|
11760
|
-
function saveLkgSlotToDb(db, sessionId, slot, publishMetadata) {
|
|
11761
|
-
const fingerprint = slotFingerprint(slot);
|
|
11762
|
-
if (!publishMetadata && persistedFingerprints.get(db)?.get(sessionId) === fingerprint)
|
|
11763
|
-
return true;
|
|
11764
|
-
const layout = layoutLkgPrefix(slot.jsonPrefix);
|
|
11765
|
-
try {
|
|
11766
|
-
db.transaction(() => {
|
|
11767
|
-
const storedHashes = new Map;
|
|
11768
|
-
for (const row of db.prepare("SELECT chunk, hash FROM lkg_slot_chunks WHERE session_id = ?").all(sessionId)) {
|
|
11769
|
-
storedHashes.set(row.chunk, row.hash);
|
|
11770
|
-
}
|
|
11771
|
-
const upsertChunk = db.prepare(`INSERT INTO lkg_slot_chunks (session_id, chunk, hash, body) VALUES (?, ?, ?, ?)
|
|
11772
|
-
ON CONFLICT(session_id, chunk) DO UPDATE SET hash = excluded.hash, body = excluded.body`);
|
|
11773
|
-
for (let index = 0;index < layout.chunks.length; index += 1) {
|
|
11774
|
-
if (storedHashes.get(index) === layout.chunkHashes[index])
|
|
11775
|
-
continue;
|
|
11776
|
-
upsertChunk.run(sessionId, index, layout.chunkHashes[index], layout.chunks[index]);
|
|
11777
|
-
}
|
|
11778
|
-
db.prepare("DELETE FROM lkg_slot_chunks WHERE session_id = ? AND chunk >= ?").run(sessionId, layout.chunks.length);
|
|
11779
|
-
db.prepare(`INSERT INTO lkg_slots (
|
|
11780
|
-
session_id, json_prefix_chars, json_prefix_chunks, json_prefix_hash,
|
|
11781
|
-
input_id_seq, input_content_digests, input_content_signatures,
|
|
11782
|
-
last_input_message_id, model_key, provider_key,
|
|
11783
|
-
captured_at, row_version, capture_sequence
|
|
11784
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
11785
|
-
ON CONFLICT(session_id) DO UPDATE SET
|
|
11786
|
-
json_prefix_chars = excluded.json_prefix_chars,
|
|
11787
|
-
json_prefix_chunks = excluded.json_prefix_chunks,
|
|
11788
|
-
json_prefix_hash = excluded.json_prefix_hash,
|
|
11789
|
-
input_id_seq = excluded.input_id_seq,
|
|
11790
|
-
input_content_digests = excluded.input_content_digests,
|
|
11791
|
-
input_content_signatures = excluded.input_content_signatures,
|
|
11792
|
-
last_input_message_id = excluded.last_input_message_id,
|
|
11793
|
-
model_key = excluded.model_key,
|
|
11794
|
-
provider_key = excluded.provider_key,
|
|
11795
|
-
captured_at = excluded.captured_at,
|
|
11796
|
-
row_version = excluded.row_version,
|
|
11797
|
-
capture_sequence = excluded.capture_sequence`).run(sessionId, layout.chars, layout.chunks.length, layout.hash, JSON.stringify(slot.piOutputEntryIds ? {
|
|
11798
|
-
version: 1,
|
|
11799
|
-
inputIds: slot.inputIdSeq,
|
|
11800
|
-
piOutputEntryIds: slot.piOutputEntryIds
|
|
11801
|
-
} : slot.inputIdSeq), JSON.stringify(slot.inputContentDigests), slot.inputContentSignatures ? JSON.stringify(slot.inputContentSignatures) : null, slot.lastInputMessageId, slot.modelKey, slot.providerKey, slot.capturedAt, slot.rowVersion ?? null, slot.captureSequence ?? null);
|
|
11802
|
-
publishMetadata?.();
|
|
11803
|
-
}).immediate();
|
|
11804
|
-
rememberFingerprint(db, sessionId, fingerprint);
|
|
11805
|
-
return true;
|
|
11806
|
-
} catch (error) {
|
|
11807
|
-
if (!publishMetadata)
|
|
11808
|
-
sessionLog2(sessionId, "LKG snapshot persistence failed (in-memory slot retained):", error);
|
|
11809
|
-
return false;
|
|
11810
|
-
}
|
|
11811
|
-
}
|
|
11812
|
-
function clearPersistedLkgSlot(db, sessionId) {
|
|
11813
|
-
try {
|
|
11814
|
-
clearPersistedLkgSlotStrict(db, sessionId);
|
|
11815
|
-
} catch (error) {
|
|
11816
|
-
sessionLog2(sessionId, "LKG snapshot durable clear failed:", error);
|
|
11817
|
-
}
|
|
11818
|
-
}
|
|
11819
|
-
function clearPersistedLkgSlotStrict(db, sessionId) {
|
|
11820
|
-
db.transaction(() => {
|
|
11821
|
-
db.prepare("DELETE FROM lkg_slot_chunks WHERE session_id = ?").run(sessionId);
|
|
11822
|
-
db.prepare("DELETE FROM lkg_slots WHERE session_id = ?").run(sessionId);
|
|
11823
|
-
}).immediate();
|
|
11824
|
-
persistedFingerprints.get(db)?.delete(sessionId);
|
|
11825
|
-
}
|
|
11826
|
-
function loadPersistedLkgSlot(db, sessionId) {
|
|
11827
|
-
if (isRustMarkerAdmissionFenced(db, sessionId))
|
|
11828
|
-
return;
|
|
11829
|
-
let row;
|
|
11830
|
-
let chunkRows;
|
|
11831
|
-
try {
|
|
11832
|
-
({ row, chunkRows } = db.transaction(() => {
|
|
11833
|
-
const slotRow = db.prepare("SELECT * FROM lkg_slots WHERE session_id = ?").get(sessionId);
|
|
11834
|
-
if (!slotRow)
|
|
11835
|
-
return { row: undefined, chunkRows: [] };
|
|
11836
|
-
const slices = db.prepare("SELECT chunk, hash, body FROM lkg_slot_chunks WHERE session_id = ? ORDER BY chunk").all(sessionId);
|
|
11837
|
-
return { row: slotRow, chunkRows: slices };
|
|
11838
|
-
}).deferred());
|
|
11839
|
-
} catch (error) {
|
|
11840
|
-
sessionLog2(sessionId, "LKG snapshot durable load failed:", error);
|
|
11841
|
-
return;
|
|
11842
|
-
}
|
|
11843
|
-
if (!row)
|
|
11844
|
-
return;
|
|
11845
|
-
const prefix = assembleLkgPrefix({
|
|
11846
|
-
chars: row.json_prefix_chars,
|
|
11847
|
-
chunks: row.json_prefix_chunks,
|
|
11848
|
-
hash: row.json_prefix_hash
|
|
11849
|
-
}, chunkRows);
|
|
11850
|
-
const slot = prefix ? parsePersistedLkgSlot({ ...row, json_prefix: prefix.jsonPrefix }) : undefined;
|
|
11851
|
-
if (!prefix || !slot) {
|
|
11852
|
-
if (!prefix)
|
|
11853
|
-
sessionLog2(sessionId, "LKG snapshot slices failed verification; slot cleared");
|
|
11854
|
-
clearPersistedLkgSlot(db, sessionId);
|
|
11855
|
-
return;
|
|
11856
|
-
}
|
|
11857
|
-
return slot;
|
|
11858
|
-
}
|
|
11859
|
-
function pruneStaleLkgSlotsBatch(db, now) {
|
|
11860
|
-
const previousTimeout = db.prepare("PRAGMA busy_timeout").get();
|
|
11861
|
-
const cutoff = now - 7 * 24 * 60 * 60 * 1000;
|
|
11862
|
-
const stale = `captured_at < ? AND NOT EXISTS (
|
|
11863
|
-
SELECT 1 FROM session_projects sp
|
|
11864
|
-
WHERE sp.session_id = lkg_slots.session_id AND sp.updated_at >= ?
|
|
11865
|
-
)`;
|
|
11866
|
-
const slot = db.prepare(`SELECT session_id FROM lkg_slots WHERE ${stale} LIMIT 1`).get(cutoff, cutoff);
|
|
11867
|
-
const chunks = db.prepare(`SELECT rowid FROM lkg_slot_chunks c WHERE
|
|
11868
|
-
session_id = ? OR NOT EXISTS (SELECT 1 FROM lkg_slots s WHERE s.session_id = c.session_id)
|
|
11869
|
-
LIMIT 25`).all(slot?.session_id ?? "");
|
|
11870
|
-
if (!slot && chunks.length === 0)
|
|
11871
|
-
return { slots: 0, chunks: 0 };
|
|
11872
|
-
try {
|
|
11873
|
-
db.exec("PRAGMA busy_timeout = 0");
|
|
11874
|
-
let transactionStartedAt = 0;
|
|
11875
|
-
const changes = db.transaction(() => {
|
|
11876
|
-
transactionStartedAt = performance.now();
|
|
11877
|
-
const removed = slot ? db.prepare(`DELETE FROM lkg_slots WHERE session_id = ? AND ${stale}`).run(slot.session_id, cutoff, cutoff).changes : 0;
|
|
11878
|
-
const removeChunk = db.prepare(`DELETE FROM lkg_slot_chunks WHERE rowid = ? AND NOT EXISTS (
|
|
11879
|
-
SELECT 1 FROM lkg_slots s WHERE s.session_id = lkg_slot_chunks.session_id
|
|
11880
|
-
)`);
|
|
11881
|
-
let removedChunks = 0;
|
|
11882
|
-
for (const { rowid } of chunks)
|
|
11883
|
-
removedChunks += removeChunk.run(rowid).changes;
|
|
11884
|
-
return { slots: removed, chunks: removedChunks };
|
|
11885
|
-
}).immediate();
|
|
11886
|
-
logSlowWriteTransaction("lkg_stale_gc", transactionStartedAt);
|
|
11887
|
-
if (changes.slots && slot)
|
|
11888
|
-
persistedFingerprints.get(db)?.delete(slot.session_id);
|
|
11889
|
-
return changes;
|
|
11890
|
-
} finally {
|
|
11891
|
-
db.exec(`PRAGMA busy_timeout = ${Number(previousTimeout.timeout) || 0}`);
|
|
11892
|
-
}
|
|
11893
|
-
}
|
|
11894
|
-
async function drainStaleLkgSlots(db, now = Date.now(), budgetMs = 2000) {
|
|
11895
|
-
let removed = 0;
|
|
11896
|
-
await drainBackgroundBatches(() => {
|
|
11897
|
-
const batch = pruneStaleLkgSlotsBatch(db, now);
|
|
11898
|
-
removed += batch.slots;
|
|
11899
|
-
return batch.slots + batch.chunks > 0;
|
|
11900
|
-
}, { budgetMs });
|
|
11901
|
-
return removed;
|
|
11902
|
-
}
|
|
11903
|
-
|
|
11904
|
-
// src/hooks/magic-context/openai-compat-adjacency.ts
|
|
11905
|
-
function assertOpenAiCompatAdjacency(messages) {
|
|
11906
|
-
const violations = [];
|
|
11907
|
-
for (let i = 0;i < messages.length; i++) {
|
|
11908
|
-
const msg = messages[i];
|
|
11909
|
-
if (msg.role !== "assistant" || !msg.tool_calls || msg.tool_calls.length === 0) {
|
|
11910
|
-
continue;
|
|
11911
|
-
}
|
|
11912
|
-
const expectedIds = msg.tool_calls.map((tc) => tc.id);
|
|
11913
|
-
const expectedSet = new Set(expectedIds);
|
|
11914
|
-
const collected = new Map;
|
|
11915
|
-
let j = i + 1;
|
|
11916
|
-
while (j < messages.length && messages[j].role === "tool") {
|
|
11917
|
-
const toolMsg = messages[j];
|
|
11918
|
-
const id = toolMsg.tool_call_id;
|
|
11919
|
-
if (!id) {
|
|
11920
|
-
violations.push({
|
|
11921
|
-
index: i,
|
|
11922
|
-
kind: "unmatched_tool_call_id",
|
|
11923
|
-
detail: `tool message at index ${j} missing tool_call_id`
|
|
11924
|
-
});
|
|
11925
|
-
} else if (!expectedSet.has(id)) {
|
|
11926
|
-
violations.push({
|
|
11927
|
-
index: i,
|
|
11928
|
-
kind: "unmatched_tool_call_id",
|
|
11929
|
-
toolCallId: id,
|
|
11930
|
-
assistantToolCallIds: expectedIds,
|
|
11931
|
-
detail: `tool message at index ${j} references unexpected id ${id}`
|
|
11932
|
-
});
|
|
11933
|
-
} else {
|
|
11934
|
-
collected.set(id, j);
|
|
11935
|
-
}
|
|
11936
|
-
j++;
|
|
11937
|
-
}
|
|
11938
|
-
const followingRoles = messages.slice(i + 1, Math.min(messages.length, i + 4)).map((m) => m.role);
|
|
11939
|
-
const missing = expectedIds.filter((id) => !collected.has(id));
|
|
11940
|
-
if (missing.length > 0) {
|
|
11941
|
-
violations.push({
|
|
11942
|
-
index: i,
|
|
11943
|
-
kind: "missing_tool_messages",
|
|
11944
|
-
assistantToolCallIds: expectedIds,
|
|
11945
|
-
followingRoles,
|
|
11946
|
-
detail: missing.length === expectedIds.length ? `assistant at index ${i} has tool_calls but next messages are not contiguous tool role (following: ${followingRoles.join(", ") || "none"})` : `assistant at index ${i} missing tool results for: ${missing.join(", ")}`
|
|
11947
|
-
});
|
|
11948
|
-
if (j < messages.length && messages[j].role !== "tool") {
|
|
11949
|
-
const last = violations[violations.length - 1];
|
|
11950
|
-
last.detail += `; blocked by ${messages.slice(i + 1, j + 1).map((m, off) => `${m.role}[${i + 1 + off}]`).join(", ")}`;
|
|
11951
|
-
}
|
|
11952
|
-
}
|
|
11953
|
-
}
|
|
11954
|
-
for (let i = 0;i < messages.length; i++) {
|
|
11955
|
-
if (messages[i].role !== "tool")
|
|
11956
|
-
continue;
|
|
11957
|
-
const id = messages[i].tool_call_id ?? "";
|
|
11958
|
-
if (!id)
|
|
11959
|
-
continue;
|
|
11960
|
-
let found = false;
|
|
11961
|
-
for (let k = i - 1;k >= 0; k--) {
|
|
11962
|
-
const prev = messages[k];
|
|
11963
|
-
if (prev.role === "assistant" && prev.tool_calls?.some((tc) => tc.id === id)) {
|
|
11964
|
-
const between = messages.slice(k + 1, i);
|
|
11965
|
-
if (between.every((m) => m.role === "tool")) {
|
|
11966
|
-
found = true;
|
|
11967
|
-
}
|
|
11968
|
-
break;
|
|
11969
|
-
}
|
|
11970
|
-
if (prev.role === "assistant" || prev.role === "user")
|
|
11971
|
-
break;
|
|
11972
|
-
}
|
|
11973
|
-
if (!found) {
|
|
11974
|
-
violations.push({
|
|
11975
|
-
index: i,
|
|
11976
|
-
kind: "orphan_tool_message",
|
|
11977
|
-
toolCallId: id,
|
|
11978
|
-
detail: `tool message at index ${i} is not immediately after its assistant tool_calls`
|
|
11979
|
-
});
|
|
11980
|
-
}
|
|
11981
|
-
}
|
|
11982
|
-
return { ok: violations.length === 0, violations };
|
|
11983
|
-
}
|
|
11984
|
-
|
|
11985
|
-
// src/hooks/magic-context/lkg-replay.ts
|
|
11986
|
-
function canonicalLkgModelKeys(modelKey, providerKey) {
|
|
11987
|
-
const canonicalModelKey = modelKey ? piModelRefToCanonical(modelKey) : null;
|
|
11988
|
-
const slash = canonicalModelKey?.indexOf("/") ?? -1;
|
|
11989
|
-
return {
|
|
11990
|
-
modelKey: canonicalModelKey,
|
|
11991
|
-
providerKey: slash > 0 && canonicalModelKey ? canonicalModelKey.slice(0, slash) : providerKey
|
|
11992
|
-
};
|
|
11993
|
-
}
|
|
11994
|
-
function resolveLkgModelKeys(messages) {
|
|
11995
|
-
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
11996
|
-
const info = messages[index]?.info;
|
|
11997
|
-
const nested = info?.model;
|
|
11998
|
-
if (nested && typeof nested === "object") {
|
|
11999
|
-
const provider = nested.providerID;
|
|
12000
|
-
const model = nested.modelID;
|
|
12001
|
-
if (typeof provider === "string" && typeof model === "string") {
|
|
12002
|
-
return canonicalLkgModelKeys(`${provider}/${model}`, provider);
|
|
12003
|
-
}
|
|
12004
|
-
}
|
|
12005
|
-
const provider = info?.providerID;
|
|
12006
|
-
const model = info?.modelID;
|
|
12007
|
-
if (typeof provider === "string" && typeof model === "string") {
|
|
12008
|
-
return canonicalLkgModelKeys(`${provider}/${model}`, provider);
|
|
12009
|
-
}
|
|
12010
|
-
}
|
|
12011
|
-
return { modelKey: null, providerKey: null };
|
|
12012
|
-
}
|
|
12013
|
-
function projectLkgEntry(messages) {
|
|
12014
|
-
return projectEntryWithDigests(messages, messages.map(lkgContentDigest));
|
|
12015
|
-
}
|
|
12016
|
-
function createLkgEntryProjector(options = {}) {
|
|
12017
|
-
const cache = options.maxBytes === undefined ? sharedLkgEntryDigests : new LkgEntryDigestCache({
|
|
12018
|
-
sessionMaxBytes: options.maxBytes,
|
|
12019
|
-
totalMaxBytes: options.maxBytes,
|
|
12020
|
-
maxSessions: 16
|
|
12021
|
-
});
|
|
12022
|
-
return (sessionId, messages) => {
|
|
12023
|
-
const { digests, stats } = cache.digests(sessionId, messages);
|
|
12024
|
-
options.onReuse?.(stats);
|
|
12025
|
-
return projectEntryWithDigests(messages, digests);
|
|
12026
|
-
};
|
|
12027
|
-
}
|
|
12028
|
-
function projectEntryWithDigests(messages, digests) {
|
|
12029
|
-
return messages.map((message, index) => {
|
|
12030
|
-
const info = messageInfo(message);
|
|
12031
|
-
const time = info.time;
|
|
12032
|
-
const timeRecord = time && typeof time === "object" ? time : null;
|
|
12033
|
-
const timeCandidates = [
|
|
12034
|
-
timeRecord?.created,
|
|
12035
|
-
info.timeCreated,
|
|
12036
|
-
info.time_created,
|
|
12037
|
-
info.createdAt,
|
|
12038
|
-
info.created_at
|
|
12039
|
-
];
|
|
12040
|
-
let timeCreated = null;
|
|
12041
|
-
for (const value of timeCandidates) {
|
|
12042
|
-
if (typeof value === "number" && Number.isFinite(value)) {
|
|
12043
|
-
timeCreated = value;
|
|
12044
|
-
break;
|
|
12045
|
-
}
|
|
12046
|
-
}
|
|
12047
|
-
let hasIncompleteTool = false;
|
|
12048
|
-
for (const rawPart of messageParts(message)) {
|
|
12049
|
-
if (!rawPart || typeof rawPart !== "object")
|
|
12050
|
-
continue;
|
|
12051
|
-
const part = rawPart;
|
|
12052
|
-
if (part.type !== "tool" || part.providerExecuted === true)
|
|
12053
|
-
continue;
|
|
12054
|
-
const state = part.state;
|
|
12055
|
-
const status = state && typeof state === "object" ? state.status : undefined;
|
|
12056
|
-
if (status !== "completed") {
|
|
12057
|
-
hasIncompleteTool = true;
|
|
12058
|
-
break;
|
|
12059
|
-
}
|
|
12060
|
-
}
|
|
12061
|
-
const id = info.id;
|
|
12062
|
-
const projection = {
|
|
12063
|
-
id: typeof id === "string" && id.length > 0 ? id : null,
|
|
12064
|
-
role: typeof info.role === "string" ? info.role : undefined,
|
|
12065
|
-
synthetic: info.synthetic === true,
|
|
12066
|
-
timeCreated,
|
|
12067
|
-
finish: info.finish,
|
|
12068
|
-
hasIncompleteTool
|
|
12069
|
-
};
|
|
12070
|
-
const contentDigest = digests[index] ?? null;
|
|
12071
|
-
Object.defineProperty(projection, "contentDigest", {
|
|
12072
|
-
value: () => contentDigest,
|
|
12073
|
-
enumerable: false
|
|
12074
|
-
});
|
|
12075
|
-
return projection;
|
|
12076
|
-
});
|
|
12077
|
-
}
|
|
12078
|
-
function recordValue(info, key) {
|
|
12079
|
-
return info && typeof info === "object" ? info[key] : undefined;
|
|
12080
|
-
}
|
|
12081
|
-
function messageInfo(message) {
|
|
12082
|
-
if (message.info && typeof message.info === "object")
|
|
12083
|
-
return message.info;
|
|
12084
|
-
return message;
|
|
12085
|
-
}
|
|
12086
|
-
function messageParts(message) {
|
|
12087
|
-
return Array.isArray(message.parts) ? message.parts : [];
|
|
12088
|
-
}
|
|
12089
|
-
function isSynthetic(message) {
|
|
12090
|
-
return recordValue(messageInfo(message), "synthetic") === true;
|
|
12091
|
-
}
|
|
12092
|
-
function hasSyntheticParts(message) {
|
|
12093
|
-
const parts = messageParts(message);
|
|
12094
|
-
return parts.length > 0 && parts.every((part) => {
|
|
12095
|
-
return Boolean(part && typeof part === "object" && part.synthetic === true);
|
|
12096
|
-
});
|
|
12097
|
-
}
|
|
12098
|
-
function isSyntheticOutput(message) {
|
|
12099
|
-
return isSynthetic(message) || hasSyntheticParts(message);
|
|
12100
|
-
}
|
|
12101
|
-
function messageRole(message) {
|
|
12102
|
-
const infoRole = recordValue(messageInfo(message), "role");
|
|
12103
|
-
if (typeof infoRole === "string")
|
|
12104
|
-
return infoRole;
|
|
12105
|
-
const role = recordValue(message, "role");
|
|
12106
|
-
return typeof role === "string" ? role : undefined;
|
|
12107
|
-
}
|
|
12108
|
-
function messageId(message) {
|
|
12109
|
-
const id = recordValue(messageInfo(message), "id") ?? recordValue(message, "id");
|
|
12110
|
-
return typeof id === "string" && id.length > 0 ? id : null;
|
|
12111
|
-
}
|
|
12112
|
-
function latestAssistant(messages) {
|
|
12113
|
-
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
12114
|
-
if (messages[index].role === "assistant")
|
|
12115
|
-
return messages[index];
|
|
12116
|
-
}
|
|
12117
|
-
return null;
|
|
12118
|
-
}
|
|
12119
|
-
function isRealUser(message) {
|
|
12120
|
-
return message.role === "user" && !message.synthetic && message.id !== null;
|
|
12121
|
-
}
|
|
12122
|
-
function assistantIsActive(message) {
|
|
12123
|
-
return message.finish === "tool-calls" || message.hasIncompleteTool;
|
|
12124
|
-
}
|
|
12125
|
-
function findLkgAnchor(messages) {
|
|
12126
|
-
const assistant = latestAssistant(messages);
|
|
12127
|
-
const assistantTime = assistant?.timeCreated ?? null;
|
|
12128
|
-
if (assistant && assistantTime === null)
|
|
12129
|
-
return null;
|
|
12130
|
-
let anchor = -1;
|
|
12131
|
-
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
12132
|
-
const message = messages[index];
|
|
12133
|
-
if (!isRealUser(message))
|
|
12134
|
-
continue;
|
|
12135
|
-
if (assistant && assistantIsActive(assistant)) {
|
|
12136
|
-
if (assistantTime === null || message.timeCreated === null || message.timeCreated <= assistantTime) {
|
|
12137
|
-
continue;
|
|
12138
|
-
}
|
|
12139
|
-
}
|
|
12140
|
-
anchor = index;
|
|
12141
|
-
break;
|
|
12142
|
-
}
|
|
12143
|
-
return anchor >= 0 ? anchor : null;
|
|
12144
|
-
}
|
|
12145
|
-
function asEntryProjection(input) {
|
|
12146
|
-
if (input.length === 0 || "hasIncompleteTool" in input[0]) {
|
|
12147
|
-
return input;
|
|
12148
|
-
}
|
|
12149
|
-
return projectLkgEntry(input);
|
|
12150
|
-
}
|
|
12151
|
-
function outputMessageIsPostAnchor(message, inputIndexById, anchorIndex) {
|
|
12152
|
-
const id = messageId(message);
|
|
12153
|
-
if (id !== null) {
|
|
12154
|
-
const inputIndex = inputIndexById.get(id);
|
|
12155
|
-
if (inputIndex !== undefined)
|
|
12156
|
-
return inputIndex > anchorIndex;
|
|
12157
|
-
if (!isSyntheticOutput(message))
|
|
12158
|
-
return null;
|
|
12159
|
-
const linked = ["sourceMessageId", "ownerMessageId", "anchorMessageId", "messageId"].map((key) => recordValue(messageInfo(message), key)).find((value) => typeof value === "string");
|
|
12160
|
-
if (typeof linked === "string") {
|
|
12161
|
-
const linkedIndex = inputIndexById.get(linked);
|
|
12162
|
-
if (linkedIndex === undefined)
|
|
12163
|
-
return null;
|
|
12164
|
-
return linkedIndex > anchorIndex;
|
|
12165
|
-
}
|
|
12166
|
-
return false;
|
|
12167
|
-
}
|
|
12168
|
-
if (!isSyntheticOutput(message))
|
|
12169
|
-
return null;
|
|
12170
|
-
const linked = ["sourceMessageId", "ownerMessageId", "anchorMessageId"].map((key) => recordValue(message.info, key)).find((value) => typeof value === "string");
|
|
12171
|
-
if (typeof linked !== "string")
|
|
12172
|
-
return false;
|
|
12173
|
-
const linkedIndex = inputIndexById.get(linked);
|
|
12174
|
-
return linkedIndex === undefined ? null : linkedIndex > anchorIndex;
|
|
12175
|
-
}
|
|
12176
|
-
function buildLkgPrefix(input, output) {
|
|
12177
|
-
const projected = asEntryProjection(input);
|
|
12178
|
-
const anchorIndex = findLkgAnchor(projected);
|
|
12179
|
-
if (anchorIndex === null)
|
|
12180
|
-
return null;
|
|
12181
|
-
const ids = projected.map((message) => message.id);
|
|
12182
|
-
if (ids.some((id) => id === null))
|
|
12183
|
-
return null;
|
|
12184
|
-
const validIds = ids;
|
|
12185
|
-
if (new Set(validIds).size !== validIds.length)
|
|
12186
|
-
return null;
|
|
12187
|
-
const anchorMessageId = validIds[anchorIndex];
|
|
12188
|
-
const inputContentDigests = projected.slice(0, anchorIndex + 1).map((message) => message.contentDigest?.() ?? null);
|
|
12189
|
-
if (inputContentDigests.some((digest) => digest === null))
|
|
12190
|
-
return null;
|
|
12191
|
-
const inputIndexById = new Map(validIds.map((id, index) => [id, index]));
|
|
12192
|
-
const prefix = [];
|
|
12193
|
-
for (const message of output) {
|
|
12194
|
-
const postAnchor = outputMessageIsPostAnchor(message, inputIndexById, anchorIndex);
|
|
12195
|
-
if (postAnchor === null)
|
|
12196
|
-
return null;
|
|
12197
|
-
if (!postAnchor)
|
|
12198
|
-
prefix.push(providerVisibleMessage(message));
|
|
12199
|
-
}
|
|
12200
|
-
let jsonPrefix;
|
|
12201
|
-
try {
|
|
12202
|
-
jsonPrefix = JSON.stringify(prefix);
|
|
12203
|
-
if (typeof jsonPrefix !== "string")
|
|
12204
|
-
return null;
|
|
12205
|
-
} catch {
|
|
12206
|
-
return null;
|
|
12207
|
-
}
|
|
12208
|
-
return {
|
|
12209
|
-
anchorIndex,
|
|
12210
|
-
anchorMessageId,
|
|
12211
|
-
inputIdSeq: validIds.slice(0, anchorIndex + 1),
|
|
12212
|
-
inputContentDigests,
|
|
12213
|
-
jsonPrefix
|
|
12214
|
-
};
|
|
12215
|
-
}
|
|
12216
|
-
function captureLkgSlot(args) {
|
|
12217
|
-
const built = buildLkgPrefix(args.input, args.output);
|
|
12218
|
-
if (!built)
|
|
12219
|
-
return false;
|
|
12220
|
-
const modelKeys = canonicalLkgModelKeys(args.modelKey, args.providerKey);
|
|
12221
|
-
const slot = {
|
|
12222
|
-
jsonPrefix: built.jsonPrefix,
|
|
12223
|
-
inputIdSeq: built.inputIdSeq,
|
|
12224
|
-
inputContentDigests: built.inputContentDigests,
|
|
12225
|
-
lastInputMessageId: built.anchorMessageId,
|
|
12226
|
-
modelKey: modelKeys.modelKey,
|
|
12227
|
-
providerKey: modelKeys.providerKey,
|
|
12228
|
-
capturedAt: args.capturedAt ?? Date.now()
|
|
12229
|
-
};
|
|
12230
|
-
const captured = captureSlot(args.sessionId, slot);
|
|
12231
|
-
if (captured)
|
|
12232
|
-
noteCapturedLkgRequest({
|
|
12233
|
-
sessionId: args.sessionId,
|
|
12234
|
-
slot,
|
|
12235
|
-
request: built.anchorIndex === args.input.length - 1 ? claimLkgRequestIdentity(args.sessionId) : undefined,
|
|
12236
|
-
systemPromptTokens: args.systemPromptTokens ?? 0,
|
|
12237
|
-
agentName: args.agentName
|
|
12238
|
-
});
|
|
12239
|
-
return captured;
|
|
12240
|
-
}
|
|
12241
|
-
function entryIdsAreValid(slot, entryIds) {
|
|
12242
|
-
if (slot.inputIdSeq.length === 0 || entryIds.length < slot.inputIdSeq.length)
|
|
12243
|
-
return false;
|
|
12244
|
-
if (slot.inputIdSeq[slot.inputIdSeq.length - 1] !== slot.lastInputMessageId)
|
|
12245
|
-
return false;
|
|
12246
|
-
const seen = new Set;
|
|
12247
|
-
for (const id of entryIds) {
|
|
12248
|
-
if (!id || seen.has(id))
|
|
12249
|
-
return false;
|
|
12250
|
-
seen.add(id);
|
|
12251
|
-
}
|
|
12252
|
-
if (entryIds.indexOf(slot.lastInputMessageId) !== slot.inputIdSeq.length - 1)
|
|
12253
|
-
return false;
|
|
12254
|
-
for (let index = 0;index < slot.inputIdSeq.length; index += 1) {
|
|
12255
|
-
if (entryIds[index] !== slot.inputIdSeq[index])
|
|
12256
|
-
return false;
|
|
12257
|
-
}
|
|
12258
|
-
return true;
|
|
12259
|
-
}
|
|
12260
|
-
function entryContentIsValid(slot, entry) {
|
|
12261
|
-
return entry.entryContentDigests.length >= slot.inputContentDigests.length && slot.inputContentDigests.every((digest, index) => isLegacyLkgDigest(digest) ? entry.entryLegacyContentDigests?.[index] === digest : entry.entryContentDigests[index] === digest);
|
|
12262
|
-
}
|
|
12263
|
-
function partCallIds(message) {
|
|
12264
|
-
const ids = [];
|
|
12265
|
-
for (const rawPart of messageParts(message)) {
|
|
12266
|
-
if (!rawPart || typeof rawPart !== "object")
|
|
12267
|
-
continue;
|
|
12268
|
-
const part = rawPart;
|
|
12269
|
-
if (part.type !== "tool" && part.type !== "tool_use")
|
|
12270
|
-
continue;
|
|
12271
|
-
const callId = part.callID ?? part.callId ?? part.id;
|
|
12272
|
-
if (typeof callId === "string" && callId.length > 0)
|
|
12273
|
-
ids.push(callId);
|
|
12274
|
-
}
|
|
12275
|
-
return ids;
|
|
12276
|
-
}
|
|
12277
|
-
function partResultIds(message) {
|
|
12278
|
-
const ids = [];
|
|
12279
|
-
for (const rawPart of messageParts(message)) {
|
|
12280
|
-
if (!rawPart || typeof rawPart !== "object")
|
|
12281
|
-
continue;
|
|
12282
|
-
const part = rawPart;
|
|
12283
|
-
if (part.type !== "tool_result" && part.type !== "tool-result")
|
|
12284
|
-
continue;
|
|
12285
|
-
const callId = part.tool_call_id ?? part.tool_use_id ?? part.callID ?? part.callId;
|
|
12286
|
-
if (typeof callId === "string" && callId.length > 0)
|
|
12287
|
-
ids.push(callId);
|
|
12288
|
-
}
|
|
12289
|
-
return ids;
|
|
12290
|
-
}
|
|
12291
|
-
function partIsReasoning(part) {
|
|
12292
|
-
return Boolean(part && typeof part === "object" && part.type === "reasoning");
|
|
12293
|
-
}
|
|
12294
|
-
function partIsAnthropicThinking(part) {
|
|
12295
|
-
if (!part || typeof part !== "object")
|
|
12296
|
-
return false;
|
|
12297
|
-
const type = part.type;
|
|
12298
|
-
return type === "thinking" || type === "reasoning" || type === "redacted_thinking";
|
|
12299
|
-
}
|
|
12300
|
-
function partEndsAnthropicAssistantRun(part) {
|
|
12301
|
-
if (!part || typeof part !== "object")
|
|
12302
|
-
return false;
|
|
12303
|
-
const value = part;
|
|
12304
|
-
if (value.type !== "tool" || value.providerExecuted === true || !value.state || typeof value.state !== "object") {
|
|
12305
|
-
return false;
|
|
12306
|
-
}
|
|
12307
|
-
const status = value.state.status;
|
|
12308
|
-
return status === "completed" || status === "error";
|
|
12309
|
-
}
|
|
12310
|
-
function partIsOpenCodeStepMetadata(part) {
|
|
12311
|
-
if (!part || typeof part !== "object")
|
|
12312
|
-
return false;
|
|
12313
|
-
const type = part.type;
|
|
12314
|
-
return type === "step-start" || type === "step-finish";
|
|
12315
|
-
}
|
|
12316
|
-
function validateAnthropicReasoningRuns(messages) {
|
|
12317
|
-
let index = 0;
|
|
12318
|
-
while (index < messages.length) {
|
|
12319
|
-
if (messageRole(messages[index]) !== "assistant") {
|
|
12320
|
-
index += 1;
|
|
12321
|
-
continue;
|
|
12322
|
-
}
|
|
12323
|
-
let firstMessageInRun = null;
|
|
12324
|
-
let sawOtherContent = false;
|
|
12325
|
-
while (index < messages.length && messageRole(messages[index]) === "assistant") {
|
|
12326
|
-
for (const part of messageParts(messages[index])) {
|
|
12327
|
-
if (partEndsAnthropicAssistantRun(part)) {
|
|
12328
|
-
firstMessageInRun = null;
|
|
12329
|
-
sawOtherContent = false;
|
|
12330
|
-
} else if (!partIsOpenCodeStepMetadata(part)) {
|
|
12331
|
-
if (firstMessageInRun === null)
|
|
12332
|
-
firstMessageInRun = index;
|
|
12333
|
-
if (partIsAnthropicThinking(part)) {
|
|
12334
|
-
if (sawOtherContent || index !== firstMessageInRun)
|
|
12335
|
-
return false;
|
|
12336
|
-
} else {
|
|
12337
|
-
sawOtherContent = true;
|
|
12338
|
-
}
|
|
12339
|
-
}
|
|
12340
|
-
}
|
|
12341
|
-
index += 1;
|
|
12342
|
-
}
|
|
12343
|
-
}
|
|
12344
|
-
return true;
|
|
12345
|
-
}
|
|
12346
|
-
function validateLkgSeamBoundary(prefix, tail) {
|
|
12347
|
-
const last = prefix[prefix.length - 1];
|
|
12348
|
-
const first = tail[0];
|
|
12349
|
-
if (!last || !first)
|
|
12350
|
-
return true;
|
|
12351
|
-
const lastCalls = partCallIds(last);
|
|
12352
|
-
if (lastCalls.length === 0)
|
|
12353
|
-
return true;
|
|
12354
|
-
const firstCalls = new Set([...partCallIds(first), ...partResultIds(first)]);
|
|
12355
|
-
if (messageRole(first) === "tool" || lastCalls.some((callId) => firstCalls.has(callId)))
|
|
12356
|
-
return false;
|
|
12357
|
-
return !messageParts(last).some((part) => {
|
|
12358
|
-
if (!part || typeof part !== "object")
|
|
12359
|
-
return false;
|
|
12360
|
-
const value = part;
|
|
12361
|
-
if (value.type !== "tool")
|
|
12362
|
-
return false;
|
|
12363
|
-
const state = value.state;
|
|
12364
|
-
return !state || typeof state !== "object" || state.status !== "completed";
|
|
12365
|
-
});
|
|
12366
|
-
}
|
|
12367
|
-
function validateLkgSeam(prefix, tail, providerKey) {
|
|
12368
|
-
const all = [...prefix, ...tail];
|
|
12369
|
-
const ids = new Set;
|
|
12370
|
-
const calls = new Set;
|
|
12371
|
-
const results = new Set;
|
|
12372
|
-
for (const message of all) {
|
|
12373
|
-
const id = messageId(message);
|
|
12374
|
-
if (id !== null) {
|
|
12375
|
-
if (ids.has(id))
|
|
12376
|
-
return false;
|
|
12377
|
-
ids.add(id);
|
|
12378
|
-
}
|
|
12379
|
-
for (const callId of partCallIds(message)) {
|
|
12380
|
-
if (calls.has(callId))
|
|
12381
|
-
return false;
|
|
12382
|
-
calls.add(callId);
|
|
12383
|
-
}
|
|
12384
|
-
for (const callId of partResultIds(message)) {
|
|
12385
|
-
if (results.has(callId))
|
|
12386
|
-
return false;
|
|
12387
|
-
results.add(callId);
|
|
12388
|
-
}
|
|
12389
|
-
if (messageRole(message) !== "assistant" && messageParts(message).some(partIsReasoning))
|
|
12390
|
-
return false;
|
|
12391
|
-
if (providerKey !== "anthropic" && messageParts(message).some((part) => {
|
|
12392
|
-
if (!part || typeof part !== "object")
|
|
12393
|
-
return false;
|
|
12394
|
-
const value = part;
|
|
12395
|
-
return (value.type === "text" || value.type === "reasoning") && value.text === "";
|
|
12396
|
-
}))
|
|
12397
|
-
return false;
|
|
12398
|
-
}
|
|
12399
|
-
if (!validateLkgSeamBoundary(prefix, tail))
|
|
12400
|
-
return false;
|
|
12401
|
-
const wireCandidates = all.map((message) => message);
|
|
12402
|
-
if (wireCandidates.every((message) => typeof message.role === "string")) {
|
|
12403
|
-
const adjacency = assertOpenAiCompatAdjacency(wireCandidates);
|
|
12404
|
-
if (!adjacency.ok)
|
|
12405
|
-
return false;
|
|
12406
|
-
const wireCallIds = new Set;
|
|
12407
|
-
for (const wireMessage of wireCandidates) {
|
|
12408
|
-
for (const call of wireMessage.tool_calls ?? []) {
|
|
12409
|
-
if (wireCallIds.has(call.id))
|
|
12410
|
-
return false;
|
|
12411
|
-
wireCallIds.add(call.id);
|
|
12412
|
-
}
|
|
12413
|
-
}
|
|
12414
|
-
}
|
|
12415
|
-
return true;
|
|
12416
|
-
}
|
|
12417
|
-
function replayLkg(args) {
|
|
12418
|
-
const slot = getSlot(args.sessionId);
|
|
12419
|
-
if (!slot)
|
|
12420
|
-
return { ok: false, reason: "lkg_invalidated_reshape" };
|
|
12421
|
-
const requestedModelKeys = canonicalLkgModelKeys(args.modelKey, args.providerKey);
|
|
12422
|
-
const capturedModelKeys = canonicalLkgModelKeys(slot.modelKey, slot.providerKey);
|
|
12423
|
-
if (capturedModelKeys.modelKey !== requestedModelKeys.modelKey || capturedModelKeys.providerKey !== requestedModelKeys.providerKey) {
|
|
12424
|
-
dropSlot(args.sessionId, "lkg_model_mismatch");
|
|
12425
|
-
return { ok: false, reason: "lkg_model_mismatch" };
|
|
12426
|
-
}
|
|
12427
|
-
const entry = args.entry ?? noteEntry(args.sessionId, args.messages);
|
|
12428
|
-
if (!entry || entry.anchorIndex !== slot.inputIdSeq.length - 1 || !entryIdsAreValid(slot, entry.entryInputIds)) {
|
|
12429
|
-
dropSlot(args.sessionId, "lkg_invalidated_reshape");
|
|
12430
|
-
return { ok: false, reason: "lkg_invalidated_reshape" };
|
|
12431
|
-
}
|
|
12432
|
-
if (!entryContentIsValid(slot, entry)) {
|
|
12433
|
-
dropSlot(args.sessionId, "lkg_content_mismatch");
|
|
12434
|
-
return { ok: false, reason: "lkg_content_mismatch" };
|
|
12435
|
-
}
|
|
12436
|
-
let prefix;
|
|
12437
|
-
try {
|
|
12438
|
-
const parsed = JSON.parse(slot.jsonPrefix);
|
|
12439
|
-
if (!Array.isArray(parsed))
|
|
12440
|
-
throw new Error("prefix is not an array");
|
|
12441
|
-
prefix = parsed;
|
|
12442
|
-
} catch {
|
|
12443
|
-
dropSlot(args.sessionId, "lkg_seam_invalid");
|
|
12444
|
-
return { ok: false, reason: "lkg_seam_invalid" };
|
|
12445
|
-
}
|
|
12446
|
-
const replayed = [...prefix, ...entry.pristineTail];
|
|
12447
|
-
args.prepareReplay?.(replayed);
|
|
12448
|
-
if (!args.skipSeamValidation) {
|
|
12449
|
-
if (!validateLkgSeamBoundary(prefix, entry.pristineTail)) {
|
|
12450
|
-
dropSlot(args.sessionId, "lkg_unsafe_seam");
|
|
12451
|
-
return { ok: false, reason: "lkg_unsafe_seam" };
|
|
12452
|
-
}
|
|
12453
|
-
if (!validateLkgSeam(prefix, entry.pristineTail, requestedModelKeys.providerKey)) {
|
|
12454
|
-
dropSlot(args.sessionId, "lkg_seam_invalid");
|
|
12455
|
-
return { ok: false, reason: "lkg_seam_invalid" };
|
|
12456
|
-
}
|
|
12457
|
-
}
|
|
12458
|
-
if (requestedModelKeys.providerKey === "anthropic" && !validateAnthropicReasoningRuns(replayed)) {
|
|
12459
|
-
dropSlot(args.sessionId, "lkg_anthropic_reasoning_run_invalid");
|
|
12460
|
-
return { ok: false, reason: "lkg_anthropic_reasoning_run_invalid" };
|
|
12461
|
-
}
|
|
12462
|
-
return { ok: true, messages: replayed };
|
|
12463
|
-
}
|
|
12464
|
-
function messageIdOf(message) {
|
|
12465
|
-
if (typeof message !== "object" || message === null)
|
|
12466
|
-
return;
|
|
12467
|
-
const info = message.info;
|
|
12468
|
-
if (typeof info !== "object" || info === null)
|
|
12469
|
-
return;
|
|
12470
|
-
const id = info.id;
|
|
12471
|
-
return typeof id === "string" ? id : undefined;
|
|
12472
|
-
}
|
|
12473
|
-
function coldStartRawServedIndex(args) {
|
|
12474
|
-
const raw = messagesById(args.rawInput);
|
|
12475
|
-
const rendered = messagesById(args.moduleOutput);
|
|
12476
|
-
const rawKeys = [];
|
|
12477
|
-
let runStart = args.slotMessages.length;
|
|
12478
|
-
while (runStart > 0) {
|
|
12479
|
-
const served = args.slotMessages[runStart - 1];
|
|
12480
|
-
const id = messageIdOf(served);
|
|
12481
|
-
const rawMessage = id === undefined ? undefined : raw.get(id);
|
|
12482
|
-
if (rawMessage === undefined)
|
|
12483
|
-
break;
|
|
12484
|
-
const rawKey = args.key(rawMessage);
|
|
12485
|
-
if (args.key(served) !== rawKey)
|
|
12486
|
-
break;
|
|
12487
|
-
runStart -= 1;
|
|
12488
|
-
rawKeys[runStart] = rawKey;
|
|
12489
|
-
}
|
|
12490
|
-
for (let index = runStart;index < args.slotMessages.length; index += 1) {
|
|
12491
|
-
const id = messageIdOf(args.slotMessages[index]);
|
|
12492
|
-
const moduleMessage = rendered.get(id);
|
|
12493
|
-
if (moduleMessage !== undefined && args.key(moduleMessage) !== rawKeys[index]) {
|
|
12494
|
-
const runStartId = messageIdOf(args.slotMessages[runStart]);
|
|
12495
|
-
const rawRunStart = args.rawInput.findIndex((message) => messageIdOf(message) === runStartId);
|
|
12496
|
-
return { index, rawRunStart };
|
|
12497
|
-
}
|
|
12498
|
-
}
|
|
12499
|
-
return null;
|
|
12500
|
-
}
|
|
12501
|
-
function messagesById(messages) {
|
|
12502
|
-
const map = new Map;
|
|
12503
|
-
for (const message of messages) {
|
|
12504
|
-
const id = messageIdOf(message);
|
|
12505
|
-
if (id !== undefined)
|
|
12506
|
-
map.set(id, message);
|
|
12507
|
-
}
|
|
12508
|
-
return map;
|
|
12509
|
-
}
|
|
12510
|
-
function coldStartUncapturedReplay(args) {
|
|
12511
|
-
const lastSlotId = messageIdOf(args.slotMessages.at(-1));
|
|
12512
|
-
if (lastSlotId === undefined)
|
|
12513
|
-
return null;
|
|
12514
|
-
const slotEnd = args.rawInput.findIndex((message) => messageIdOf(message) === lastSlotId);
|
|
12515
|
-
if (slotEnd < 0)
|
|
12516
|
-
return null;
|
|
12517
|
-
const rendered = messagesById(args.moduleOutput);
|
|
12518
|
-
for (let index = slotEnd + 1;index < args.rawInput.length - 1; index += 1) {
|
|
12519
|
-
const rawMessage = args.rawInput[index];
|
|
12520
|
-
const info = rawMessage?.info;
|
|
12521
|
-
if (info?.role !== "user" || info.synthetic === true)
|
|
12522
|
-
continue;
|
|
12523
|
-
const id = messageIdOf(rawMessage);
|
|
12524
|
-
const moduleMessage = id === undefined ? undefined : rendered.get(id);
|
|
12525
|
-
if (moduleMessage === undefined)
|
|
12526
|
-
continue;
|
|
12527
|
-
if (args.key(moduleMessage) === args.key(rawMessage))
|
|
12528
|
-
continue;
|
|
12529
|
-
return {
|
|
12530
|
-
lastServed: [...args.slotMessages, ...args.rawInput.slice(slotEnd + 1)],
|
|
12531
|
-
rawUserIndex: index
|
|
12532
|
-
};
|
|
12533
|
-
}
|
|
12534
|
-
return null;
|
|
12535
|
-
}
|
|
12536
|
-
|
|
12537
11050
|
// src/hooks/magic-context/pass-outcome.ts
|
|
12538
11051
|
var PASS_DEGRADATION_EFFECTS = {
|
|
12539
11052
|
"store-generation-rebase-failure": "changes-request",
|
|
@@ -12597,7 +11110,7 @@ function createPassOutcome() {
|
|
|
12597
11110
|
}
|
|
12598
11111
|
|
|
12599
11112
|
// src/hooks/magic-context/rust-mode-transform.ts
|
|
12600
|
-
import { createHash as
|
|
11113
|
+
import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
|
|
12601
11114
|
|
|
12602
11115
|
// src/features/magic-context/memory/single-store-embedding-drain.ts
|
|
12603
11116
|
function isWatermarkRow(row) {
|
|
@@ -12661,7 +11174,7 @@ function advanceEmbeddedWatermark(db, projectPath, upTo) {
|
|
|
12661
11174
|
}
|
|
12662
11175
|
|
|
12663
11176
|
// src/features/magic-context/mural/source-revision.ts
|
|
12664
|
-
import { createHash as
|
|
11177
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
12665
11178
|
var statements = new WeakMap;
|
|
12666
11179
|
function muralSourceRevision(db, projectPath) {
|
|
12667
11180
|
let statement = statements.get(db);
|
|
@@ -12678,7 +11191,7 @@ function muralSourceRevision(db, projectPath) {
|
|
|
12678
11191
|
statements.set(db, statement);
|
|
12679
11192
|
}
|
|
12680
11193
|
const row = statement.get(projectPath, Date.now());
|
|
12681
|
-
return
|
|
11194
|
+
return createHash2("sha256").update(row.revision).digest("hex");
|
|
12682
11195
|
}
|
|
12683
11196
|
|
|
12684
11197
|
// src/features/magic-context/install-instance-id.ts
|
|
@@ -15265,13 +13778,13 @@ function replaceMessagesInPlace(output, next) {
|
|
|
15265
13778
|
target.splice(0, target.length, ...next);
|
|
15266
13779
|
return target;
|
|
15267
13780
|
}
|
|
15268
|
-
function
|
|
13781
|
+
function messageInfo(value) {
|
|
15269
13782
|
if (!isRecord4(value))
|
|
15270
13783
|
return {};
|
|
15271
13784
|
return isRecord4(value.info) ? value.info : value;
|
|
15272
13785
|
}
|
|
15273
|
-
function
|
|
15274
|
-
const id =
|
|
13786
|
+
function messageIdOf(message) {
|
|
13787
|
+
const id = messageInfo(message).id;
|
|
15275
13788
|
return typeof id === "string" && id.length > 0 ? id : null;
|
|
15276
13789
|
}
|
|
15277
13790
|
function contentSnapshotsFor(messages) {
|
|
@@ -15329,10 +13842,10 @@ function messageCacheSignature(message) {
|
|
|
15329
13842
|
const parts = Array.isArray(message.parts) ? message.parts : [];
|
|
15330
13843
|
const serializedParts = JSON.stringify(parts) ?? "null";
|
|
15331
13844
|
const serializedMessage = JSON.stringify(message) ?? "null";
|
|
15332
|
-
return `${
|
|
13845
|
+
return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash4("sha256").update(serializedMessage).digest("hex")}`;
|
|
15333
13846
|
}
|
|
15334
13847
|
function advanceWireFingerprint(previous, encoded) {
|
|
15335
|
-
return
|
|
13848
|
+
return createHash4("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
|
|
15336
13849
|
}
|
|
15337
13850
|
function buildWireFingerprint(encoded) {
|
|
15338
13851
|
let fingerprint = "rust-wire-v1";
|
|
@@ -15346,7 +13859,7 @@ function buildWireFingerprint(encoded) {
|
|
|
15346
13859
|
}
|
|
15347
13860
|
function newestUserMessage(messages) {
|
|
15348
13861
|
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
15349
|
-
if (
|
|
13862
|
+
if (messageInfo(messages[index]).role === "user")
|
|
15350
13863
|
return messages[index];
|
|
15351
13864
|
}
|
|
15352
13865
|
return;
|
|
@@ -15435,14 +13948,14 @@ function formatRustPassLog(args) {
|
|
|
15435
13948
|
return `rust pass: decision=${args.decision} reason=${args.reason}${schedulerFields}${historianFields}${identityFields} served_from=${args.servedFrom} in=${args.inputCount} out=${args.outputCount} applied=${args.applied} row_version=${rowVersion} elapsed=${args.elapsedMs.toFixed(1)} ms module=${args.moduleElapsedMs.toFixed(1)} ms stages=identity_resolve:${timings.identityResolve.toFixed(1)} prompt_surface:${timings.promptSurface.toFixed(1)} mural_resolve:${timings.muralResolve.toFixed(1)} prefix_guard:${timings.prefixGuard.toFixed(1)} ordinal_resolve:${timings.ordinalResolve.toFixed(1)} ordinal_rebuild:${timings.ordinalRebuild.toFixed(1)} ordinal_rows:${timings.ordinalRows} ordinal_mode:${timings.ordinalMode} state_sync:${timings.stateSync.toFixed(1)} clone:${timings.clone.toFixed(1)} wire_build:${timings.wireBuild.toFixed(1)} wire_messages:${timings.wireMessages} transport:${timings.transport.toFixed(1)} transport_pages:${timings.transportPages} transport_bytes:${timings.transportBytes} apply:${timings.apply.toFixed(1)} lkg_snapshot:${timings.lkgSnapshot.toFixed(1)} mirror_pull:${timings.mirrorPull.toFixed(1)} compartment_mirror:${timings.compartmentMirror.toFixed(1)} other:${unattributed.toFixed(1)} transport_lane:${timings.transportDetail.lane.toFixed(1)} transport_route:${timings.transportDetail.route.toFixed(1)} transport_encode:${timings.transportDetail.encode.toFixed(1)} transport_issue:${timings.transportDetail.issue.toFixed(1)} transport_response_wait_decode:${timings.transportDetail.responseWait.toFixed(1)} transport_settle:${timings.transportDetail.settle.toFixed(1)} transport_wrapper:${Math.max(0, timings.transport - Object.values(timings.transportDetail).reduce((sum, ms) => sum + ms, 0)).toFixed(1)} preflight:${timings.preflight.toFixed(1)} todo_verdict:${timings.todoVerdict.toFixed(1)} todo_probe:${timings.todoProbe.toFixed(1)} todo_persist:${timings.todoPersist.toFixed(1)} todo_probe_required:${timings.todoProbeRequired} todo_probe_reason:${timings.todoProbeReason} todo_unprobed_bust:${timings.todoUnprobedBust} session_directory:${timings.sessionDirectory.toFixed(1)} paging:${timings.paging.toFixed(1)} output_clone:${timings.outputClone.toFixed(1)} delivery:${timings.delivery.toFixed(1)} bookkeeping:${timings.bookkeeping.toFixed(1)}`;
|
|
15436
13949
|
}
|
|
15437
13950
|
function isSyntheticUserMessage(message) {
|
|
15438
|
-
if (!message ||
|
|
13951
|
+
if (!message || messageInfo(message).role !== "user" || !Array.isArray(message.parts)) {
|
|
15439
13952
|
return false;
|
|
15440
13953
|
}
|
|
15441
13954
|
return message.parts.length > 0 && message.parts.every((part) => isRecord4(part) && (part.synthetic === true || part.ignored === true));
|
|
15442
13955
|
}
|
|
15443
13956
|
function observeSyntheticTurn(state, messages) {
|
|
15444
13957
|
const newest = newestUserMessage(messages);
|
|
15445
|
-
const info =
|
|
13958
|
+
const info = messageInfo(newest);
|
|
15446
13959
|
const messageId = typeof info.id === "string" ? info.id : null;
|
|
15447
13960
|
const synthetic = isSyntheticUserMessage(newest);
|
|
15448
13961
|
const isNewMessage = messageId === null || messageId !== state.lastObservedUserMessageId;
|
|
@@ -15456,14 +13969,14 @@ function observeSyntheticTurn(state, messages) {
|
|
|
15456
13969
|
return synthetic;
|
|
15457
13970
|
}
|
|
15458
13971
|
function assertNativeBoundary(output, sessionId, boundaryId) {
|
|
15459
|
-
const first = output.find((message) =>
|
|
15460
|
-
const info =
|
|
13972
|
+
const first = output.find((message) => messageInfo(message).role !== "system");
|
|
13973
|
+
const info = messageInfo(first);
|
|
15461
13974
|
const parts = isRecord4(first) && Array.isArray(first.parts) ? first.parts : [];
|
|
15462
13975
|
const synthetic = parts.length > 0 && parts.every((part) => isRecord4(part) && part.synthetic === true);
|
|
15463
13976
|
if (info.role === "user" && info.sessionID === sessionId && synthetic)
|
|
15464
13977
|
return;
|
|
15465
13978
|
const headSummary = output.slice(0, 3).map((message) => {
|
|
15466
|
-
const mi =
|
|
13979
|
+
const mi = messageInfo(message);
|
|
15467
13980
|
const mParts = isRecord4(message) && Array.isArray(message.parts) ? message.parts : [];
|
|
15468
13981
|
const partDesc = mParts.slice(0, 5).map((part) => isRecord4(part) ? `${String(part.type)}${part.synthetic === true ? "" : "!"}` : "?").join(",");
|
|
15469
13982
|
return `role=${String(mi.role)} sid=${mi.sessionID === sessionId ? "ok" : String(mi.sessionID ?? "absent")} id=${String(mi.id ?? "-").slice(0, 24)} parts=[${partDesc}]`;
|
|
@@ -16247,8 +14760,15 @@ function createRustModeTransform(deps, options) {
|
|
|
16247
14760
|
sessionLog2(sessionId, fit.detail);
|
|
16248
14761
|
return false;
|
|
16249
14762
|
}
|
|
14763
|
+
rememberLkgDirtyRevision(sessionId, markLkgRecoveryDirty({
|
|
14764
|
+
sessionId,
|
|
14765
|
+
slot,
|
|
14766
|
+
processLocalProof: hasProcessLocalLkgProof(sessionId),
|
|
14767
|
+
ownDirtyRevision: lkgDirtyRevision(sessionId)
|
|
14768
|
+
}));
|
|
16250
14769
|
const replayInputCount = currentMessages.length;
|
|
16251
14770
|
replaceMessagesInPlace(output, replay.messages);
|
|
14771
|
+
ensureState(states, sessionId).lkgLatestServedDigest = lkgServedArrayDigest(JSON.stringify(replay.messages));
|
|
16252
14772
|
enterLkgReplayFreeze(ensureState(states, sessionId), replayInputCount);
|
|
16253
14773
|
sessionLog2(sessionId, "lkg_replay_served");
|
|
16254
14774
|
return true;
|
|
@@ -16385,34 +14905,40 @@ function createRustModeTransform(deps, options) {
|
|
|
16385
14905
|
agentName: deps.getNotificationParams?.(sessionId)?.agent
|
|
16386
14906
|
};
|
|
16387
14907
|
};
|
|
16388
|
-
const commitRustCapture = (state, plan, requireDurable = false) => {
|
|
14908
|
+
const commitRustCapture = (state, plan, requireDurable = false, prepareOnly = false) => {
|
|
16389
14909
|
if (states.get(plan.sessionId) !== state || plan.captureSequence !== state.lkgCaptureSequence || plan.rowVersion < state.lkgLastCapturedRowVersion) {
|
|
16390
14910
|
return "superseded";
|
|
16391
14911
|
}
|
|
16392
|
-
|
|
16393
|
-
|
|
16394
|
-
id,
|
|
16395
|
-
|
|
16396
|
-
|
|
16397
|
-
|
|
16398
|
-
|
|
16399
|
-
|
|
16400
|
-
|
|
16401
|
-
|
|
16402
|
-
|
|
16403
|
-
|
|
16404
|
-
|
|
16405
|
-
|
|
16406
|
-
|
|
16407
|
-
|
|
16408
|
-
|
|
16409
|
-
|
|
16410
|
-
|
|
16411
|
-
|
|
16412
|
-
|
|
16413
|
-
|
|
16414
|
-
|
|
14912
|
+
if (!plan.prepared) {
|
|
14913
|
+
const prior = getSlot(plan.sessionId);
|
|
14914
|
+
const inputs = plan.inputIds.map((id, index) => ({
|
|
14915
|
+
id,
|
|
14916
|
+
fields: plan.inputSnapshots[index]?.fields ?? []
|
|
14917
|
+
}));
|
|
14918
|
+
const accepted = state.lkgAcceptedCapture;
|
|
14919
|
+
const {
|
|
14920
|
+
digests: inputContentDigests,
|
|
14921
|
+
inputContentSignatures,
|
|
14922
|
+
reusedPrefix
|
|
14923
|
+
} = rustCaptureDigests(inputs, prior?.modelKey === plan.modelKey && prior?.providerKey === plan.providerKey && prior?.captureSequence === accepted?.captureSequence && prior?.rowVersion === accepted?.rowVersion ? prior : undefined, accepted?.inputs ?? null);
|
|
14924
|
+
const slot = {
|
|
14925
|
+
jsonPrefix: plan.jsonPrefix,
|
|
14926
|
+
inputIdSeq: plan.inputIds,
|
|
14927
|
+
inputContentDigests,
|
|
14928
|
+
inputContentSignatures,
|
|
14929
|
+
lastInputMessageId: plan.inputIds[plan.inputIds.length - 1],
|
|
14930
|
+
modelKey: plan.modelKey,
|
|
14931
|
+
providerKey: plan.providerKey,
|
|
14932
|
+
capturedAt: plan.capturedAt,
|
|
14933
|
+
rowVersion: plan.rowVersion,
|
|
14934
|
+
captureSequence: plan.captureSequence
|
|
14935
|
+
};
|
|
14936
|
+
plan.prepared = { slot, inputs, reusedPrefix };
|
|
14937
|
+
}
|
|
14938
|
+
const { slot, inputs, reusedPrefix } = plan.prepared;
|
|
16415
14939
|
const rejection = lkgSlotRejection(plan.sessionId, slot);
|
|
14940
|
+
if (prepareOnly)
|
|
14941
|
+
return rejection === null ? "captured" : "superseded";
|
|
16416
14942
|
const captured = rejection === null && captureSlot(plan.sessionId, slot);
|
|
16417
14943
|
if (!captured)
|
|
16418
14944
|
throw new Error(`LKG slot rejected the prepared snapshot: ${rejection ?? "over the LKG heap budget"}`);
|
|
@@ -16429,7 +14955,14 @@ function createRustModeTransform(deps, options) {
|
|
|
16429
14955
|
agentName: plan.agentName
|
|
16430
14956
|
});
|
|
16431
14957
|
options.onLkgCaptureForTests?.(reusedPrefix);
|
|
16432
|
-
const persisted = saveLkgSlotToDb(deps.db, plan.sessionId, slot
|
|
14958
|
+
const persisted = saveLkgSlotToDb(deps.db, plan.sessionId, slot, undefined, {
|
|
14959
|
+
rebuild: requireDurable,
|
|
14960
|
+
ownDirtyRevision: plan.fenceRevision ?? lkgDirtyRevision(plan.sessionId),
|
|
14961
|
+
requiredRevision: plan.fenceRevision,
|
|
14962
|
+
cleanDigest: plan.fenceRevision ? state.lkgLatestServedDigest : lkgServedArrayDigest(plan.jsonPrefix),
|
|
14963
|
+
retainDirtyRevision: !plan.eligibleForClean || plan.returnedDigest !== state.lkgLatestServedDigest ? plan.fenceRevision : undefined
|
|
14964
|
+
});
|
|
14965
|
+
plan.committed = persisted;
|
|
16433
14966
|
if (requireDurable && !persisted) {
|
|
16434
14967
|
throw new Error("priced LKG snapshot did not reach durable storage");
|
|
16435
14968
|
}
|
|
@@ -16439,10 +14972,18 @@ function createRustModeTransform(deps, options) {
|
|
|
16439
14972
|
};
|
|
16440
14973
|
const run = async (sessionId, messages, output, sessionMeta) => {
|
|
16441
14974
|
const passStartedAt = performance.now();
|
|
14975
|
+
const dateRequest = systemDateRequestForOutput(deps.historyRefreshSessions, output) ?? beginSystemDateRequest(deps.historyRefreshSessions, sessionId, "messages", systemDateTurnId(messages), systemDateRequestIdentity(output));
|
|
14976
|
+
bindSystemDateRequest(output, dateRequest);
|
|
16442
14977
|
const passObservedAtMs = Date.now();
|
|
16443
14978
|
const state = ensureState(states, sessionId);
|
|
14979
|
+
let entrySlot = getSlot(sessionId);
|
|
14980
|
+
try {
|
|
14981
|
+
entrySlot = loadPersistedLkgSlot(deps.db, sessionId, true) ?? entrySlot;
|
|
14982
|
+
} catch {}
|
|
14983
|
+
const recoveryFenceRebuild = !!entrySlot && !hasProcessLocalLkgProof(sessionId) && !hasCleanLkgRecoveryFence(sessionId, entrySlot);
|
|
16444
14984
|
let markerApplyAttempted = false;
|
|
16445
14985
|
let markerDefinitelyNoCut = false;
|
|
14986
|
+
let captureForCertificate;
|
|
16446
14987
|
let markerSafeSnapshot;
|
|
16447
14988
|
let markerOriginalMessages;
|
|
16448
14989
|
state.lastPassMarkerApplyAttempted = false;
|
|
@@ -16953,7 +15494,7 @@ function createRustModeTransform(deps, options) {
|
|
|
16953
15494
|
logStage(sessionId, "clone", cloneStartedAt, timings, wireDelta ? "mode=projection-tail" : "mode=projection-full");
|
|
16954
15495
|
const provisionalBase = wireDelta ? (() => {
|
|
16955
15496
|
for (let index = wireDelta.rawStart - 1;index >= 0; index -= 1) {
|
|
16956
|
-
const priorId =
|
|
15497
|
+
const priorId = messageIdOf(messages[index]);
|
|
16957
15498
|
if (!priorId)
|
|
16958
15499
|
continue;
|
|
16959
15500
|
const prior = state.idOrdinalMemo.get(priorId);
|
|
@@ -17005,7 +15546,7 @@ function createRustModeTransform(deps, options) {
|
|
|
17005
15546
|
state.ordinalMemoStoredCount = resolved.memoStoredCount;
|
|
17006
15547
|
state.ordinalMemoCanonicalCount = resolved.memoCanonicalCount;
|
|
17007
15548
|
state.ordinalMemoVerifyPending = false;
|
|
17008
|
-
const firstInputId = messages[0] ?
|
|
15549
|
+
const firstInputId = messages[0] ? messageIdOf(messages[0]) : null;
|
|
17009
15550
|
inputFirstOrdinal = firstInputId ? state.idOrdinalMemo.get(firstInputId) ?? null : null;
|
|
17010
15551
|
const syncPass = {
|
|
17011
15552
|
db: deps.db,
|
|
@@ -17031,10 +15572,10 @@ function createRustModeTransform(deps, options) {
|
|
|
17031
15572
|
const todoCandidates = wireDelta ? messages.slice(todoStart) : messages;
|
|
17032
15573
|
const todoCalls = wireDelta ? new Map(state.todoCallSignatures) : new Map;
|
|
17033
15574
|
for (const [offset, message] of todoCandidates.entries()) {
|
|
17034
|
-
const id =
|
|
15575
|
+
const id = messageIdOf(message) ?? `index:${todoStart + offset}`;
|
|
17035
15576
|
const parts = message.parts?.filter((part) => isRecord4(part) && part.type === "tool" && part.tool === "todowrite");
|
|
17036
15577
|
if (parts?.length) {
|
|
17037
|
-
todoCalls.set(id,
|
|
15578
|
+
todoCalls.set(id, createHash4("sha256").update(JSON.stringify(parts)).digest("hex"));
|
|
17038
15579
|
} else {
|
|
17039
15580
|
todoCalls.delete(id);
|
|
17040
15581
|
}
|
|
@@ -17120,9 +15661,9 @@ function createRustModeTransform(deps, options) {
|
|
|
17120
15661
|
return {
|
|
17121
15662
|
rawCount: messages.length,
|
|
17122
15663
|
wireCount: encodedInput.length,
|
|
17123
|
-
rawLastId: rawLast ?
|
|
15664
|
+
rawLastId: rawLast ? messageIdOf(rawLast) : null,
|
|
17124
15665
|
rawLastSignature: rawLast ? messageCacheSignature(rawLast) : null,
|
|
17125
|
-
rawLastVisible: rawLast !== undefined && encodedInput.some((entry) => entry.mid ===
|
|
15666
|
+
rawLastVisible: rawLast !== undefined && encodedInput.some((entry) => entry.mid === messageIdOf(rawLast)),
|
|
17126
15667
|
ckFingerprint: ckFingerprint.fingerprint,
|
|
17127
15668
|
ckPrefixFingerprintBeforeLast: ckFingerprint.prefixFingerprintBeforeLast,
|
|
17128
15669
|
nativeFingerprint: nativeFingerprint.fingerprint,
|
|
@@ -17146,11 +15687,11 @@ function createRustModeTransform(deps, options) {
|
|
|
17146
15687
|
nativePrefixFingerprintBeforeLast = nativeFingerprint;
|
|
17147
15688
|
nativeFingerprint = advanceWireFingerprint(nativeFingerprint, nativeMessages[index]);
|
|
17148
15689
|
}
|
|
17149
|
-
const rawLastVisible = rawLast !== undefined && encodedInput.some((entry) => entry.mid ===
|
|
15690
|
+
const rawLastVisible = rawLast !== undefined && encodedInput.some((entry) => entry.mid === messageIdOf(rawLast));
|
|
17150
15691
|
return {
|
|
17151
15692
|
rawCount: messages.length,
|
|
17152
15693
|
wireCount: wireDelta.wireStart + encodedInput.length,
|
|
17153
|
-
rawLastId: rawLast ?
|
|
15694
|
+
rawLastId: rawLast ? messageIdOf(rawLast) : null,
|
|
17154
15695
|
rawLastSignature: rawLast ? messageCacheSignature(rawLast) : null,
|
|
17155
15696
|
rawLastVisible,
|
|
17156
15697
|
ckFingerprint,
|
|
@@ -17366,9 +15907,9 @@ function createRustModeTransform(deps, options) {
|
|
|
17366
15907
|
pendingWireCache = {
|
|
17367
15908
|
rawCount: messages.length,
|
|
17368
15909
|
wireCount: retryEncodedInput.length,
|
|
17369
|
-
rawLastId: retryRawLast ?
|
|
15910
|
+
rawLastId: retryRawLast ? messageIdOf(retryRawLast) : null,
|
|
17370
15911
|
rawLastSignature: retryRawLast ? messageCacheSignature(retryRawLast) : null,
|
|
17371
|
-
rawLastVisible: retryRawLast !== undefined && retryEncodedInput.some((entry) => entry.mid ===
|
|
15912
|
+
rawLastVisible: retryRawLast !== undefined && retryEncodedInput.some((entry) => entry.mid === messageIdOf(retryRawLast)),
|
|
17372
15913
|
ckFingerprint: retryCkFingerprint.fingerprint,
|
|
17373
15914
|
ckPrefixFingerprintBeforeLast: retryCkFingerprint.prefixFingerprintBeforeLast,
|
|
17374
15915
|
nativeFingerprint: retryNativeFingerprint.fingerprint,
|
|
@@ -17511,6 +16052,11 @@ function createRustModeTransform(deps, options) {
|
|
|
17511
16052
|
} else if (coldStartLastServed) {
|
|
17512
16053
|
frozenReleaseLastServed = coldStartLastServed;
|
|
17513
16054
|
}
|
|
16055
|
+
if (recoveryFenceRebuild) {
|
|
16056
|
+
frozenReplayReleased = true;
|
|
16057
|
+
frozenReleaseReason = "lkg_recovery_fence_unproven";
|
|
16058
|
+
frozenReleaseLastServed = { messages: null, proven: false };
|
|
16059
|
+
}
|
|
17514
16060
|
if (state.lkgRepresentationFrozen && !shouldAdoptModuleAfterFreeze(moduleDecisionBusts, frozenReplayReleased)) {
|
|
17515
16061
|
if (state.lkgFrozenAtInputCount === null) {
|
|
17516
16062
|
state.lkgFrozenAtInputCount = inputCount;
|
|
@@ -17541,11 +16087,32 @@ function createRustModeTransform(deps, options) {
|
|
|
17541
16087
|
frozenReleaseReason = releaseReason;
|
|
17542
16088
|
frozenReleaseLastServed = lastServedSnapshot();
|
|
17543
16089
|
} else {
|
|
17544
|
-
|
|
17545
|
-
|
|
17546
|
-
|
|
17547
|
-
|
|
17548
|
-
|
|
16090
|
+
let frozenAdmitted = false;
|
|
16091
|
+
try {
|
|
16092
|
+
const frozenSlot = getSlot(sessionId);
|
|
16093
|
+
if (!frozenSlot)
|
|
16094
|
+
throw new LkgRecoveryFenceError("Frozen request disappeared before return");
|
|
16095
|
+
rememberLkgDirtyRevision(sessionId, markLkgRecoveryDirty({
|
|
16096
|
+
sessionId,
|
|
16097
|
+
slot: frozenSlot,
|
|
16098
|
+
processLocalProof: hasProcessLocalLkgProof(sessionId),
|
|
16099
|
+
ownDirtyRevision: lkgDirtyRevision(sessionId)
|
|
16100
|
+
}));
|
|
16101
|
+
frozenAdmitted = true;
|
|
16102
|
+
} catch (error) {
|
|
16103
|
+
if (!(error instanceof LkgRecoveryFenceError))
|
|
16104
|
+
throw error;
|
|
16105
|
+
frozenReplayReleased = true;
|
|
16106
|
+
frozenReleaseReason = "lkg_recovery_fence_unproven";
|
|
16107
|
+
frozenReleaseLastServed = lastServedSnapshot();
|
|
16108
|
+
}
|
|
16109
|
+
if (frozenAdmitted) {
|
|
16110
|
+
appliedMessages = frozen.messages;
|
|
16111
|
+
replayedFrozenRepresentation = true;
|
|
16112
|
+
servedFrom = "lkg_frozen";
|
|
16113
|
+
sessionLog2(sessionId, "lkg_frozen_replay_served");
|
|
16114
|
+
sessionLog2(sessionId, `lkg_frozen_replay_debt healthy_passes=${frozenHealthyPassesAfterApply} raw_messages=${rawTailGrowth}`);
|
|
16115
|
+
}
|
|
17549
16116
|
}
|
|
17550
16117
|
}
|
|
17551
16118
|
}
|
|
@@ -17676,6 +16243,23 @@ function createRustModeTransform(deps, options) {
|
|
|
17676
16243
|
let captureMode = "async";
|
|
17677
16244
|
if (capturePlan)
|
|
17678
16245
|
state.lkgLastServedCaptureSequence = capturePlan.captureSequence;
|
|
16246
|
+
if (capturePlan) {
|
|
16247
|
+
const previousSlot = getSlot(sessionId);
|
|
16248
|
+
const installed = commitRustCapture(state, capturePlan, false, true);
|
|
16249
|
+
if (installed === "captured" && capturePlan.prepared) {
|
|
16250
|
+
if (!synchronousReplacement && !state.lkgSyncCaptureRequired) {
|
|
16251
|
+
capturePlan.fenceRevision = prepareLkgCaptureFence({
|
|
16252
|
+
sessionId,
|
|
16253
|
+
previousSlot,
|
|
16254
|
+
slot: capturePlan.prepared.slot,
|
|
16255
|
+
ownDirtyRevision: lkgDirtyRevision(sessionId),
|
|
16256
|
+
rebuild: synchronousReplacement
|
|
16257
|
+
});
|
|
16258
|
+
rememberLkgDirtyRevision(sessionId, capturePlan.fenceRevision);
|
|
16259
|
+
}
|
|
16260
|
+
captureForCertificate = capturePlan;
|
|
16261
|
+
}
|
|
16262
|
+
}
|
|
17679
16263
|
const endRecoveryAfterResetCapture = () => {
|
|
17680
16264
|
if (signedThinkingReset && thinkingRecovery.restore) {
|
|
17681
16265
|
endLatestThinkingRecoveryAfterReset(deps.db, sessionId);
|
|
@@ -17685,13 +16269,14 @@ function createRustModeTransform(deps, options) {
|
|
|
17685
16269
|
if (states.get(sessionId) !== state || capturePlan && capturePlan.captureSequence !== state.lkgCaptureSequence) {
|
|
17686
16270
|
return;
|
|
17687
16271
|
}
|
|
17688
|
-
if (!markerDefinitelyNoCut)
|
|
16272
|
+
if (!markerDefinitelyNoCut && !(error instanceof LkgRecoveryFenceError))
|
|
17689
16273
|
dropSlot(sessionId, `lkg_${mode}_capture_failed`);
|
|
17690
16274
|
state.lkgAcceptedCapture = undefined;
|
|
17691
16275
|
state.lkgSyncCaptureRequired = true;
|
|
17692
16276
|
sessionLog2(sessionId, `LKG ${mode.toUpperCase()} CAPTURE FAILED; forcing synchronous capture on the next applied pass:`, error);
|
|
17693
16277
|
};
|
|
17694
16278
|
if (!capturePlan) {
|
|
16279
|
+
invalidateCleanLkgRecoveryFence(sessionId, () => loadPersistedLkgSlot(deps.db, sessionId));
|
|
17695
16280
|
captureMode = "declined";
|
|
17696
16281
|
const error = new Error("LKG snapshot preparation was rejected");
|
|
17697
16282
|
captureFailed("async", error);
|
|
@@ -17704,7 +16289,7 @@ function createRustModeTransform(deps, options) {
|
|
|
17704
16289
|
endRecoveryAfterResetCapture();
|
|
17705
16290
|
} catch (error) {
|
|
17706
16291
|
captureFailed("sync", error);
|
|
17707
|
-
if (synchronousReplacement)
|
|
16292
|
+
if (synchronousReplacement || error instanceof LkgRecoveryFenceError)
|
|
17708
16293
|
throw error;
|
|
17709
16294
|
}
|
|
17710
16295
|
} else {
|
|
@@ -17730,6 +16315,7 @@ function createRustModeTransform(deps, options) {
|
|
|
17730
16315
|
throw error;
|
|
17731
16316
|
}
|
|
17732
16317
|
const bookkeepingStartedAt = performance.now();
|
|
16318
|
+
finishSystemDateRefresh(deps.historyRefreshSessions, dateRequest, moduleDecisionBusts);
|
|
17733
16319
|
if (shouldAdoptModuleAfterFreeze(moduleDecisionBusts, frozenReplayReleased)) {
|
|
17734
16320
|
if (frozenReleaseReason) {
|
|
17735
16321
|
sessionLog2(sessionId, `lkg_frozen_replay_released reason=${frozenReleaseReason}`);
|
|
@@ -17842,17 +16428,66 @@ function createRustModeTransform(deps, options) {
|
|
|
17842
16428
|
systemPromptHash: sessionMeta.systemPromptHash
|
|
17843
16429
|
});
|
|
17844
16430
|
captureOpencodeReasoningBudgetStatus(sessionId, output.messages, resolveKeepReasoningTokens(deps.keepReasoningTokens, modelKey ?? undefined), isPrefixBoundThinkingModel(model?.providerID, model?.modelID));
|
|
16431
|
+
if (!moduleDecisionBusts && inputHasActiveThinking && isPrefixBoundThinkingModel(model?.providerID, model?.modelID)) {
|
|
16432
|
+
recordHeldHeadForRequest(sessionId, currentLkgRequestIdentity(sessionId), (ownsHistory) => deferDeliveredSystemRefresh(deps, sessionId, ownsHistory));
|
|
16433
|
+
}
|
|
17845
16434
|
finishPass(true);
|
|
17846
16435
|
if (state.markerAdmissionFenced) {
|
|
17847
16436
|
setRustMarkerAdmissionFence(deps.db, sessionId, false);
|
|
17848
16437
|
state.markerAdmissionFenced = false;
|
|
17849
16438
|
}
|
|
16439
|
+
const returnedJson = JSON.stringify(output.messages);
|
|
16440
|
+
state.lkgLatestServedDigest = lkgServedArrayDigest(returnedJson);
|
|
16441
|
+
if (captureForCertificate) {
|
|
16442
|
+
captureForCertificate.returnedDigest = state.lkgLatestServedDigest;
|
|
16443
|
+
if (captureForCertificate.prepared && captureForCertificate.captureSequence === state.lkgCaptureSequence && captureForCertificate.rowVersion >= state.lkgLastCapturedRowVersion) {
|
|
16444
|
+
const returnedSlot = {
|
|
16445
|
+
...captureForCertificate.prepared.slot,
|
|
16446
|
+
jsonPrefix: returnedJson
|
|
16447
|
+
};
|
|
16448
|
+
captureSlot(sessionId, returnedSlot);
|
|
16449
|
+
noteCapturedLkgRequest({
|
|
16450
|
+
sessionId,
|
|
16451
|
+
slot: returnedSlot,
|
|
16452
|
+
request: captureForCertificate.requestIdentity,
|
|
16453
|
+
systemPromptTokens: captureForCertificate.systemPromptTokens,
|
|
16454
|
+
agentName: captureForCertificate.agentName
|
|
16455
|
+
});
|
|
16456
|
+
}
|
|
16457
|
+
captureForCertificate.eligibleForClean = lkgServedArrayDigest(captureForCertificate.jsonPrefix) === state.lkgLatestServedDigest;
|
|
16458
|
+
if ((!captureForCertificate.committed || !captureForCertificate.eligibleForClean) && captureForCertificate.prepared && !captureForCertificate.fenceRevision) {
|
|
16459
|
+
captureForCertificate.fenceRevision = prepareLkgCaptureFence({
|
|
16460
|
+
sessionId,
|
|
16461
|
+
slot: captureForCertificate.prepared.slot,
|
|
16462
|
+
previousSlot: loadPersistedLkgSlot(deps.db, sessionId, true),
|
|
16463
|
+
ownDirtyRevision: lkgDirtyRevision(sessionId),
|
|
16464
|
+
rebuild: true
|
|
16465
|
+
});
|
|
16466
|
+
rememberLkgDirtyRevision(sessionId, captureForCertificate.fenceRevision);
|
|
16467
|
+
}
|
|
16468
|
+
if (captureForCertificate.committed && captureForCertificate.eligibleForClean && captureForCertificate.prepared && captureForCertificate.fenceRevision) {
|
|
16469
|
+
try {
|
|
16470
|
+
certifyCommittedLkgCapture({
|
|
16471
|
+
sessionId,
|
|
16472
|
+
slot: captureForCertificate.prepared.slot,
|
|
16473
|
+
revision: captureForCertificate.fenceRevision,
|
|
16474
|
+
latestServedDigest: state.lkgLatestServedDigest,
|
|
16475
|
+
load: () => loadPersistedLkgSlot(deps.db, sessionId, true)
|
|
16476
|
+
});
|
|
16477
|
+
} catch (error) {
|
|
16478
|
+
sessionLog2(sessionId, "Last-good certificate remains dirty after publication failure:", error);
|
|
16479
|
+
}
|
|
16480
|
+
}
|
|
16481
|
+
}
|
|
17850
16482
|
} catch (error) {
|
|
17851
16483
|
if (markerDefinitelyNoCut) {
|
|
17852
16484
|
try {
|
|
17853
16485
|
deps.db.transaction(() => {
|
|
17854
16486
|
if (markerSafeSnapshot) {
|
|
17855
|
-
if (!saveLkgSlotToDb(deps.db, sessionId, markerSafeSnapshot
|
|
16487
|
+
if (!saveLkgSlotToDb(deps.db, sessionId, markerSafeSnapshot, undefined, {
|
|
16488
|
+
ownDirtyRevision: captureForCertificate?.fenceRevision,
|
|
16489
|
+
requiredRevision: captureForCertificate?.fenceRevision
|
|
16490
|
+
}))
|
|
17856
16491
|
throw new Error("could not restore the unchanged-boundary LKG");
|
|
17857
16492
|
} else {
|
|
17858
16493
|
clearPersistedLkgSlotStrict(deps.db, sessionId);
|
|
@@ -17942,7 +16577,7 @@ function createRustModeTransform(deps, options) {
|
|
|
17942
16577
|
});
|
|
17943
16578
|
}
|
|
17944
16579
|
const refusedUser = newestUserMessage(messages);
|
|
17945
|
-
const refusedUserMessageId = refusedUser ?
|
|
16580
|
+
const refusedUserMessageId = refusedUser ? messageIdOf(refusedUser) : null;
|
|
17946
16581
|
if (refusedUserMessageId) {
|
|
17947
16582
|
try {
|
|
17948
16583
|
options.onEngineReconnectRefusal?.({
|
|
@@ -18497,6 +17132,7 @@ function resolveTransformHostSeams(deps) {
|
|
|
18497
17132
|
};
|
|
18498
17133
|
}
|
|
18499
17134
|
function createTransform(deps) {
|
|
17135
|
+
registerSystemDateRefresh(deps.historyRefreshSessions);
|
|
18500
17136
|
const finalWireUsage = createFinalWireUsageTracker();
|
|
18501
17137
|
const host = resolveTransformHostSeams(deps);
|
|
18502
17138
|
const loadedSessions = new Set;
|
|
@@ -18520,8 +17156,8 @@ function createTransform(deps) {
|
|
|
18520
17156
|
entryReuse = stats;
|
|
18521
17157
|
}
|
|
18522
17158
|
});
|
|
18523
|
-
const deferredHistoryRefreshSessions = deps.deferredHistoryRefreshSessions
|
|
18524
|
-
const deferredMaterializationSessions = deps.deferredMaterializationSessions
|
|
17159
|
+
const deferredHistoryRefreshSessions = deps.deferredHistoryRefreshSessions ??= new Set;
|
|
17160
|
+
const deferredMaterializationSessions = deps.deferredMaterializationSessions ??= new Set;
|
|
18525
17161
|
const observeCommitNudgeTransition = (sessionId, hasRecentCommit, isSubagent) => {
|
|
18526
17162
|
const hadPriorCommitState = deps.commitSeenLastPass?.has(sessionId) ?? false;
|
|
18527
17163
|
const sawCommitLastPass = deps.commitSeenLastPass?.get(sessionId) ?? false;
|
|
@@ -18542,11 +17178,14 @@ function createTransform(deps) {
|
|
|
18542
17178
|
return;
|
|
18543
17179
|
}
|
|
18544
17180
|
deps.onMessagesPassStarted?.(sessionId, messages);
|
|
17181
|
+
const dateRequest = systemDateRequestForOutput(deps.historyRefreshSessions, output) ?? beginSystemDateRequest(deps.historyRefreshSessions, sessionId, "messages", systemDateTurnId(messages), systemDateRequestIdentity(output));
|
|
17182
|
+
bindSystemDateRequest(output, dateRequest);
|
|
18545
17183
|
const temporalCandidates = deps.experimentalTemporalAwareness ? collectTemporalCandidates(messages) : undefined;
|
|
18546
17184
|
const temporalReplayIds = temporalCandidates ? messages.flatMap((message) => message.info.id ? [message.info.id] : []) : undefined;
|
|
18547
17185
|
logTransformTiming(sessionId, "findSessionId", tSessionId, `messages=${messages.length}`);
|
|
18548
17186
|
const tLkgEntry = performance.now();
|
|
18549
17187
|
const lkgInput = deps.transformMode === "rust" ? [] : projectEntry(sessionId, messages);
|
|
17188
|
+
const recovery = deps.compactionOff || deps.transformMode === "rust" ? {} : readLkgRecoveryPrefix(sessionId, lkgInput, messages, deps.db);
|
|
18550
17189
|
logTransformTiming(sessionId, "lkg.entryProjection", tLkgEntry, deps.transformMode === "rust" || !entryReuse ? undefined : `reused=${entryReuse.reused} retained=${entryReuse.retained} retainedBytes=${entryReuse.retainedBytes}`);
|
|
18551
17190
|
const resolvedSessionId = sessionId;
|
|
18552
17191
|
const runNotificationParams = (sid) => {
|
|
@@ -18930,7 +17569,7 @@ function createTransform(deps) {
|
|
|
18930
17569
|
const schedulerDeferReason = schedulerDecision === "defer" ? "scheduler_defer" : null;
|
|
18931
17570
|
const historyRefreshExplicitBeforePrepare = !freezeM0M1 && deps.historyRefreshSessions.has(sessionId);
|
|
18932
17571
|
const deferredHistoryWasPendingAtPassStart = !freezeM0M1 && deferredHistoryRefreshSessions.has(sessionId);
|
|
18933
|
-
const prefixTrimSourceOrder =
|
|
17572
|
+
const prefixTrimSourceOrder = capturePrefixTrimSourceOrder(messages);
|
|
18934
17573
|
const earlyActiveRunBlocksMaterialization = (getActiveCompartmentRun(sessionId) !== undefined || sessionMeta.compartmentInProgress) && contextUsageEarly.percentage < forceMaterializationPercentage;
|
|
18935
17574
|
const canConsumeDeferredEarly = canConsumeDeferredOnThisPass({
|
|
18936
17575
|
schedulerDecision,
|
|
@@ -19143,6 +17782,26 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19143
17782
|
logTransformTiming(sessionId, "injectTemporalMarkers", tTemporal);
|
|
19144
17783
|
}
|
|
19145
17784
|
let taggingSucceeded = false;
|
|
17785
|
+
let recoveryBatch = null;
|
|
17786
|
+
let recoveryNormalized = false;
|
|
17787
|
+
const normalizeRecoveryTail = recovery.prefix ? () => {
|
|
17788
|
+
if (recoveryNormalized)
|
|
17789
|
+
return;
|
|
17790
|
+
const tail = messages.filter((message) => recovery.prefix?.untaggedInputIds.has(message.info.id ?? ""));
|
|
17791
|
+
const tagged = tagMessages(sessionId, tail, deps.tagger, db, {
|
|
17792
|
+
skipPrefixInjection: !ctxReduceCallable,
|
|
17793
|
+
servedMessages: messages,
|
|
17794
|
+
normalizeRestoredAssistantText: deps.normalizeRestoredAssistantText
|
|
17795
|
+
});
|
|
17796
|
+
for (const [number, target] of tagged.targets)
|
|
17797
|
+
targets.set(number, target);
|
|
17798
|
+
for (const [message, parts] of tagged.reasoningByMessage)
|
|
17799
|
+
reasoningByMessage.set(message, parts);
|
|
17800
|
+
for (const [message, number] of tagged.messageTagNumbers)
|
|
17801
|
+
messageTagNumbers.set(message, number);
|
|
17802
|
+
recoveryBatch = tagged.batch;
|
|
17803
|
+
recoveryNormalized = true;
|
|
17804
|
+
} : undefined;
|
|
19146
17805
|
if (!compactionOff) {
|
|
19147
17806
|
try {
|
|
19148
17807
|
const t0 = performance.now();
|
|
@@ -19153,17 +17812,23 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19153
17812
|
const messagesForTagging = messagesBeforeInitialPrepare && hiddenMessagesAtCompactionSeam.length > 0 ? messagesBeforeInitialPrepare : messages;
|
|
19154
17813
|
const canAdoptScopedToolSweep = isCacheBusting || canConsumeDeferredEarly;
|
|
19155
17814
|
const scopedToolSweep = useScopedToolSweep(db, sessionId, canAdoptScopedToolSweep) ? true : createPreAdoptionToolSweepResolver(db, sessionId);
|
|
19156
|
-
const result = tagMessages(sessionId, messagesForTagging, deps.tagger, db, {
|
|
17815
|
+
const result = tagMessages(sessionId, recovery.prefix ? messagesForTagging.filter((message) => !recovery.prefix?.untaggedInputIds.has(message.info.id ?? "")) : messagesForTagging, deps.tagger, db, {
|
|
19157
17816
|
skipPrefixInjection,
|
|
19158
17817
|
scopedToolSweep,
|
|
19159
|
-
servedMessages: messages
|
|
17818
|
+
servedMessages: messages,
|
|
17819
|
+
normalizeRestoredAssistantText: deps.normalizeRestoredAssistantText
|
|
19160
17820
|
});
|
|
19161
17821
|
targets = result.targets;
|
|
19162
17822
|
if (thinkingRecovery.restore)
|
|
19163
17823
|
restoreLatestTurnOriginals = captureLatestTurnOriginals(messages);
|
|
19164
17824
|
reasoningByMessage = result.reasoningByMessage;
|
|
19165
17825
|
messageTagNumbers = result.messageTagNumbers;
|
|
19166
|
-
batch =
|
|
17826
|
+
batch = {
|
|
17827
|
+
finalize: () => {
|
|
17828
|
+
result.batch?.finalize();
|
|
17829
|
+
recoveryBatch?.finalize();
|
|
17830
|
+
}
|
|
17831
|
+
};
|
|
19167
17832
|
if (resolvedProviderID && !isAnthropicFamilyRoute(resolvedProviderID, modelForBudget?.modelID)) {
|
|
19168
17833
|
for (const target of targets.values()) {
|
|
19169
17834
|
if (target.requiresToolArcSkeleton)
|
|
@@ -19284,7 +17949,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19284
17949
|
sessionMeta = { ...sessionMeta, compartmentInProgress };
|
|
19285
17950
|
logTransformTiming(sessionId, "compartmentPhase", tCompartmentPhase);
|
|
19286
17951
|
if (pendingCompartmentInjection?.needsFreshMaterialization) {
|
|
19287
|
-
deps.pendingMaterializationSessions
|
|
17952
|
+
requestPendingMaterialization(deps.pendingMaterializationSessions, sessionId, "boundary_repair");
|
|
19288
17953
|
deferredMaterializationSessions.add(sessionId);
|
|
19289
17954
|
}
|
|
19290
17955
|
const hardModel = deps.liveModelBySession?.get(sessionId);
|
|
@@ -19380,6 +18045,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19380
18045
|
const protectedCutoff = protectionWindow.cutoff;
|
|
19381
18046
|
const tPostProcess = performance.now();
|
|
19382
18047
|
const postTransformResult = await runPostTransformPhase({
|
|
18048
|
+
normalizeRecoveryTail,
|
|
19383
18049
|
compactionMarkerStrategy: deps.compactionMarkerStrategy ?? defaultCompactionMarkerStrategy,
|
|
19384
18050
|
sessionId,
|
|
19385
18051
|
db,
|
|
@@ -19412,7 +18078,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19412
18078
|
freezeM0M1,
|
|
19413
18079
|
activeThinkingPrefixHold,
|
|
19414
18080
|
directoryPrefixHold: unresolvedDirectoryHold,
|
|
19415
|
-
forceSignedRebuildForFit: thinkingFitRetries.has(sessionId),
|
|
18081
|
+
forceSignedRebuildForFit: thinkingFitRetries.has(sessionId) || !!recovery.rebuildReason,
|
|
19416
18082
|
readLastServedMessages: () => {
|
|
19417
18083
|
const slot = getInMemorySlot(sessionId) ?? loadPersistedLkgSlot(db, sessionId);
|
|
19418
18084
|
try {
|
|
@@ -19475,6 +18141,15 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19475
18141
|
muralEnabled: deps.muralEnabled
|
|
19476
18142
|
}
|
|
19477
18143
|
});
|
|
18144
|
+
if (recovery.prefix && !recoveryNormalized) {
|
|
18145
|
+
const priorIds = new Set(recovery.prefix.inputs.map((input) => input.id));
|
|
18146
|
+
const newIds = new Set(lkgInput.flatMap((input) => input.id && !priorIds.has(input.id) ? [input.id] : []));
|
|
18147
|
+
const suffix = messages.filter((message) => message.info.id && newIds.has(message.info.id));
|
|
18148
|
+
messages.splice(0, messages.length, ...JSON.parse(recovery.prefix.json), ...suffix);
|
|
18149
|
+
}
|
|
18150
|
+
const recoveryReleaseReason = recovery.rebuildReason ?? (recoveryNormalized ? "recovery_tail_normalized" : undefined);
|
|
18151
|
+
if (recoveryReleaseReason)
|
|
18152
|
+
postTransformResult.bustedThisPass = true;
|
|
19478
18153
|
passOutcome.markFinalized();
|
|
19479
18154
|
const finalWireTail = describeFinalWireTail(messages);
|
|
19480
18155
|
let finalWireEstimate;
|
|
@@ -19508,7 +18183,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19508
18183
|
if ((finalWireEstimate?.refusalGrade || finalWireEstimate?.refusalBasis === "byte-bound" && finalWireEstimate.refusalTokens !== undefined) && boundaryContextLimit > 0 && (finalWireEstimate.refusalTokens ?? finalWireEstimate.tokens) > boundaryContextLimit) {
|
|
19509
18184
|
if (!thinkingFitRetries.has(sessionId) && activeThinkingPrefixHold && originalForThinkingFit && hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID)) {
|
|
19510
18185
|
thinkingFitRetries.add(sessionId);
|
|
19511
|
-
deps.pendingMaterializationSessions
|
|
18186
|
+
requestPendingMaterialization(deps.pendingMaterializationSessions, sessionId, "fit_retry");
|
|
19512
18187
|
messages.splice(0, messages.length, ...originalForThinkingFit);
|
|
19513
18188
|
try {
|
|
19514
18189
|
await transform({}, output);
|
|
@@ -19634,11 +18309,16 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19634
18309
|
if (!finalWireEstimate) {
|
|
19635
18310
|
sessionLog2(sessionId, `transform: final-wire telemetry estimate=unavailable trusted=false conversation=unknown tools=unknown system=unknown toolDefinitions=unknown tail=${finalWireTail}`);
|
|
19636
18311
|
}
|
|
19637
|
-
|
|
18312
|
+
finishSystemDateRefresh(deps.historyRefreshSessions, dateRequest, postTransformResult.bustedThisPass && !activeThinkingPrefixHold || postTransformResult.thinkingReleasedForFit === true);
|
|
18313
|
+
if (activeThinkingPrefixHold && !postTransformResult.thinkingReleasedForFit && sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) {
|
|
18314
|
+
recordHeldHeadForRequest(sessionId, currentLkgRequestIdentity(sessionId), (ownsHistory) => deferDeliveredSystemRefresh(deps, sessionId, ownsHistory));
|
|
18315
|
+
}
|
|
18316
|
+
if (passOutcome.captureEligible || recovery.prefix || recoveryReleaseReason) {
|
|
19638
18317
|
const keys = resolveLkgModelKeys(messages);
|
|
19639
18318
|
const modelKey = modelForBudget ? `${modelForBudget.providerID}/${modelForBudget.modelID}` : keys.modelKey;
|
|
19640
18319
|
const providerKey = modelForBudget?.providerID ?? keys.providerKey;
|
|
19641
18320
|
const captured = captureLkgSlot({
|
|
18321
|
+
completeOutput: !!recovery.prefix || !!recoveryReleaseReason || isPrefixBoundThinkingModel(resolvedProviderID, modelForBudget?.modelID),
|
|
19642
18322
|
sessionId,
|
|
19643
18323
|
input: lkgInput,
|
|
19644
18324
|
output: messages,
|
|
@@ -19650,13 +18330,37 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19650
18330
|
if (captured) {
|
|
19651
18331
|
const capturedSlot = getInMemorySlot(sessionId);
|
|
19652
18332
|
if (capturedSlot) {
|
|
19653
|
-
|
|
18333
|
+
const revision = lkgDirtyRevision(sessionId) ?? dirtyLkgRecoveryRevision(sessionId, capturedSlot);
|
|
18334
|
+
const fence = {
|
|
18335
|
+
ownDirtyRevision: revision,
|
|
18336
|
+
requiredRevision: revision && ownsLkgDirtyFence(sessionId, revision) ? revision : undefined,
|
|
18337
|
+
rebuild: !!recoveryReleaseReason,
|
|
18338
|
+
retainDirtyRevision: recovery.prefix && !recoveryReleaseReason ? revision : undefined
|
|
18339
|
+
};
|
|
18340
|
+
withoutSqliteTransformPass2(() => setImmediate(() => {
|
|
18341
|
+
if (fence.requiredRevision) {
|
|
18342
|
+
const latest = getInMemorySlot(sessionId);
|
|
18343
|
+
if (!latest || latest.capturedAt !== capturedSlot.capturedAt || latest.jsonPrefix !== capturedSlot.jsonPrefix || latest.lastInputMessageId !== capturedSlot.lastInputMessageId || latest.modelKey !== capturedSlot.modelKey || latest.providerKey !== capturedSlot.providerKey)
|
|
18344
|
+
return;
|
|
18345
|
+
}
|
|
18346
|
+
try {
|
|
18347
|
+
saveLkgSlotToDb(db, sessionId, capturedSlot, undefined, fence);
|
|
18348
|
+
} catch (error) {
|
|
18349
|
+
sessionLog2(sessionId, "Last-good deferred publication remains uncertified:", error);
|
|
18350
|
+
}
|
|
18351
|
+
}));
|
|
19654
18352
|
}
|
|
18353
|
+
noteLkgHealthyPrefix(sessionId, lkgInput, messages, !!recoveryReleaseReason);
|
|
19655
18354
|
}
|
|
19656
|
-
if (
|
|
19657
|
-
|
|
18355
|
+
if (!captured) {
|
|
18356
|
+
if (postTransformResult.bustedThisPass)
|
|
18357
|
+
dropSlot(sessionId, "lkg_refresh_declined");
|
|
18358
|
+
noteUncertifiedNormalLkg(sessionId, invalidateCleanLkgRecoveryFence(sessionId, () => loadPersistedLkgSlot(db, sessionId, true), lkgDirtyRevision(sessionId)));
|
|
19658
18359
|
}
|
|
19659
18360
|
} else if (passOutcome.degradations.length > 0) {
|
|
18361
|
+
if (compactionOff) {
|
|
18362
|
+
noteUncertifiedNormalLkg(sessionId, invalidateCleanLkgRecoveryFence(sessionId, () => loadPersistedLkgSlot(db, sessionId, true), lkgDirtyRevision(sessionId)));
|
|
18363
|
+
}
|
|
19660
18364
|
sessionLog2(sessionId, `lkg_capture_declined degradations=${passOutcome.degradations.map((item) => item.site).join(",")}`);
|
|
19661
18365
|
}
|
|
19662
18366
|
if (postTransformResult.bustedThisPass || hardCacheExpired) {
|
|
@@ -19675,7 +18379,8 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19675
18379
|
droppedTokens: postTransformResult.droppedTokens,
|
|
19676
18380
|
droppedCount: postTransformResult.droppedCount,
|
|
19677
18381
|
inputTokens: contextUsage.inputTokens,
|
|
19678
|
-
bustedThisPass: true
|
|
18382
|
+
bustedThisPass: true,
|
|
18383
|
+
lkgFrozenReleaseReason: recoveryReleaseReason
|
|
19679
18384
|
});
|
|
19680
18385
|
}
|
|
19681
18386
|
logTransformTiming(sessionId, "postTransformPhase", tPostProcess);
|
|
@@ -19955,6 +18660,8 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
19955
18660
|
dropSlot(sessionId, "lkg_invalidated_reshape");
|
|
19956
18661
|
sessionLog2(sessionId, "lkg_invalidated_reshape");
|
|
19957
18662
|
} else if (sessionId && entry) {
|
|
18663
|
+
if (!args.rust && lkgRecoveryEntryUnproven(sessionId, entry, output.messages))
|
|
18664
|
+
return false;
|
|
19958
18665
|
let replayBlocked = false;
|
|
19959
18666
|
try {
|
|
19960
18667
|
const db = openDatabase();
|
|
@@ -19982,6 +18689,10 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
19982
18689
|
resolvedProviderID: keys.providerKey ?? undefined
|
|
19983
18690
|
})
|
|
19984
18691
|
});
|
|
18692
|
+
if (replay.ok && !rust && lkgRecoveryReplayUnproven(sessionId)) {
|
|
18693
|
+
sessionLog2(sessionId, "lkg_restart_rebuild_required");
|
|
18694
|
+
return false;
|
|
18695
|
+
}
|
|
19985
18696
|
let tsFit = true;
|
|
19986
18697
|
if (replay.ok && !rust && keys.providerKey && keys.modelKey) {
|
|
19987
18698
|
const model = {
|
|
@@ -20012,6 +18723,24 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
20012
18723
|
replayBlocked = true;
|
|
20013
18724
|
sessionLog2(sessionId, "lkg_replay_does_not_fit");
|
|
20014
18725
|
} else if (replay.ok) {
|
|
18726
|
+
const recoverySlot = getSlot(sessionId);
|
|
18727
|
+
if (!recoverySlot)
|
|
18728
|
+
return false;
|
|
18729
|
+
const revision = markLkgRecoveryDirty({
|
|
18730
|
+
sessionId,
|
|
18731
|
+
slot: recoverySlot,
|
|
18732
|
+
processLocalProof: hasProcessLocalLkgProof(sessionId),
|
|
18733
|
+
ownDirtyRevision: lkgDirtyRevision(sessionId)
|
|
18734
|
+
});
|
|
18735
|
+
rememberLkgDirtyRevision(sessionId, revision);
|
|
18736
|
+
if (!rust && !noteLkgRecoveryPrefix({
|
|
18737
|
+
sessionId,
|
|
18738
|
+
entry,
|
|
18739
|
+
messages: replay.messages,
|
|
18740
|
+
...keys
|
|
18741
|
+
}))
|
|
18742
|
+
return false;
|
|
18743
|
+
retirePendingSystemPromptDelivery(sessionId);
|
|
20015
18744
|
args.onLkgReplay?.();
|
|
20016
18745
|
replaceMessagesInPlace2(output, replay.messages);
|
|
20017
18746
|
noteExternalLkgReplay(rust, sessionId, inputCount);
|
|
@@ -20801,7 +19530,7 @@ function getAsyncModule() {
|
|
|
20801
19530
|
await beforeModuleLoad();
|
|
20802
19531
|
const [{ default: singlefileAsyncifyVariant }, { newQuickJSAsyncWASMModuleFromVariant }] = await importPluginModule(() => Promise.all([
|
|
20803
19532
|
import("./index-6e4mwffh.js").then((m)=>__toESM(m.default,1)),
|
|
20804
|
-
import("./index-
|
|
19533
|
+
import("./index-69vas84q.js")
|
|
20805
19534
|
]));
|
|
20806
19535
|
const module = await newQuickJSAsyncWASMModuleFromVariant(singlefileAsyncifyVariant);
|
|
20807
19536
|
return module;
|
|
@@ -21324,7 +20053,7 @@ function computeOpenCodeWorkMetricsIncremental(openCodeDb, sessionId, carry) {
|
|
|
21324
20053
|
import { readFileSync, statSync } from "node:fs";
|
|
21325
20054
|
|
|
21326
20055
|
// src/plugin/embedding-bootstrap-helpers.ts
|
|
21327
|
-
import { createHash as
|
|
20056
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
21328
20057
|
var EMBEDDING_AFFECTING_KEYS = new Set([
|
|
21329
20058
|
"embedding.api_key",
|
|
21330
20059
|
"embedding.endpoint",
|
|
@@ -21372,7 +20101,7 @@ var EMBEDDING_WARNING_TERMS = [
|
|
|
21372
20101
|
];
|
|
21373
20102
|
var loggedFailureSignatures = new Map;
|
|
21374
20103
|
function sha256Prefix(value, length = 16) {
|
|
21375
|
-
return
|
|
20104
|
+
return createHash5("sha256").update(value).digest("hex").slice(0, length);
|
|
21376
20105
|
}
|
|
21377
20106
|
function warningLooksEmbeddingRelated(message) {
|
|
21378
20107
|
const lower = message.toLowerCase();
|
|
@@ -22826,7 +21555,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
22826
21555
|
return { count: buildCompartmentCount(db, sessionId, moduleStatus) };
|
|
22827
21556
|
});
|
|
22828
21557
|
const buildManagedCtx = async (db) => {
|
|
22829
|
-
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-
|
|
21558
|
+
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-enckmg7y.js"));
|
|
22830
21559
|
const { resolveHistorianModel } = await importPluginModule(() => import("./model-resolution-nx97z3x7.js"));
|
|
22831
21560
|
const { userMemoryCollectionEnabled } = await importPluginModule(() => import("./task-config-x0hq3qfd.js"));
|
|
22832
21561
|
const DEFAULT_HISTORIAN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
@@ -22862,8 +21591,8 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
22862
21591
|
const db = readDatabase();
|
|
22863
21592
|
if (!db)
|
|
22864
21593
|
return { ok: false, error: "db unavailable" };
|
|
22865
|
-
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-
|
|
22866
|
-
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-
|
|
21594
|
+
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-5xy7w136.js"));
|
|
21595
|
+
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-f6v698r5.js"));
|
|
22867
21596
|
log2(`[rpc] recomp requested for session ${sessionId}`);
|
|
22868
21597
|
if (!args.client && !args.hiddenCompletionExecutor) {
|
|
22869
21598
|
return {
|
|
@@ -22915,7 +21644,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
22915
21644
|
}
|
|
22916
21645
|
liveSessionState.historyRefreshSessions.add(sessionId);
|
|
22917
21646
|
liveSessionState.systemPromptRefreshSessions.add(sessionId);
|
|
22918
|
-
liveSessionState.pendingMaterializationSessions
|
|
21647
|
+
requestPendingMaterialization(liveSessionState.pendingMaterializationSessions, sessionId, "user_flush");
|
|
22919
21648
|
return { ok: true, message };
|
|
22920
21649
|
});
|
|
22921
21650
|
rpcServer.handle("wrapup", async (params) => {
|
|
@@ -22932,7 +21661,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
22932
21661
|
const db = readDatabase();
|
|
22933
21662
|
if (!db)
|
|
22934
21663
|
return { ok: false, error: "db unavailable" };
|
|
22935
|
-
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-
|
|
21664
|
+
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-yem5422s.js"));
|
|
22936
21665
|
const model = liveSessionState.liveModelBySession.get(sessionId);
|
|
22937
21666
|
const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
|
|
22938
21667
|
const ctx = {
|
|
@@ -23921,8 +22650,8 @@ function hostMediaFromEncoded(value) {
|
|
|
23921
22650
|
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
23922
22651
|
|
|
23923
22652
|
// src/v2/fold/owner.ts
|
|
23924
|
-
import { createHash as
|
|
23925
|
-
var foldDigest = (value) =>
|
|
22653
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
22654
|
+
var foldDigest = (value) => createHash6("sha256").update(value).digest("hex");
|
|
23926
22655
|
|
|
23927
22656
|
class FoldOwner {
|
|
23928
22657
|
storage;
|
|
@@ -24229,6 +22958,11 @@ function toolStateContent(state) {
|
|
|
24229
22958
|
`);
|
|
24230
22959
|
}
|
|
24231
22960
|
|
|
22961
|
+
// src/v2/hooks/copied-tag-notation.ts
|
|
22962
|
+
function stripCopiedTagNotation(text) {
|
|
22963
|
+
return text.includes("§") ? stripPersistedAssistantText(text) : text;
|
|
22964
|
+
}
|
|
22965
|
+
|
|
24232
22966
|
// src/v2/hooks/payload.ts
|
|
24233
22967
|
var HEAD_IDS = ["__magic_context_v2_m0__", "__magic_context_v2_m1__"];
|
|
24234
22968
|
var HOST_CONTENT_TYPES = new Set([
|
|
@@ -24445,6 +23179,8 @@ function adaptPayload(draft, admittedIDs = new Set) {
|
|
|
24445
23179
|
if (paired.has(content))
|
|
24446
23180
|
continue;
|
|
24447
23181
|
const part = callParts.get(content) ?? (content.type === "tool-result" ? nativeTool(undefined, { part: content, message }) : clonePreservingInstances(content));
|
|
23182
|
+
if (message.role === "assistant" && part.type === "text" && typeof part.text === "string")
|
|
23183
|
+
part.text = stripCopiedTagNotation(part.text);
|
|
24448
23184
|
if (message.id && admittedIDs.has(message.id))
|
|
24449
23185
|
part.synthetic = true;
|
|
24450
23186
|
parts.push(part);
|
|
@@ -26509,11 +25245,11 @@ class DeletedSessionTombstones {
|
|
|
26509
25245
|
}
|
|
26510
25246
|
|
|
26511
25247
|
// src/features/magic-context/dreamer/task-executor.ts
|
|
26512
|
-
import { createHash as
|
|
25248
|
+
import { createHash as createHash13 } from "node:crypto";
|
|
26513
25249
|
import { existsSync as existsSync7, readFileSync as readFileSync8 } from "node:fs";
|
|
26514
25250
|
|
|
26515
25251
|
// src/features/magic-context/mural/compress-cues.ts
|
|
26516
|
-
import { createHash as
|
|
25252
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
26517
25253
|
|
|
26518
25254
|
// src/features/magic-context/dreamer/storage-dream-state.ts
|
|
26519
25255
|
var getDreamStateStatements = new WeakMap;
|
|
@@ -27243,7 +25979,7 @@ async function applyCuesThroughModule(args, chunk, manifestText, signal) {
|
|
|
27243
25979
|
log2(`[dreamer] compress-cues: skipped cue for memory ${entry.id} (${failure.reason}; rejection ${rejectionCount}/${CUE_REJECTION_LATCH_THRESHOLD})`);
|
|
27244
25980
|
}
|
|
27245
25981
|
}
|
|
27246
|
-
const commandId = `mural-cues:${route.moduleCommandId}:${
|
|
25982
|
+
const commandId = `mural-cues:${route.moduleCommandId}:${createHash7("sha256").update(chunk.map((candidate) => candidate.memory.id).join(",")).digest("hex").slice(0, 24)}`;
|
|
27247
25983
|
let response;
|
|
27248
25984
|
try {
|
|
27249
25985
|
response = await route.moduleClient.call({
|
|
@@ -27812,7 +26548,7 @@ function applyReviewVerdict(args, leaseKey, parsed, result) {
|
|
|
27812
26548
|
}
|
|
27813
26549
|
|
|
27814
26550
|
// src/features/magic-context/dreamer/classify.ts
|
|
27815
|
-
import { createHash as
|
|
26551
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
27816
26552
|
|
|
27817
26553
|
// src/plugin/rust-tool-backends.ts
|
|
27818
26554
|
function isRustAuthorityDrainingError(error) {
|
|
@@ -28249,7 +26985,7 @@ async function runClassifyThroughModule(args, chunk, anchors, signal, runOnHost)
|
|
|
28249
26985
|
if (entry.qualifier)
|
|
28250
26986
|
modelVariants[entry.model] = entry.qualifier;
|
|
28251
26987
|
}
|
|
28252
|
-
const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${
|
|
26988
|
+
const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${createHash8("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`;
|
|
28253
26989
|
const runTask = (hostCompletion) => args.moduleClient?.call({
|
|
28254
26990
|
sessionId: args.moduleSessionId,
|
|
28255
26991
|
projectRoot: args.moduleProjectRoot,
|
|
@@ -28524,7 +27260,7 @@ function takeCurateSafetyRefusalCount(sessionId) {
|
|
|
28524
27260
|
|
|
28525
27261
|
// src/features/magic-context/dreamer/docs-proposals.ts
|
|
28526
27262
|
import { execFileSync } from "node:child_process";
|
|
28527
|
-
import { createHash as
|
|
27263
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
28528
27264
|
import {
|
|
28529
27265
|
existsSync as existsSync4,
|
|
28530
27266
|
mkdirSync,
|
|
@@ -28539,7 +27275,7 @@ import {
|
|
|
28539
27275
|
import { tmpdir } from "node:os";
|
|
28540
27276
|
import { join as join7 } from "node:path";
|
|
28541
27277
|
var FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
|
|
28542
|
-
var hash = (text) =>
|
|
27278
|
+
var hash = (text) => createHash9("sha256").update(text).digest("hex");
|
|
28543
27279
|
var proposalDir = (projectDir) => join7(projectDir, ".cortexkit/magic-context/docs-update-proposals");
|
|
28544
27280
|
function docsBaseHashes(projectDir) {
|
|
28545
27281
|
return Object.fromEntries(FILES.map((name) => [
|
|
@@ -29075,7 +27811,7 @@ function throwIfAborted2(signal) {
|
|
|
29075
27811
|
}
|
|
29076
27812
|
|
|
29077
27813
|
// src/features/magic-context/smart-notes/compiler.ts
|
|
29078
|
-
import { createHash as
|
|
27814
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
29079
27815
|
|
|
29080
27816
|
// src/features/magic-context/smart-notes/compiler-prompt.ts
|
|
29081
27817
|
var SMART_NOTE_COMPILER_SYSTEM_PROMPT = `You are the Magic Context smart-note compiler for the magic-context system.
|
|
@@ -29406,7 +28142,7 @@ function manifestAdvisoryWarnings(code, manifest) {
|
|
|
29406
28142
|
return warnings;
|
|
29407
28143
|
}
|
|
29408
28144
|
function hashCheck(surfaceCondition, compiledCheck, manifest, checkCron) {
|
|
29409
|
-
return
|
|
28145
|
+
return createHash10("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
|
|
29410
28146
|
}
|
|
29411
28147
|
function extractJsonObject(output) {
|
|
29412
28148
|
const fenced = output.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
@@ -30172,7 +28908,7 @@ function snapshotMaintainDocsFiles(docsDir) {
|
|
|
30172
28908
|
}
|
|
30173
28909
|
|
|
30174
28910
|
// src/features/magic-context/dreamer/map-memories.ts
|
|
30175
|
-
import { createHash as
|
|
28911
|
+
import { createHash as createHash11 } from "node:crypto";
|
|
30176
28912
|
|
|
30177
28913
|
// src/features/magic-context/dreamer/map-memories-prompt.ts
|
|
30178
28914
|
import { existsSync as existsSync6, statSync as statSync3 } from "node:fs";
|
|
@@ -30645,7 +29381,7 @@ async function applyParsedBatchMappings(args, batch, parsed, budgetFinalized = f
|
|
|
30645
29381
|
name: "memory.set_mapping",
|
|
30646
29382
|
arguments: {
|
|
30647
29383
|
memory_project: args.projectIdentity,
|
|
30648
|
-
command_id: `${args.moduleRoute.moduleCommandId}:${
|
|
29384
|
+
command_id: `${args.moduleRoute.moduleCommandId}:${createHash11("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
|
|
30649
29385
|
rows
|
|
30650
29386
|
}
|
|
30651
29387
|
}
|
|
@@ -31880,7 +30616,7 @@ function insertDreamRun(db, run) {
|
|
|
31880
30616
|
}
|
|
31881
30617
|
|
|
31882
30618
|
// src/features/magic-context/dreamer/verify.ts
|
|
31883
|
-
import { createHash as
|
|
30619
|
+
import { createHash as createHash12 } from "node:crypto";
|
|
31884
30620
|
|
|
31885
30621
|
// src/features/magic-context/dreamer/verify-diff.ts
|
|
31886
30622
|
import { execFile as execFile2 } from "node:child_process";
|
|
@@ -32624,7 +31360,7 @@ async function applyParsedVerifyManifest(args, batch, parsed, headAtPrompt, budg
|
|
|
32624
31360
|
name: "memory.set_verification",
|
|
32625
31361
|
arguments: {
|
|
32626
31362
|
memory_project: args.projectIdentity,
|
|
32627
|
-
command_id: `${args.moduleRoute.moduleCommandId}:${
|
|
31363
|
+
command_id: `${args.moduleRoute.moduleCommandId}:${createHash12("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
|
|
32628
31364
|
rows
|
|
32629
31365
|
}
|
|
32630
31366
|
}
|
|
@@ -33430,7 +32166,7 @@ function parseFrictionGateVerdict(verdict) {
|
|
|
33430
32166
|
}
|
|
33431
32167
|
function computeRetrospectiveWindowKey(flagged) {
|
|
33432
32168
|
const anchors = flagged.map((message) => `${message.sessionId}:${message.ts}`).sort().join("|");
|
|
33433
|
-
return
|
|
32169
|
+
return createHash13("sha256").update(anchors).digest("hex").slice(0, 32);
|
|
33434
32170
|
}
|
|
33435
32171
|
function renderFrictionWindow(messages, flaggedOrdinals, radius = 2) {
|
|
33436
32172
|
const flagged = new Set(flaggedOrdinals);
|
|
@@ -35384,9 +34120,9 @@ function hiddenTerminalError(event) {
|
|
|
35384
34120
|
}
|
|
35385
34121
|
|
|
35386
34122
|
// src/v2/hooks/lkg-system.ts
|
|
35387
|
-
import { createHash as
|
|
34123
|
+
import { createHash as createHash14 } from "node:crypto";
|
|
35388
34124
|
function identity(slot) {
|
|
35389
|
-
return
|
|
34125
|
+
return createHash14("sha256").update(JSON.stringify({
|
|
35390
34126
|
capturedAt: slot.capturedAt,
|
|
35391
34127
|
captureSequence: slot.captureSequence,
|
|
35392
34128
|
rowVersion: slot.rowVersion,
|
|
@@ -36415,6 +35151,24 @@ function createV2RawMessageProvider(reader, sessionID) {
|
|
|
36415
35151
|
};
|
|
36416
35152
|
}
|
|
36417
35153
|
|
|
35154
|
+
// src/v2/hooks/system-prompt-response.ts
|
|
35155
|
+
function bindV2SystemPromptResponse(sessionId, reader) {
|
|
35156
|
+
const request = currentLkgRequestIdentity(sessionId);
|
|
35157
|
+
if (request?.kind !== "v2" || request.responseAfterSequence === undefined)
|
|
35158
|
+
return;
|
|
35159
|
+
const first = reader.assistantSince(sessionId, request.responseAfterSequence)[0];
|
|
35160
|
+
if (!first)
|
|
35161
|
+
return;
|
|
35162
|
+
const createdAt = first.data.time?.created ?? first.time_created;
|
|
35163
|
+
if (typeof createdAt !== "number")
|
|
35164
|
+
return;
|
|
35165
|
+
bindSystemPromptResponse(sessionId, request, {
|
|
35166
|
+
responseId: first.id,
|
|
35167
|
+
createdAt,
|
|
35168
|
+
modelKey: first.data.model?.providerID && first.data.model?.id ? `${first.data.model.providerID}/${first.data.model.id}` : undefined
|
|
35169
|
+
});
|
|
35170
|
+
}
|
|
35171
|
+
|
|
36418
35172
|
// ../../node_modules/.bun/zod@4.1.8/node_modules/zod/v4/core/core.js
|
|
36419
35173
|
var NEVER = Object.freeze({
|
|
36420
35174
|
status: "aborted"
|
|
@@ -48185,7 +46939,7 @@ function resolveCtxExpandMode(args, domain) {
|
|
|
48185
46939
|
}
|
|
48186
46940
|
|
|
48187
46941
|
// src/tools/ctx-expand/render.ts
|
|
48188
|
-
import { createHash as
|
|
46942
|
+
import { createHash as createHash15 } from "node:crypto";
|
|
48189
46943
|
function isRecord6(value) {
|
|
48190
46944
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
48191
46945
|
}
|
|
@@ -48409,7 +47163,7 @@ function renderItemByTag(db, sessionId, number, textIndexDomain = "part") {
|
|
|
48409
47163
|
const index = scoped ? Number(scoped[2]) : 0;
|
|
48410
47164
|
const piText = message.parts.filter((part) => isRecord6(part) && part.type === "text");
|
|
48411
47165
|
const part = message.parts[index];
|
|
48412
|
-
const matching = derived ? piText.filter((part) => isRecord6(part) && typeof part.text === "string" &&
|
|
47166
|
+
const matching = derived ? piText.filter((part) => isRecord6(part) && typeof part.text === "string" && createHash15("sha256").update(part.text).digest("hex") === derived[3]) : [];
|
|
48413
47167
|
const selected = derived ? matching[Number(derived[4])] : textIndexDomain === "text" ? piText[index] : part;
|
|
48414
47168
|
return selected ? renderPartFull(selected) ?? "" : `Tag ${number}'s original text part is no longer in stored history.`;
|
|
48415
47169
|
}
|
|
@@ -49159,7 +47913,7 @@ import { existsSync as existsSync9 } from "node:fs";
|
|
|
49159
47913
|
import { isAbsolute as isAbsolute2 } from "node:path";
|
|
49160
47914
|
|
|
49161
47915
|
// ../retina-local-fs/src/path-fence.ts
|
|
49162
|
-
import { lstat as lstat2,
|
|
47916
|
+
import { lstat as lstat2, realpath as realpath2 } from "node:fs/promises";
|
|
49163
47917
|
import { homedir as homedir4 } from "node:os";
|
|
49164
47918
|
import { basename, dirname as dirname2, isAbsolute, join as join10, relative, resolve as resolve2, sep } from "node:path";
|
|
49165
47919
|
|
|
@@ -49227,18 +47981,16 @@ async function canonicalPath(path, allowMissing) {
|
|
|
49227
47981
|
const suffix = [];
|
|
49228
47982
|
let candidate = path;
|
|
49229
47983
|
while (true) {
|
|
47984
|
+
let symbolicLink = false;
|
|
49230
47985
|
try {
|
|
49231
|
-
|
|
49232
|
-
if (metadata.isSymbolicLink()) {
|
|
49233
|
-
const target = await readlink(candidate);
|
|
49234
|
-
const resolvedTarget = resolve2(dirname2(candidate), target);
|
|
49235
|
-
return canonicalPath(join10(resolvedTarget, ...suffix), true);
|
|
49236
|
-
}
|
|
47986
|
+
symbolicLink = (await lstat2(candidate)).isSymbolicLink();
|
|
49237
47987
|
} catch (candidateError) {
|
|
49238
47988
|
if (!isMissingError(candidateError)) {
|
|
49239
47989
|
throw fsError(path, candidateError);
|
|
49240
47990
|
}
|
|
49241
47991
|
}
|
|
47992
|
+
if (symbolicLink)
|
|
47993
|
+
throw fsError(path, error);
|
|
49242
47994
|
const parent = dirname2(candidate);
|
|
49243
47995
|
if (parent === candidate) {
|
|
49244
47996
|
throw fsError(path, error);
|
|
@@ -49923,12 +48675,18 @@ Stamp: file reads, search results and tool outputs the work ahead no longer need
|
|
|
49923
48675
|
Keep: user messages (never stamp one for its directive), your own conversation text, unresolved errors, raw evidence you haven't extracted yet, and outputs whose exact wording may still matter.
|
|
49924
48676
|
|
|
49925
48677
|
Look at each tag before stamping it; never blanket-stamp a range like "1-50". Many small targeted stamps beat one sweep. \`drop\` accepts "3-5", "1,2,9", "1-5,8,12-15".`;
|
|
49926
|
-
|
|
49927
|
-
|
|
49928
|
-
|
|
48678
|
+
function formatCtxReduceReply(stampedCount, selfStampCount = 0) {
|
|
48679
|
+
const parts = [];
|
|
48680
|
+
if (stampedCount > 0) {
|
|
48681
|
+
parts.push(`${stampedCount} tag${stampedCount === 1 ? "" : "s"} stamped.`);
|
|
48682
|
+
}
|
|
48683
|
+
if (selfStampCount > 0) {
|
|
48684
|
+
parts.push(selfStampCount === 1 ? "1 was a ctx_reduce call; leave those alone, they are cleaned up automatically." : `${selfStampCount} were ctx_reduce calls; leave those alone, they are cleaned up automatically.`);
|
|
48685
|
+
}
|
|
48686
|
+
return parts.join(" ");
|
|
49929
48687
|
}
|
|
49930
48688
|
// src/tools/ctx-reduce/tools.ts
|
|
49931
|
-
import { createHash as
|
|
48689
|
+
import { createHash as createHash16 } from "node:crypto";
|
|
49932
48690
|
|
|
49933
48691
|
// src/features/magic-context/range-parser.ts
|
|
49934
48692
|
function parseRangeString(input) {
|
|
@@ -49978,12 +48736,6 @@ function parseInteger(str) {
|
|
|
49978
48736
|
}
|
|
49979
48737
|
|
|
49980
48738
|
// src/tools/ctx-reduce/tools.ts
|
|
49981
|
-
function formatRawDropForAck(rawDrop) {
|
|
49982
|
-
return rawDrop.trim().split(",").map((token) => {
|
|
49983
|
-
const trimmed = token.trim();
|
|
49984
|
-
return /^\d+$/.test(trimmed) ? `§${trimmed}§` : trimmed;
|
|
49985
|
-
}).join(", ");
|
|
49986
|
-
}
|
|
49987
48739
|
var ctxReduceArgsShape = {
|
|
49988
48740
|
drop: tool.schema.string().optional().describe('Tag IDs to drop: "3-5", "1,2,9", "1-5,8,12-15".')
|
|
49989
48741
|
};
|
|
@@ -49997,11 +48749,11 @@ function createCtxReduceTool(deps) {
|
|
|
49997
48749
|
const stableId = `oc-${sessionId}-${callId}`;
|
|
49998
48750
|
if (Buffer.byteLength(stableId) <= 128)
|
|
49999
48751
|
return stableId;
|
|
50000
|
-
return `oc-${
|
|
48752
|
+
return `oc-${createHash16("sha256").update(stableId).digest("hex")}`;
|
|
50001
48753
|
}
|
|
50002
48754
|
fallbackCommandSequence += 1;
|
|
50003
48755
|
const monotonicId = `oc-${sessionId}-${fallbackCommandSequence}`;
|
|
50004
|
-
return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${
|
|
48756
|
+
return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash16("sha256").update(monotonicId).digest("hex")}`;
|
|
50005
48757
|
};
|
|
50006
48758
|
return tool({
|
|
50007
48759
|
description: CTX_REDUCE_DESCRIPTION,
|
|
@@ -50034,22 +48786,21 @@ function createCtxReduceTool(deps) {
|
|
|
50034
48786
|
}
|
|
50035
48787
|
const queued = typeof record.queued === "number" ? record.queued : 0;
|
|
50036
48788
|
const refusedStamps = Array.isArray(record.ctx_reduce_self_stamps) ? record.ctx_reduce_self_stamps.filter((tagNumber) => typeof tagNumber === "number" && Number.isInteger(tagNumber)) : [];
|
|
50037
|
-
const
|
|
48789
|
+
const refusedStampCount = new Set(refusedStamps).size;
|
|
50038
48790
|
const acceptedTagNumbers = Array.isArray(record.ctx_reduce_queued_tags) ? record.ctx_reduce_queued_tags.filter((tagNumber) => typeof tagNumber === "number" && Number.isInteger(tagNumber)) : null;
|
|
50039
48791
|
if (queued <= 0) {
|
|
50040
|
-
|
|
50041
|
-
|
|
48792
|
+
const alreadyStampedCount = acceptedTagNumbers ? new Set(acceptedTagNumbers).size : 0;
|
|
48793
|
+
const reply = formatCtxReduceReply(alreadyStampedCount, refusedStampCount);
|
|
48794
|
+
if (reply)
|
|
48795
|
+
return reply;
|
|
50042
48796
|
return "All requested tags were already queued or processed. No new action is needed.";
|
|
50043
48797
|
}
|
|
50044
|
-
|
|
50045
|
-
|
|
50046
|
-
|
|
50047
|
-
|
|
50048
|
-
|
|
50049
|
-
|
|
50050
|
-
}
|
|
50051
|
-
const acknowledgedDrop = acceptedTagNumbers ? formatIds(acceptedTagNumbers) : formatRawDropForAck(args.drop);
|
|
50052
|
-
return `Queued: drop ${acknowledgedDrop}.${refusedStampNote ? ` ${refusedStampNote}` : ""}`;
|
|
48798
|
+
const reportedTagNumbers = [
|
|
48799
|
+
...Array.isArray(record.held_tag_numbers) ? record.held_tag_numbers.filter((number) => typeof number === "number") : [],
|
|
48800
|
+
...Array.isArray(record.immediate_tag_numbers) ? record.immediate_tag_numbers.filter((number) => typeof number === "number") : []
|
|
48801
|
+
];
|
|
48802
|
+
const stampedCount = acceptedTagNumbers ? new Set(acceptedTagNumbers).size : reportedTagNumbers.length > 0 ? new Set(reportedTagNumbers).size : queued;
|
|
48803
|
+
return formatCtxReduceReply(stampedCount, refusedStampCount);
|
|
50053
48804
|
} catch (error) {
|
|
50054
48805
|
sessionLog2(sessionId, "ctx_reduce capability refusal", error);
|
|
50055
48806
|
return renderCapabilityRefusal("context_cleanup");
|
|
@@ -50069,21 +48820,9 @@ function createCtxReduceTool(deps) {
|
|
|
50069
48820
|
return `Error: Unknown tag(s) ${formatIds(unknownIds)}. Check available tags in conversation.`;
|
|
50070
48821
|
}
|
|
50071
48822
|
const ctxReduceSelfStampIds = new Set(allTags.filter((tag) => tag.toolName?.toLowerCase() === "ctx_reduce").map((tag) => tag.tagNumber));
|
|
50072
|
-
const
|
|
48823
|
+
const ctxReduceSelfStampCount = new Set(dropIds.filter((id) => ctxReduceSelfStampIds.has(id))).size;
|
|
50073
48824
|
dropIds = dropIds.filter((id) => !ctxReduceSelfStampIds.has(id));
|
|
50074
|
-
let protectedSet;
|
|
50075
|
-
if (deps.protectedSet) {
|
|
50076
|
-
protectedSet = typeof deps.protectedSet === "function" ? deps.protectedSet(sessionId) : deps.protectedSet;
|
|
50077
|
-
} else if (deps.getProtectionWindow) {
|
|
50078
|
-
protectedSet = deps.getProtectionWindow(sessionId).protectedTagNumbers;
|
|
50079
|
-
} else {
|
|
50080
|
-
protectedSet = getProtectionWindowForSession(deps.db, sessionId, deps.floor).protectedTagNumbers;
|
|
50081
|
-
}
|
|
50082
48825
|
const tagStatusMap = new Map(allTags.map((tag) => [tag.tagNumber, tag.status]));
|
|
50083
|
-
protectedSet = new Set([
|
|
50084
|
-
...protectedSet,
|
|
50085
|
-
...protectedToolTagNumbers(getActiveTagsBySession2(deps.db, sessionId), deps.protectedTools)
|
|
50086
|
-
]);
|
|
50087
48826
|
const inertWhitespaceTagNumbers = new Set(getInertWhitespaceAssistantTagsByNumbers2(deps.db, sessionId, dropIds).map((tag) => tag.tagNumber));
|
|
50088
48827
|
const inertDropIds = [
|
|
50089
48828
|
...new Set(dropIds.filter((id) => inertWhitespaceTagNumbers.has(id)))
|
|
@@ -50100,15 +48839,15 @@ function createCtxReduceTool(deps) {
|
|
|
50100
48839
|
if (conflicts.length > 0) {
|
|
50101
48840
|
return `Error: Conflicting operations — ${conflicts.join("; ")}.`;
|
|
50102
48841
|
}
|
|
50103
|
-
const
|
|
48842
|
+
const stampedCount = new Set(dropIds.filter((id) => !inertWhitespaceTagNumbers.has(id))).size;
|
|
50104
48843
|
dropIds = dropIds.filter((id) => !inertWhitespaceTagNumbers.has(id) && tagStatusMap.get(id) !== "dropped" && pendingMap.get(id) !== "drop");
|
|
50105
|
-
const skippedCount = preFilterDropCount - dropIds.length;
|
|
50106
48844
|
if (dropIds.length === 0) {
|
|
50107
|
-
const
|
|
50108
|
-
if (
|
|
50109
|
-
|
|
50110
|
-
|
|
50111
|
-
|
|
48845
|
+
const reply = formatCtxReduceReply(stampedCount, ctxReduceSelfStampCount);
|
|
48846
|
+
if (reply)
|
|
48847
|
+
return `${reply}${inertNote ? ` ${inertNote}` : ""}`;
|
|
48848
|
+
if (inertNote)
|
|
48849
|
+
return inertNote;
|
|
48850
|
+
return "All requested tags were already queued or processed. No new action is needed.";
|
|
50112
48851
|
}
|
|
50113
48852
|
try {
|
|
50114
48853
|
deps.db.transaction(() => {
|
|
@@ -50123,25 +48862,8 @@ function createCtxReduceTool(deps) {
|
|
|
50123
48862
|
}
|
|
50124
48863
|
const currentInputTokens = deps.getSessionTokens?.(sessionId) ?? getOrCreateSessionMeta(deps.db, sessionId).lastInputTokens;
|
|
50125
48864
|
updateSessionMeta(deps.db, sessionId, { lastNudgeTokens: currentInputTokens });
|
|
50126
|
-
const
|
|
50127
|
-
|
|
50128
|
-
const skippedNote = skippedCount > 0 ? ` ${skippedCount} requested tag${skippedCount === 1 ? " was" : "s were"} already queued and need no action.` : "";
|
|
50129
|
-
let heldSentence = "";
|
|
50130
|
-
if (deferredDropIds.length === 1) {
|
|
50131
|
-
heldSentence = `Held: §${deferredDropIds[0]} is inside the protected working set; it applies once newer work displaces it.`;
|
|
50132
|
-
} else if (deferredDropIds.length > 1) {
|
|
50133
|
-
heldSentence = `Held: ${deferredDropIds.map((id) => `§${id}`).join(", ")} are inside the protected working set; they apply once newer work displaces them.`;
|
|
50134
|
-
}
|
|
50135
|
-
if (immediateDropIds.length > 0 && heldSentence.length > 0) {
|
|
50136
|
-
return `Queued: drop ${formatIds(immediateDropIds)}.${skippedNote}${inertNote ? ` ${inertNote}` : ""} ${heldSentence}${ctxReduceSelfStampNote ? ` ${ctxReduceSelfStampNote}` : ""}`;
|
|
50137
|
-
}
|
|
50138
|
-
if (immediateDropIds.length > 0) {
|
|
50139
|
-
return `Queued: drop ${formatIds(immediateDropIds)}.${skippedNote}${inertNote ? ` ${inertNote}` : ""}${ctxReduceSelfStampNote ? ` ${ctxReduceSelfStampNote}` : ""}`;
|
|
50140
|
-
}
|
|
50141
|
-
if (heldSentence.length > 0) {
|
|
50142
|
-
return `${heldSentence}${skippedNote}${inertNote ? ` ${inertNote}` : ""}${ctxReduceSelfStampNote ? ` ${ctxReduceSelfStampNote}` : ""}`;
|
|
50143
|
-
}
|
|
50144
|
-
return `Queued: drop ${formatIds(dropIds)}.${skippedNote}${inertNote ? ` ${inertNote}` : ""}${ctxReduceSelfStampNote ? ` ${ctxReduceSelfStampNote}` : ""}`;
|
|
48865
|
+
const reply = formatCtxReduceReply(stampedCount, ctxReduceSelfStampCount);
|
|
48866
|
+
return `${reply}${inertNote ? ` ${inertNote}` : ""}`;
|
|
50145
48867
|
}
|
|
50146
48868
|
});
|
|
50147
48869
|
}
|
|
@@ -50657,8 +49379,16 @@ async function applyV2SystemPrompt(systemPrompt, draft) {
|
|
|
50657
49379
|
}
|
|
50658
49380
|
})));
|
|
50659
49381
|
const system = { system: draft.system.map((part) => String(part.text ?? "")) };
|
|
49382
|
+
bindSystemDateOutput(system.system, () => {
|
|
49383
|
+
draft.system.splice(0, draft.system.length, ...system.system.map((text, index) => ({
|
|
49384
|
+
...draft.system[index],
|
|
49385
|
+
type: "text",
|
|
49386
|
+
text
|
|
49387
|
+
})));
|
|
49388
|
+
});
|
|
50660
49389
|
await systemPrompt.handler({
|
|
50661
49390
|
sessionID: draft.sessionID,
|
|
49391
|
+
dateRefreshRequest: draft,
|
|
50662
49392
|
model: { providerID: draft.model.providerID, modelID: draft.model.id }
|
|
50663
49393
|
}, system);
|
|
50664
49394
|
const originals = [...draft.system];
|
|
@@ -50908,6 +49638,7 @@ async function registerContext(context) {
|
|
|
50908
49638
|
const agents = new Map;
|
|
50909
49639
|
const sessionDirectories = new Map;
|
|
50910
49640
|
const historyRefreshSessions = new Set;
|
|
49641
|
+
registerSystemDateRefresh(historyRefreshSessions);
|
|
50911
49642
|
const pendingMaterializationSessions = new Set;
|
|
50912
49643
|
const lastHeuristicsTurnId = new Map;
|
|
50913
49644
|
const restoredRows = new RestoredRowCache;
|
|
@@ -51029,6 +49760,11 @@ async function registerContext(context) {
|
|
|
51029
49760
|
try {
|
|
51030
49761
|
const latest = reader.latestAssistant(draft.sessionID);
|
|
51031
49762
|
latestLkgResponseIds.set(draft.sessionID, latest?.id);
|
|
49763
|
+
try {
|
|
49764
|
+
bindV2SystemPromptResponse(draft.sessionID, reader);
|
|
49765
|
+
} catch (error) {
|
|
49766
|
+
sessionLog2(draft.sessionID, "v2 response ownership unavailable; keeping system identity pending", error);
|
|
49767
|
+
}
|
|
51032
49768
|
if (latest)
|
|
51033
49769
|
noteLkgProviderResponse({
|
|
51034
49770
|
sessionId: draft.sessionID,
|
|
@@ -51142,6 +49878,7 @@ async function registerContext(context) {
|
|
|
51142
49878
|
continue;
|
|
51143
49879
|
}
|
|
51144
49880
|
if (event.type === "session.deleted") {
|
|
49881
|
+
clearLkgMeasuredRequest(sessionID);
|
|
51145
49882
|
deletedSessions.add(sessionID);
|
|
51146
49883
|
transform?.clearSessionLogState(sessionID);
|
|
51147
49884
|
if (db) {
|
|
@@ -51158,7 +49895,7 @@ async function registerContext(context) {
|
|
|
51158
49895
|
agents.delete(sessionID);
|
|
51159
49896
|
channel1.delete(sessionID);
|
|
51160
49897
|
historyRefreshSessions.delete(sessionID);
|
|
51161
|
-
pendingMaterializationSessions
|
|
49898
|
+
clearPendingMaterialization(pendingMaterializationSessions, sessionID);
|
|
51162
49899
|
lastHeuristicsTurnId.delete(sessionID);
|
|
51163
49900
|
restoredRows.forget(sessionID);
|
|
51164
49901
|
await nativeFoldReplay?.forget(sessionID);
|
|
@@ -51270,6 +50007,7 @@ async function registerContext(context) {
|
|
|
51270
50007
|
const systemAtEntry = structuredClone(draft.system);
|
|
51271
50008
|
const slotAtEntry = getSlot(draft.sessionID);
|
|
51272
50009
|
const restoreLkgSystem = () => {
|
|
50010
|
+
retirePendingSystemPromptDelivery(draft.sessionID);
|
|
51273
50011
|
if (!lkgSystems.restore(draft.sessionID, getSlot(draft.sessionID), systemAtEntry, draft.system)) {
|
|
51274
50012
|
sessionLog2(draft.sessionID, "lkg_system_state_mismatch");
|
|
51275
50013
|
throw new Error("LKG system identity is unavailable or changed");
|
|
@@ -51402,6 +50140,18 @@ async function registerContext(context) {
|
|
|
51402
50140
|
injectionEnabled: config.system_prompt_injection.enabled,
|
|
51403
50141
|
injectionSkipSignatures: config.system_prompt_injection.skip_signatures
|
|
51404
50142
|
});
|
|
50143
|
+
let responseAfterSequence;
|
|
50144
|
+
try {
|
|
50145
|
+
const responseReader = openStoreReader();
|
|
50146
|
+
try {
|
|
50147
|
+
responseAfterSequence = responseReader.latestSequence(draft.sessionID);
|
|
50148
|
+
} finally {
|
|
50149
|
+
responseReader.close();
|
|
50150
|
+
}
|
|
50151
|
+
} catch (error) {
|
|
50152
|
+
sessionLog2(draft.sessionID, "v2 response boundary unavailable; no system delivery acknowledgement", error);
|
|
50153
|
+
}
|
|
50154
|
+
beginV2LkgRequest(draft.sessionID, `${draft.model.providerID}/${draft.model.id}`, latestLkgResponseIds.get(draft.sessionID), responseAfterSequence);
|
|
51405
50155
|
await applyV2SystemPrompt(systemPrompt, draft);
|
|
51406
50156
|
await preloadTokenizer();
|
|
51407
50157
|
passDuties ??= createChatMessageHook({
|
|
@@ -51433,6 +50183,7 @@ async function registerContext(context) {
|
|
|
51433
50183
|
contextUsageMap: usage,
|
|
51434
50184
|
compactionOff,
|
|
51435
50185
|
storeGeneration: "v2",
|
|
50186
|
+
normalizeRestoredAssistantText: stripCopiedTagNotation,
|
|
51436
50187
|
hostCleanupCompactionMarkers: () => ({
|
|
51437
50188
|
verified: true,
|
|
51438
50189
|
removedLineages: 0,
|
|
@@ -51510,7 +50261,7 @@ async function registerContext(context) {
|
|
|
51510
50261
|
const boundaryRepair = !rustModeModuleClient && db && !compactionOff ? checkHistoryBoundary(db, reader, draft.sessionID) : undefined;
|
|
51511
50262
|
if (boundaryRepair?.kind === "repaired" || boundaryRepair?.kind === "baseline-reset") {
|
|
51512
50263
|
historyRefreshSessions.add(draft.sessionID);
|
|
51513
|
-
pendingMaterializationSessions
|
|
50264
|
+
requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "boundary_repair");
|
|
51514
50265
|
}
|
|
51515
50266
|
const incoming = cut && draft.messages.find((message) => message.id === cut.id);
|
|
51516
50267
|
postFold = cut !== undefined;
|
|
@@ -51528,7 +50279,7 @@ async function registerContext(context) {
|
|
|
51528
50279
|
}
|
|
51529
50280
|
if (nativeRestored && nativeFoldReplay?.sourceChanged(draft.sessionID)) {
|
|
51530
50281
|
historyRefreshSessions.add(draft.sessionID);
|
|
51531
|
-
pendingMaterializationSessions
|
|
50282
|
+
requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "host_history_change");
|
|
51532
50283
|
}
|
|
51533
50284
|
if (cut && incoming && nativeRestored) {
|
|
51534
50285
|
const present = new Set(draft.messages.flatMap((message) => message.id ? [message.id] : []));
|
|
@@ -51546,7 +50297,7 @@ async function registerContext(context) {
|
|
|
51546
50297
|
onHard: (reason) => {
|
|
51547
50298
|
sessionLog2(draft.sessionID, `HARD reason=${reason}`);
|
|
51548
50299
|
materialize(draft);
|
|
51549
|
-
pendingMaterializationSessions
|
|
50300
|
+
requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "host_compaction");
|
|
51550
50301
|
}
|
|
51551
50302
|
});
|
|
51552
50303
|
checkpoint = structuredClone(identity.rendered ?? incoming);
|
|
@@ -51582,7 +50333,7 @@ async function registerContext(context) {
|
|
|
51582
50333
|
}
|
|
51583
50334
|
}
|
|
51584
50335
|
const mapped = adaptPayload(draft, admitted);
|
|
51585
|
-
|
|
50336
|
+
bindSystemDateRequestIdentity(mapped, draft);
|
|
51586
50337
|
await createMessagesTransformHandler({
|
|
51587
50338
|
magicContext: { "experimental.chat.messages.transform": transform },
|
|
51588
50339
|
compactionOff,
|