@cortexkit/opencode-magic-context 0.49.0 → 0.49.2
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
|
@@ -40,7 +40,6 @@ import {
|
|
|
40
40
|
indexCoordinationInput2
|
|
41
41
|
} from "./index-kb9nn0a0.js";
|
|
42
42
|
import {
|
|
43
|
-
canonicalProjectDirectory,
|
|
44
43
|
shouldSkipHomeProjectMemory,
|
|
45
44
|
ProjectIdentityError,
|
|
46
45
|
takeDubiousOwnershipProjectIdentityWarning,
|
|
@@ -54,11 +53,10 @@ import {
|
|
|
54
53
|
storedPathBelongsToIdentity,
|
|
55
54
|
beginBootQuietPeriod,
|
|
56
55
|
scheduleAfterBootQuiet
|
|
57
|
-
} from "./index-
|
|
56
|
+
} from "./index-gzky5rva.js";
|
|
58
57
|
import {
|
|
59
58
|
recordSessionProjectIdentity,
|
|
60
59
|
hasRecordedSessionProjectIdentity,
|
|
61
|
-
drainBackgroundBatches,
|
|
62
60
|
GIT_SWEEP_LEASE_RENEWAL_MS,
|
|
63
61
|
acquireGitSweepLease,
|
|
64
62
|
renewGitSweepLease,
|
|
@@ -82,7 +80,7 @@ import {
|
|
|
82
80
|
drainCommitBacklogForProject2,
|
|
83
81
|
embedSessionCompartmentChunks2,
|
|
84
82
|
getEmbeddingCoverageStatus2
|
|
85
|
-
} from "./index-
|
|
83
|
+
} from "./index-fg00p1cg.js";
|
|
86
84
|
import {
|
|
87
85
|
hasTrustedAbsoluteWall,
|
|
88
86
|
applyProvenInputFloor,
|
|
@@ -94,7 +92,7 @@ import {
|
|
|
94
92
|
deriveTriggerBudget2,
|
|
95
93
|
resolveKnownHistorianContextLimit2,
|
|
96
94
|
resolveHistorianProducerLimits2
|
|
97
|
-
} from "./index-
|
|
95
|
+
} from "./index-w23dh319.js";
|
|
98
96
|
import {
|
|
99
97
|
resolveModelCalibration,
|
|
100
98
|
calibrateBuckets,
|
|
@@ -110,12 +108,10 @@ import {
|
|
|
110
108
|
normalizeText
|
|
111
109
|
} from "./index-qx53vezw.js";
|
|
112
110
|
import {
|
|
113
|
-
protectedToolTagNumbers,
|
|
114
111
|
protectedToolTokenCount,
|
|
115
112
|
peelLeadingMcTagNotation,
|
|
116
113
|
isRecord,
|
|
117
114
|
contentTagOwnerMessageId,
|
|
118
|
-
providerVisibleMessage,
|
|
119
115
|
normalizeTodoStateJson,
|
|
120
116
|
computeSyntheticCallId,
|
|
121
117
|
CHANNEL1_SENTINEL,
|
|
@@ -150,6 +146,19 @@ import {
|
|
|
150
146
|
import {
|
|
151
147
|
observeTemporalDecisions
|
|
152
148
|
} from "./index-1bt88epp.js";
|
|
149
|
+
import {
|
|
150
|
+
withContentLanguageDirective,
|
|
151
|
+
parseCron,
|
|
152
|
+
nextOccurrence,
|
|
153
|
+
nextDueAtMs,
|
|
154
|
+
promptSurfaceConfigIdentity,
|
|
155
|
+
resolveModelConfigValue,
|
|
156
|
+
resolvePromptSurface,
|
|
157
|
+
DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE,
|
|
158
|
+
DEFAULT_HISTORIAN_TIMEOUT_MS,
|
|
159
|
+
DEFAULT_LOCAL_EMBEDDING_MODEL,
|
|
160
|
+
DREAM_TASK_PROMOTION_DEFAULTS
|
|
161
|
+
} from "./index-k6xvbj2e.js";
|
|
153
162
|
import {
|
|
154
163
|
isRawCompactionSummaryInfo2,
|
|
155
164
|
extractInMemoryMessageViews2,
|
|
@@ -161,26 +170,104 @@ import {
|
|
|
161
170
|
withReadOnlySessionDb,
|
|
162
171
|
assistantAwaitingTools,
|
|
163
172
|
latestPersistedMessageForRecovery,
|
|
173
|
+
latestRealUserTurnIdFromOpenCodeDb,
|
|
164
174
|
findLastAssistantModelFromOpenCodeDb
|
|
165
|
-
} from "./index-
|
|
175
|
+
} from "./index-0pjvpfkf.js";
|
|
166
176
|
import {
|
|
167
177
|
expandToolPart,
|
|
168
178
|
estimateTrueRawMessageTokens,
|
|
169
179
|
toolPartHasUserAnswer,
|
|
170
180
|
DreamTokenBudgetExceeded,
|
|
171
181
|
isEditTool,
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
182
|
+
decodeMergedReasoningParts,
|
|
183
|
+
MAX_EXECUTE_THRESHOLD,
|
|
184
|
+
escalationBands,
|
|
185
|
+
sessionDecisionCalibration,
|
|
186
|
+
getProtectionWindowForSession,
|
|
187
|
+
ensureSessionMetaRow,
|
|
188
|
+
isRustMarkerAdmissionFenced,
|
|
189
|
+
setRustMarkerAdmissionFence,
|
|
190
|
+
readReplayEnvelope,
|
|
191
|
+
updateReplayDocument,
|
|
192
|
+
isEmergencyRecoveryArmed,
|
|
193
|
+
isProviderOverflowReconfirmed,
|
|
194
|
+
isProviderOverflowFailClosedProven,
|
|
195
|
+
getEmergencyRecoveryArmedAt,
|
|
196
|
+
loadPersistedUsage,
|
|
197
|
+
loadProtectedTailMeta,
|
|
198
|
+
resetProtectedTailNoEligibleHead,
|
|
199
|
+
resolveCompactionModeRecord,
|
|
200
|
+
getCompactionModeRecord,
|
|
201
|
+
setCompactionModeRecord,
|
|
202
|
+
getProtectedTailDrainBudgetSkip,
|
|
203
|
+
clearPersistedReasoningWatermark,
|
|
204
|
+
getEmergencyInputSample,
|
|
205
|
+
clearEmergencyDropSample,
|
|
206
|
+
getLastNudgeUndropped,
|
|
207
|
+
setLastNudgeUndropped,
|
|
208
|
+
getChannel1NudgeState,
|
|
209
|
+
setChannel1NudgeState,
|
|
210
|
+
markChannel1PostReduceGracePending,
|
|
211
|
+
getChannel2NudgeState,
|
|
212
|
+
getChannel2NudgeClaim,
|
|
213
|
+
setChannel2NudgeState,
|
|
214
|
+
casChannel2NudgeState,
|
|
215
|
+
claimChannel2NudgeState,
|
|
216
|
+
casChannel2NudgeClaim,
|
|
217
|
+
setPersistedNoteNudgeTrigger,
|
|
218
|
+
getNoteNudgeAnchors,
|
|
219
|
+
getAutoSearchHintDecisions,
|
|
220
|
+
getPersistedTodoPermissionDenied,
|
|
221
|
+
setPersistedTodoPermissionDenied,
|
|
222
|
+
getPersistedTodoSyntheticAnchor,
|
|
223
|
+
setPersistedTodoSyntheticAnchor,
|
|
224
|
+
clearPersistedTodoSyntheticAnchor,
|
|
225
|
+
setNoteLastReadAt,
|
|
226
|
+
getHistorianFailureState,
|
|
227
|
+
clearHistorianFailureState,
|
|
228
|
+
getOverflowState,
|
|
229
|
+
loadTransformPassStateSnapshot,
|
|
230
|
+
recordOverflowDetected,
|
|
231
|
+
clearEmergencyRecovery,
|
|
232
|
+
clearDetectedContextLimit,
|
|
233
|
+
getPersistedCompactionMarkerState,
|
|
234
|
+
setPersistedCompactionMarkerState,
|
|
235
|
+
getStrippedPlaceholderIds,
|
|
236
|
+
thinkingBindingRecoveryFrozenId,
|
|
237
|
+
getThinkingBindingRecoveryTarget,
|
|
238
|
+
armThinkingBindingRecovery,
|
|
239
|
+
clearThinkingBindingRecoveryIf,
|
|
240
|
+
getMergedReasoningStrippedIds,
|
|
241
|
+
addMergedReasoningStrippedIds,
|
|
242
|
+
getStaleReduceStrippedIds,
|
|
243
|
+
getProcessedImageStrippedIds,
|
|
244
|
+
getPendingCompactionMarkerState,
|
|
245
|
+
getCompactionMarkerHealth,
|
|
246
|
+
clearPendingCompactionMarkerStateIf,
|
|
247
|
+
setSessionWorkMetrics,
|
|
248
|
+
getObservedEpochFloor,
|
|
249
|
+
resolveEpochFloorForPass,
|
|
178
250
|
detectLatestTurnThinkingMismatch,
|
|
179
251
|
isPrefixBoundThinkingModel,
|
|
180
252
|
detectOverflow,
|
|
181
253
|
modelAcceptsEmptyContent,
|
|
182
254
|
isAnthropicFamilyRoute,
|
|
183
255
|
variantChangeBustsProviderCache,
|
|
256
|
+
activeAnthropicTurnStart,
|
|
257
|
+
replayClearedReasoning,
|
|
258
|
+
replayStrippedInlineThinking,
|
|
259
|
+
stripClearedReasoning,
|
|
260
|
+
findReasoningBearingAssistantIds,
|
|
261
|
+
snapshotTrailingBlankSourceDecisions,
|
|
262
|
+
projectOpencodeReasoningBudgetCutoff,
|
|
263
|
+
resolveKeepReasoningTokens,
|
|
264
|
+
reasoningBudgetCutoff,
|
|
265
|
+
describeFinalWireTail,
|
|
266
|
+
estimateMessageTokens,
|
|
267
|
+
wireContentBytes,
|
|
268
|
+
createFinalWireUsageTracker,
|
|
269
|
+
estimateFinalWireInputTokens,
|
|
270
|
+
estimateAppendedWireTokens,
|
|
184
271
|
setRawMessageProvider2,
|
|
185
272
|
cleanUserText2,
|
|
186
273
|
withRawSessionMessageCache2,
|
|
@@ -197,7 +284,7 @@ import {
|
|
|
197
284
|
readRawSessionMessageById2,
|
|
198
285
|
readSessionChunk2,
|
|
199
286
|
readRawSessionSeedTail2
|
|
200
|
-
} from "./index-
|
|
287
|
+
} from "./index-sv0bb7vg.js";
|
|
201
288
|
import {
|
|
202
289
|
getMeasuredToolDefinitionTokens
|
|
203
290
|
} from "./index-h2wc01qk.js";
|
|
@@ -215,29 +302,10 @@ import {
|
|
|
215
302
|
buildDreamTaskRuntimeConfigs2,
|
|
216
303
|
userMemoryCollectionEnabled2
|
|
217
304
|
} from "./index-ghc9f0n7.js";
|
|
218
|
-
import {
|
|
219
|
-
withContentLanguageDirective,
|
|
220
|
-
parseCron,
|
|
221
|
-
nextOccurrence,
|
|
222
|
-
nextDueAtMs,
|
|
223
|
-
promptSurfaceConfigIdentity,
|
|
224
|
-
resolveModelConfigValue,
|
|
225
|
-
resolvePromptSurface,
|
|
226
|
-
DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE,
|
|
227
|
-
DEFAULT_HISTORIAN_TIMEOUT_MS,
|
|
228
|
-
DEFAULT_LOCAL_EMBEDDING_MODEL,
|
|
229
|
-
DREAM_TASK_PROMOTION_DEFAULTS,
|
|
230
|
-
getLocalEmbeddingNativeMemoryStats
|
|
231
|
-
} from "./index-kq57tdf0.js";
|
|
232
305
|
import {
|
|
233
306
|
isFailClosedBlockingError,
|
|
234
307
|
shouldBypassFailClosedBlock,
|
|
235
308
|
resolveAgentNameFromMessages,
|
|
236
|
-
registerOwnRpcServerInstance,
|
|
237
|
-
rpcPortDir,
|
|
238
|
-
rpcPortFilePath,
|
|
239
|
-
parseRpcPortFile,
|
|
240
|
-
inspectProcessesAsync,
|
|
241
309
|
getUnconfirmedMigrationHolders,
|
|
242
310
|
getSchemaFenceRejection,
|
|
243
311
|
getMigrationOnOpenRefusal,
|
|
@@ -247,13 +315,21 @@ import {
|
|
|
247
315
|
runSqliteOptimize,
|
|
248
316
|
openDatabase,
|
|
249
317
|
openCurrentDatabase
|
|
250
|
-
} from "./index-
|
|
318
|
+
} from "./index-zg8yq4ya.js";
|
|
319
|
+
import {
|
|
320
|
+
registerOwnRpcServerInstance,
|
|
321
|
+
rpcPortDir,
|
|
322
|
+
rpcPortFilePath,
|
|
323
|
+
parseRpcPortFile,
|
|
324
|
+
inspectProcessesAsync
|
|
325
|
+
} from "./index-6m7rdv7y.js";
|
|
251
326
|
import {
|
|
252
327
|
configureContextDatabasePragmas2
|
|
253
328
|
} from "./index-fb3zxn06.js";
|
|
254
329
|
import {
|
|
255
|
-
|
|
256
|
-
|
|
330
|
+
canonicalProjectDirectory
|
|
331
|
+
} from "./index-7w18gg78.js";
|
|
332
|
+
import {
|
|
257
333
|
unescapeXml,
|
|
258
334
|
resolveWorkspaceShareCategories,
|
|
259
335
|
resolveWorkspaceIdentitySet,
|
|
@@ -261,7 +337,7 @@ import {
|
|
|
261
337
|
resolveStoredPathWorkspaceIdentity,
|
|
262
338
|
storedPathBelongsToWorkspace,
|
|
263
339
|
computeWorkspaceEpochFingerprint
|
|
264
|
-
} from "./index-
|
|
340
|
+
} from "./index-att4bfan.js";
|
|
265
341
|
import {
|
|
266
342
|
V2_MEMORY_CATEGORIES,
|
|
267
343
|
CATEGORY_PRIORITY
|
|
@@ -275,7 +351,6 @@ import {
|
|
|
275
351
|
cortexKitProjectConfigBasePath,
|
|
276
352
|
resolveLegacyConfigSources,
|
|
277
353
|
loadPluginConfigDetailed,
|
|
278
|
-
BoundedSessionMap,
|
|
279
354
|
historianRunConfig,
|
|
280
355
|
currentPluginConfigReader,
|
|
281
356
|
clampProducerAtomChars,
|
|
@@ -293,90 +368,51 @@ import {
|
|
|
293
368
|
embedRunStateBySession,
|
|
294
369
|
invalidateAutoEmbedSession,
|
|
295
370
|
getEmbedDrainUiStatus,
|
|
296
|
-
ensureSessionMetaRow,
|
|
297
371
|
getCompartments,
|
|
298
372
|
getLastCompartmentEndMessage,
|
|
299
373
|
getLastCompartmentEndMessageId,
|
|
300
|
-
MAX_EXECUTE_THRESHOLD,
|
|
301
|
-
escalationBands,
|
|
302
|
-
decodeMergedReasoningParts,
|
|
303
|
-
sessionDecisionCalibration,
|
|
304
|
-
getProtectionWindowForSession,
|
|
305
|
-
isRustMarkerAdmissionFenced,
|
|
306
|
-
setRustMarkerAdmissionFence,
|
|
307
|
-
readReplayEnvelope,
|
|
308
|
-
updateReplayDocument,
|
|
309
|
-
isEmergencyRecoveryArmed,
|
|
310
|
-
isProviderOverflowReconfirmed,
|
|
311
|
-
isProviderOverflowFailClosedProven,
|
|
312
|
-
getEmergencyRecoveryArmedAt,
|
|
313
|
-
loadPersistedUsage,
|
|
314
|
-
loadProtectedTailMeta,
|
|
315
|
-
resetProtectedTailNoEligibleHead,
|
|
316
|
-
resolveCompactionModeRecord,
|
|
317
|
-
getCompactionModeRecord,
|
|
318
|
-
setCompactionModeRecord,
|
|
319
|
-
getProtectedTailDrainBudgetSkip,
|
|
320
|
-
clearPersistedReasoningWatermark,
|
|
321
|
-
getEmergencyInputSample,
|
|
322
|
-
clearEmergencyDropSample,
|
|
323
|
-
getLastNudgeUndropped,
|
|
324
|
-
setLastNudgeUndropped,
|
|
325
|
-
getChannel1NudgeState,
|
|
326
|
-
setChannel1NudgeState,
|
|
327
|
-
markChannel1PostReduceGracePending,
|
|
328
|
-
getChannel2NudgeState,
|
|
329
|
-
getChannel2NudgeClaim,
|
|
330
|
-
setChannel2NudgeState,
|
|
331
|
-
casChannel2NudgeState,
|
|
332
|
-
claimChannel2NudgeState,
|
|
333
|
-
casChannel2NudgeClaim,
|
|
334
|
-
setPersistedNoteNudgeTrigger,
|
|
335
|
-
getNoteNudgeAnchors,
|
|
336
|
-
getAutoSearchHintDecisions,
|
|
337
|
-
getPersistedTodoPermissionDenied,
|
|
338
|
-
setPersistedTodoPermissionDenied,
|
|
339
|
-
getPersistedTodoSyntheticAnchor,
|
|
340
|
-
setPersistedTodoSyntheticAnchor,
|
|
341
|
-
clearPersistedTodoSyntheticAnchor,
|
|
342
|
-
setNoteLastReadAt,
|
|
343
|
-
getHistorianFailureState,
|
|
344
|
-
clearHistorianFailureState,
|
|
345
|
-
getOverflowState,
|
|
346
|
-
loadTransformPassStateSnapshot,
|
|
347
|
-
recordOverflowDetected,
|
|
348
|
-
clearEmergencyRecovery,
|
|
349
|
-
clearDetectedContextLimit,
|
|
350
|
-
getPersistedCompactionMarkerState,
|
|
351
|
-
setPersistedCompactionMarkerState,
|
|
352
|
-
getStrippedPlaceholderIds,
|
|
353
|
-
thinkingBindingRecoveryFrozenId,
|
|
354
|
-
getThinkingBindingRecoveryTarget,
|
|
355
|
-
armThinkingBindingRecovery,
|
|
356
|
-
clearThinkingBindingRecoveryIf,
|
|
357
|
-
getMergedReasoningStrippedIds,
|
|
358
|
-
addMergedReasoningStrippedIds,
|
|
359
|
-
getStaleReduceStrippedIds,
|
|
360
|
-
getProcessedImageStrippedIds,
|
|
361
|
-
getPendingCompactionMarkerState,
|
|
362
|
-
getCompactionMarkerHealth,
|
|
363
|
-
clearPendingCompactionMarkerStateIf,
|
|
364
|
-
setSessionWorkMetrics,
|
|
365
|
-
getObservedEpochFloor,
|
|
366
|
-
resolveEpochFloorForPass,
|
|
367
374
|
providerResponseFailed,
|
|
375
|
+
getOrCreateSessionMeta,
|
|
376
|
+
updateSessionMeta,
|
|
377
|
+
retryPendingSessionCleanups,
|
|
378
|
+
retryPendingRustSessionCleanupsForProject,
|
|
379
|
+
requestPendingMaterialization,
|
|
380
|
+
clearPendingMaterialization,
|
|
381
|
+
recordSystemPromptForRequest,
|
|
382
|
+
recordHeldHeadForRequest,
|
|
383
|
+
isHeldHeadForRequest,
|
|
384
|
+
deferDeliveredSystemRefresh,
|
|
385
|
+
retirePendingSystemPromptDelivery,
|
|
368
386
|
claimLkgRequestIdentity,
|
|
387
|
+
currentLkgRequestIdentity,
|
|
369
388
|
noteCapturedLkgRequest,
|
|
370
389
|
measuredLkgPrefix,
|
|
390
|
+
saveLkgSlotToDb,
|
|
391
|
+
clearPersistedLkgSlotStrict,
|
|
392
|
+
loadPersistedLkgSlot,
|
|
393
|
+
drainStaleLkgSlots,
|
|
394
|
+
resolveLkgModelKeys,
|
|
395
|
+
createLkgEntryProjector,
|
|
396
|
+
captureLkgSlot,
|
|
397
|
+
replayLkg,
|
|
398
|
+
coldStartRawServedIndex,
|
|
399
|
+
coldStartUncapturedReplay,
|
|
400
|
+
noteUncertifiedNormalLkg,
|
|
401
|
+
hasProcessLocalLkgProof,
|
|
402
|
+
lkgDirtyRevision,
|
|
403
|
+
rememberLkgDirtyRevision,
|
|
404
|
+
noteLkgRecoveryPrefix,
|
|
405
|
+
readLkgRecoveryPrefix,
|
|
406
|
+
noteLkgHealthyPrefix,
|
|
407
|
+
lkgRecoveryReplayUnproven,
|
|
408
|
+
lkgRecoveryEntryUnproven,
|
|
371
409
|
beginLkgPass,
|
|
372
410
|
visitMessageContentFields,
|
|
373
411
|
contentSnapshotValue,
|
|
374
412
|
messageContentFields,
|
|
375
413
|
signatureForFields,
|
|
376
|
-
isLegacyLkgDigest,
|
|
377
414
|
exactReusablePrefix,
|
|
378
415
|
incrementalLkgContentDigests,
|
|
379
|
-
lkgContentDigest,
|
|
380
416
|
lkgSlotRejection,
|
|
381
417
|
captureSlot,
|
|
382
418
|
getInMemorySlot,
|
|
@@ -384,18 +420,12 @@ import {
|
|
|
384
420
|
forgetInMemorySlot,
|
|
385
421
|
dropSlot,
|
|
386
422
|
noteEntry,
|
|
387
|
-
LkgEntryDigestCache,
|
|
388
|
-
sharedLkgEntryDigests,
|
|
389
423
|
getLkgSlotHeapStats,
|
|
390
424
|
TOOL_SWEEP_SCOPED_MARKER,
|
|
391
425
|
useScopedToolSweep,
|
|
392
426
|
createPreAdoptionToolSweepResolver,
|
|
393
427
|
queueMemoryMutation,
|
|
394
428
|
getMaxMemoryMutationIdForProjects,
|
|
395
|
-
getOrCreateSessionMeta,
|
|
396
|
-
updateSessionMeta,
|
|
397
|
-
retryPendingSessionCleanups,
|
|
398
|
-
retryPendingRustSessionCleanupsForProject,
|
|
399
429
|
GLOBAL_USER_PROFILE_PROJECT_PATH,
|
|
400
430
|
getProjectState,
|
|
401
431
|
bumpProjectUserProfileVersion,
|
|
@@ -478,7 +508,7 @@ import {
|
|
|
478
508
|
snapRangeToCompartments,
|
|
479
509
|
getActiveCompartmentRun,
|
|
480
510
|
startCompartmentAgent
|
|
481
|
-
} from "./index-
|
|
511
|
+
} from "./index-zfzdpeq2.js";
|
|
482
512
|
import {
|
|
483
513
|
SubcClient,
|
|
484
514
|
connectionFileExists,
|
|
@@ -488,6 +518,16 @@ import {
|
|
|
488
518
|
SynapseEmbeddingProvider
|
|
489
519
|
} from "./index-vkbqdnkj.js";
|
|
490
520
|
import {
|
|
521
|
+
BoundedSessionMap,
|
|
522
|
+
LkgRecoveryFenceError,
|
|
523
|
+
lkgServedArrayDigest,
|
|
524
|
+
hasCleanLkgRecoveryFence,
|
|
525
|
+
dirtyLkgRecoveryRevision,
|
|
526
|
+
ownsLkgDirtyFence,
|
|
527
|
+
invalidateCleanLkgRecoveryFence,
|
|
528
|
+
prepareLkgCaptureFence,
|
|
529
|
+
certifyCommittedLkgCapture,
|
|
530
|
+
markLkgRecoveryDirty,
|
|
491
531
|
getMessageIndexSourceIdentity,
|
|
492
532
|
isMessageIndexSourceCurrent,
|
|
493
533
|
getLastIndexedOrdinal,
|
|
@@ -497,7 +537,7 @@ import {
|
|
|
497
537
|
indexSingleMessage,
|
|
498
538
|
indexMessagesAfterOrdinal,
|
|
499
539
|
sweepOrphanedOpenCodeMessageIndexes
|
|
500
|
-
} from "./index-
|
|
540
|
+
} from "./index-sfhndpcb.js";
|
|
501
541
|
import {
|
|
502
542
|
renderUserFacingFailure,
|
|
503
543
|
userFacingFailureCode,
|
|
@@ -541,7 +581,7 @@ import {
|
|
|
541
581
|
readGitFileChangeTimesSince,
|
|
542
582
|
verificationFileExists,
|
|
543
583
|
normalizeVerificationFiles
|
|
544
|
-
} from "./index-
|
|
584
|
+
} from "./index-rafsaxac.js";
|
|
545
585
|
import {
|
|
546
586
|
registerNotificationSink2,
|
|
547
587
|
pushNotification2,
|
|
@@ -549,6 +589,9 @@ import {
|
|
|
549
589
|
drainNotifications2,
|
|
550
590
|
isTuiConnected2
|
|
551
591
|
} from "./index-x8a7jmkh.js";
|
|
592
|
+
import {
|
|
593
|
+
getLocalEmbeddingNativeMemoryStats
|
|
594
|
+
} from "./index-gbmqa9x9.js";
|
|
552
595
|
import {
|
|
553
596
|
saveEmbeddingIfHashMatches,
|
|
554
597
|
invalidateProject2,
|
|
@@ -556,7 +599,7 @@ import {
|
|
|
556
599
|
} from "./index-4dhv7mqz.js";
|
|
557
600
|
import {
|
|
558
601
|
cosineSimilarity
|
|
559
|
-
} from "./index-
|
|
602
|
+
} from "./index-r2zcs71c.js";
|
|
560
603
|
import {
|
|
561
604
|
computeCueContentHash,
|
|
562
605
|
hasMuralCueColumns,
|
|
@@ -602,17 +645,17 @@ import {
|
|
|
602
645
|
resolveMemoriesByIdsForSearch2,
|
|
603
646
|
unifiedSearch2,
|
|
604
647
|
formatSearchResults2
|
|
605
|
-
} from "./index-
|
|
648
|
+
} from "./index-fdtkt5r1.js";
|
|
606
649
|
import {
|
|
607
650
|
flushIgnoredMessages2,
|
|
608
651
|
clearIgnoredMessages2,
|
|
609
652
|
observeIgnoredNotificationEvent2,
|
|
610
653
|
sendStatusNotification2
|
|
611
|
-
} from "./index-
|
|
654
|
+
} from "./index-xgrwmj82.js";
|
|
612
655
|
import {
|
|
613
656
|
setRecompStarting2,
|
|
614
657
|
setRecompTerminal2
|
|
615
|
-
} from "./index-
|
|
658
|
+
} from "./index-eypn4ba6.js";
|
|
616
659
|
import {
|
|
617
660
|
searchMessageHistoryOffThread,
|
|
618
661
|
findSessionId,
|
|
@@ -631,14 +674,6 @@ import {
|
|
|
631
674
|
canConsumeDeferredOnThisPass,
|
|
632
675
|
hasReclaimRide,
|
|
633
676
|
reclaimRideLabel,
|
|
634
|
-
replayClearedReasoning,
|
|
635
|
-
replayStrippedInlineThinking,
|
|
636
|
-
stripClearedReasoning,
|
|
637
|
-
findReasoningBearingAssistantIds,
|
|
638
|
-
snapshotTrailingBlankSourceDecisions,
|
|
639
|
-
projectOpencodeReasoningBudgetCutoff,
|
|
640
|
-
resolveKeepReasoningTokens,
|
|
641
|
-
reasoningBudgetCutoff,
|
|
642
677
|
captureOpencodeReasoningBudgetStatus,
|
|
643
678
|
reasoningBudgetStatusLine,
|
|
644
679
|
ENGINE_RECONNECTING_USER_MESSAGE,
|
|
@@ -670,14 +705,14 @@ import {
|
|
|
670
705
|
abortSessionFailClosed2,
|
|
671
706
|
evaluateEmergencyFailClosed2,
|
|
672
707
|
runPostTransformPhase2
|
|
673
|
-
} from "./index-
|
|
708
|
+
} from "./index-p0n5ryq8.js";
|
|
674
709
|
import {
|
|
675
710
|
ANNOUNCEMENT_VERSION2,
|
|
676
711
|
ANNOUNCEMENT_FEATURES2,
|
|
677
712
|
ANNOUNCEMENT_FOOTER2,
|
|
678
713
|
markAnnouncementSeen2,
|
|
679
714
|
shouldShowAnnouncement2
|
|
680
|
-
} from "./index-
|
|
715
|
+
} from "./index-mw7c950g.js";
|
|
681
716
|
import {
|
|
682
717
|
resolvePromptContext2
|
|
683
718
|
} from "./index-fmsr7v69.js";
|
|
@@ -697,7 +732,7 @@ import {
|
|
|
697
732
|
writeStorageFileAtomicSync,
|
|
698
733
|
writeStorageFileAsync,
|
|
699
734
|
createStorageWriteStream
|
|
700
|
-
} from "./index-
|
|
735
|
+
} from "./index-fvnzcnww.js";
|
|
701
736
|
import {
|
|
702
737
|
canonicalModelIdentity,
|
|
703
738
|
piModelRefToCanonical,
|
|
@@ -4932,7 +4967,7 @@ function getAsyncModule() {
|
|
|
4932
4967
|
await beforeModuleLoad();
|
|
4933
4968
|
const [{ default: singlefileAsyncifyVariant }, { newQuickJSAsyncWASMModuleFromVariant }] = await importPluginModule(() => Promise.all([
|
|
4934
4969
|
import("./index-e7vx3byk.js").then((m)=>__toESM(m.default,1)),
|
|
4935
|
-
import("./index-
|
|
4970
|
+
import("./index-69vas84q.js")
|
|
4936
4971
|
]));
|
|
4937
4972
|
const module = await newQuickJSAsyncWASMModuleFromVariant(singlefileAsyncifyVariant);
|
|
4938
4973
|
return module;
|
|
@@ -10799,325 +10834,47 @@ function clearDreamerTickFailure(db) {
|
|
|
10799
10834
|
db.prepare("DELETE FROM schema_migrations_meta WHERE key = ?").run(DREAMER_TICK_FAILURE_KEY);
|
|
10800
10835
|
}
|
|
10801
10836
|
|
|
10802
|
-
// src/
|
|
10803
|
-
|
|
10804
|
-
|
|
10805
|
-
|
|
10806
|
-
|
|
10807
|
-
|
|
10837
|
+
// src/plugin/dream-timer.ts
|
|
10838
|
+
var DREAM_TIMER_INTERVAL_MS = 15 * 60 * 1000;
|
|
10839
|
+
var GIT_COMMIT_BACKLOG_DRAIN_MAX_MS = 5 * 60 * 1000;
|
|
10840
|
+
var BOOT_PROJECT_JITTER_SLOT_MS = 1000;
|
|
10841
|
+
var activeTimer = null;
|
|
10842
|
+
var tickInFlight = false;
|
|
10843
|
+
var startupTickTimer = null;
|
|
10844
|
+
var startupTimers = new Map;
|
|
10845
|
+
var startupJitters = new Map;
|
|
10846
|
+
var nextStartupJitterSlot = 0;
|
|
10847
|
+
function directoryStillExists(directory) {
|
|
10808
10848
|
try {
|
|
10809
|
-
|
|
10849
|
+
return statSync2(directory).isDirectory();
|
|
10810
10850
|
} catch {
|
|
10811
|
-
return
|
|
10851
|
+
return false;
|
|
10812
10852
|
}
|
|
10813
|
-
|
|
10853
|
+
}
|
|
10854
|
+
function openTimerDatabaseOrNull(context) {
|
|
10855
|
+
let db;
|
|
10856
|
+
try {
|
|
10857
|
+
db = openCurrentDatabase();
|
|
10858
|
+
} catch (error) {
|
|
10859
|
+
log2(`[dreamer] storage fatal; skipping ${context}: ${getErrorMessage(error)}`);
|
|
10814
10860
|
return null;
|
|
10815
|
-
const result = [];
|
|
10816
|
-
for (const entry of parsed) {
|
|
10817
|
-
if (typeof entry !== "string" || entry.length === 0)
|
|
10818
|
-
return null;
|
|
10819
|
-
result.push(entry);
|
|
10820
10861
|
}
|
|
10821
|
-
|
|
10822
|
-
}
|
|
10823
|
-
function parseNullableString(value) {
|
|
10824
|
-
if (value === null || value === undefined)
|
|
10862
|
+
if (!db) {
|
|
10863
|
+
log2(`[dreamer] storage unavailable; skipping ${context} (the cache schema is newer than this binary supports — restart/upgrade OpenCode/Pi/Magic Context to recover)`);
|
|
10825
10864
|
return null;
|
|
10826
|
-
|
|
10865
|
+
}
|
|
10866
|
+
return db;
|
|
10827
10867
|
}
|
|
10828
|
-
|
|
10829
|
-
|
|
10868
|
+
var refusedEmptyIdentityDirectories = new Set;
|
|
10869
|
+
function logEmptyIdentityRefusalOnce(directory) {
|
|
10870
|
+
if (refusedEmptyIdentityDirectories.has(directory))
|
|
10830
10871
|
return;
|
|
10831
|
-
|
|
10872
|
+
refusedEmptyIdentityDirectories.add(directory);
|
|
10873
|
+
log2(`[dreamer] not registering ${directory}: it has no project identity, so no project-scoped work runs for it`);
|
|
10832
10874
|
}
|
|
10833
|
-
|
|
10834
|
-
|
|
10835
|
-
|
|
10836
|
-
const record = row;
|
|
10837
|
-
const jsonPrefix = record.json_prefix;
|
|
10838
|
-
const lastInputMessageId = record.last_input_message_id;
|
|
10839
|
-
const capturedAt = record.captured_at;
|
|
10840
|
-
let inputIdsRaw = record.input_id_seq;
|
|
10841
|
-
let piOutputEntryIds;
|
|
10842
|
-
if (typeof inputIdsRaw === "string") {
|
|
10843
|
-
try {
|
|
10844
|
-
const metadata = JSON.parse(inputIdsRaw);
|
|
10845
|
-
if (metadata && !Array.isArray(metadata) && metadata.version === 1 && Array.isArray(metadata.piOutputEntryIds)) {
|
|
10846
|
-
if (!metadata.piOutputEntryIds.every((id) => id === null || typeof id === "string" && id.length > 0))
|
|
10847
|
-
return;
|
|
10848
|
-
piOutputEntryIds = metadata.piOutputEntryIds;
|
|
10849
|
-
inputIdsRaw = JSON.stringify(metadata.inputIds);
|
|
10850
|
-
}
|
|
10851
|
-
} catch {
|
|
10852
|
-
return;
|
|
10853
|
-
}
|
|
10854
|
-
}
|
|
10855
|
-
const inputIdSeq = parseStringArray(inputIdsRaw);
|
|
10856
|
-
const inputContentDigests = parseStringArray(record.input_content_digests);
|
|
10857
|
-
const modelKey = parseNullableString(record.model_key);
|
|
10858
|
-
const providerKey = parseNullableString(record.provider_key);
|
|
10859
|
-
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) {
|
|
10860
|
-
return;
|
|
10861
|
-
}
|
|
10862
|
-
if (piOutputEntryIds) {
|
|
10863
|
-
try {
|
|
10864
|
-
const output = JSON.parse(jsonPrefix);
|
|
10865
|
-
const inputs = new Set(inputIdSeq);
|
|
10866
|
-
if (!Array.isArray(output) || output.length !== piOutputEntryIds.length || piOutputEntryIds.some((id) => id !== null && !inputs.has(id)))
|
|
10867
|
-
return;
|
|
10868
|
-
} catch {
|
|
10869
|
-
return;
|
|
10870
|
-
}
|
|
10871
|
-
}
|
|
10872
|
-
let inputContentSignatures;
|
|
10873
|
-
if (record.input_content_signatures !== null && record.input_content_signatures !== undefined) {
|
|
10874
|
-
const parsed = parseStringArray(record.input_content_signatures);
|
|
10875
|
-
if (parsed === null || parsed.length !== inputIdSeq.length)
|
|
10876
|
-
return;
|
|
10877
|
-
inputContentSignatures = parsed;
|
|
10878
|
-
}
|
|
10879
|
-
const slot = {
|
|
10880
|
-
jsonPrefix,
|
|
10881
|
-
inputIdSeq,
|
|
10882
|
-
inputContentDigests,
|
|
10883
|
-
lastInputMessageId,
|
|
10884
|
-
modelKey,
|
|
10885
|
-
providerKey,
|
|
10886
|
-
capturedAt
|
|
10887
|
-
};
|
|
10888
|
-
if (inputContentSignatures)
|
|
10889
|
-
slot.inputContentSignatures = inputContentSignatures;
|
|
10890
|
-
if (piOutputEntryIds)
|
|
10891
|
-
slot.piOutputEntryIds = piOutputEntryIds;
|
|
10892
|
-
const rowVersion = parseNullableInteger(record.row_version);
|
|
10893
|
-
if (rowVersion !== undefined)
|
|
10894
|
-
slot.rowVersion = rowVersion;
|
|
10895
|
-
const captureSequence = parseNullableInteger(record.capture_sequence);
|
|
10896
|
-
if (captureSequence !== undefined)
|
|
10897
|
-
slot.captureSequence = captureSequence;
|
|
10898
|
-
return slot;
|
|
10899
|
-
}
|
|
10900
|
-
var persistedFingerprints = new WeakMap;
|
|
10901
|
-
var PERSISTED_FINGERPRINT_MAX_SESSIONS = 1000;
|
|
10902
|
-
function rememberFingerprint(db, sessionId, fingerprint) {
|
|
10903
|
-
let saved = persistedFingerprints.get(db);
|
|
10904
|
-
if (!saved) {
|
|
10905
|
-
saved = new Map;
|
|
10906
|
-
persistedFingerprints.set(db, saved);
|
|
10907
|
-
}
|
|
10908
|
-
saved.delete(sessionId);
|
|
10909
|
-
if (saved.size >= PERSISTED_FINGERPRINT_MAX_SESSIONS) {
|
|
10910
|
-
const oldest = saved.keys().next().value;
|
|
10911
|
-
if (oldest !== undefined)
|
|
10912
|
-
saved.delete(oldest);
|
|
10913
|
-
}
|
|
10914
|
-
saved.set(sessionId, fingerprint);
|
|
10915
|
-
}
|
|
10916
|
-
function slotFingerprint(slot) {
|
|
10917
|
-
return createHash8("sha256").update(JSON.stringify([
|
|
10918
|
-
slot.jsonPrefix,
|
|
10919
|
-
slot.inputIdSeq,
|
|
10920
|
-
slot.inputContentDigests,
|
|
10921
|
-
slot.inputContentSignatures,
|
|
10922
|
-
slot.piOutputEntryIds,
|
|
10923
|
-
slot.lastInputMessageId,
|
|
10924
|
-
slot.modelKey,
|
|
10925
|
-
slot.providerKey,
|
|
10926
|
-
slot.rowVersion,
|
|
10927
|
-
slot.captureSequence
|
|
10928
|
-
])).digest("hex");
|
|
10929
|
-
}
|
|
10930
|
-
function saveLkgSlotToDb(db, sessionId, slot, publishMetadata) {
|
|
10931
|
-
const fingerprint = slotFingerprint(slot);
|
|
10932
|
-
if (!publishMetadata && persistedFingerprints.get(db)?.get(sessionId) === fingerprint)
|
|
10933
|
-
return true;
|
|
10934
|
-
const layout = layoutLkgPrefix(slot.jsonPrefix);
|
|
10935
|
-
try {
|
|
10936
|
-
db.transaction(() => {
|
|
10937
|
-
const storedHashes = new Map;
|
|
10938
|
-
for (const row of db.prepare("SELECT chunk, hash FROM lkg_slot_chunks WHERE session_id = ?").all(sessionId)) {
|
|
10939
|
-
storedHashes.set(row.chunk, row.hash);
|
|
10940
|
-
}
|
|
10941
|
-
const upsertChunk = db.prepare(`INSERT INTO lkg_slot_chunks (session_id, chunk, hash, body) VALUES (?, ?, ?, ?)
|
|
10942
|
-
ON CONFLICT(session_id, chunk) DO UPDATE SET hash = excluded.hash, body = excluded.body`);
|
|
10943
|
-
for (let index = 0;index < layout.chunks.length; index += 1) {
|
|
10944
|
-
if (storedHashes.get(index) === layout.chunkHashes[index])
|
|
10945
|
-
continue;
|
|
10946
|
-
upsertChunk.run(sessionId, index, layout.chunkHashes[index], layout.chunks[index]);
|
|
10947
|
-
}
|
|
10948
|
-
db.prepare("DELETE FROM lkg_slot_chunks WHERE session_id = ? AND chunk >= ?").run(sessionId, layout.chunks.length);
|
|
10949
|
-
db.prepare(`INSERT INTO lkg_slots (
|
|
10950
|
-
session_id, json_prefix_chars, json_prefix_chunks, json_prefix_hash,
|
|
10951
|
-
input_id_seq, input_content_digests, input_content_signatures,
|
|
10952
|
-
last_input_message_id, model_key, provider_key,
|
|
10953
|
-
captured_at, row_version, capture_sequence
|
|
10954
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
10955
|
-
ON CONFLICT(session_id) DO UPDATE SET
|
|
10956
|
-
json_prefix_chars = excluded.json_prefix_chars,
|
|
10957
|
-
json_prefix_chunks = excluded.json_prefix_chunks,
|
|
10958
|
-
json_prefix_hash = excluded.json_prefix_hash,
|
|
10959
|
-
input_id_seq = excluded.input_id_seq,
|
|
10960
|
-
input_content_digests = excluded.input_content_digests,
|
|
10961
|
-
input_content_signatures = excluded.input_content_signatures,
|
|
10962
|
-
last_input_message_id = excluded.last_input_message_id,
|
|
10963
|
-
model_key = excluded.model_key,
|
|
10964
|
-
provider_key = excluded.provider_key,
|
|
10965
|
-
captured_at = excluded.captured_at,
|
|
10966
|
-
row_version = excluded.row_version,
|
|
10967
|
-
capture_sequence = excluded.capture_sequence`).run(sessionId, layout.chars, layout.chunks.length, layout.hash, JSON.stringify(slot.piOutputEntryIds ? {
|
|
10968
|
-
version: 1,
|
|
10969
|
-
inputIds: slot.inputIdSeq,
|
|
10970
|
-
piOutputEntryIds: slot.piOutputEntryIds
|
|
10971
|
-
} : 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);
|
|
10972
|
-
publishMetadata?.();
|
|
10973
|
-
}).immediate();
|
|
10974
|
-
rememberFingerprint(db, sessionId, fingerprint);
|
|
10975
|
-
return true;
|
|
10976
|
-
} catch (error) {
|
|
10977
|
-
if (!publishMetadata)
|
|
10978
|
-
sessionLog2(sessionId, "LKG snapshot persistence failed (in-memory slot retained):", error);
|
|
10979
|
-
return false;
|
|
10980
|
-
}
|
|
10981
|
-
}
|
|
10982
|
-
function clearPersistedLkgSlot(db, sessionId) {
|
|
10983
|
-
try {
|
|
10984
|
-
clearPersistedLkgSlotStrict(db, sessionId);
|
|
10985
|
-
} catch (error) {
|
|
10986
|
-
sessionLog2(sessionId, "LKG snapshot durable clear failed:", error);
|
|
10987
|
-
}
|
|
10988
|
-
}
|
|
10989
|
-
function clearPersistedLkgSlotStrict(db, sessionId) {
|
|
10990
|
-
db.transaction(() => {
|
|
10991
|
-
db.prepare("DELETE FROM lkg_slot_chunks WHERE session_id = ?").run(sessionId);
|
|
10992
|
-
db.prepare("DELETE FROM lkg_slots WHERE session_id = ?").run(sessionId);
|
|
10993
|
-
}).immediate();
|
|
10994
|
-
persistedFingerprints.get(db)?.delete(sessionId);
|
|
10995
|
-
}
|
|
10996
|
-
function loadPersistedLkgSlot(db, sessionId) {
|
|
10997
|
-
if (isRustMarkerAdmissionFenced(db, sessionId))
|
|
10998
|
-
return;
|
|
10999
|
-
let row;
|
|
11000
|
-
let chunkRows;
|
|
11001
|
-
try {
|
|
11002
|
-
({ row, chunkRows } = db.transaction(() => {
|
|
11003
|
-
const slotRow = db.prepare("SELECT * FROM lkg_slots WHERE session_id = ?").get(sessionId);
|
|
11004
|
-
if (!slotRow)
|
|
11005
|
-
return { row: undefined, chunkRows: [] };
|
|
11006
|
-
const slices = db.prepare("SELECT chunk, hash, body FROM lkg_slot_chunks WHERE session_id = ? ORDER BY chunk").all(sessionId);
|
|
11007
|
-
return { row: slotRow, chunkRows: slices };
|
|
11008
|
-
}).deferred());
|
|
11009
|
-
} catch (error) {
|
|
11010
|
-
sessionLog2(sessionId, "LKG snapshot durable load failed:", error);
|
|
11011
|
-
return;
|
|
11012
|
-
}
|
|
11013
|
-
if (!row)
|
|
11014
|
-
return;
|
|
11015
|
-
const prefix = assembleLkgPrefix({
|
|
11016
|
-
chars: row.json_prefix_chars,
|
|
11017
|
-
chunks: row.json_prefix_chunks,
|
|
11018
|
-
hash: row.json_prefix_hash
|
|
11019
|
-
}, chunkRows);
|
|
11020
|
-
const slot = prefix ? parsePersistedLkgSlot({ ...row, json_prefix: prefix.jsonPrefix }) : undefined;
|
|
11021
|
-
if (!prefix || !slot) {
|
|
11022
|
-
if (!prefix)
|
|
11023
|
-
sessionLog2(sessionId, "LKG snapshot slices failed verification; slot cleared");
|
|
11024
|
-
clearPersistedLkgSlot(db, sessionId);
|
|
11025
|
-
return;
|
|
11026
|
-
}
|
|
11027
|
-
return slot;
|
|
11028
|
-
}
|
|
11029
|
-
function pruneStaleLkgSlotsBatch(db, now) {
|
|
11030
|
-
const previousTimeout = db.prepare("PRAGMA busy_timeout").get();
|
|
11031
|
-
const cutoff = now - 7 * 24 * 60 * 60 * 1000;
|
|
11032
|
-
const stale = `captured_at < ? AND NOT EXISTS (
|
|
11033
|
-
SELECT 1 FROM session_projects sp
|
|
11034
|
-
WHERE sp.session_id = lkg_slots.session_id AND sp.updated_at >= ?
|
|
11035
|
-
)`;
|
|
11036
|
-
const slot = db.prepare(`SELECT session_id FROM lkg_slots WHERE ${stale} LIMIT 1`).get(cutoff, cutoff);
|
|
11037
|
-
const chunks = db.prepare(`SELECT rowid FROM lkg_slot_chunks c WHERE
|
|
11038
|
-
session_id = ? OR NOT EXISTS (SELECT 1 FROM lkg_slots s WHERE s.session_id = c.session_id)
|
|
11039
|
-
LIMIT 25`).all(slot?.session_id ?? "");
|
|
11040
|
-
if (!slot && chunks.length === 0)
|
|
11041
|
-
return { slots: 0, chunks: 0 };
|
|
11042
|
-
try {
|
|
11043
|
-
db.exec("PRAGMA busy_timeout = 0");
|
|
11044
|
-
let transactionStartedAt = 0;
|
|
11045
|
-
const changes = db.transaction(() => {
|
|
11046
|
-
transactionStartedAt = performance.now();
|
|
11047
|
-
const removed = slot ? db.prepare(`DELETE FROM lkg_slots WHERE session_id = ? AND ${stale}`).run(slot.session_id, cutoff, cutoff).changes : 0;
|
|
11048
|
-
const removeChunk = db.prepare(`DELETE FROM lkg_slot_chunks WHERE rowid = ? AND NOT EXISTS (
|
|
11049
|
-
SELECT 1 FROM lkg_slots s WHERE s.session_id = lkg_slot_chunks.session_id
|
|
11050
|
-
)`);
|
|
11051
|
-
let removedChunks = 0;
|
|
11052
|
-
for (const { rowid } of chunks)
|
|
11053
|
-
removedChunks += removeChunk.run(rowid).changes;
|
|
11054
|
-
return { slots: removed, chunks: removedChunks };
|
|
11055
|
-
}).immediate();
|
|
11056
|
-
logSlowWriteTransaction("lkg_stale_gc", transactionStartedAt);
|
|
11057
|
-
if (changes.slots && slot)
|
|
11058
|
-
persistedFingerprints.get(db)?.delete(slot.session_id);
|
|
11059
|
-
return changes;
|
|
11060
|
-
} finally {
|
|
11061
|
-
db.exec(`PRAGMA busy_timeout = ${Number(previousTimeout.timeout) || 0}`);
|
|
11062
|
-
}
|
|
11063
|
-
}
|
|
11064
|
-
async function drainStaleLkgSlots(db, now = Date.now(), budgetMs = 2000) {
|
|
11065
|
-
let removed = 0;
|
|
11066
|
-
await drainBackgroundBatches(() => {
|
|
11067
|
-
const batch = pruneStaleLkgSlotsBatch(db, now);
|
|
11068
|
-
removed += batch.slots;
|
|
11069
|
-
return batch.slots + batch.chunks > 0;
|
|
11070
|
-
}, { budgetMs });
|
|
11071
|
-
return removed;
|
|
11072
|
-
}
|
|
11073
|
-
function createDbLkgPersistence(db) {
|
|
11074
|
-
return {
|
|
11075
|
-
load: (sessionId) => loadPersistedLkgSlot(db, sessionId),
|
|
11076
|
-
clear: (sessionId) => clearPersistedLkgSlot(db, sessionId)
|
|
11077
|
-
};
|
|
11078
|
-
}
|
|
11079
|
-
|
|
11080
|
-
// src/plugin/dream-timer.ts
|
|
11081
|
-
var DREAM_TIMER_INTERVAL_MS = 15 * 60 * 1000;
|
|
11082
|
-
var GIT_COMMIT_BACKLOG_DRAIN_MAX_MS = 5 * 60 * 1000;
|
|
11083
|
-
var BOOT_PROJECT_JITTER_SLOT_MS = 1000;
|
|
11084
|
-
var activeTimer = null;
|
|
11085
|
-
var tickInFlight = false;
|
|
11086
|
-
var startupTickTimer = null;
|
|
11087
|
-
var startupTimers = new Map;
|
|
11088
|
-
var startupJitters = new Map;
|
|
11089
|
-
var nextStartupJitterSlot = 0;
|
|
11090
|
-
function directoryStillExists(directory) {
|
|
11091
|
-
try {
|
|
11092
|
-
return statSync2(directory).isDirectory();
|
|
11093
|
-
} catch {
|
|
11094
|
-
return false;
|
|
11095
|
-
}
|
|
11096
|
-
}
|
|
11097
|
-
function openTimerDatabaseOrNull(context) {
|
|
11098
|
-
let db;
|
|
11099
|
-
try {
|
|
11100
|
-
db = openCurrentDatabase();
|
|
11101
|
-
} catch (error) {
|
|
11102
|
-
log2(`[dreamer] storage fatal; skipping ${context}: ${getErrorMessage(error)}`);
|
|
11103
|
-
return null;
|
|
11104
|
-
}
|
|
11105
|
-
if (!db) {
|
|
11106
|
-
log2(`[dreamer] storage unavailable; skipping ${context} (the cache schema is newer than this binary supports — restart/upgrade OpenCode/Pi/Magic Context to recover)`);
|
|
11107
|
-
return null;
|
|
11108
|
-
}
|
|
11109
|
-
return db;
|
|
11110
|
-
}
|
|
11111
|
-
var refusedEmptyIdentityDirectories = new Set;
|
|
11112
|
-
function logEmptyIdentityRefusalOnce(directory) {
|
|
11113
|
-
if (refusedEmptyIdentityDirectories.has(directory))
|
|
11114
|
-
return;
|
|
11115
|
-
refusedEmptyIdentityDirectories.add(directory);
|
|
11116
|
-
log2(`[dreamer] not registering ${directory}: it has no project identity, so no project-scoped work runs for it`);
|
|
11117
|
-
}
|
|
11118
|
-
var registeredProjects = new Map;
|
|
11119
|
-
function stopDreamScheduleTimerIfIdle() {
|
|
11120
|
-
if (registeredProjects.size !== 0)
|
|
10875
|
+
var registeredProjects = new Map;
|
|
10876
|
+
function stopDreamScheduleTimerIfIdle() {
|
|
10877
|
+
if (registeredProjects.size !== 0)
|
|
11121
10878
|
return;
|
|
11122
10879
|
const stopped = activeTimer !== null || startupTickTimer !== null;
|
|
11123
10880
|
if (activeTimer) {
|
|
@@ -11528,7 +11285,7 @@ async function sweepGitCommits(args) {
|
|
|
11528
11285
|
import { readFileSync as readFileSync4, statSync as statSync3 } from "node:fs";
|
|
11529
11286
|
|
|
11530
11287
|
// src/plugin/embedding-bootstrap-helpers.ts
|
|
11531
|
-
import { createHash as
|
|
11288
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
11532
11289
|
var EMBEDDING_AFFECTING_KEYS = new Set([
|
|
11533
11290
|
"embedding.api_key",
|
|
11534
11291
|
"embedding.endpoint",
|
|
@@ -11576,7 +11333,7 @@ var EMBEDDING_WARNING_TERMS = [
|
|
|
11576
11333
|
];
|
|
11577
11334
|
var loggedFailureSignatures = new Map;
|
|
11578
11335
|
function sha256Prefix(value, length = 16) {
|
|
11579
|
-
return
|
|
11336
|
+
return createHash8("sha256").update(value).digest("hex").slice(0, length);
|
|
11580
11337
|
}
|
|
11581
11338
|
function warningLooksEmbeddingRelated(message) {
|
|
11582
11339
|
const lower = message.toLowerCase();
|
|
@@ -14661,7 +14418,7 @@ function createChatMessageHook(args) {
|
|
|
14661
14418
|
sessionLog2(sessionId, `variant changed (${previousVariant} -> ${input.variant}), triggering flush`);
|
|
14662
14419
|
args.historyRefreshSessions.add(sessionId);
|
|
14663
14420
|
args.systemPromptRefreshSessions.add(sessionId);
|
|
14664
|
-
args.pendingMaterializationSessions
|
|
14421
|
+
requestPendingMaterialization(args.pendingMaterializationSessions, sessionId, "variant_change");
|
|
14665
14422
|
args.lastHeuristicsTurnId.delete(sessionId);
|
|
14666
14423
|
} else {
|
|
14667
14424
|
sessionLog2(sessionId, `variant changed (${previousVariant} -> ${input.variant}) on ${providerID ?? "unknown"}/${modelID ?? "unknown"} without a proven natural cache bust; deferring flush to next natural bust`);
|
|
@@ -14729,7 +14486,7 @@ function createEventHook(args) {
|
|
|
14729
14486
|
args.historyRefreshSessions.delete(sessionId);
|
|
14730
14487
|
args.deferredHistoryRefreshSessions.delete(sessionId);
|
|
14731
14488
|
args.systemPromptRefreshSessions.delete(sessionId);
|
|
14732
|
-
args.pendingMaterializationSessions
|
|
14489
|
+
clearPendingMaterialization(args.pendingMaterializationSessions, sessionId);
|
|
14733
14490
|
args.deferredMaterializationSessions.delete(sessionId);
|
|
14734
14491
|
args.lastHeuristicsTurnId.delete(sessionId);
|
|
14735
14492
|
args.commitSeenLastPass?.delete(sessionId);
|
|
@@ -15886,7 +15643,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
15886
15643
|
return { count: buildCompartmentCount(db, sessionId, moduleStatus) };
|
|
15887
15644
|
});
|
|
15888
15645
|
const buildManagedCtx = async (db) => {
|
|
15889
|
-
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-
|
|
15646
|
+
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-j4ry8j8n.js"));
|
|
15890
15647
|
const { resolveHistorianModel } = await importPluginModule(() => import("./model-resolution-nx97z3x7.js"));
|
|
15891
15648
|
const { userMemoryCollectionEnabled } = await importPluginModule(() => import("./task-config-cgpg0nvh.js"));
|
|
15892
15649
|
const DEFAULT_HISTORIAN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
@@ -15922,8 +15679,8 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
15922
15679
|
const db = readDatabase();
|
|
15923
15680
|
if (!db)
|
|
15924
15681
|
return { ok: false, error: "db unavailable" };
|
|
15925
|
-
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-
|
|
15926
|
-
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-
|
|
15682
|
+
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-kpkhkjhq.js"));
|
|
15683
|
+
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-xffh3bbe.js"));
|
|
15927
15684
|
log2(`[rpc] recomp requested for session ${sessionId}`);
|
|
15928
15685
|
if (!args.client && !args.hiddenCompletionExecutor) {
|
|
15929
15686
|
return {
|
|
@@ -15975,7 +15732,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
15975
15732
|
}
|
|
15976
15733
|
liveSessionState.historyRefreshSessions.add(sessionId);
|
|
15977
15734
|
liveSessionState.systemPromptRefreshSessions.add(sessionId);
|
|
15978
|
-
liveSessionState.pendingMaterializationSessions
|
|
15735
|
+
requestPendingMaterialization(liveSessionState.pendingMaterializationSessions, sessionId, "user_flush");
|
|
15979
15736
|
return { ok: true, message };
|
|
15980
15737
|
});
|
|
15981
15738
|
rpcServer.handle("wrapup", async (params) => {
|
|
@@ -15992,7 +15749,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
15992
15749
|
const db = readDatabase();
|
|
15993
15750
|
if (!db)
|
|
15994
15751
|
return { ok: false, error: "db unavailable" };
|
|
15995
|
-
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-
|
|
15752
|
+
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-xvrr27ws.js"));
|
|
15996
15753
|
const model = liveSessionState.liveModelBySession.get(sessionId);
|
|
15997
15754
|
const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
|
|
15998
15755
|
const ctx = {
|
|
@@ -16074,6 +15831,15 @@ var canonicalReasons = new Set([
|
|
|
16074
15831
|
"project_memory_epoch",
|
|
16075
15832
|
"ttl_idle",
|
|
16076
15833
|
"explicit_flush",
|
|
15834
|
+
"user_flush",
|
|
15835
|
+
"fit_retry",
|
|
15836
|
+
"pending_materialization",
|
|
15837
|
+
"variant_change",
|
|
15838
|
+
"recomp",
|
|
15839
|
+
"boundary_repair",
|
|
15840
|
+
"host_history_change",
|
|
15841
|
+
"thinking_hold",
|
|
15842
|
+
"mutation_drift",
|
|
16077
15843
|
"max_mutation_id",
|
|
16078
15844
|
"first_render",
|
|
16079
15845
|
"pressure_refold",
|
|
@@ -16671,639 +16437,6 @@ function commitCompactionModeRecord(db, sessionId, record) {
|
|
|
16671
16437
|
setCompactionModeRecord(db, sessionId, record);
|
|
16672
16438
|
}
|
|
16673
16439
|
|
|
16674
|
-
// src/hooks/magic-context/openai-compat-adjacency.ts
|
|
16675
|
-
function assertOpenAiCompatAdjacency(messages) {
|
|
16676
|
-
const violations = [];
|
|
16677
|
-
for (let i = 0;i < messages.length; i++) {
|
|
16678
|
-
const msg = messages[i];
|
|
16679
|
-
if (msg.role !== "assistant" || !msg.tool_calls || msg.tool_calls.length === 0) {
|
|
16680
|
-
continue;
|
|
16681
|
-
}
|
|
16682
|
-
const expectedIds = msg.tool_calls.map((tc) => tc.id);
|
|
16683
|
-
const expectedSet = new Set(expectedIds);
|
|
16684
|
-
const collected = new Map;
|
|
16685
|
-
let j = i + 1;
|
|
16686
|
-
while (j < messages.length && messages[j].role === "tool") {
|
|
16687
|
-
const toolMsg = messages[j];
|
|
16688
|
-
const id = toolMsg.tool_call_id;
|
|
16689
|
-
if (!id) {
|
|
16690
|
-
violations.push({
|
|
16691
|
-
index: i,
|
|
16692
|
-
kind: "unmatched_tool_call_id",
|
|
16693
|
-
detail: `tool message at index ${j} missing tool_call_id`
|
|
16694
|
-
});
|
|
16695
|
-
} else if (!expectedSet.has(id)) {
|
|
16696
|
-
violations.push({
|
|
16697
|
-
index: i,
|
|
16698
|
-
kind: "unmatched_tool_call_id",
|
|
16699
|
-
toolCallId: id,
|
|
16700
|
-
assistantToolCallIds: expectedIds,
|
|
16701
|
-
detail: `tool message at index ${j} references unexpected id ${id}`
|
|
16702
|
-
});
|
|
16703
|
-
} else {
|
|
16704
|
-
collected.set(id, j);
|
|
16705
|
-
}
|
|
16706
|
-
j++;
|
|
16707
|
-
}
|
|
16708
|
-
const followingRoles = messages.slice(i + 1, Math.min(messages.length, i + 4)).map((m) => m.role);
|
|
16709
|
-
const missing = expectedIds.filter((id) => !collected.has(id));
|
|
16710
|
-
if (missing.length > 0) {
|
|
16711
|
-
violations.push({
|
|
16712
|
-
index: i,
|
|
16713
|
-
kind: "missing_tool_messages",
|
|
16714
|
-
assistantToolCallIds: expectedIds,
|
|
16715
|
-
followingRoles,
|
|
16716
|
-
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(", ")}`
|
|
16717
|
-
});
|
|
16718
|
-
if (j < messages.length && messages[j].role !== "tool") {
|
|
16719
|
-
const last = violations[violations.length - 1];
|
|
16720
|
-
last.detail += `; blocked by ${messages.slice(i + 1, j + 1).map((m, off) => `${m.role}[${i + 1 + off}]`).join(", ")}`;
|
|
16721
|
-
}
|
|
16722
|
-
}
|
|
16723
|
-
}
|
|
16724
|
-
for (let i = 0;i < messages.length; i++) {
|
|
16725
|
-
if (messages[i].role !== "tool")
|
|
16726
|
-
continue;
|
|
16727
|
-
const id = messages[i].tool_call_id ?? "";
|
|
16728
|
-
if (!id)
|
|
16729
|
-
continue;
|
|
16730
|
-
let found = false;
|
|
16731
|
-
for (let k = i - 1;k >= 0; k--) {
|
|
16732
|
-
const prev = messages[k];
|
|
16733
|
-
if (prev.role === "assistant" && prev.tool_calls?.some((tc) => tc.id === id)) {
|
|
16734
|
-
const between = messages.slice(k + 1, i);
|
|
16735
|
-
if (between.every((m) => m.role === "tool")) {
|
|
16736
|
-
found = true;
|
|
16737
|
-
}
|
|
16738
|
-
break;
|
|
16739
|
-
}
|
|
16740
|
-
if (prev.role === "assistant" || prev.role === "user")
|
|
16741
|
-
break;
|
|
16742
|
-
}
|
|
16743
|
-
if (!found) {
|
|
16744
|
-
violations.push({
|
|
16745
|
-
index: i,
|
|
16746
|
-
kind: "orphan_tool_message",
|
|
16747
|
-
toolCallId: id,
|
|
16748
|
-
detail: `tool message at index ${i} is not immediately after its assistant tool_calls`
|
|
16749
|
-
});
|
|
16750
|
-
}
|
|
16751
|
-
}
|
|
16752
|
-
return { ok: violations.length === 0, violations };
|
|
16753
|
-
}
|
|
16754
|
-
|
|
16755
|
-
// src/hooks/magic-context/lkg-replay.ts
|
|
16756
|
-
function canonicalLkgModelKeys(modelKey, providerKey) {
|
|
16757
|
-
const canonicalModelKey = modelKey ? piModelRefToCanonical(modelKey) : null;
|
|
16758
|
-
const slash = canonicalModelKey?.indexOf("/") ?? -1;
|
|
16759
|
-
return {
|
|
16760
|
-
modelKey: canonicalModelKey,
|
|
16761
|
-
providerKey: slash > 0 && canonicalModelKey ? canonicalModelKey.slice(0, slash) : providerKey
|
|
16762
|
-
};
|
|
16763
|
-
}
|
|
16764
|
-
function resolveLkgModelKeys(messages) {
|
|
16765
|
-
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
16766
|
-
const info = messages[index]?.info;
|
|
16767
|
-
const nested = info?.model;
|
|
16768
|
-
if (nested && typeof nested === "object") {
|
|
16769
|
-
const provider = nested.providerID;
|
|
16770
|
-
const model = nested.modelID;
|
|
16771
|
-
if (typeof provider === "string" && typeof model === "string") {
|
|
16772
|
-
return canonicalLkgModelKeys(`${provider}/${model}`, provider);
|
|
16773
|
-
}
|
|
16774
|
-
}
|
|
16775
|
-
const provider = info?.providerID;
|
|
16776
|
-
const model = info?.modelID;
|
|
16777
|
-
if (typeof provider === "string" && typeof model === "string") {
|
|
16778
|
-
return canonicalLkgModelKeys(`${provider}/${model}`, provider);
|
|
16779
|
-
}
|
|
16780
|
-
}
|
|
16781
|
-
return { modelKey: null, providerKey: null };
|
|
16782
|
-
}
|
|
16783
|
-
function projectLkgEntry(messages) {
|
|
16784
|
-
return projectEntryWithDigests(messages, messages.map(lkgContentDigest));
|
|
16785
|
-
}
|
|
16786
|
-
function createLkgEntryProjector(options = {}) {
|
|
16787
|
-
const cache = options.maxBytes === undefined ? sharedLkgEntryDigests : new LkgEntryDigestCache({
|
|
16788
|
-
sessionMaxBytes: options.maxBytes,
|
|
16789
|
-
totalMaxBytes: options.maxBytes,
|
|
16790
|
-
maxSessions: 16
|
|
16791
|
-
});
|
|
16792
|
-
return (sessionId, messages) => {
|
|
16793
|
-
const { digests, stats } = cache.digests(sessionId, messages);
|
|
16794
|
-
options.onReuse?.(stats);
|
|
16795
|
-
return projectEntryWithDigests(messages, digests);
|
|
16796
|
-
};
|
|
16797
|
-
}
|
|
16798
|
-
function projectEntryWithDigests(messages, digests) {
|
|
16799
|
-
return messages.map((message, index) => {
|
|
16800
|
-
const info = messageInfo(message);
|
|
16801
|
-
const time = info.time;
|
|
16802
|
-
const timeRecord = time && typeof time === "object" ? time : null;
|
|
16803
|
-
const timeCandidates = [
|
|
16804
|
-
timeRecord?.created,
|
|
16805
|
-
info.timeCreated,
|
|
16806
|
-
info.time_created,
|
|
16807
|
-
info.createdAt,
|
|
16808
|
-
info.created_at
|
|
16809
|
-
];
|
|
16810
|
-
let timeCreated = null;
|
|
16811
|
-
for (const value of timeCandidates) {
|
|
16812
|
-
if (typeof value === "number" && Number.isFinite(value)) {
|
|
16813
|
-
timeCreated = value;
|
|
16814
|
-
break;
|
|
16815
|
-
}
|
|
16816
|
-
}
|
|
16817
|
-
let hasIncompleteTool = false;
|
|
16818
|
-
for (const rawPart of messageParts(message)) {
|
|
16819
|
-
if (!rawPart || typeof rawPart !== "object")
|
|
16820
|
-
continue;
|
|
16821
|
-
const part = rawPart;
|
|
16822
|
-
if (part.type !== "tool" || part.providerExecuted === true)
|
|
16823
|
-
continue;
|
|
16824
|
-
const state = part.state;
|
|
16825
|
-
const status = state && typeof state === "object" ? state.status : undefined;
|
|
16826
|
-
if (status !== "completed") {
|
|
16827
|
-
hasIncompleteTool = true;
|
|
16828
|
-
break;
|
|
16829
|
-
}
|
|
16830
|
-
}
|
|
16831
|
-
const id = info.id;
|
|
16832
|
-
const projection = {
|
|
16833
|
-
id: typeof id === "string" && id.length > 0 ? id : null,
|
|
16834
|
-
role: typeof info.role === "string" ? info.role : undefined,
|
|
16835
|
-
synthetic: info.synthetic === true,
|
|
16836
|
-
timeCreated,
|
|
16837
|
-
finish: info.finish,
|
|
16838
|
-
hasIncompleteTool
|
|
16839
|
-
};
|
|
16840
|
-
const contentDigest = digests[index] ?? null;
|
|
16841
|
-
Object.defineProperty(projection, "contentDigest", {
|
|
16842
|
-
value: () => contentDigest,
|
|
16843
|
-
enumerable: false
|
|
16844
|
-
});
|
|
16845
|
-
return projection;
|
|
16846
|
-
});
|
|
16847
|
-
}
|
|
16848
|
-
function recordValue(info, key) {
|
|
16849
|
-
return info && typeof info === "object" ? info[key] : undefined;
|
|
16850
|
-
}
|
|
16851
|
-
function messageInfo(message) {
|
|
16852
|
-
if (message.info && typeof message.info === "object")
|
|
16853
|
-
return message.info;
|
|
16854
|
-
return message;
|
|
16855
|
-
}
|
|
16856
|
-
function messageParts(message) {
|
|
16857
|
-
return Array.isArray(message.parts) ? message.parts : [];
|
|
16858
|
-
}
|
|
16859
|
-
function isSynthetic(message) {
|
|
16860
|
-
return recordValue(messageInfo(message), "synthetic") === true;
|
|
16861
|
-
}
|
|
16862
|
-
function hasSyntheticParts(message) {
|
|
16863
|
-
const parts = messageParts(message);
|
|
16864
|
-
return parts.length > 0 && parts.every((part) => {
|
|
16865
|
-
return Boolean(part && typeof part === "object" && part.synthetic === true);
|
|
16866
|
-
});
|
|
16867
|
-
}
|
|
16868
|
-
function isSyntheticOutput(message) {
|
|
16869
|
-
return isSynthetic(message) || hasSyntheticParts(message);
|
|
16870
|
-
}
|
|
16871
|
-
function messageRole(message) {
|
|
16872
|
-
const infoRole = recordValue(messageInfo(message), "role");
|
|
16873
|
-
if (typeof infoRole === "string")
|
|
16874
|
-
return infoRole;
|
|
16875
|
-
const role = recordValue(message, "role");
|
|
16876
|
-
return typeof role === "string" ? role : undefined;
|
|
16877
|
-
}
|
|
16878
|
-
function messageId(message) {
|
|
16879
|
-
const id = recordValue(messageInfo(message), "id") ?? recordValue(message, "id");
|
|
16880
|
-
return typeof id === "string" && id.length > 0 ? id : null;
|
|
16881
|
-
}
|
|
16882
|
-
function latestAssistant(messages) {
|
|
16883
|
-
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
16884
|
-
if (messages[index].role === "assistant")
|
|
16885
|
-
return messages[index];
|
|
16886
|
-
}
|
|
16887
|
-
return null;
|
|
16888
|
-
}
|
|
16889
|
-
function isRealUser(message) {
|
|
16890
|
-
return message.role === "user" && !message.synthetic && message.id !== null;
|
|
16891
|
-
}
|
|
16892
|
-
function assistantIsActive(message) {
|
|
16893
|
-
return message.finish === "tool-calls" || message.hasIncompleteTool;
|
|
16894
|
-
}
|
|
16895
|
-
function findLkgAnchor(messages) {
|
|
16896
|
-
const assistant = latestAssistant(messages);
|
|
16897
|
-
const assistantTime = assistant?.timeCreated ?? null;
|
|
16898
|
-
if (assistant && assistantTime === null)
|
|
16899
|
-
return null;
|
|
16900
|
-
let anchor = -1;
|
|
16901
|
-
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
16902
|
-
const message = messages[index];
|
|
16903
|
-
if (!isRealUser(message))
|
|
16904
|
-
continue;
|
|
16905
|
-
if (assistant && assistantIsActive(assistant)) {
|
|
16906
|
-
if (assistantTime === null || message.timeCreated === null || message.timeCreated <= assistantTime) {
|
|
16907
|
-
continue;
|
|
16908
|
-
}
|
|
16909
|
-
}
|
|
16910
|
-
anchor = index;
|
|
16911
|
-
break;
|
|
16912
|
-
}
|
|
16913
|
-
return anchor >= 0 ? anchor : null;
|
|
16914
|
-
}
|
|
16915
|
-
function asEntryProjection(input) {
|
|
16916
|
-
if (input.length === 0 || "hasIncompleteTool" in input[0]) {
|
|
16917
|
-
return input;
|
|
16918
|
-
}
|
|
16919
|
-
return projectLkgEntry(input);
|
|
16920
|
-
}
|
|
16921
|
-
function outputMessageIsPostAnchor(message, inputIndexById, anchorIndex) {
|
|
16922
|
-
const id = messageId(message);
|
|
16923
|
-
if (id !== null) {
|
|
16924
|
-
const inputIndex = inputIndexById.get(id);
|
|
16925
|
-
if (inputIndex !== undefined)
|
|
16926
|
-
return inputIndex > anchorIndex;
|
|
16927
|
-
if (!isSyntheticOutput(message))
|
|
16928
|
-
return null;
|
|
16929
|
-
const linked = ["sourceMessageId", "ownerMessageId", "anchorMessageId", "messageId"].map((key) => recordValue(messageInfo(message), key)).find((value) => typeof value === "string");
|
|
16930
|
-
if (typeof linked === "string") {
|
|
16931
|
-
const linkedIndex = inputIndexById.get(linked);
|
|
16932
|
-
if (linkedIndex === undefined)
|
|
16933
|
-
return null;
|
|
16934
|
-
return linkedIndex > anchorIndex;
|
|
16935
|
-
}
|
|
16936
|
-
return false;
|
|
16937
|
-
}
|
|
16938
|
-
if (!isSyntheticOutput(message))
|
|
16939
|
-
return null;
|
|
16940
|
-
const linked = ["sourceMessageId", "ownerMessageId", "anchorMessageId"].map((key) => recordValue(message.info, key)).find((value) => typeof value === "string");
|
|
16941
|
-
if (typeof linked !== "string")
|
|
16942
|
-
return false;
|
|
16943
|
-
const linkedIndex = inputIndexById.get(linked);
|
|
16944
|
-
return linkedIndex === undefined ? null : linkedIndex > anchorIndex;
|
|
16945
|
-
}
|
|
16946
|
-
function buildLkgPrefix(input, output) {
|
|
16947
|
-
const projected = asEntryProjection(input);
|
|
16948
|
-
const anchorIndex = findLkgAnchor(projected);
|
|
16949
|
-
if (anchorIndex === null)
|
|
16950
|
-
return null;
|
|
16951
|
-
const ids = projected.map((message) => message.id);
|
|
16952
|
-
if (ids.some((id) => id === null))
|
|
16953
|
-
return null;
|
|
16954
|
-
const validIds = ids;
|
|
16955
|
-
if (new Set(validIds).size !== validIds.length)
|
|
16956
|
-
return null;
|
|
16957
|
-
const anchorMessageId = validIds[anchorIndex];
|
|
16958
|
-
const inputContentDigests = projected.slice(0, anchorIndex + 1).map((message) => message.contentDigest?.() ?? null);
|
|
16959
|
-
if (inputContentDigests.some((digest) => digest === null))
|
|
16960
|
-
return null;
|
|
16961
|
-
const inputIndexById = new Map(validIds.map((id, index) => [id, index]));
|
|
16962
|
-
const prefix = [];
|
|
16963
|
-
for (const message of output) {
|
|
16964
|
-
const postAnchor = outputMessageIsPostAnchor(message, inputIndexById, anchorIndex);
|
|
16965
|
-
if (postAnchor === null)
|
|
16966
|
-
return null;
|
|
16967
|
-
if (!postAnchor)
|
|
16968
|
-
prefix.push(providerVisibleMessage(message));
|
|
16969
|
-
}
|
|
16970
|
-
let jsonPrefix;
|
|
16971
|
-
try {
|
|
16972
|
-
jsonPrefix = JSON.stringify(prefix);
|
|
16973
|
-
if (typeof jsonPrefix !== "string")
|
|
16974
|
-
return null;
|
|
16975
|
-
} catch {
|
|
16976
|
-
return null;
|
|
16977
|
-
}
|
|
16978
|
-
return {
|
|
16979
|
-
anchorIndex,
|
|
16980
|
-
anchorMessageId,
|
|
16981
|
-
inputIdSeq: validIds.slice(0, anchorIndex + 1),
|
|
16982
|
-
inputContentDigests,
|
|
16983
|
-
jsonPrefix
|
|
16984
|
-
};
|
|
16985
|
-
}
|
|
16986
|
-
function captureLkgSlot(args) {
|
|
16987
|
-
const built = buildLkgPrefix(args.input, args.output);
|
|
16988
|
-
if (!built)
|
|
16989
|
-
return false;
|
|
16990
|
-
const modelKeys = canonicalLkgModelKeys(args.modelKey, args.providerKey);
|
|
16991
|
-
const slot = {
|
|
16992
|
-
jsonPrefix: built.jsonPrefix,
|
|
16993
|
-
inputIdSeq: built.inputIdSeq,
|
|
16994
|
-
inputContentDigests: built.inputContentDigests,
|
|
16995
|
-
lastInputMessageId: built.anchorMessageId,
|
|
16996
|
-
modelKey: modelKeys.modelKey,
|
|
16997
|
-
providerKey: modelKeys.providerKey,
|
|
16998
|
-
capturedAt: args.capturedAt ?? Date.now()
|
|
16999
|
-
};
|
|
17000
|
-
const captured = captureSlot(args.sessionId, slot);
|
|
17001
|
-
if (captured)
|
|
17002
|
-
noteCapturedLkgRequest({
|
|
17003
|
-
sessionId: args.sessionId,
|
|
17004
|
-
slot,
|
|
17005
|
-
request: built.anchorIndex === args.input.length - 1 ? claimLkgRequestIdentity(args.sessionId) : undefined,
|
|
17006
|
-
systemPromptTokens: args.systemPromptTokens ?? 0,
|
|
17007
|
-
agentName: args.agentName
|
|
17008
|
-
});
|
|
17009
|
-
return captured;
|
|
17010
|
-
}
|
|
17011
|
-
function entryIdsAreValid(slot, entryIds) {
|
|
17012
|
-
if (slot.inputIdSeq.length === 0 || entryIds.length < slot.inputIdSeq.length)
|
|
17013
|
-
return false;
|
|
17014
|
-
if (slot.inputIdSeq[slot.inputIdSeq.length - 1] !== slot.lastInputMessageId)
|
|
17015
|
-
return false;
|
|
17016
|
-
const seen = new Set;
|
|
17017
|
-
for (const id of entryIds) {
|
|
17018
|
-
if (!id || seen.has(id))
|
|
17019
|
-
return false;
|
|
17020
|
-
seen.add(id);
|
|
17021
|
-
}
|
|
17022
|
-
if (entryIds.indexOf(slot.lastInputMessageId) !== slot.inputIdSeq.length - 1)
|
|
17023
|
-
return false;
|
|
17024
|
-
for (let index = 0;index < slot.inputIdSeq.length; index += 1) {
|
|
17025
|
-
if (entryIds[index] !== slot.inputIdSeq[index])
|
|
17026
|
-
return false;
|
|
17027
|
-
}
|
|
17028
|
-
return true;
|
|
17029
|
-
}
|
|
17030
|
-
function entryContentIsValid(slot, entry) {
|
|
17031
|
-
return entry.entryContentDigests.length >= slot.inputContentDigests.length && slot.inputContentDigests.every((digest, index) => isLegacyLkgDigest(digest) ? entry.entryLegacyContentDigests?.[index] === digest : entry.entryContentDigests[index] === digest);
|
|
17032
|
-
}
|
|
17033
|
-
function partCallIds(message) {
|
|
17034
|
-
const ids = [];
|
|
17035
|
-
for (const rawPart of messageParts(message)) {
|
|
17036
|
-
if (!rawPart || typeof rawPart !== "object")
|
|
17037
|
-
continue;
|
|
17038
|
-
const part = rawPart;
|
|
17039
|
-
if (part.type !== "tool" && part.type !== "tool_use")
|
|
17040
|
-
continue;
|
|
17041
|
-
const callId = part.callID ?? part.callId ?? part.id;
|
|
17042
|
-
if (typeof callId === "string" && callId.length > 0)
|
|
17043
|
-
ids.push(callId);
|
|
17044
|
-
}
|
|
17045
|
-
return ids;
|
|
17046
|
-
}
|
|
17047
|
-
function partResultIds(message) {
|
|
17048
|
-
const ids = [];
|
|
17049
|
-
for (const rawPart of messageParts(message)) {
|
|
17050
|
-
if (!rawPart || typeof rawPart !== "object")
|
|
17051
|
-
continue;
|
|
17052
|
-
const part = rawPart;
|
|
17053
|
-
if (part.type !== "tool_result" && part.type !== "tool-result")
|
|
17054
|
-
continue;
|
|
17055
|
-
const callId = part.tool_call_id ?? part.tool_use_id ?? part.callID ?? part.callId;
|
|
17056
|
-
if (typeof callId === "string" && callId.length > 0)
|
|
17057
|
-
ids.push(callId);
|
|
17058
|
-
}
|
|
17059
|
-
return ids;
|
|
17060
|
-
}
|
|
17061
|
-
function partIsReasoning(part) {
|
|
17062
|
-
return Boolean(part && typeof part === "object" && part.type === "reasoning");
|
|
17063
|
-
}
|
|
17064
|
-
function partIsAnthropicThinking(part) {
|
|
17065
|
-
if (!part || typeof part !== "object")
|
|
17066
|
-
return false;
|
|
17067
|
-
const type = part.type;
|
|
17068
|
-
return type === "thinking" || type === "reasoning" || type === "redacted_thinking";
|
|
17069
|
-
}
|
|
17070
|
-
function partEndsAnthropicAssistantRun(part) {
|
|
17071
|
-
if (!part || typeof part !== "object")
|
|
17072
|
-
return false;
|
|
17073
|
-
const value = part;
|
|
17074
|
-
if (value.type !== "tool" || value.providerExecuted === true || !value.state || typeof value.state !== "object") {
|
|
17075
|
-
return false;
|
|
17076
|
-
}
|
|
17077
|
-
const status = value.state.status;
|
|
17078
|
-
return status === "completed" || status === "error";
|
|
17079
|
-
}
|
|
17080
|
-
function partIsOpenCodeStepMetadata(part) {
|
|
17081
|
-
if (!part || typeof part !== "object")
|
|
17082
|
-
return false;
|
|
17083
|
-
const type = part.type;
|
|
17084
|
-
return type === "step-start" || type === "step-finish";
|
|
17085
|
-
}
|
|
17086
|
-
function validateAnthropicReasoningRuns(messages) {
|
|
17087
|
-
let index = 0;
|
|
17088
|
-
while (index < messages.length) {
|
|
17089
|
-
if (messageRole(messages[index]) !== "assistant") {
|
|
17090
|
-
index += 1;
|
|
17091
|
-
continue;
|
|
17092
|
-
}
|
|
17093
|
-
let firstMessageInRun = null;
|
|
17094
|
-
let sawOtherContent = false;
|
|
17095
|
-
while (index < messages.length && messageRole(messages[index]) === "assistant") {
|
|
17096
|
-
for (const part of messageParts(messages[index])) {
|
|
17097
|
-
if (partEndsAnthropicAssistantRun(part)) {
|
|
17098
|
-
firstMessageInRun = null;
|
|
17099
|
-
sawOtherContent = false;
|
|
17100
|
-
} else if (!partIsOpenCodeStepMetadata(part)) {
|
|
17101
|
-
if (firstMessageInRun === null)
|
|
17102
|
-
firstMessageInRun = index;
|
|
17103
|
-
if (partIsAnthropicThinking(part)) {
|
|
17104
|
-
if (sawOtherContent || index !== firstMessageInRun)
|
|
17105
|
-
return false;
|
|
17106
|
-
} else {
|
|
17107
|
-
sawOtherContent = true;
|
|
17108
|
-
}
|
|
17109
|
-
}
|
|
17110
|
-
}
|
|
17111
|
-
index += 1;
|
|
17112
|
-
}
|
|
17113
|
-
}
|
|
17114
|
-
return true;
|
|
17115
|
-
}
|
|
17116
|
-
function validateLkgSeamBoundary(prefix, tail) {
|
|
17117
|
-
const last = prefix[prefix.length - 1];
|
|
17118
|
-
const first = tail[0];
|
|
17119
|
-
if (!last || !first)
|
|
17120
|
-
return true;
|
|
17121
|
-
const lastCalls = partCallIds(last);
|
|
17122
|
-
if (lastCalls.length === 0)
|
|
17123
|
-
return true;
|
|
17124
|
-
const firstCalls = new Set([...partCallIds(first), ...partResultIds(first)]);
|
|
17125
|
-
if (messageRole(first) === "tool" || lastCalls.some((callId) => firstCalls.has(callId)))
|
|
17126
|
-
return false;
|
|
17127
|
-
return !messageParts(last).some((part) => {
|
|
17128
|
-
if (!part || typeof part !== "object")
|
|
17129
|
-
return false;
|
|
17130
|
-
const value = part;
|
|
17131
|
-
if (value.type !== "tool")
|
|
17132
|
-
return false;
|
|
17133
|
-
const state = value.state;
|
|
17134
|
-
return !state || typeof state !== "object" || state.status !== "completed";
|
|
17135
|
-
});
|
|
17136
|
-
}
|
|
17137
|
-
function validateLkgSeam(prefix, tail, providerKey) {
|
|
17138
|
-
const all = [...prefix, ...tail];
|
|
17139
|
-
const ids = new Set;
|
|
17140
|
-
const calls = new Set;
|
|
17141
|
-
const results = new Set;
|
|
17142
|
-
for (const message of all) {
|
|
17143
|
-
const id = messageId(message);
|
|
17144
|
-
if (id !== null) {
|
|
17145
|
-
if (ids.has(id))
|
|
17146
|
-
return false;
|
|
17147
|
-
ids.add(id);
|
|
17148
|
-
}
|
|
17149
|
-
for (const callId of partCallIds(message)) {
|
|
17150
|
-
if (calls.has(callId))
|
|
17151
|
-
return false;
|
|
17152
|
-
calls.add(callId);
|
|
17153
|
-
}
|
|
17154
|
-
for (const callId of partResultIds(message)) {
|
|
17155
|
-
if (results.has(callId))
|
|
17156
|
-
return false;
|
|
17157
|
-
results.add(callId);
|
|
17158
|
-
}
|
|
17159
|
-
if (messageRole(message) !== "assistant" && messageParts(message).some(partIsReasoning))
|
|
17160
|
-
return false;
|
|
17161
|
-
if (providerKey !== "anthropic" && messageParts(message).some((part) => {
|
|
17162
|
-
if (!part || typeof part !== "object")
|
|
17163
|
-
return false;
|
|
17164
|
-
const value = part;
|
|
17165
|
-
return (value.type === "text" || value.type === "reasoning") && value.text === "";
|
|
17166
|
-
}))
|
|
17167
|
-
return false;
|
|
17168
|
-
}
|
|
17169
|
-
if (!validateLkgSeamBoundary(prefix, tail))
|
|
17170
|
-
return false;
|
|
17171
|
-
const wireCandidates = all.map((message) => message);
|
|
17172
|
-
if (wireCandidates.every((message) => typeof message.role === "string")) {
|
|
17173
|
-
const adjacency = assertOpenAiCompatAdjacency(wireCandidates);
|
|
17174
|
-
if (!adjacency.ok)
|
|
17175
|
-
return false;
|
|
17176
|
-
const wireCallIds = new Set;
|
|
17177
|
-
for (const wireMessage of wireCandidates) {
|
|
17178
|
-
for (const call of wireMessage.tool_calls ?? []) {
|
|
17179
|
-
if (wireCallIds.has(call.id))
|
|
17180
|
-
return false;
|
|
17181
|
-
wireCallIds.add(call.id);
|
|
17182
|
-
}
|
|
17183
|
-
}
|
|
17184
|
-
}
|
|
17185
|
-
return true;
|
|
17186
|
-
}
|
|
17187
|
-
function replayLkg(args) {
|
|
17188
|
-
const slot = getSlot(args.sessionId);
|
|
17189
|
-
if (!slot)
|
|
17190
|
-
return { ok: false, reason: "lkg_invalidated_reshape" };
|
|
17191
|
-
const requestedModelKeys = canonicalLkgModelKeys(args.modelKey, args.providerKey);
|
|
17192
|
-
const capturedModelKeys = canonicalLkgModelKeys(slot.modelKey, slot.providerKey);
|
|
17193
|
-
if (capturedModelKeys.modelKey !== requestedModelKeys.modelKey || capturedModelKeys.providerKey !== requestedModelKeys.providerKey) {
|
|
17194
|
-
dropSlot(args.sessionId, "lkg_model_mismatch");
|
|
17195
|
-
return { ok: false, reason: "lkg_model_mismatch" };
|
|
17196
|
-
}
|
|
17197
|
-
const entry = args.entry ?? noteEntry(args.sessionId, args.messages);
|
|
17198
|
-
if (!entry || entry.anchorIndex !== slot.inputIdSeq.length - 1 || !entryIdsAreValid(slot, entry.entryInputIds)) {
|
|
17199
|
-
dropSlot(args.sessionId, "lkg_invalidated_reshape");
|
|
17200
|
-
return { ok: false, reason: "lkg_invalidated_reshape" };
|
|
17201
|
-
}
|
|
17202
|
-
if (!entryContentIsValid(slot, entry)) {
|
|
17203
|
-
dropSlot(args.sessionId, "lkg_content_mismatch");
|
|
17204
|
-
return { ok: false, reason: "lkg_content_mismatch" };
|
|
17205
|
-
}
|
|
17206
|
-
let prefix;
|
|
17207
|
-
try {
|
|
17208
|
-
const parsed = JSON.parse(slot.jsonPrefix);
|
|
17209
|
-
if (!Array.isArray(parsed))
|
|
17210
|
-
throw new Error("prefix is not an array");
|
|
17211
|
-
prefix = parsed;
|
|
17212
|
-
} catch {
|
|
17213
|
-
dropSlot(args.sessionId, "lkg_seam_invalid");
|
|
17214
|
-
return { ok: false, reason: "lkg_seam_invalid" };
|
|
17215
|
-
}
|
|
17216
|
-
const replayed = [...prefix, ...entry.pristineTail];
|
|
17217
|
-
args.prepareReplay?.(replayed);
|
|
17218
|
-
if (!args.skipSeamValidation) {
|
|
17219
|
-
if (!validateLkgSeamBoundary(prefix, entry.pristineTail)) {
|
|
17220
|
-
dropSlot(args.sessionId, "lkg_unsafe_seam");
|
|
17221
|
-
return { ok: false, reason: "lkg_unsafe_seam" };
|
|
17222
|
-
}
|
|
17223
|
-
if (!validateLkgSeam(prefix, entry.pristineTail, requestedModelKeys.providerKey)) {
|
|
17224
|
-
dropSlot(args.sessionId, "lkg_seam_invalid");
|
|
17225
|
-
return { ok: false, reason: "lkg_seam_invalid" };
|
|
17226
|
-
}
|
|
17227
|
-
}
|
|
17228
|
-
if (requestedModelKeys.providerKey === "anthropic" && !validateAnthropicReasoningRuns(replayed)) {
|
|
17229
|
-
dropSlot(args.sessionId, "lkg_anthropic_reasoning_run_invalid");
|
|
17230
|
-
return { ok: false, reason: "lkg_anthropic_reasoning_run_invalid" };
|
|
17231
|
-
}
|
|
17232
|
-
return { ok: true, messages: replayed };
|
|
17233
|
-
}
|
|
17234
|
-
function messageIdOf(message) {
|
|
17235
|
-
if (typeof message !== "object" || message === null)
|
|
17236
|
-
return;
|
|
17237
|
-
const info = message.info;
|
|
17238
|
-
if (typeof info !== "object" || info === null)
|
|
17239
|
-
return;
|
|
17240
|
-
const id = info.id;
|
|
17241
|
-
return typeof id === "string" ? id : undefined;
|
|
17242
|
-
}
|
|
17243
|
-
function coldStartRawServedIndex(args) {
|
|
17244
|
-
const raw = messagesById(args.rawInput);
|
|
17245
|
-
const rendered = messagesById(args.moduleOutput);
|
|
17246
|
-
const rawKeys = [];
|
|
17247
|
-
let runStart = args.slotMessages.length;
|
|
17248
|
-
while (runStart > 0) {
|
|
17249
|
-
const served = args.slotMessages[runStart - 1];
|
|
17250
|
-
const id = messageIdOf(served);
|
|
17251
|
-
const rawMessage = id === undefined ? undefined : raw.get(id);
|
|
17252
|
-
if (rawMessage === undefined)
|
|
17253
|
-
break;
|
|
17254
|
-
const rawKey = args.key(rawMessage);
|
|
17255
|
-
if (args.key(served) !== rawKey)
|
|
17256
|
-
break;
|
|
17257
|
-
runStart -= 1;
|
|
17258
|
-
rawKeys[runStart] = rawKey;
|
|
17259
|
-
}
|
|
17260
|
-
for (let index = runStart;index < args.slotMessages.length; index += 1) {
|
|
17261
|
-
const id = messageIdOf(args.slotMessages[index]);
|
|
17262
|
-
const moduleMessage = rendered.get(id);
|
|
17263
|
-
if (moduleMessage !== undefined && args.key(moduleMessage) !== rawKeys[index]) {
|
|
17264
|
-
const runStartId = messageIdOf(args.slotMessages[runStart]);
|
|
17265
|
-
const rawRunStart = args.rawInput.findIndex((message) => messageIdOf(message) === runStartId);
|
|
17266
|
-
return { index, rawRunStart };
|
|
17267
|
-
}
|
|
17268
|
-
}
|
|
17269
|
-
return null;
|
|
17270
|
-
}
|
|
17271
|
-
function messagesById(messages) {
|
|
17272
|
-
const map = new Map;
|
|
17273
|
-
for (const message of messages) {
|
|
17274
|
-
const id = messageIdOf(message);
|
|
17275
|
-
if (id !== undefined)
|
|
17276
|
-
map.set(id, message);
|
|
17277
|
-
}
|
|
17278
|
-
return map;
|
|
17279
|
-
}
|
|
17280
|
-
function coldStartUncapturedReplay(args) {
|
|
17281
|
-
const lastSlotId = messageIdOf(args.slotMessages.at(-1));
|
|
17282
|
-
if (lastSlotId === undefined)
|
|
17283
|
-
return null;
|
|
17284
|
-
const slotEnd = args.rawInput.findIndex((message) => messageIdOf(message) === lastSlotId);
|
|
17285
|
-
if (slotEnd < 0)
|
|
17286
|
-
return null;
|
|
17287
|
-
const rendered = messagesById(args.moduleOutput);
|
|
17288
|
-
for (let index = slotEnd + 1;index < args.rawInput.length - 1; index += 1) {
|
|
17289
|
-
const rawMessage = args.rawInput[index];
|
|
17290
|
-
const info = rawMessage?.info;
|
|
17291
|
-
if (info?.role !== "user" || info.synthetic === true)
|
|
17292
|
-
continue;
|
|
17293
|
-
const id = messageIdOf(rawMessage);
|
|
17294
|
-
const moduleMessage = id === undefined ? undefined : rendered.get(id);
|
|
17295
|
-
if (moduleMessage === undefined)
|
|
17296
|
-
continue;
|
|
17297
|
-
if (args.key(moduleMessage) === args.key(rawMessage))
|
|
17298
|
-
continue;
|
|
17299
|
-
return {
|
|
17300
|
-
lastServed: [...args.slotMessages, ...args.rawInput.slice(slotEnd + 1)],
|
|
17301
|
-
rawUserIndex: index
|
|
17302
|
-
};
|
|
17303
|
-
}
|
|
17304
|
-
return null;
|
|
17305
|
-
}
|
|
17306
|
-
|
|
17307
16440
|
// src/hooks/magic-context/pass-outcome.ts
|
|
17308
16441
|
var PASS_DEGRADATION_EFFECTS = {
|
|
17309
16442
|
"store-generation-rebase-failure": "changes-request",
|
|
@@ -17367,7 +16500,7 @@ function createPassOutcome() {
|
|
|
17367
16500
|
}
|
|
17368
16501
|
|
|
17369
16502
|
// src/hooks/magic-context/rust-mode-transform.ts
|
|
17370
|
-
import { createHash as
|
|
16503
|
+
import { createHash as createHash11, randomUUID as randomUUID6 } from "node:crypto";
|
|
17371
16504
|
|
|
17372
16505
|
// src/features/magic-context/memory/single-store-embedding-drain.ts
|
|
17373
16506
|
function isWatermarkRow(row) {
|
|
@@ -17431,7 +16564,7 @@ function advanceEmbeddedWatermark(db, projectPath, upTo) {
|
|
|
17431
16564
|
}
|
|
17432
16565
|
|
|
17433
16566
|
// src/features/magic-context/mural/source-revision.ts
|
|
17434
|
-
import { createHash as
|
|
16567
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
17435
16568
|
var statements = new WeakMap;
|
|
17436
16569
|
function muralSourceRevision(db, projectPath) {
|
|
17437
16570
|
let statement = statements.get(db);
|
|
@@ -17448,7 +16581,7 @@ function muralSourceRevision(db, projectPath) {
|
|
|
17448
16581
|
statements.set(db, statement);
|
|
17449
16582
|
}
|
|
17450
16583
|
const row = statement.get(projectPath, Date.now());
|
|
17451
|
-
return
|
|
16584
|
+
return createHash9("sha256").update(row.revision).digest("hex");
|
|
17452
16585
|
}
|
|
17453
16586
|
|
|
17454
16587
|
// src/features/magic-context/install-instance-id.ts
|
|
@@ -20013,6 +19146,141 @@ function resolveSchedulerDecision(scheduler, sessionMeta, contextUsage, sessionI
|
|
|
20013
19146
|
}
|
|
20014
19147
|
}
|
|
20015
19148
|
|
|
19149
|
+
// src/hooks/magic-context/system-date-refresh.ts
|
|
19150
|
+
var channels = new WeakMap;
|
|
19151
|
+
var outputUpdates = new WeakMap;
|
|
19152
|
+
var outputIdentities = new WeakMap;
|
|
19153
|
+
var outputRequests = new WeakMap;
|
|
19154
|
+
function systemDateTurnId(messages) {
|
|
19155
|
+
const start = activeAnthropicTurnStart(messages, true);
|
|
19156
|
+
if (start === undefined)
|
|
19157
|
+
return;
|
|
19158
|
+
const message = messages[start - 1];
|
|
19159
|
+
const id = message.info?.id ?? message.id;
|
|
19160
|
+
return typeof id === "string" && id.length > 0 ? id : undefined;
|
|
19161
|
+
}
|
|
19162
|
+
function bindSystemDateRequestIdentity(output, identity) {
|
|
19163
|
+
outputIdentities.set(output, identity);
|
|
19164
|
+
}
|
|
19165
|
+
function systemDateRequestIdentity(output) {
|
|
19166
|
+
return outputIdentities.get(output);
|
|
19167
|
+
}
|
|
19168
|
+
function bindSystemDateRequest(output, request) {
|
|
19169
|
+
if (request)
|
|
19170
|
+
outputRequests.set(output, request);
|
|
19171
|
+
}
|
|
19172
|
+
function systemDateRequestForOutput(history, output) {
|
|
19173
|
+
const request = outputRequests.get(output);
|
|
19174
|
+
return state(history, request);
|
|
19175
|
+
}
|
|
19176
|
+
function bindSystemDateOutput(system, update) {
|
|
19177
|
+
outputUpdates.set(system, update);
|
|
19178
|
+
}
|
|
19179
|
+
function publishSystemDateOutput(system) {
|
|
19180
|
+
outputUpdates.get(system)?.();
|
|
19181
|
+
outputUpdates.delete(system);
|
|
19182
|
+
}
|
|
19183
|
+
function registerSystemDateRefresh(history) {
|
|
19184
|
+
if (!channels.has(history))
|
|
19185
|
+
channels.set(history, new Map);
|
|
19186
|
+
}
|
|
19187
|
+
function hasSystemDateRefresh(history) {
|
|
19188
|
+
return channels.has(history);
|
|
19189
|
+
}
|
|
19190
|
+
function beginSystemDateRequest(history, sessionId, stage, turnId, identity) {
|
|
19191
|
+
const channel = channels.get(history);
|
|
19192
|
+
if (!channel)
|
|
19193
|
+
return;
|
|
19194
|
+
let requests = channel.get(sessionId);
|
|
19195
|
+
if (!requests)
|
|
19196
|
+
channel.set(sessionId, requests = new Map);
|
|
19197
|
+
let request = identity === undefined ? undefined : requests.get(identity);
|
|
19198
|
+
if (identity === undefined) {
|
|
19199
|
+
const candidates = [...requests.values()].filter((candidate) => !candidate.explicit && !(candidate.systemSeen && candidate.messagesSeen) && (stage === "system-after-messages" || candidate.turnId === turnId));
|
|
19200
|
+
const matching = candidates.filter((candidate) => !candidate.ambiguous && (stage === "messages" ? candidate.systemSeen && !candidate.messagesSeen : candidate.messagesSeen && !candidate.systemSeen));
|
|
19201
|
+
if (turnId !== undefined && candidates.length === 1 && matching.length === 1) {
|
|
19202
|
+
request = matching[0];
|
|
19203
|
+
} else if (candidates.length > 0) {
|
|
19204
|
+
for (const candidate of candidates)
|
|
19205
|
+
candidate.ambiguous = true;
|
|
19206
|
+
}
|
|
19207
|
+
}
|
|
19208
|
+
if (!request) {
|
|
19209
|
+
const sameTurn = [...requests.values()].some((candidate) => !candidate.explicit && !(candidate.systemSeen && candidate.messagesSeen) && (stage === "system-after-messages" || candidate.turnId === turnId));
|
|
19210
|
+
request = {
|
|
19211
|
+
sessionId,
|
|
19212
|
+
identity: identity ?? {},
|
|
19213
|
+
turnId,
|
|
19214
|
+
explicit: identity !== undefined,
|
|
19215
|
+
systemSeen: false,
|
|
19216
|
+
systemDone: false,
|
|
19217
|
+
messagesSeen: false,
|
|
19218
|
+
permitted: undefined,
|
|
19219
|
+
ambiguous: identity === undefined && (turnId === undefined || sameTurn)
|
|
19220
|
+
};
|
|
19221
|
+
const blocked = [...requests.values()].filter((candidate) => !candidate.explicit && candidate.ambiguous && !(candidate.systemSeen && candidate.messagesSeen) && candidate.turnId === turnId).length;
|
|
19222
|
+
if (request.explicit || !request.ambiguous || blocked < 2)
|
|
19223
|
+
requests.set(request.identity, request);
|
|
19224
|
+
}
|
|
19225
|
+
if (stage === "messages")
|
|
19226
|
+
request.messagesSeen = true;
|
|
19227
|
+
else
|
|
19228
|
+
request.systemSeen = true;
|
|
19229
|
+
return request;
|
|
19230
|
+
}
|
|
19231
|
+
function state(history, request) {
|
|
19232
|
+
if (!request)
|
|
19233
|
+
return;
|
|
19234
|
+
const current = channels.get(history)?.get(request.sessionId)?.get(request.identity);
|
|
19235
|
+
return current === request ? current : undefined;
|
|
19236
|
+
}
|
|
19237
|
+
function systemDateRefreshPermission(history, request) {
|
|
19238
|
+
const current = state(history, request);
|
|
19239
|
+
return current?.ambiguous ? undefined : current?.permitted;
|
|
19240
|
+
}
|
|
19241
|
+
function waitForSystemDateRefresh(history, request, apply) {
|
|
19242
|
+
const current = state(history, request);
|
|
19243
|
+
if (!current)
|
|
19244
|
+
return false;
|
|
19245
|
+
current.waiting = apply;
|
|
19246
|
+
return true;
|
|
19247
|
+
}
|
|
19248
|
+
function retire(history, current) {
|
|
19249
|
+
const unpairable = !current.explicit && current.turnId === undefined;
|
|
19250
|
+
if (!unpairable && (!current.systemDone || current.permitted === undefined))
|
|
19251
|
+
return;
|
|
19252
|
+
if (unpairable) {
|
|
19253
|
+
const apply = current.waiting;
|
|
19254
|
+
current.waiting = undefined;
|
|
19255
|
+
apply?.(false);
|
|
19256
|
+
}
|
|
19257
|
+
const channel = channels.get(history);
|
|
19258
|
+
const requests = channel?.get(current.sessionId);
|
|
19259
|
+
requests?.delete(current.identity);
|
|
19260
|
+
if (requests?.size === 0)
|
|
19261
|
+
channel?.delete(current.sessionId);
|
|
19262
|
+
}
|
|
19263
|
+
function finishSystemDateRefresh(history, request, permitted) {
|
|
19264
|
+
const current = state(history, request);
|
|
19265
|
+
if (!current)
|
|
19266
|
+
return;
|
|
19267
|
+
current.permitted = current.ambiguous ? false : permitted;
|
|
19268
|
+
const apply = current.waiting;
|
|
19269
|
+
current.waiting = undefined;
|
|
19270
|
+
apply?.(current.permitted);
|
|
19271
|
+
retire(history, current);
|
|
19272
|
+
}
|
|
19273
|
+
function finishSystemDateHook(history, request) {
|
|
19274
|
+
const current = state(history, request);
|
|
19275
|
+
if (!current)
|
|
19276
|
+
return;
|
|
19277
|
+
current.systemDone = true;
|
|
19278
|
+
retire(history, current);
|
|
19279
|
+
}
|
|
19280
|
+
function clearSystemDateRefresh(history, sessionId) {
|
|
19281
|
+
channels.get(history)?.delete(sessionId);
|
|
19282
|
+
}
|
|
19283
|
+
|
|
20016
19284
|
// src/hooks/magic-context/rust-mode-transform.ts
|
|
20017
19285
|
class RustTransformProtocolError extends Error {
|
|
20018
19286
|
code = "rust_transform_protocol_error";
|
|
@@ -20146,13 +19414,13 @@ function replaceMessagesInPlace(output, next) {
|
|
|
20146
19414
|
target.splice(0, target.length, ...next);
|
|
20147
19415
|
return target;
|
|
20148
19416
|
}
|
|
20149
|
-
function
|
|
19417
|
+
function messageInfo(value) {
|
|
20150
19418
|
if (!isRecord3(value))
|
|
20151
19419
|
return {};
|
|
20152
19420
|
return isRecord3(value.info) ? value.info : value;
|
|
20153
19421
|
}
|
|
20154
|
-
function
|
|
20155
|
-
const id =
|
|
19422
|
+
function messageIdOf(message) {
|
|
19423
|
+
const id = messageInfo(message).id;
|
|
20156
19424
|
return typeof id === "string" && id.length > 0 ? id : null;
|
|
20157
19425
|
}
|
|
20158
19426
|
function contentSnapshotsFor(messages) {
|
|
@@ -20210,10 +19478,10 @@ function messageCacheSignature(message) {
|
|
|
20210
19478
|
const parts = Array.isArray(message.parts) ? message.parts : [];
|
|
20211
19479
|
const serializedParts = JSON.stringify(parts) ?? "null";
|
|
20212
19480
|
const serializedMessage = JSON.stringify(message) ?? "null";
|
|
20213
|
-
return `${
|
|
19481
|
+
return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash11("sha256").update(serializedMessage).digest("hex")}`;
|
|
20214
19482
|
}
|
|
20215
19483
|
function advanceWireFingerprint(previous, encoded) {
|
|
20216
|
-
return
|
|
19484
|
+
return createHash11("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
|
|
20217
19485
|
}
|
|
20218
19486
|
function buildWireFingerprint(encoded) {
|
|
20219
19487
|
let fingerprint = "rust-wire-v1";
|
|
@@ -20227,7 +19495,7 @@ function buildWireFingerprint(encoded) {
|
|
|
20227
19495
|
}
|
|
20228
19496
|
function newestUserMessage(messages) {
|
|
20229
19497
|
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
20230
|
-
if (
|
|
19498
|
+
if (messageInfo(messages[index]).role === "user")
|
|
20231
19499
|
return messages[index];
|
|
20232
19500
|
}
|
|
20233
19501
|
return;
|
|
@@ -20316,14 +19584,14 @@ function formatRustPassLog(args) {
|
|
|
20316
19584
|
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)}`;
|
|
20317
19585
|
}
|
|
20318
19586
|
function isSyntheticUserMessage(message) {
|
|
20319
|
-
if (!message ||
|
|
19587
|
+
if (!message || messageInfo(message).role !== "user" || !Array.isArray(message.parts)) {
|
|
20320
19588
|
return false;
|
|
20321
19589
|
}
|
|
20322
19590
|
return message.parts.length > 0 && message.parts.every((part) => isRecord3(part) && (part.synthetic === true || part.ignored === true));
|
|
20323
19591
|
}
|
|
20324
19592
|
function observeSyntheticTurn(state, messages) {
|
|
20325
19593
|
const newest = newestUserMessage(messages);
|
|
20326
|
-
const info =
|
|
19594
|
+
const info = messageInfo(newest);
|
|
20327
19595
|
const messageId = typeof info.id === "string" ? info.id : null;
|
|
20328
19596
|
const synthetic = isSyntheticUserMessage(newest);
|
|
20329
19597
|
const isNewMessage = messageId === null || messageId !== state.lastObservedUserMessageId;
|
|
@@ -20337,14 +19605,14 @@ function observeSyntheticTurn(state, messages) {
|
|
|
20337
19605
|
return synthetic;
|
|
20338
19606
|
}
|
|
20339
19607
|
function assertNativeBoundary(output, sessionId, boundaryId) {
|
|
20340
|
-
const first = output.find((message) =>
|
|
20341
|
-
const info =
|
|
19608
|
+
const first = output.find((message) => messageInfo(message).role !== "system");
|
|
19609
|
+
const info = messageInfo(first);
|
|
20342
19610
|
const parts = isRecord3(first) && Array.isArray(first.parts) ? first.parts : [];
|
|
20343
19611
|
const synthetic = parts.length > 0 && parts.every((part) => isRecord3(part) && part.synthetic === true);
|
|
20344
19612
|
if (info.role === "user" && info.sessionID === sessionId && synthetic)
|
|
20345
19613
|
return;
|
|
20346
19614
|
const headSummary = output.slice(0, 3).map((message) => {
|
|
20347
|
-
const mi =
|
|
19615
|
+
const mi = messageInfo(message);
|
|
20348
19616
|
const mParts = isRecord3(message) && Array.isArray(message.parts) ? message.parts : [];
|
|
20349
19617
|
const partDesc = mParts.slice(0, 5).map((part) => isRecord3(part) ? `${String(part.type)}${part.synthetic === true ? "" : "!"}` : "?").join(",");
|
|
20350
19618
|
return `role=${String(mi.role)} sid=${mi.sessionID === sessionId ? "ok" : String(mi.sessionID ?? "absent")} id=${String(mi.id ?? "-").slice(0, 24)} parts=[${partDesc}]`;
|
|
@@ -21138,8 +20406,15 @@ function createRustModeTransform(deps, options) {
|
|
|
21138
20406
|
sessionLog2(sessionId, fit.detail);
|
|
21139
20407
|
return false;
|
|
21140
20408
|
}
|
|
20409
|
+
rememberLkgDirtyRevision(sessionId, markLkgRecoveryDirty({
|
|
20410
|
+
sessionId,
|
|
20411
|
+
slot,
|
|
20412
|
+
processLocalProof: hasProcessLocalLkgProof(sessionId),
|
|
20413
|
+
ownDirtyRevision: lkgDirtyRevision(sessionId)
|
|
20414
|
+
}));
|
|
21141
20415
|
const replayInputCount = currentMessages.length;
|
|
21142
20416
|
replaceMessagesInPlace(output, replay.messages);
|
|
20417
|
+
ensureState(states, sessionId).lkgLatestServedDigest = lkgServedArrayDigest(JSON.stringify(replay.messages));
|
|
21143
20418
|
enterLkgReplayFreeze(ensureState(states, sessionId), replayInputCount);
|
|
21144
20419
|
sessionLog2(sessionId, "lkg_replay_served");
|
|
21145
20420
|
return true;
|
|
@@ -21276,34 +20551,40 @@ function createRustModeTransform(deps, options) {
|
|
|
21276
20551
|
agentName: deps.getNotificationParams?.(sessionId)?.agent
|
|
21277
20552
|
};
|
|
21278
20553
|
};
|
|
21279
|
-
const commitRustCapture = (state, plan, requireDurable = false) => {
|
|
20554
|
+
const commitRustCapture = (state, plan, requireDurable = false, prepareOnly = false) => {
|
|
21280
20555
|
if (states.get(plan.sessionId) !== state || plan.captureSequence !== state.lkgCaptureSequence || plan.rowVersion < state.lkgLastCapturedRowVersion) {
|
|
21281
20556
|
return "superseded";
|
|
21282
20557
|
}
|
|
21283
|
-
|
|
21284
|
-
|
|
21285
|
-
id,
|
|
21286
|
-
|
|
21287
|
-
|
|
21288
|
-
|
|
21289
|
-
|
|
21290
|
-
|
|
21291
|
-
|
|
21292
|
-
|
|
21293
|
-
|
|
21294
|
-
|
|
21295
|
-
|
|
21296
|
-
|
|
21297
|
-
|
|
21298
|
-
|
|
21299
|
-
|
|
21300
|
-
|
|
21301
|
-
|
|
21302
|
-
|
|
21303
|
-
|
|
21304
|
-
|
|
21305
|
-
|
|
20558
|
+
if (!plan.prepared) {
|
|
20559
|
+
const prior = getSlot(plan.sessionId);
|
|
20560
|
+
const inputs = plan.inputIds.map((id, index) => ({
|
|
20561
|
+
id,
|
|
20562
|
+
fields: plan.inputSnapshots[index]?.fields ?? []
|
|
20563
|
+
}));
|
|
20564
|
+
const accepted = state.lkgAcceptedCapture;
|
|
20565
|
+
const {
|
|
20566
|
+
digests: inputContentDigests,
|
|
20567
|
+
inputContentSignatures,
|
|
20568
|
+
reusedPrefix
|
|
20569
|
+
} = rustCaptureDigests(inputs, prior?.modelKey === plan.modelKey && prior?.providerKey === plan.providerKey && prior?.captureSequence === accepted?.captureSequence && prior?.rowVersion === accepted?.rowVersion ? prior : undefined, accepted?.inputs ?? null);
|
|
20570
|
+
const slot = {
|
|
20571
|
+
jsonPrefix: plan.jsonPrefix,
|
|
20572
|
+
inputIdSeq: plan.inputIds,
|
|
20573
|
+
inputContentDigests,
|
|
20574
|
+
inputContentSignatures,
|
|
20575
|
+
lastInputMessageId: plan.inputIds[plan.inputIds.length - 1],
|
|
20576
|
+
modelKey: plan.modelKey,
|
|
20577
|
+
providerKey: plan.providerKey,
|
|
20578
|
+
capturedAt: plan.capturedAt,
|
|
20579
|
+
rowVersion: plan.rowVersion,
|
|
20580
|
+
captureSequence: plan.captureSequence
|
|
20581
|
+
};
|
|
20582
|
+
plan.prepared = { slot, inputs, reusedPrefix };
|
|
20583
|
+
}
|
|
20584
|
+
const { slot, inputs, reusedPrefix } = plan.prepared;
|
|
21306
20585
|
const rejection = lkgSlotRejection(plan.sessionId, slot);
|
|
20586
|
+
if (prepareOnly)
|
|
20587
|
+
return rejection === null ? "captured" : "superseded";
|
|
21307
20588
|
const captured = rejection === null && captureSlot(plan.sessionId, slot);
|
|
21308
20589
|
if (!captured)
|
|
21309
20590
|
throw new Error(`LKG slot rejected the prepared snapshot: ${rejection ?? "over the LKG heap budget"}`);
|
|
@@ -21320,7 +20601,14 @@ function createRustModeTransform(deps, options) {
|
|
|
21320
20601
|
agentName: plan.agentName
|
|
21321
20602
|
});
|
|
21322
20603
|
options.onLkgCaptureForTests?.(reusedPrefix);
|
|
21323
|
-
const persisted = saveLkgSlotToDb(deps.db, plan.sessionId, slot
|
|
20604
|
+
const persisted = saveLkgSlotToDb(deps.db, plan.sessionId, slot, undefined, {
|
|
20605
|
+
rebuild: requireDurable,
|
|
20606
|
+
ownDirtyRevision: plan.fenceRevision ?? lkgDirtyRevision(plan.sessionId),
|
|
20607
|
+
requiredRevision: plan.fenceRevision,
|
|
20608
|
+
cleanDigest: plan.fenceRevision ? state.lkgLatestServedDigest : lkgServedArrayDigest(plan.jsonPrefix),
|
|
20609
|
+
retainDirtyRevision: !plan.eligibleForClean || plan.returnedDigest !== state.lkgLatestServedDigest ? plan.fenceRevision : undefined
|
|
20610
|
+
});
|
|
20611
|
+
plan.committed = persisted;
|
|
21324
20612
|
if (requireDurable && !persisted) {
|
|
21325
20613
|
throw new Error("priced LKG snapshot did not reach durable storage");
|
|
21326
20614
|
}
|
|
@@ -21330,10 +20618,18 @@ function createRustModeTransform(deps, options) {
|
|
|
21330
20618
|
};
|
|
21331
20619
|
const run = async (sessionId, messages, output, sessionMeta) => {
|
|
21332
20620
|
const passStartedAt = performance.now();
|
|
20621
|
+
const dateRequest = systemDateRequestForOutput(deps.historyRefreshSessions, output) ?? beginSystemDateRequest(deps.historyRefreshSessions, sessionId, "messages", systemDateTurnId(messages), systemDateRequestIdentity(output));
|
|
20622
|
+
bindSystemDateRequest(output, dateRequest);
|
|
21333
20623
|
const passObservedAtMs = Date.now();
|
|
21334
20624
|
const state = ensureState(states, sessionId);
|
|
20625
|
+
let entrySlot = getSlot(sessionId);
|
|
20626
|
+
try {
|
|
20627
|
+
entrySlot = loadPersistedLkgSlot(deps.db, sessionId, true) ?? entrySlot;
|
|
20628
|
+
} catch {}
|
|
20629
|
+
const recoveryFenceRebuild = !!entrySlot && !hasProcessLocalLkgProof(sessionId) && !hasCleanLkgRecoveryFence(sessionId, entrySlot);
|
|
21335
20630
|
let markerApplyAttempted = false;
|
|
21336
20631
|
let markerDefinitelyNoCut = false;
|
|
20632
|
+
let captureForCertificate;
|
|
21337
20633
|
let markerSafeSnapshot;
|
|
21338
20634
|
let markerOriginalMessages;
|
|
21339
20635
|
state.lastPassMarkerApplyAttempted = false;
|
|
@@ -21844,7 +21140,7 @@ function createRustModeTransform(deps, options) {
|
|
|
21844
21140
|
logStage(sessionId, "clone", cloneStartedAt, timings, wireDelta ? "mode=projection-tail" : "mode=projection-full");
|
|
21845
21141
|
const provisionalBase = wireDelta ? (() => {
|
|
21846
21142
|
for (let index = wireDelta.rawStart - 1;index >= 0; index -= 1) {
|
|
21847
|
-
const priorId =
|
|
21143
|
+
const priorId = messageIdOf(messages[index]);
|
|
21848
21144
|
if (!priorId)
|
|
21849
21145
|
continue;
|
|
21850
21146
|
const prior = state.idOrdinalMemo.get(priorId);
|
|
@@ -21896,7 +21192,7 @@ function createRustModeTransform(deps, options) {
|
|
|
21896
21192
|
state.ordinalMemoStoredCount = resolved.memoStoredCount;
|
|
21897
21193
|
state.ordinalMemoCanonicalCount = resolved.memoCanonicalCount;
|
|
21898
21194
|
state.ordinalMemoVerifyPending = false;
|
|
21899
|
-
const firstInputId = messages[0] ?
|
|
21195
|
+
const firstInputId = messages[0] ? messageIdOf(messages[0]) : null;
|
|
21900
21196
|
inputFirstOrdinal = firstInputId ? state.idOrdinalMemo.get(firstInputId) ?? null : null;
|
|
21901
21197
|
const syncPass = {
|
|
21902
21198
|
db: deps.db,
|
|
@@ -21922,10 +21218,10 @@ function createRustModeTransform(deps, options) {
|
|
|
21922
21218
|
const todoCandidates = wireDelta ? messages.slice(todoStart) : messages;
|
|
21923
21219
|
const todoCalls = wireDelta ? new Map(state.todoCallSignatures) : new Map;
|
|
21924
21220
|
for (const [offset, message] of todoCandidates.entries()) {
|
|
21925
|
-
const id =
|
|
21221
|
+
const id = messageIdOf(message) ?? `index:${todoStart + offset}`;
|
|
21926
21222
|
const parts = message.parts?.filter((part) => isRecord3(part) && part.type === "tool" && part.tool === "todowrite");
|
|
21927
21223
|
if (parts?.length) {
|
|
21928
|
-
todoCalls.set(id,
|
|
21224
|
+
todoCalls.set(id, createHash11("sha256").update(JSON.stringify(parts)).digest("hex"));
|
|
21929
21225
|
} else {
|
|
21930
21226
|
todoCalls.delete(id);
|
|
21931
21227
|
}
|
|
@@ -22011,9 +21307,9 @@ function createRustModeTransform(deps, options) {
|
|
|
22011
21307
|
return {
|
|
22012
21308
|
rawCount: messages.length,
|
|
22013
21309
|
wireCount: encodedInput.length,
|
|
22014
|
-
rawLastId: rawLast ?
|
|
21310
|
+
rawLastId: rawLast ? messageIdOf(rawLast) : null,
|
|
22015
21311
|
rawLastSignature: rawLast ? messageCacheSignature(rawLast) : null,
|
|
22016
|
-
rawLastVisible: rawLast !== undefined && encodedInput.some((entry) => entry.mid ===
|
|
21312
|
+
rawLastVisible: rawLast !== undefined && encodedInput.some((entry) => entry.mid === messageIdOf(rawLast)),
|
|
22017
21313
|
ckFingerprint: ckFingerprint.fingerprint,
|
|
22018
21314
|
ckPrefixFingerprintBeforeLast: ckFingerprint.prefixFingerprintBeforeLast,
|
|
22019
21315
|
nativeFingerprint: nativeFingerprint.fingerprint,
|
|
@@ -22037,11 +21333,11 @@ function createRustModeTransform(deps, options) {
|
|
|
22037
21333
|
nativePrefixFingerprintBeforeLast = nativeFingerprint;
|
|
22038
21334
|
nativeFingerprint = advanceWireFingerprint(nativeFingerprint, nativeMessages[index]);
|
|
22039
21335
|
}
|
|
22040
|
-
const rawLastVisible = rawLast !== undefined && encodedInput.some((entry) => entry.mid ===
|
|
21336
|
+
const rawLastVisible = rawLast !== undefined && encodedInput.some((entry) => entry.mid === messageIdOf(rawLast));
|
|
22041
21337
|
return {
|
|
22042
21338
|
rawCount: messages.length,
|
|
22043
21339
|
wireCount: wireDelta.wireStart + encodedInput.length,
|
|
22044
|
-
rawLastId: rawLast ?
|
|
21340
|
+
rawLastId: rawLast ? messageIdOf(rawLast) : null,
|
|
22045
21341
|
rawLastSignature: rawLast ? messageCacheSignature(rawLast) : null,
|
|
22046
21342
|
rawLastVisible,
|
|
22047
21343
|
ckFingerprint,
|
|
@@ -22257,9 +21553,9 @@ function createRustModeTransform(deps, options) {
|
|
|
22257
21553
|
pendingWireCache = {
|
|
22258
21554
|
rawCount: messages.length,
|
|
22259
21555
|
wireCount: retryEncodedInput.length,
|
|
22260
|
-
rawLastId: retryRawLast ?
|
|
21556
|
+
rawLastId: retryRawLast ? messageIdOf(retryRawLast) : null,
|
|
22261
21557
|
rawLastSignature: retryRawLast ? messageCacheSignature(retryRawLast) : null,
|
|
22262
|
-
rawLastVisible: retryRawLast !== undefined && retryEncodedInput.some((entry) => entry.mid ===
|
|
21558
|
+
rawLastVisible: retryRawLast !== undefined && retryEncodedInput.some((entry) => entry.mid === messageIdOf(retryRawLast)),
|
|
22263
21559
|
ckFingerprint: retryCkFingerprint.fingerprint,
|
|
22264
21560
|
ckPrefixFingerprintBeforeLast: retryCkFingerprint.prefixFingerprintBeforeLast,
|
|
22265
21561
|
nativeFingerprint: retryNativeFingerprint.fingerprint,
|
|
@@ -22402,6 +21698,11 @@ function createRustModeTransform(deps, options) {
|
|
|
22402
21698
|
} else if (coldStartLastServed) {
|
|
22403
21699
|
frozenReleaseLastServed = coldStartLastServed;
|
|
22404
21700
|
}
|
|
21701
|
+
if (recoveryFenceRebuild) {
|
|
21702
|
+
frozenReplayReleased = true;
|
|
21703
|
+
frozenReleaseReason = "lkg_recovery_fence_unproven";
|
|
21704
|
+
frozenReleaseLastServed = { messages: null, proven: false };
|
|
21705
|
+
}
|
|
22405
21706
|
if (state.lkgRepresentationFrozen && !shouldAdoptModuleAfterFreeze(moduleDecisionBusts, frozenReplayReleased)) {
|
|
22406
21707
|
if (state.lkgFrozenAtInputCount === null) {
|
|
22407
21708
|
state.lkgFrozenAtInputCount = inputCount;
|
|
@@ -22432,11 +21733,32 @@ function createRustModeTransform(deps, options) {
|
|
|
22432
21733
|
frozenReleaseReason = releaseReason;
|
|
22433
21734
|
frozenReleaseLastServed = lastServedSnapshot();
|
|
22434
21735
|
} else {
|
|
22435
|
-
|
|
22436
|
-
|
|
22437
|
-
|
|
22438
|
-
|
|
22439
|
-
|
|
21736
|
+
let frozenAdmitted = false;
|
|
21737
|
+
try {
|
|
21738
|
+
const frozenSlot = getSlot(sessionId);
|
|
21739
|
+
if (!frozenSlot)
|
|
21740
|
+
throw new LkgRecoveryFenceError("Frozen request disappeared before return");
|
|
21741
|
+
rememberLkgDirtyRevision(sessionId, markLkgRecoveryDirty({
|
|
21742
|
+
sessionId,
|
|
21743
|
+
slot: frozenSlot,
|
|
21744
|
+
processLocalProof: hasProcessLocalLkgProof(sessionId),
|
|
21745
|
+
ownDirtyRevision: lkgDirtyRevision(sessionId)
|
|
21746
|
+
}));
|
|
21747
|
+
frozenAdmitted = true;
|
|
21748
|
+
} catch (error) {
|
|
21749
|
+
if (!(error instanceof LkgRecoveryFenceError))
|
|
21750
|
+
throw error;
|
|
21751
|
+
frozenReplayReleased = true;
|
|
21752
|
+
frozenReleaseReason = "lkg_recovery_fence_unproven";
|
|
21753
|
+
frozenReleaseLastServed = lastServedSnapshot();
|
|
21754
|
+
}
|
|
21755
|
+
if (frozenAdmitted) {
|
|
21756
|
+
appliedMessages = frozen.messages;
|
|
21757
|
+
replayedFrozenRepresentation = true;
|
|
21758
|
+
servedFrom = "lkg_frozen";
|
|
21759
|
+
sessionLog2(sessionId, "lkg_frozen_replay_served");
|
|
21760
|
+
sessionLog2(sessionId, `lkg_frozen_replay_debt healthy_passes=${frozenHealthyPassesAfterApply} raw_messages=${rawTailGrowth}`);
|
|
21761
|
+
}
|
|
22440
21762
|
}
|
|
22441
21763
|
}
|
|
22442
21764
|
}
|
|
@@ -22567,6 +21889,23 @@ function createRustModeTransform(deps, options) {
|
|
|
22567
21889
|
let captureMode = "async";
|
|
22568
21890
|
if (capturePlan)
|
|
22569
21891
|
state.lkgLastServedCaptureSequence = capturePlan.captureSequence;
|
|
21892
|
+
if (capturePlan) {
|
|
21893
|
+
const previousSlot = getSlot(sessionId);
|
|
21894
|
+
const installed = commitRustCapture(state, capturePlan, false, true);
|
|
21895
|
+
if (installed === "captured" && capturePlan.prepared) {
|
|
21896
|
+
if (!synchronousReplacement && !state.lkgSyncCaptureRequired) {
|
|
21897
|
+
capturePlan.fenceRevision = prepareLkgCaptureFence({
|
|
21898
|
+
sessionId,
|
|
21899
|
+
previousSlot,
|
|
21900
|
+
slot: capturePlan.prepared.slot,
|
|
21901
|
+
ownDirtyRevision: lkgDirtyRevision(sessionId),
|
|
21902
|
+
rebuild: synchronousReplacement
|
|
21903
|
+
});
|
|
21904
|
+
rememberLkgDirtyRevision(sessionId, capturePlan.fenceRevision);
|
|
21905
|
+
}
|
|
21906
|
+
captureForCertificate = capturePlan;
|
|
21907
|
+
}
|
|
21908
|
+
}
|
|
22570
21909
|
const endRecoveryAfterResetCapture = () => {
|
|
22571
21910
|
if (signedThinkingReset && thinkingRecovery.restore) {
|
|
22572
21911
|
endLatestThinkingRecoveryAfterReset(deps.db, sessionId);
|
|
@@ -22576,13 +21915,14 @@ function createRustModeTransform(deps, options) {
|
|
|
22576
21915
|
if (states.get(sessionId) !== state || capturePlan && capturePlan.captureSequence !== state.lkgCaptureSequence) {
|
|
22577
21916
|
return;
|
|
22578
21917
|
}
|
|
22579
|
-
if (!markerDefinitelyNoCut)
|
|
21918
|
+
if (!markerDefinitelyNoCut && !(error instanceof LkgRecoveryFenceError))
|
|
22580
21919
|
dropSlot(sessionId, `lkg_${mode}_capture_failed`);
|
|
22581
21920
|
state.lkgAcceptedCapture = undefined;
|
|
22582
21921
|
state.lkgSyncCaptureRequired = true;
|
|
22583
21922
|
sessionLog2(sessionId, `LKG ${mode.toUpperCase()} CAPTURE FAILED; forcing synchronous capture on the next applied pass:`, error);
|
|
22584
21923
|
};
|
|
22585
21924
|
if (!capturePlan) {
|
|
21925
|
+
invalidateCleanLkgRecoveryFence(sessionId, () => loadPersistedLkgSlot(deps.db, sessionId));
|
|
22586
21926
|
captureMode = "declined";
|
|
22587
21927
|
const error = new Error("LKG snapshot preparation was rejected");
|
|
22588
21928
|
captureFailed("async", error);
|
|
@@ -22595,7 +21935,7 @@ function createRustModeTransform(deps, options) {
|
|
|
22595
21935
|
endRecoveryAfterResetCapture();
|
|
22596
21936
|
} catch (error) {
|
|
22597
21937
|
captureFailed("sync", error);
|
|
22598
|
-
if (synchronousReplacement)
|
|
21938
|
+
if (synchronousReplacement || error instanceof LkgRecoveryFenceError)
|
|
22599
21939
|
throw error;
|
|
22600
21940
|
}
|
|
22601
21941
|
} else {
|
|
@@ -22621,6 +21961,7 @@ function createRustModeTransform(deps, options) {
|
|
|
22621
21961
|
throw error;
|
|
22622
21962
|
}
|
|
22623
21963
|
const bookkeepingStartedAt = performance.now();
|
|
21964
|
+
finishSystemDateRefresh(deps.historyRefreshSessions, dateRequest, moduleDecisionBusts);
|
|
22624
21965
|
if (shouldAdoptModuleAfterFreeze(moduleDecisionBusts, frozenReplayReleased)) {
|
|
22625
21966
|
if (frozenReleaseReason) {
|
|
22626
21967
|
sessionLog2(sessionId, `lkg_frozen_replay_released reason=${frozenReleaseReason}`);
|
|
@@ -22733,17 +22074,66 @@ function createRustModeTransform(deps, options) {
|
|
|
22733
22074
|
systemPromptHash: sessionMeta.systemPromptHash
|
|
22734
22075
|
});
|
|
22735
22076
|
captureOpencodeReasoningBudgetStatus(sessionId, output.messages, resolveKeepReasoningTokens(deps.keepReasoningTokens, modelKey ?? undefined), isPrefixBoundThinkingModel(model?.providerID, model?.modelID));
|
|
22077
|
+
if (!moduleDecisionBusts && inputHasActiveThinking && isPrefixBoundThinkingModel(model?.providerID, model?.modelID)) {
|
|
22078
|
+
recordHeldHeadForRequest(sessionId, currentLkgRequestIdentity(sessionId), (ownsHistory) => deferDeliveredSystemRefresh(deps, sessionId, ownsHistory));
|
|
22079
|
+
}
|
|
22736
22080
|
finishPass(true);
|
|
22737
22081
|
if (state.markerAdmissionFenced) {
|
|
22738
22082
|
setRustMarkerAdmissionFence(deps.db, sessionId, false);
|
|
22739
22083
|
state.markerAdmissionFenced = false;
|
|
22740
22084
|
}
|
|
22085
|
+
const returnedJson = JSON.stringify(output.messages);
|
|
22086
|
+
state.lkgLatestServedDigest = lkgServedArrayDigest(returnedJson);
|
|
22087
|
+
if (captureForCertificate) {
|
|
22088
|
+
captureForCertificate.returnedDigest = state.lkgLatestServedDigest;
|
|
22089
|
+
if (captureForCertificate.prepared && captureForCertificate.captureSequence === state.lkgCaptureSequence && captureForCertificate.rowVersion >= state.lkgLastCapturedRowVersion) {
|
|
22090
|
+
const returnedSlot = {
|
|
22091
|
+
...captureForCertificate.prepared.slot,
|
|
22092
|
+
jsonPrefix: returnedJson
|
|
22093
|
+
};
|
|
22094
|
+
captureSlot(sessionId, returnedSlot);
|
|
22095
|
+
noteCapturedLkgRequest({
|
|
22096
|
+
sessionId,
|
|
22097
|
+
slot: returnedSlot,
|
|
22098
|
+
request: captureForCertificate.requestIdentity,
|
|
22099
|
+
systemPromptTokens: captureForCertificate.systemPromptTokens,
|
|
22100
|
+
agentName: captureForCertificate.agentName
|
|
22101
|
+
});
|
|
22102
|
+
}
|
|
22103
|
+
captureForCertificate.eligibleForClean = lkgServedArrayDigest(captureForCertificate.jsonPrefix) === state.lkgLatestServedDigest;
|
|
22104
|
+
if ((!captureForCertificate.committed || !captureForCertificate.eligibleForClean) && captureForCertificate.prepared && !captureForCertificate.fenceRevision) {
|
|
22105
|
+
captureForCertificate.fenceRevision = prepareLkgCaptureFence({
|
|
22106
|
+
sessionId,
|
|
22107
|
+
slot: captureForCertificate.prepared.slot,
|
|
22108
|
+
previousSlot: loadPersistedLkgSlot(deps.db, sessionId, true),
|
|
22109
|
+
ownDirtyRevision: lkgDirtyRevision(sessionId),
|
|
22110
|
+
rebuild: true
|
|
22111
|
+
});
|
|
22112
|
+
rememberLkgDirtyRevision(sessionId, captureForCertificate.fenceRevision);
|
|
22113
|
+
}
|
|
22114
|
+
if (captureForCertificate.committed && captureForCertificate.eligibleForClean && captureForCertificate.prepared && captureForCertificate.fenceRevision) {
|
|
22115
|
+
try {
|
|
22116
|
+
certifyCommittedLkgCapture({
|
|
22117
|
+
sessionId,
|
|
22118
|
+
slot: captureForCertificate.prepared.slot,
|
|
22119
|
+
revision: captureForCertificate.fenceRevision,
|
|
22120
|
+
latestServedDigest: state.lkgLatestServedDigest,
|
|
22121
|
+
load: () => loadPersistedLkgSlot(deps.db, sessionId, true)
|
|
22122
|
+
});
|
|
22123
|
+
} catch (error) {
|
|
22124
|
+
sessionLog2(sessionId, "Last-good certificate remains dirty after publication failure:", error);
|
|
22125
|
+
}
|
|
22126
|
+
}
|
|
22127
|
+
}
|
|
22741
22128
|
} catch (error) {
|
|
22742
22129
|
if (markerDefinitelyNoCut) {
|
|
22743
22130
|
try {
|
|
22744
22131
|
deps.db.transaction(() => {
|
|
22745
22132
|
if (markerSafeSnapshot) {
|
|
22746
|
-
if (!saveLkgSlotToDb(deps.db, sessionId, markerSafeSnapshot
|
|
22133
|
+
if (!saveLkgSlotToDb(deps.db, sessionId, markerSafeSnapshot, undefined, {
|
|
22134
|
+
ownDirtyRevision: captureForCertificate?.fenceRevision,
|
|
22135
|
+
requiredRevision: captureForCertificate?.fenceRevision
|
|
22136
|
+
}))
|
|
22747
22137
|
throw new Error("could not restore the unchanged-boundary LKG");
|
|
22748
22138
|
} else {
|
|
22749
22139
|
clearPersistedLkgSlotStrict(deps.db, sessionId);
|
|
@@ -22833,7 +22223,7 @@ function createRustModeTransform(deps, options) {
|
|
|
22833
22223
|
});
|
|
22834
22224
|
}
|
|
22835
22225
|
const refusedUser = newestUserMessage(messages);
|
|
22836
|
-
const refusedUserMessageId = refusedUser ?
|
|
22226
|
+
const refusedUserMessageId = refusedUser ? messageIdOf(refusedUser) : null;
|
|
22837
22227
|
if (refusedUserMessageId) {
|
|
22838
22228
|
try {
|
|
22839
22229
|
options.onEngineReconnectRefusal?.({
|
|
@@ -23397,6 +22787,7 @@ function resolveTransformHostSeams(deps) {
|
|
|
23397
22787
|
};
|
|
23398
22788
|
}
|
|
23399
22789
|
function createTransform(deps) {
|
|
22790
|
+
registerSystemDateRefresh(deps.historyRefreshSessions);
|
|
23400
22791
|
const finalWireUsage = createFinalWireUsageTracker();
|
|
23401
22792
|
const host = resolveTransformHostSeams(deps);
|
|
23402
22793
|
const loadedSessions = new Set;
|
|
@@ -23420,8 +22811,8 @@ function createTransform(deps) {
|
|
|
23420
22811
|
entryReuse = stats;
|
|
23421
22812
|
}
|
|
23422
22813
|
});
|
|
23423
|
-
const deferredHistoryRefreshSessions = deps.deferredHistoryRefreshSessions
|
|
23424
|
-
const deferredMaterializationSessions = deps.deferredMaterializationSessions
|
|
22814
|
+
const deferredHistoryRefreshSessions = deps.deferredHistoryRefreshSessions ??= new Set;
|
|
22815
|
+
const deferredMaterializationSessions = deps.deferredMaterializationSessions ??= new Set;
|
|
23425
22816
|
const observeCommitNudgeTransition = (sessionId, hasRecentCommit, isSubagent) => {
|
|
23426
22817
|
const hadPriorCommitState = deps.commitSeenLastPass?.has(sessionId) ?? false;
|
|
23427
22818
|
const sawCommitLastPass = deps.commitSeenLastPass?.get(sessionId) ?? false;
|
|
@@ -23442,11 +22833,14 @@ function createTransform(deps) {
|
|
|
23442
22833
|
return;
|
|
23443
22834
|
}
|
|
23444
22835
|
deps.onMessagesPassStarted?.(sessionId, messages);
|
|
22836
|
+
const dateRequest = systemDateRequestForOutput(deps.historyRefreshSessions, output) ?? beginSystemDateRequest(deps.historyRefreshSessions, sessionId, "messages", systemDateTurnId(messages), systemDateRequestIdentity(output));
|
|
22837
|
+
bindSystemDateRequest(output, dateRequest);
|
|
23445
22838
|
const temporalCandidates = deps.experimentalTemporalAwareness ? collectTemporalCandidates(messages) : undefined;
|
|
23446
22839
|
const temporalReplayIds = temporalCandidates ? messages.flatMap((message) => message.info.id ? [message.info.id] : []) : undefined;
|
|
23447
22840
|
logTransformTiming(sessionId, "findSessionId", tSessionId, `messages=${messages.length}`);
|
|
23448
22841
|
const tLkgEntry = performance.now();
|
|
23449
22842
|
const lkgInput = deps.transformMode === "rust" ? [] : projectEntry(sessionId, messages);
|
|
22843
|
+
const recovery = deps.compactionOff || deps.transformMode === "rust" ? {} : readLkgRecoveryPrefix(sessionId, lkgInput, messages, deps.db);
|
|
23450
22844
|
logTransformTiming(sessionId, "lkg.entryProjection", tLkgEntry, deps.transformMode === "rust" || !entryReuse ? undefined : `reused=${entryReuse.reused} retained=${entryReuse.retained} retainedBytes=${entryReuse.retainedBytes}`);
|
|
23451
22845
|
const resolvedSessionId = sessionId;
|
|
23452
22846
|
const runNotificationParams = (sid) => {
|
|
@@ -23830,7 +23224,7 @@ function createTransform(deps) {
|
|
|
23830
23224
|
const schedulerDeferReason = schedulerDecision === "defer" ? "scheduler_defer" : null;
|
|
23831
23225
|
const historyRefreshExplicitBeforePrepare = !freezeM0M1 && deps.historyRefreshSessions.has(sessionId);
|
|
23832
23226
|
const deferredHistoryWasPendingAtPassStart = !freezeM0M1 && deferredHistoryRefreshSessions.has(sessionId);
|
|
23833
|
-
const prefixTrimSourceOrder =
|
|
23227
|
+
const prefixTrimSourceOrder = capturePrefixTrimSourceOrder(messages);
|
|
23834
23228
|
const earlyActiveRunBlocksMaterialization = (getActiveCompartmentRun(sessionId) !== undefined || sessionMeta.compartmentInProgress) && contextUsageEarly.percentage < forceMaterializationPercentage;
|
|
23835
23229
|
const canConsumeDeferredEarly = canConsumeDeferredOnThisPass({
|
|
23836
23230
|
schedulerDecision,
|
|
@@ -24043,6 +23437,26 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
24043
23437
|
logTransformTiming(sessionId, "injectTemporalMarkers", tTemporal);
|
|
24044
23438
|
}
|
|
24045
23439
|
let taggingSucceeded = false;
|
|
23440
|
+
let recoveryBatch = null;
|
|
23441
|
+
let recoveryNormalized = false;
|
|
23442
|
+
const normalizeRecoveryTail = recovery.prefix ? () => {
|
|
23443
|
+
if (recoveryNormalized)
|
|
23444
|
+
return;
|
|
23445
|
+
const tail = messages.filter((message) => recovery.prefix?.untaggedInputIds.has(message.info.id ?? ""));
|
|
23446
|
+
const tagged = tagMessages(sessionId, tail, deps.tagger, db, {
|
|
23447
|
+
skipPrefixInjection: !ctxReduceCallable,
|
|
23448
|
+
servedMessages: messages,
|
|
23449
|
+
normalizeRestoredAssistantText: deps.normalizeRestoredAssistantText
|
|
23450
|
+
});
|
|
23451
|
+
for (const [number, target] of tagged.targets)
|
|
23452
|
+
targets.set(number, target);
|
|
23453
|
+
for (const [message, parts] of tagged.reasoningByMessage)
|
|
23454
|
+
reasoningByMessage.set(message, parts);
|
|
23455
|
+
for (const [message, number] of tagged.messageTagNumbers)
|
|
23456
|
+
messageTagNumbers.set(message, number);
|
|
23457
|
+
recoveryBatch = tagged.batch;
|
|
23458
|
+
recoveryNormalized = true;
|
|
23459
|
+
} : undefined;
|
|
24046
23460
|
if (!compactionOff) {
|
|
24047
23461
|
try {
|
|
24048
23462
|
const t0 = performance.now();
|
|
@@ -24053,17 +23467,23 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
24053
23467
|
const messagesForTagging = messagesBeforeInitialPrepare && hiddenMessagesAtCompactionSeam.length > 0 ? messagesBeforeInitialPrepare : messages;
|
|
24054
23468
|
const canAdoptScopedToolSweep = isCacheBusting || canConsumeDeferredEarly;
|
|
24055
23469
|
const scopedToolSweep = useScopedToolSweep(db, sessionId, canAdoptScopedToolSweep) ? true : createPreAdoptionToolSweepResolver(db, sessionId);
|
|
24056
|
-
const result = tagMessages(sessionId, messagesForTagging, deps.tagger, db, {
|
|
23470
|
+
const result = tagMessages(sessionId, recovery.prefix ? messagesForTagging.filter((message) => !recovery.prefix?.untaggedInputIds.has(message.info.id ?? "")) : messagesForTagging, deps.tagger, db, {
|
|
24057
23471
|
skipPrefixInjection,
|
|
24058
23472
|
scopedToolSweep,
|
|
24059
|
-
servedMessages: messages
|
|
23473
|
+
servedMessages: messages,
|
|
23474
|
+
normalizeRestoredAssistantText: deps.normalizeRestoredAssistantText
|
|
24060
23475
|
});
|
|
24061
23476
|
targets = result.targets;
|
|
24062
23477
|
if (thinkingRecovery.restore)
|
|
24063
23478
|
restoreLatestTurnOriginals = captureLatestTurnOriginals(messages);
|
|
24064
23479
|
reasoningByMessage = result.reasoningByMessage;
|
|
24065
23480
|
messageTagNumbers = result.messageTagNumbers;
|
|
24066
|
-
batch =
|
|
23481
|
+
batch = {
|
|
23482
|
+
finalize: () => {
|
|
23483
|
+
result.batch?.finalize();
|
|
23484
|
+
recoveryBatch?.finalize();
|
|
23485
|
+
}
|
|
23486
|
+
};
|
|
24067
23487
|
if (resolvedProviderID && !isAnthropicFamilyRoute(resolvedProviderID, modelForBudget?.modelID)) {
|
|
24068
23488
|
for (const target of targets.values()) {
|
|
24069
23489
|
if (target.requiresToolArcSkeleton)
|
|
@@ -24184,7 +23604,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
24184
23604
|
sessionMeta = { ...sessionMeta, compartmentInProgress };
|
|
24185
23605
|
logTransformTiming(sessionId, "compartmentPhase", tCompartmentPhase);
|
|
24186
23606
|
if (pendingCompartmentInjection?.needsFreshMaterialization) {
|
|
24187
|
-
deps.pendingMaterializationSessions
|
|
23607
|
+
requestPendingMaterialization(deps.pendingMaterializationSessions, sessionId, "boundary_repair");
|
|
24188
23608
|
deferredMaterializationSessions.add(sessionId);
|
|
24189
23609
|
}
|
|
24190
23610
|
const hardModel = deps.liveModelBySession?.get(sessionId);
|
|
@@ -24280,6 +23700,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
24280
23700
|
const protectedCutoff = protectionWindow.cutoff;
|
|
24281
23701
|
const tPostProcess = performance.now();
|
|
24282
23702
|
const postTransformResult = await runPostTransformPhase2({
|
|
23703
|
+
normalizeRecoveryTail,
|
|
24283
23704
|
compactionMarkerStrategy: deps.compactionMarkerStrategy ?? defaultCompactionMarkerStrategy2,
|
|
24284
23705
|
sessionId,
|
|
24285
23706
|
db,
|
|
@@ -24312,7 +23733,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
24312
23733
|
freezeM0M1,
|
|
24313
23734
|
activeThinkingPrefixHold,
|
|
24314
23735
|
directoryPrefixHold: unresolvedDirectoryHold,
|
|
24315
|
-
forceSignedRebuildForFit: thinkingFitRetries.has(sessionId),
|
|
23736
|
+
forceSignedRebuildForFit: thinkingFitRetries.has(sessionId) || !!recovery.rebuildReason,
|
|
24316
23737
|
readLastServedMessages: () => {
|
|
24317
23738
|
const slot = getInMemorySlot(sessionId) ?? loadPersistedLkgSlot(db, sessionId);
|
|
24318
23739
|
try {
|
|
@@ -24375,6 +23796,15 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
24375
23796
|
muralEnabled: deps.muralEnabled
|
|
24376
23797
|
}
|
|
24377
23798
|
});
|
|
23799
|
+
if (recovery.prefix && !recoveryNormalized) {
|
|
23800
|
+
const priorIds = new Set(recovery.prefix.inputs.map((input) => input.id));
|
|
23801
|
+
const newIds = new Set(lkgInput.flatMap((input) => input.id && !priorIds.has(input.id) ? [input.id] : []));
|
|
23802
|
+
const suffix = messages.filter((message) => message.info.id && newIds.has(message.info.id));
|
|
23803
|
+
messages.splice(0, messages.length, ...JSON.parse(recovery.prefix.json), ...suffix);
|
|
23804
|
+
}
|
|
23805
|
+
const recoveryReleaseReason = recovery.rebuildReason ?? (recoveryNormalized ? "recovery_tail_normalized" : undefined);
|
|
23806
|
+
if (recoveryReleaseReason)
|
|
23807
|
+
postTransformResult.bustedThisPass = true;
|
|
24378
23808
|
passOutcome.markFinalized();
|
|
24379
23809
|
const finalWireTail = describeFinalWireTail(messages);
|
|
24380
23810
|
let finalWireEstimate;
|
|
@@ -24408,7 +23838,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
24408
23838
|
if ((finalWireEstimate?.refusalGrade || finalWireEstimate?.refusalBasis === "byte-bound" && finalWireEstimate.refusalTokens !== undefined) && boundaryContextLimit > 0 && (finalWireEstimate.refusalTokens ?? finalWireEstimate.tokens) > boundaryContextLimit) {
|
|
24409
23839
|
if (!thinkingFitRetries.has(sessionId) && activeThinkingPrefixHold && originalForThinkingFit && hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID)) {
|
|
24410
23840
|
thinkingFitRetries.add(sessionId);
|
|
24411
|
-
deps.pendingMaterializationSessions
|
|
23841
|
+
requestPendingMaterialization(deps.pendingMaterializationSessions, sessionId, "fit_retry");
|
|
24412
23842
|
messages.splice(0, messages.length, ...originalForThinkingFit);
|
|
24413
23843
|
try {
|
|
24414
23844
|
await transform({}, output);
|
|
@@ -24534,11 +23964,16 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
24534
23964
|
if (!finalWireEstimate) {
|
|
24535
23965
|
sessionLog2(sessionId, `transform: final-wire telemetry estimate=unavailable trusted=false conversation=unknown tools=unknown system=unknown toolDefinitions=unknown tail=${finalWireTail}`);
|
|
24536
23966
|
}
|
|
24537
|
-
|
|
23967
|
+
finishSystemDateRefresh(deps.historyRefreshSessions, dateRequest, postTransformResult.bustedThisPass && !activeThinkingPrefixHold || postTransformResult.thinkingReleasedForFit === true);
|
|
23968
|
+
if (activeThinkingPrefixHold && !postTransformResult.thinkingReleasedForFit && sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) {
|
|
23969
|
+
recordHeldHeadForRequest(sessionId, currentLkgRequestIdentity(sessionId), (ownsHistory) => deferDeliveredSystemRefresh(deps, sessionId, ownsHistory));
|
|
23970
|
+
}
|
|
23971
|
+
if (passOutcome.captureEligible || recovery.prefix || recoveryReleaseReason) {
|
|
24538
23972
|
const keys = resolveLkgModelKeys(messages);
|
|
24539
23973
|
const modelKey = modelForBudget ? `${modelForBudget.providerID}/${modelForBudget.modelID}` : keys.modelKey;
|
|
24540
23974
|
const providerKey = modelForBudget?.providerID ?? keys.providerKey;
|
|
24541
23975
|
const captured = captureLkgSlot({
|
|
23976
|
+
completeOutput: !!recovery.prefix || !!recoveryReleaseReason || isPrefixBoundThinkingModel(resolvedProviderID, modelForBudget?.modelID),
|
|
24542
23977
|
sessionId,
|
|
24543
23978
|
input: lkgInput,
|
|
24544
23979
|
output: messages,
|
|
@@ -24550,13 +23985,37 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
24550
23985
|
if (captured) {
|
|
24551
23986
|
const capturedSlot = getInMemorySlot(sessionId);
|
|
24552
23987
|
if (capturedSlot) {
|
|
24553
|
-
|
|
23988
|
+
const revision = lkgDirtyRevision(sessionId) ?? dirtyLkgRecoveryRevision(sessionId, capturedSlot);
|
|
23989
|
+
const fence = {
|
|
23990
|
+
ownDirtyRevision: revision,
|
|
23991
|
+
requiredRevision: revision && ownsLkgDirtyFence(sessionId, revision) ? revision : undefined,
|
|
23992
|
+
rebuild: !!recoveryReleaseReason,
|
|
23993
|
+
retainDirtyRevision: recovery.prefix && !recoveryReleaseReason ? revision : undefined
|
|
23994
|
+
};
|
|
23995
|
+
withoutSqliteTransformPass2(() => setImmediate(() => {
|
|
23996
|
+
if (fence.requiredRevision) {
|
|
23997
|
+
const latest = getInMemorySlot(sessionId);
|
|
23998
|
+
if (!latest || latest.capturedAt !== capturedSlot.capturedAt || latest.jsonPrefix !== capturedSlot.jsonPrefix || latest.lastInputMessageId !== capturedSlot.lastInputMessageId || latest.modelKey !== capturedSlot.modelKey || latest.providerKey !== capturedSlot.providerKey)
|
|
23999
|
+
return;
|
|
24000
|
+
}
|
|
24001
|
+
try {
|
|
24002
|
+
saveLkgSlotToDb(db, sessionId, capturedSlot, undefined, fence);
|
|
24003
|
+
} catch (error) {
|
|
24004
|
+
sessionLog2(sessionId, "Last-good deferred publication remains uncertified:", error);
|
|
24005
|
+
}
|
|
24006
|
+
}));
|
|
24554
24007
|
}
|
|
24008
|
+
noteLkgHealthyPrefix(sessionId, lkgInput, messages, !!recoveryReleaseReason);
|
|
24555
24009
|
}
|
|
24556
|
-
if (
|
|
24557
|
-
|
|
24010
|
+
if (!captured) {
|
|
24011
|
+
if (postTransformResult.bustedThisPass)
|
|
24012
|
+
dropSlot(sessionId, "lkg_refresh_declined");
|
|
24013
|
+
noteUncertifiedNormalLkg(sessionId, invalidateCleanLkgRecoveryFence(sessionId, () => loadPersistedLkgSlot(db, sessionId, true), lkgDirtyRevision(sessionId)));
|
|
24558
24014
|
}
|
|
24559
24015
|
} else if (passOutcome.degradations.length > 0) {
|
|
24016
|
+
if (compactionOff) {
|
|
24017
|
+
noteUncertifiedNormalLkg(sessionId, invalidateCleanLkgRecoveryFence(sessionId, () => loadPersistedLkgSlot(db, sessionId, true), lkgDirtyRevision(sessionId)));
|
|
24018
|
+
}
|
|
24560
24019
|
sessionLog2(sessionId, `lkg_capture_declined degradations=${passOutcome.degradations.map((item) => item.site).join(",")}`);
|
|
24561
24020
|
}
|
|
24562
24021
|
if (postTransformResult.bustedThisPass || hardCacheExpired) {
|
|
@@ -24575,7 +24034,8 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
24575
24034
|
droppedTokens: postTransformResult.droppedTokens,
|
|
24576
24035
|
droppedCount: postTransformResult.droppedCount,
|
|
24577
24036
|
inputTokens: contextUsage.inputTokens,
|
|
24578
|
-
bustedThisPass: true
|
|
24037
|
+
bustedThisPass: true,
|
|
24038
|
+
lkgFrozenReleaseReason: recoveryReleaseReason
|
|
24579
24039
|
});
|
|
24580
24040
|
}
|
|
24581
24041
|
logTransformTiming(sessionId, "postTransformPhase", tPostProcess);
|
|
@@ -24906,7 +24366,26 @@ function createRustRefusalRecovery(options) {
|
|
|
24906
24366
|
}
|
|
24907
24367
|
|
|
24908
24368
|
// src/hooks/magic-context/system-prompt-hash.ts
|
|
24909
|
-
import { createHash as
|
|
24369
|
+
import { createHash as createHash12 } from "node:crypto";
|
|
24370
|
+
|
|
24371
|
+
// src/hooks/magic-context/system-prompt-dates.ts
|
|
24372
|
+
function replaceHostDates(prompt, replace) {
|
|
24373
|
+
const fields = /<(plugin-env|environment|env)>[\s\S]*?<\/\1>|Today's date: [^\r\n<]+/g;
|
|
24374
|
+
return prompt.replace(fields, (block) => block.replace(/(^[\t ]*(?:Date|Today's date):[\t ]*)([^\r\n<]+)/gm, (_line, label, date) => `${label}${replace(date)}`));
|
|
24375
|
+
}
|
|
24376
|
+
function systemPromptDates(prompt, sticky) {
|
|
24377
|
+
const values = [];
|
|
24378
|
+
replaceHostDates(prompt, (date) => {
|
|
24379
|
+
values.push(date);
|
|
24380
|
+
return date;
|
|
24381
|
+
});
|
|
24382
|
+
const prior = sticky ? JSON.parse(sticky) : [];
|
|
24383
|
+
let index = 0;
|
|
24384
|
+
const stable = replaceHostDates(prompt, (date) => prior[index++] ?? date);
|
|
24385
|
+
return { live: values.length ? JSON.stringify(values) : undefined, stable };
|
|
24386
|
+
}
|
|
24387
|
+
|
|
24388
|
+
// src/hooks/magic-context/system-prompt-hash.ts
|
|
24910
24389
|
var MAGIC_CONTEXT_MARKER = "## Magic Context";
|
|
24911
24390
|
var SYSTEM_PROMPT_GUIDANCE_SEPARATOR = `
|
|
24912
24391
|
|
|
@@ -24928,7 +24407,7 @@ function createSystemPromptHashHandler(deps) {
|
|
|
24928
24407
|
});
|
|
24929
24408
|
const guidanceEpochs = createPromptSurfaceGuidanceEpochCache(promptSurfaceRuntime);
|
|
24930
24409
|
const stickyDateBySession = new Map;
|
|
24931
|
-
const
|
|
24410
|
+
const processSystemPrompt = async (input, output) => {
|
|
24932
24411
|
const sessionId = input.sessionID;
|
|
24933
24412
|
if (!sessionId)
|
|
24934
24413
|
return;
|
|
@@ -24952,7 +24431,10 @@ function createSystemPromptHashHandler(deps) {
|
|
|
24952
24431
|
sessionLog2(sessionId, "system-prompt-hash skipped (matched system_prompt_injection.skip_signatures)");
|
|
24953
24432
|
return;
|
|
24954
24433
|
}
|
|
24955
|
-
const
|
|
24434
|
+
const messagesPrepared = deps.consumeMessagesPrepared?.(sessionId) ?? false;
|
|
24435
|
+
const dateRequest = beginSystemDateRequest(deps.historyRefreshSessions, sessionId, messagesPrepared ? "system-after-messages" : "system", input.dateRefreshRequest === undefined && hasSystemDateRefresh(deps.historyRefreshSessions) ? (deps.resolveDateTurnId ?? latestRealUserTurnIdFromOpenCodeDb)(sessionId) : undefined, input.dateRefreshRequest);
|
|
24436
|
+
bindSystemDateRequest(output, dateRequest);
|
|
24437
|
+
const requestMessagesFinal = messagesPrepared || systemDateRefreshPermission(deps.historyRefreshSessions, dateRequest) !== undefined;
|
|
24956
24438
|
let sessionMetaEarly;
|
|
24957
24439
|
try {
|
|
24958
24440
|
sessionMetaEarly = getOrCreateSessionMeta(deps.db, sessionId);
|
|
@@ -24984,9 +24466,7 @@ function createSystemPromptHashHandler(deps) {
|
|
|
24984
24466
|
}
|
|
24985
24467
|
const isCacheBusting = deps.systemPromptRefreshSessions.has(sessionId);
|
|
24986
24468
|
const idleCacheExpired = sessionMetaEarly !== undefined && computeHardCacheExpired(sessionMetaEarly.cacheTtl, sessionMetaEarly.lastResponseTime, Date.now());
|
|
24987
|
-
const adoptSystemChange = idleCacheExpired || requestMessagesFinal;
|
|
24988
|
-
const DATE_PATTERN = /Today's date: .+/;
|
|
24989
|
-
const DATE_PATTERN_ALL = /Today's date: .+/g;
|
|
24469
|
+
const adoptSystemChange = idleCacheExpired || requestMessagesFinal && !isHeldHeadForRequest(sessionId, currentLkgRequestIdentity(sessionId));
|
|
24990
24470
|
const liveSystemContent = output.system.join(`
|
|
24991
24471
|
`);
|
|
24992
24472
|
if (liveSystemContent.length === 0)
|
|
@@ -24995,29 +24475,56 @@ function createSystemPromptHashHandler(deps) {
|
|
|
24995
24475
|
const hasPersistedHash = previousHash !== "" && previousHash !== "0";
|
|
24996
24476
|
if (!hasPersistedHash)
|
|
24997
24477
|
stickyDateBySession.delete(sessionId);
|
|
24998
|
-
const dateElementIndexes = [];
|
|
24999
|
-
let currentDate;
|
|
25000
|
-
for (let i = 0;i < output.system.length; i++) {
|
|
25001
|
-
const match = output.system[i].match(DATE_PATTERN);
|
|
25002
|
-
if (!match)
|
|
25003
|
-
continue;
|
|
25004
|
-
dateElementIndexes.push(i);
|
|
25005
|
-
currentDate ??= match[0];
|
|
25006
|
-
}
|
|
25007
24478
|
const stickyDate = stickyDateBySession.get(sessionId);
|
|
25008
|
-
const
|
|
25009
|
-
const
|
|
24479
|
+
const dates = systemPromptDates(liveSystemContent, stickyDate);
|
|
24480
|
+
const currentDate = dates.live;
|
|
24481
|
+
const stableCandidate = dates.stable;
|
|
24482
|
+
const stableCandidateHash = createHash12("md5").update(promptSurfaceHashMaterial(stableCandidate, promptSurface.preset)).digest("hex");
|
|
25010
24483
|
const contentOrPresetChanged = hasPersistedHash && stableCandidateHash !== previousHash;
|
|
25011
|
-
const
|
|
24484
|
+
const rewritePermission = systemDateRefreshPermission(deps.historyRefreshSessions, dateRequest);
|
|
24485
|
+
let deferredDateRefresh = false;
|
|
24486
|
+
if (currentDate && stickyDate && currentDate !== stickyDate && isCacheBusting && !idleCacheExpired && !contentOrPresetChanged && !requestMessagesFinal) {
|
|
24487
|
+
const liveElements = [...output.system];
|
|
24488
|
+
deferredDateRefresh = waitForSystemDateRefresh(deps.historyRefreshSessions, dateRequest, (permitted) => {
|
|
24489
|
+
if (!permitted) {
|
|
24490
|
+
deps.systemPromptRefreshSessions.add(sessionId);
|
|
24491
|
+
return;
|
|
24492
|
+
}
|
|
24493
|
+
try {
|
|
24494
|
+
const content = liveElements.join(`
|
|
24495
|
+
`);
|
|
24496
|
+
const hash = createHash12("md5").update(promptSurfaceHashMaterial(content, promptSurface.preset)).digest("hex");
|
|
24497
|
+
updateSessionMeta(deps.db, sessionId, {
|
|
24498
|
+
systemPromptHash: hash,
|
|
24499
|
+
cachedM0SystemHash: hash,
|
|
24500
|
+
systemPromptTokens: estimateTokens(content)
|
|
24501
|
+
});
|
|
24502
|
+
stickyDateBySession.set(sessionId, currentDate);
|
|
24503
|
+
output.system.splice(0, output.system.length, ...liveElements);
|
|
24504
|
+
publishSystemDateOutput(output.system);
|
|
24505
|
+
deps.systemPromptRefreshSessions.delete(sessionId);
|
|
24506
|
+
sessionLog2(sessionId, `system prompt date updated after prefix rewrite: ${stickyDate} → ${currentDate}`);
|
|
24507
|
+
} catch (error) {
|
|
24508
|
+
deps.systemPromptRefreshSessions.add(sessionId);
|
|
24509
|
+
sessionLog2(sessionId, "system prompt date refresh failed (keeping frozen date):", error);
|
|
24510
|
+
}
|
|
24511
|
+
});
|
|
24512
|
+
}
|
|
24513
|
+
const dateMayAdvance = idleCacheExpired || contentOrPresetChanged || isCacheBusting && !deferredDateRefresh && (dateRequest ? rewritePermission === true : rewritePermission !== false);
|
|
25012
24514
|
if (currentDate && !stickyDate) {
|
|
25013
24515
|
stickyDateBySession.set(sessionId, currentDate);
|
|
25014
24516
|
} else if (currentDate && stickyDate && currentDate !== stickyDate) {
|
|
25015
24517
|
if (dateMayAdvance) {
|
|
25016
24518
|
stickyDateBySession.set(sessionId, currentDate);
|
|
25017
24519
|
sessionLog2(sessionId, `system prompt date updated: ${stickyDate} → ${currentDate} (cache-busting pass)`);
|
|
25018
|
-
} else
|
|
25019
|
-
|
|
25020
|
-
|
|
24520
|
+
} else {
|
|
24521
|
+
let offset = 0;
|
|
24522
|
+
const prior = JSON.parse(stickyDate);
|
|
24523
|
+
for (let index = 0;index < output.system.length; index++) {
|
|
24524
|
+
const element = systemPromptDates(output.system[index]);
|
|
24525
|
+
const count = element.live ? JSON.parse(element.live).length : 0;
|
|
24526
|
+
output.system[index] = systemPromptDates(output.system[index], JSON.stringify(prior.slice(offset, offset + count))).stable;
|
|
24527
|
+
offset += count;
|
|
25021
24528
|
}
|
|
25022
24529
|
sessionLog2(sessionId, `system prompt date frozen: real=${currentDate}, using=${stickyDate} (defer pass)`);
|
|
25023
24530
|
}
|
|
@@ -25026,7 +24533,8 @@ function createSystemPromptHashHandler(deps) {
|
|
|
25026
24533
|
`);
|
|
25027
24534
|
if (!availability.frozen || !modelKey)
|
|
25028
24535
|
return;
|
|
25029
|
-
const currentHash =
|
|
24536
|
+
const currentHash = createHash12("md5").update(promptSurfaceHashMaterial(systemContent, promptSurface.preset)).digest("hex");
|
|
24537
|
+
recordSystemPromptForRequest(sessionId, currentLkgRequestIdentity(sessionId), currentHash, deps.db, previousHash !== currentHash ? !deps.historyRefreshSessions.has(sessionId) : undefined, deps.historyRefreshSessions, deps.pendingMaterializationSessions);
|
|
25030
24538
|
if (!sessionMetaEarly) {
|
|
25031
24539
|
return;
|
|
25032
24540
|
}
|
|
@@ -25036,7 +24544,9 @@ function createSystemPromptHashHandler(deps) {
|
|
|
25036
24544
|
if (!adoptSystemChange) {
|
|
25037
24545
|
deps.historyRefreshSessions.add(sessionId);
|
|
25038
24546
|
deps.systemPromptRefreshSessions.add(sessionId);
|
|
25039
|
-
deps.pendingMaterializationSessions.
|
|
24547
|
+
if (!deps.pendingMaterializationSessions.has(sessionId)) {
|
|
24548
|
+
requestPendingMaterialization(deps.pendingMaterializationSessions, sessionId, "system_hash");
|
|
24549
|
+
}
|
|
25040
24550
|
deps.lastHeuristicsTurnId.delete(sessionId);
|
|
25041
24551
|
}
|
|
25042
24552
|
} else if (previousHash === "" || previousHash === "0") {
|
|
@@ -25059,13 +24569,21 @@ function createSystemPromptHashHandler(deps) {
|
|
|
25059
24569
|
sessionLog2(sessionId, "system prompt meta persist failed (fail-open):", error);
|
|
25060
24570
|
}
|
|
25061
24571
|
}
|
|
25062
|
-
if (isCacheBusting) {
|
|
24572
|
+
if (isCacheBusting && !deferredDateRefresh && (contentOrPresetChanged || !currentDate || currentDate === stickyDate || !dateRequest || rewritePermission === true)) {
|
|
25063
24573
|
deps.systemPromptRefreshSessions.delete(sessionId);
|
|
25064
24574
|
}
|
|
25065
24575
|
};
|
|
24576
|
+
const handler = async (input, output) => {
|
|
24577
|
+
try {
|
|
24578
|
+
await processSystemPrompt(input, output);
|
|
24579
|
+
} finally {
|
|
24580
|
+
finishSystemDateHook(deps.historyRefreshSessions, systemDateRequestForOutput(deps.historyRefreshSessions, output));
|
|
24581
|
+
}
|
|
24582
|
+
};
|
|
25066
24583
|
return {
|
|
25067
24584
|
handler,
|
|
25068
24585
|
clearSession: (sessionId) => {
|
|
24586
|
+
clearSystemDateRefresh(deps.historyRefreshSessions, sessionId);
|
|
25069
24587
|
guidanceEpochs.clear(sessionId);
|
|
25070
24588
|
clearSystemPromptHashSession(sessionId, {
|
|
25071
24589
|
stickyDateBySession,
|
|
@@ -25203,6 +24721,8 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
25203
24721
|
dropSlot(sessionId, "lkg_invalidated_reshape");
|
|
25204
24722
|
sessionLog2(sessionId, "lkg_invalidated_reshape");
|
|
25205
24723
|
} else if (sessionId && entry) {
|
|
24724
|
+
if (!args.rust && lkgRecoveryEntryUnproven(sessionId, entry, output.messages))
|
|
24725
|
+
return false;
|
|
25206
24726
|
let replayBlocked = false;
|
|
25207
24727
|
try {
|
|
25208
24728
|
const db = openDatabase();
|
|
@@ -25230,6 +24750,10 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
25230
24750
|
resolvedProviderID: keys.providerKey ?? undefined
|
|
25231
24751
|
})
|
|
25232
24752
|
});
|
|
24753
|
+
if (replay.ok && !rust && lkgRecoveryReplayUnproven(sessionId)) {
|
|
24754
|
+
sessionLog2(sessionId, "lkg_restart_rebuild_required");
|
|
24755
|
+
return false;
|
|
24756
|
+
}
|
|
25233
24757
|
let tsFit = true;
|
|
25234
24758
|
if (replay.ok && !rust && keys.providerKey && keys.modelKey) {
|
|
25235
24759
|
const model = {
|
|
@@ -25260,6 +24784,24 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
25260
24784
|
replayBlocked = true;
|
|
25261
24785
|
sessionLog2(sessionId, "lkg_replay_does_not_fit");
|
|
25262
24786
|
} else if (replay.ok) {
|
|
24787
|
+
const recoverySlot = getSlot(sessionId);
|
|
24788
|
+
if (!recoverySlot)
|
|
24789
|
+
return false;
|
|
24790
|
+
const revision = markLkgRecoveryDirty({
|
|
24791
|
+
sessionId,
|
|
24792
|
+
slot: recoverySlot,
|
|
24793
|
+
processLocalProof: hasProcessLocalLkgProof(sessionId),
|
|
24794
|
+
ownDirtyRevision: lkgDirtyRevision(sessionId)
|
|
24795
|
+
});
|
|
24796
|
+
rememberLkgDirtyRevision(sessionId, revision);
|
|
24797
|
+
if (!rust && !noteLkgRecoveryPrefix({
|
|
24798
|
+
sessionId,
|
|
24799
|
+
entry,
|
|
24800
|
+
messages: replay.messages,
|
|
24801
|
+
...keys
|
|
24802
|
+
}))
|
|
24803
|
+
return false;
|
|
24804
|
+
retirePendingSystemPromptDelivery(sessionId);
|
|
25263
24805
|
args.onLkgReplay?.();
|
|
25264
24806
|
replaceMessagesInPlace2(output, replay.messages);
|
|
25265
24807
|
noteExternalLkgReplay(rust, sessionId, inputCount);
|
|
@@ -25658,7 +25200,7 @@ function resolveCtxExpandMode(args, domain) {
|
|
|
25658
25200
|
}
|
|
25659
25201
|
|
|
25660
25202
|
// src/tools/ctx-expand/render.ts
|
|
25661
|
-
import { createHash as
|
|
25203
|
+
import { createHash as createHash13 } from "node:crypto";
|
|
25662
25204
|
function isRecord4(value) {
|
|
25663
25205
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
25664
25206
|
}
|
|
@@ -25882,7 +25424,7 @@ function renderItemByTag(db, sessionId, number, textIndexDomain = "part") {
|
|
|
25882
25424
|
const index = scoped ? Number(scoped[2]) : 0;
|
|
25883
25425
|
const piText = message.parts.filter((part) => isRecord4(part) && part.type === "text");
|
|
25884
25426
|
const part = message.parts[index];
|
|
25885
|
-
const matching = derived ? piText.filter((part) => isRecord4(part) && typeof part.text === "string" &&
|
|
25427
|
+
const matching = derived ? piText.filter((part) => isRecord4(part) && typeof part.text === "string" && createHash13("sha256").update(part.text).digest("hex") === derived[3]) : [];
|
|
25886
25428
|
const selected = derived ? matching[Number(derived[4])] : textIndexDomain === "text" ? piText[index] : part;
|
|
25887
25429
|
return selected ? renderPartFull(selected) ?? "" : `Tag ${number}'s original text part is no longer in stored history.`;
|
|
25888
25430
|
}
|
|
@@ -26661,7 +26203,7 @@ import { existsSync as existsSync8 } from "node:fs";
|
|
|
26661
26203
|
import { isAbsolute as isAbsolute2 } from "node:path";
|
|
26662
26204
|
|
|
26663
26205
|
// ../retina-local-fs/src/path-fence.ts
|
|
26664
|
-
import { lstat as lstat2,
|
|
26206
|
+
import { lstat as lstat2, realpath as realpath2 } from "node:fs/promises";
|
|
26665
26207
|
import { homedir } from "node:os";
|
|
26666
26208
|
import { basename, dirname as dirname2, isAbsolute, join as join6, relative, resolve, sep } from "node:path";
|
|
26667
26209
|
|
|
@@ -26729,18 +26271,16 @@ async function canonicalPath(path, allowMissing) {
|
|
|
26729
26271
|
const suffix = [];
|
|
26730
26272
|
let candidate = path;
|
|
26731
26273
|
while (true) {
|
|
26274
|
+
let symbolicLink = false;
|
|
26732
26275
|
try {
|
|
26733
|
-
|
|
26734
|
-
if (metadata.isSymbolicLink()) {
|
|
26735
|
-
const target = await readlink(candidate);
|
|
26736
|
-
const resolvedTarget = resolve(dirname2(candidate), target);
|
|
26737
|
-
return canonicalPath(join6(resolvedTarget, ...suffix), true);
|
|
26738
|
-
}
|
|
26276
|
+
symbolicLink = (await lstat2(candidate)).isSymbolicLink();
|
|
26739
26277
|
} catch (candidateError) {
|
|
26740
26278
|
if (!isMissingError(candidateError)) {
|
|
26741
26279
|
throw fsError(path, candidateError);
|
|
26742
26280
|
}
|
|
26743
26281
|
}
|
|
26282
|
+
if (symbolicLink)
|
|
26283
|
+
throw fsError(path, error);
|
|
26744
26284
|
const parent = dirname2(candidate);
|
|
26745
26285
|
if (parent === candidate) {
|
|
26746
26286
|
throw fsError(path, error);
|
|
@@ -27425,12 +26965,18 @@ Stamp: file reads, search results and tool outputs the work ahead no longer need
|
|
|
27425
26965
|
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.
|
|
27426
26966
|
|
|
27427
26967
|
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".`;
|
|
27428
|
-
|
|
27429
|
-
|
|
27430
|
-
|
|
26968
|
+
function formatCtxReduceReply(stampedCount, selfStampCount = 0) {
|
|
26969
|
+
const parts = [];
|
|
26970
|
+
if (stampedCount > 0) {
|
|
26971
|
+
parts.push(`${stampedCount} tag${stampedCount === 1 ? "" : "s"} stamped.`);
|
|
26972
|
+
}
|
|
26973
|
+
if (selfStampCount > 0) {
|
|
26974
|
+
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.`);
|
|
26975
|
+
}
|
|
26976
|
+
return parts.join(" ");
|
|
27431
26977
|
}
|
|
27432
26978
|
// src/tools/ctx-reduce/tools.ts
|
|
27433
|
-
import { createHash as
|
|
26979
|
+
import { createHash as createHash14 } from "node:crypto";
|
|
27434
26980
|
import { tool as tool4 } from "@opencode-ai/plugin";
|
|
27435
26981
|
|
|
27436
26982
|
// src/features/magic-context/range-parser.ts
|
|
@@ -27481,12 +27027,6 @@ function parseInteger(str) {
|
|
|
27481
27027
|
}
|
|
27482
27028
|
|
|
27483
27029
|
// src/tools/ctx-reduce/tools.ts
|
|
27484
|
-
function formatRawDropForAck(rawDrop) {
|
|
27485
|
-
return rawDrop.trim().split(",").map((token) => {
|
|
27486
|
-
const trimmed = token.trim();
|
|
27487
|
-
return /^\d+$/.test(trimmed) ? `§${trimmed}§` : trimmed;
|
|
27488
|
-
}).join(", ");
|
|
27489
|
-
}
|
|
27490
27030
|
var ctxReduceArgsShape = {
|
|
27491
27031
|
drop: tool4.schema.string().optional().describe('Tag IDs to drop: "3-5", "1,2,9", "1-5,8,12-15".')
|
|
27492
27032
|
};
|
|
@@ -27500,11 +27040,11 @@ function createCtxReduceTool(deps) {
|
|
|
27500
27040
|
const stableId = `oc-${sessionId}-${callId}`;
|
|
27501
27041
|
if (Buffer.byteLength(stableId) <= 128)
|
|
27502
27042
|
return stableId;
|
|
27503
|
-
return `oc-${
|
|
27043
|
+
return `oc-${createHash14("sha256").update(stableId).digest("hex")}`;
|
|
27504
27044
|
}
|
|
27505
27045
|
fallbackCommandSequence += 1;
|
|
27506
27046
|
const monotonicId = `oc-${sessionId}-${fallbackCommandSequence}`;
|
|
27507
|
-
return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${
|
|
27047
|
+
return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash14("sha256").update(monotonicId).digest("hex")}`;
|
|
27508
27048
|
};
|
|
27509
27049
|
return tool4({
|
|
27510
27050
|
description: CTX_REDUCE_DESCRIPTION,
|
|
@@ -27537,22 +27077,21 @@ function createCtxReduceTool(deps) {
|
|
|
27537
27077
|
}
|
|
27538
27078
|
const queued = typeof record.queued === "number" ? record.queued : 0;
|
|
27539
27079
|
const refusedStamps = Array.isArray(record.ctx_reduce_self_stamps) ? record.ctx_reduce_self_stamps.filter((tagNumber) => typeof tagNumber === "number" && Number.isInteger(tagNumber)) : [];
|
|
27540
|
-
const
|
|
27080
|
+
const refusedStampCount = new Set(refusedStamps).size;
|
|
27541
27081
|
const acceptedTagNumbers = Array.isArray(record.ctx_reduce_queued_tags) ? record.ctx_reduce_queued_tags.filter((tagNumber) => typeof tagNumber === "number" && Number.isInteger(tagNumber)) : null;
|
|
27542
27082
|
if (queued <= 0) {
|
|
27543
|
-
|
|
27544
|
-
|
|
27083
|
+
const alreadyStampedCount = acceptedTagNumbers ? new Set(acceptedTagNumbers).size : 0;
|
|
27084
|
+
const reply = formatCtxReduceReply(alreadyStampedCount, refusedStampCount);
|
|
27085
|
+
if (reply)
|
|
27086
|
+
return reply;
|
|
27545
27087
|
return "All requested tags were already queued or processed. No new action is needed.";
|
|
27546
27088
|
}
|
|
27547
|
-
|
|
27548
|
-
|
|
27549
|
-
|
|
27550
|
-
|
|
27551
|
-
|
|
27552
|
-
|
|
27553
|
-
}
|
|
27554
|
-
const acknowledgedDrop = acceptedTagNumbers ? formatIds(acceptedTagNumbers) : formatRawDropForAck(args.drop);
|
|
27555
|
-
return `Queued: drop ${acknowledgedDrop}.${refusedStampNote ? ` ${refusedStampNote}` : ""}`;
|
|
27089
|
+
const reportedTagNumbers = [
|
|
27090
|
+
...Array.isArray(record.held_tag_numbers) ? record.held_tag_numbers.filter((number) => typeof number === "number") : [],
|
|
27091
|
+
...Array.isArray(record.immediate_tag_numbers) ? record.immediate_tag_numbers.filter((number) => typeof number === "number") : []
|
|
27092
|
+
];
|
|
27093
|
+
const stampedCount = acceptedTagNumbers ? new Set(acceptedTagNumbers).size : reportedTagNumbers.length > 0 ? new Set(reportedTagNumbers).size : queued;
|
|
27094
|
+
return formatCtxReduceReply(stampedCount, refusedStampCount);
|
|
27556
27095
|
} catch (error) {
|
|
27557
27096
|
sessionLog2(sessionId, "ctx_reduce capability refusal", error);
|
|
27558
27097
|
return renderCapabilityRefusal("context_cleanup");
|
|
@@ -27572,21 +27111,9 @@ function createCtxReduceTool(deps) {
|
|
|
27572
27111
|
return `Error: Unknown tag(s) ${formatIds(unknownIds)}. Check available tags in conversation.`;
|
|
27573
27112
|
}
|
|
27574
27113
|
const ctxReduceSelfStampIds = new Set(allTags.filter((tag) => tag.toolName?.toLowerCase() === "ctx_reduce").map((tag) => tag.tagNumber));
|
|
27575
|
-
const
|
|
27114
|
+
const ctxReduceSelfStampCount = new Set(dropIds.filter((id) => ctxReduceSelfStampIds.has(id))).size;
|
|
27576
27115
|
dropIds = dropIds.filter((id) => !ctxReduceSelfStampIds.has(id));
|
|
27577
|
-
let protectedSet;
|
|
27578
|
-
if (deps.protectedSet) {
|
|
27579
|
-
protectedSet = typeof deps.protectedSet === "function" ? deps.protectedSet(sessionId) : deps.protectedSet;
|
|
27580
|
-
} else if (deps.getProtectionWindow) {
|
|
27581
|
-
protectedSet = deps.getProtectionWindow(sessionId).protectedTagNumbers;
|
|
27582
|
-
} else {
|
|
27583
|
-
protectedSet = getProtectionWindowForSession(deps.db, sessionId, deps.floor).protectedTagNumbers;
|
|
27584
|
-
}
|
|
27585
27116
|
const tagStatusMap = new Map(allTags.map((tag) => [tag.tagNumber, tag.status]));
|
|
27586
|
-
protectedSet = new Set([
|
|
27587
|
-
...protectedSet,
|
|
27588
|
-
...protectedToolTagNumbers(getActiveTagsBySession2(deps.db, sessionId), deps.protectedTools)
|
|
27589
|
-
]);
|
|
27590
27117
|
const inertWhitespaceTagNumbers = new Set(getInertWhitespaceAssistantTagsByNumbers2(deps.db, sessionId, dropIds).map((tag) => tag.tagNumber));
|
|
27591
27118
|
const inertDropIds = [
|
|
27592
27119
|
...new Set(dropIds.filter((id) => inertWhitespaceTagNumbers.has(id)))
|
|
@@ -27603,15 +27130,15 @@ function createCtxReduceTool(deps) {
|
|
|
27603
27130
|
if (conflicts.length > 0) {
|
|
27604
27131
|
return `Error: Conflicting operations — ${conflicts.join("; ")}.`;
|
|
27605
27132
|
}
|
|
27606
|
-
const
|
|
27133
|
+
const stampedCount = new Set(dropIds.filter((id) => !inertWhitespaceTagNumbers.has(id))).size;
|
|
27607
27134
|
dropIds = dropIds.filter((id) => !inertWhitespaceTagNumbers.has(id) && tagStatusMap.get(id) !== "dropped" && pendingMap.get(id) !== "drop");
|
|
27608
|
-
const skippedCount = preFilterDropCount - dropIds.length;
|
|
27609
27135
|
if (dropIds.length === 0) {
|
|
27610
|
-
const
|
|
27611
|
-
if (
|
|
27612
|
-
|
|
27613
|
-
|
|
27614
|
-
|
|
27136
|
+
const reply = formatCtxReduceReply(stampedCount, ctxReduceSelfStampCount);
|
|
27137
|
+
if (reply)
|
|
27138
|
+
return `${reply}${inertNote ? ` ${inertNote}` : ""}`;
|
|
27139
|
+
if (inertNote)
|
|
27140
|
+
return inertNote;
|
|
27141
|
+
return "All requested tags were already queued or processed. No new action is needed.";
|
|
27615
27142
|
}
|
|
27616
27143
|
try {
|
|
27617
27144
|
deps.db.transaction(() => {
|
|
@@ -27626,25 +27153,8 @@ function createCtxReduceTool(deps) {
|
|
|
27626
27153
|
}
|
|
27627
27154
|
const currentInputTokens = deps.getSessionTokens?.(sessionId) ?? getOrCreateSessionMeta(deps.db, sessionId).lastInputTokens;
|
|
27628
27155
|
updateSessionMeta(deps.db, sessionId, { lastNudgeTokens: currentInputTokens });
|
|
27629
|
-
const
|
|
27630
|
-
|
|
27631
|
-
const skippedNote = skippedCount > 0 ? ` ${skippedCount} requested tag${skippedCount === 1 ? " was" : "s were"} already queued and need no action.` : "";
|
|
27632
|
-
let heldSentence = "";
|
|
27633
|
-
if (deferredDropIds.length === 1) {
|
|
27634
|
-
heldSentence = `Held: §${deferredDropIds[0]} is inside the protected working set; it applies once newer work displaces it.`;
|
|
27635
|
-
} else if (deferredDropIds.length > 1) {
|
|
27636
|
-
heldSentence = `Held: ${deferredDropIds.map((id) => `§${id}`).join(", ")} are inside the protected working set; they apply once newer work displaces them.`;
|
|
27637
|
-
}
|
|
27638
|
-
if (immediateDropIds.length > 0 && heldSentence.length > 0) {
|
|
27639
|
-
return `Queued: drop ${formatIds(immediateDropIds)}.${skippedNote}${inertNote ? ` ${inertNote}` : ""} ${heldSentence}${ctxReduceSelfStampNote ? ` ${ctxReduceSelfStampNote}` : ""}`;
|
|
27640
|
-
}
|
|
27641
|
-
if (immediateDropIds.length > 0) {
|
|
27642
|
-
return `Queued: drop ${formatIds(immediateDropIds)}.${skippedNote}${inertNote ? ` ${inertNote}` : ""}${ctxReduceSelfStampNote ? ` ${ctxReduceSelfStampNote}` : ""}`;
|
|
27643
|
-
}
|
|
27644
|
-
if (heldSentence.length > 0) {
|
|
27645
|
-
return `${heldSentence}${skippedNote}${inertNote ? ` ${inertNote}` : ""}${ctxReduceSelfStampNote ? ` ${ctxReduceSelfStampNote}` : ""}`;
|
|
27646
|
-
}
|
|
27647
|
-
return `Queued: drop ${formatIds(dropIds)}.${skippedNote}${inertNote ? ` ${inertNote}` : ""}${ctxReduceSelfStampNote ? ` ${ctxReduceSelfStampNote}` : ""}`;
|
|
27156
|
+
const reply = formatCtxReduceReply(stampedCount, ctxReduceSelfStampCount);
|
|
27157
|
+
return `${reply}${inertNote ? ` ${inertNote}` : ""}`;
|
|
27648
27158
|
}
|
|
27649
27159
|
});
|
|
27650
27160
|
}
|
|
@@ -28312,4 +27822,4 @@ function applyHiddenSubagentTemperature(input, output, log) {
|
|
|
28312
27822
|
output.temperature = temperature;
|
|
28313
27823
|
}
|
|
28314
27824
|
|
|
28315
|
-
export { openOpenCodeDb, DREAMER_SYSTEM_PROMPT, runSessionProjectBackfill, SMART_NOTE_COMPILER_SYSTEM_PROMPT, createLiveSessionState, RETROSPECTIVE_MAX_USER_MESSAGE_CHARS, RETROSPECTIVE_MESSAGE_TRUNCATION_MARKER, OpenCodeRetrospectiveRawProvider, createDreamTaskExecutor, runManualDream, runDueTasksForProject,
|
|
27825
|
+
export { openOpenCodeDb, DREAMER_SYSTEM_PROMPT, runSessionProjectBackfill, SMART_NOTE_COMPILER_SYSTEM_PROMPT, createLiveSessionState, RETROSPECTIVE_MAX_USER_MESSAGE_CHARS, RETROSPECTIVE_MESSAGE_TRUNCATION_MARKER, OpenCodeRetrospectiveRawProvider, createDreamTaskExecutor, runManualDream, runDueTasksForProject, startDreamScheduleTimer, ensureProjectRegisteredFromOpenCodeDirectory, recordOpenCodeProvenInputFloor, resolveOpenCodeProvenInputFloor, resolveContextWindowGeometry, resolveContextLimit, resolveExecuteThresholdDetail, resolveModelKey, resolveSessionId, createScheduler, describeStorageUnavailability, scheduleClearAndReindex, resolveSessionCacheTtl, runEmbedHistoryDrain, pauseEmbedHistoryDrain, formatEmbedStatusText, getSessionProperties, getSessionCreatedInfo, getMessageUpdatedAssistantInfo, getMessageUpdatedInfo, getSessionErrorInfo, getMessageRemovedInfo, summarizeManualDream, createMagicContextCommandHandler, getLiveNotificationParams, createChatMessageHook, createEventHook, createCommandExecuteBeforeHook, createToolExecuteAfterHook, recordHiddenVariantWarning, buildStatusDetail, isDebugRpcEnabled, registerRpcHandlers, clearTransformDecisionSession, scheduleOpenCodeTransformDecisionWrite, maybeDeliverChannel2, armLatestThinkingRecovery, armBindingRecoverySafely, armLatestThinkingRecoveryFromError, lkgReplayLimit, measureLkgReplay, STORAGE_BUSY_MESSAGE, StorageBusyRefusalError, bindSystemDateRequestIdentity, bindSystemDateOutput, registerSystemDateRefresh, rustWrapupHistorianFields, UnmanagedOverWindowError, UnresolvedHistoryBoundaryError, clearMessageTokensCache, createTransform, createSubcModuleClient, createModuleToolBackends, createRustRefusalRecovery, createSystemPromptHashHandler, tryMessagesTransformLkgReplay, createMessagesTransformHandler, primaryOnlyToolIds, subagentToolRefusal, guardSubagentTools, hideSubagentTools, createCtxExpandTools, CTX_MEMORY_LIST_TOOL_NAME, CTX_MEMORY_ACTIONS, createCtxMemoryTools, createCtxMemoryListTools, CTX_NOTE_DESCRIPTION, withoutSmartNoteText, createCtxNoteTools, createCtxReduceTools, createCtxSearchTools, parameterDescriptionsFor, applyJsonSchemaParameterDescriptions, MagicContextRpcServer, subagentTemperature, applyHiddenSubagentTemperature };
|