@cortexkit/opencode-magic-context 0.49.52 → 0.49.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auto-search-worker.js +3 -3
- package/dist/chunk-embedding-write-worker.js +3 -4
- package/dist/{context-bkkd7br4.js → context-vx5gw5h2.js} +117 -80
- package/dist/{embedding-backfill-3wdjzrvs.js → embedding-backfill-2dvf3rcn.js} +4 -4
- package/dist/embedding-worker.js +2 -2
- package/dist/features/magic-context/compartment-embedding.d.ts.map +1 -1
- package/dist/features/magic-context/message-fts-session-filter.d.ts +1 -1
- package/dist/features/magic-context/message-fts-session-filter.d.ts.map +1 -1
- package/dist/features/magic-context/project-embedding-registry.d.ts +8 -0
- package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
- package/dist/features/magic-context/search.d.ts.map +1 -1
- package/dist/features/magic-context/storage-host-instruction-retention.d.ts +10 -3
- package/dist/features/magic-context/storage-host-instruction-retention.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta-persisted.d.ts +19 -0
- package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta.d.ts +1 -1
- package/dist/features/magic-context/storage-meta.d.ts.map +1 -1
- package/dist/features/magic-context/storage.d.ts +1 -1
- package/dist/features/magic-context/storage.d.ts.map +1 -1
- package/dist/features/magic-context/transform-decision-log.d.ts +1 -1
- package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
- package/dist/hooks/magic-context/active-anthropic-turn.d.ts +6 -0
- package/dist/hooks/magic-context/active-anthropic-turn.d.ts.map +1 -1
- package/dist/hooks/magic-context/compaction-marker-manager.d.ts +2 -1
- package/dist/hooks/magic-context/compaction-marker-manager.d.ts.map +1 -1
- package/dist/hooks/magic-context/emergency-drop.d.ts +75 -2
- package/dist/hooks/magic-context/emergency-drop.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 +14 -0
- package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
- package/dist/hooks/magic-context/heuristic-cleanup.d.ts +12 -0
- package/dist/hooks/magic-context/heuristic-cleanup.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook.d.ts.map +1 -1
- package/dist/hooks/magic-context/host-served-rows.d.ts +12 -2
- package/dist/hooks/magic-context/host-served-rows.d.ts.map +1 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts +10 -0
- package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
- package/dist/hooks/magic-context/latest-assistant-turn.d.ts +43 -0
- package/dist/hooks/magic-context/latest-assistant-turn.d.ts.map +1 -1
- package/dist/hooks/magic-context/latest-thinking-recovery.d.ts +102 -26
- package/dist/hooks/magic-context/latest-thinking-recovery.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts +18 -2
- package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
- package/dist/hooks/magic-context/pass-outcome.d.ts.map +1 -1
- package/dist/hooks/magic-context/pending-marker-rearm.d.ts +20 -0
- package/dist/hooks/magic-context/pending-marker-rearm.d.ts.map +1 -0
- package/dist/hooks/magic-context/priced-pass-sizing.d.ts +7 -0
- package/dist/hooks/magic-context/priced-pass-sizing.d.ts.map +1 -1
- package/dist/hooks/magic-context/routine-cleanup-decision.d.ts +11 -1
- package/dist/hooks/magic-context/routine-cleanup-decision.d.ts.map +1 -1
- package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
- package/dist/hooks/magic-context/served-check.d.ts +127 -0
- package/dist/hooks/magic-context/served-check.d.ts.map +1 -0
- package/dist/hooks/magic-context/signed-thinking-hold.d.ts +32 -4
- package/dist/hooks/magic-context/signed-thinking-hold.d.ts.map +1 -1
- package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +35 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/index-29ff546v.js +2747 -0
- package/dist/{index-8d7gkgjs.js → index-2vsd5064.js} +3 -3
- package/dist/{index-kaqs6h31.js → index-52x68mj4.js} +1 -1
- package/dist/{index-k2efzh9r.js → index-567xsm72.js} +7 -5
- package/dist/{index-q9m97m5g.js → index-5gqszjq9.js} +4 -4
- package/dist/{index-a4zmmhxs.js → index-5ptp2de1.js} +6 -8
- package/dist/{index-jjy5a5w0.js → index-6nqz8hsz.js} +16 -5
- package/dist/{index-a6aqpfp6.js → index-9mggb1nv.js} +403 -1
- package/dist/{index-kanfby7e.js → index-9n6mdfqy.js} +452 -442
- package/dist/{index-fxgaaptn.js → index-a3n2dczz.js} +8 -7
- package/dist/{index-g3j49m95.js → index-b6rdv8re.js} +1 -1
- package/dist/{index-qbda6a8k.js → index-by14cr73.js} +30 -19
- package/dist/{index-25tm250q.js → index-dhdv88e5.js} +1 -1
- package/dist/{index-4xpff2m1.js → index-eyr425dx.js} +820 -179
- package/dist/{index-x4h461yf.js → index-h62j8z2r.js} +1 -1
- package/dist/{index-xqhejxmd.js → index-pdh4tdcq.js} +1 -1
- package/dist/{index-9gs34125.js → index-sk6p6esd.js} +3777 -2544
- package/dist/{index-pb8ysnq2.js → index-sv5tn72j.js} +1 -1
- package/dist/{index-bamnjp2t.js → index-sx1sppd6.js} +11 -7
- package/dist/{index-x7jcqpy6.js → index-tx8nfw85.js} +539 -29
- package/dist/{index-42n4fhxy.js → index-xj5bap1r.js} +61 -54
- package/dist/{index-rbs27k1d.js → index-xstbytjn.js} +1 -1
- package/dist/{index-0jc25yjf.js → index-xvtjwhm6.js} +3 -3
- package/dist/{index-qtpkkzan.js → index-yamsmkmh.js} +4 -4
- package/dist/index.js +87 -68
- package/dist/{message-index-bounded-71b75npz.js → message-index-bounded-xav3h8qe.js} +5 -6
- package/dist/migration-worker.js +3 -4
- package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
- package/dist/plugin/messages-transform.d.ts +6 -0
- package/dist/plugin/messages-transform.d.ts.map +1 -1
- package/dist/{project-embedding-registry-5dwh5zfn.js → project-embedding-registry-f2azrq24.js} +5 -3
- package/dist/raw-ordinal-warmup-worker.js +4 -4
- package/dist/{read-session-chunk-bfv831yx.js → read-session-chunk-70aam2c1.js} +4 -5
- package/dist/{recomp-orchestrator-8gj1b7pz.js → recomp-orchestrator-wbm4kpq9.js} +15 -16
- package/dist/{render-b3zcz9x4.js → render-73vrt30h.js} +10 -11
- package/dist/{search-archive-dp9afcv1.js → search-archive-ew4c3bsw.js} +7 -8
- package/dist/{search-y3w590tn.js → search-jfwb4ms3.js} +14 -15
- package/dist/shared/test-open-files.d.ts +17 -0
- package/dist/shared/test-open-files.d.ts.map +1 -0
- package/dist/{storage-tags-kdb4qsyq.js → storage-tags-arnkn5t1.js} +4 -2
- package/dist/tools/ctx-expand/search-archive.d.ts.map +1 -1
- package/dist/{transform-postprocess-phase-8awze16a.js → transform-postprocess-phase-mt4dcbhd.js} +16 -17
- package/dist/v2/auto-search-worker.js +3 -3
- package/dist/v2/chunk-embedding-write-worker.js +3 -4
- package/dist/v2/{context-99v7x7fm.js → context-13er940g.js} +1147 -467
- package/dist/v2/{embedding-backfill-x1zpc04f.js → embedding-backfill-48qbnh7p.js} +4 -4
- package/dist/v2/embedding-worker.js +2 -2
- package/dist/v2/fold/instruction-supersession.d.ts.map +1 -1
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/{message-index-bounded-2pev910h.js → message-index-bounded-sw8hyqw1.js} +5 -6
- package/dist/v2/migration-worker.js +3 -4
- package/dist/v2/{project-embedding-registry-v2fxrs8b.js → project-embedding-registry-kwahtjgg.js} +5 -3
- package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
- package/dist/v2/{read-session-chunk-a454a4d2.js → read-session-chunk-nqkn0yb4.js} +4 -5
- package/dist/v2/{recomp-orchestrator-03fskpsa.js → recomp-orchestrator-cdkfynz4.js} +15 -16
- package/dist/v2/{render-cryx4xsj.js → render-a7j6fqbd.js} +10 -11
- package/dist/v2/{search-2qj4w7rw.js → search-8dc9ex0a.js} +13 -14
- package/dist/v2/{search-archive-xw2rsq81.js → search-archive-3a36887a.js} +7 -8
- package/dist/v2/{server-kreheyw5.js → server-0ayyh3mx.js} +5 -7
- package/dist/v2/{server-t8n27rbt.js → server-4x0xq8a1.js} +1 -1
- package/dist/v2/{server-kaqs6h31.js → server-52x68mj4.js} +1 -1
- package/dist/v2/{server-cpstyzvy.js → server-578pc4tf.js} +3 -3
- package/dist/v2/{server-sb55ddgn.js → server-5p0bjk3y.js} +1 -1
- package/dist/v2/{server-58h6rrnx.js → server-6k0rnwbd.js} +1 -1
- package/dist/v2/{server-y5cma2j1.js → server-79tbtk5w.js} +8 -7
- package/dist/v2/{server-b3h8vqa6.js → server-7rmf6a57.js} +538 -28
- package/dist/v2/{server-xjzx27w2.js → server-7waad75d.js} +29 -18
- package/dist/v2/{server-wq9y9a03.js → server-96g41nad.js} +61 -54
- package/dist/v2/{server-txdsx71h.js → server-avfc9ezb.js} +4 -4
- package/dist/v2/{server-ww7xbxxf.js → server-b0357as4.js} +357 -1
- package/dist/v2/{server-qsvm6w79.js → server-beydmd68.js} +3763 -2484
- package/dist/v2/server-gge95a03.js +2687 -0
- package/dist/v2/{server-kfw4m268.js → server-jwydbwcx.js} +1 -1
- package/dist/v2/{server-brsx45r6.js → server-kwtnrhv3.js} +1 -1
- package/dist/v2/{server-4h4acntc.js → server-rpmkz5ta.js} +11 -7
- package/dist/v2/{server-0ms13pc8.js → server-rz6g5xne.js} +16 -5
- package/dist/v2/{server-dkfs58nq.js → server-v817sf79.js} +1 -1
- package/dist/v2/{server-vjadwb3j.js → server-ycvqg2s3.js} +3 -3
- package/dist/v2/server.js +4 -4
- package/dist/v2/{storage-tags-rzv7y0n3.js → storage-tags-19da4c0m.js} +4 -2
- package/dist/v2/{v2-archive-reader-3575hw8s.js → v2-archive-reader-jm3d7ccj.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-shzv6t4v.js → wrapup-orchestrator-xnqq81c4.js} +18 -18
- package/dist/{v2-archive-reader-75fdm0te.js → v2-archive-reader-9bbfh131.js} +1 -1
- package/dist/{wrapup-orchestrator-e0z7nvnx.js → wrapup-orchestrator-svhee0fn.js} +16 -17
- package/package.json +1 -1
- package/src/shared/escalation-bands.test.ts +16 -1
- package/src/shared/sqlite-placeholders.test.ts +103 -0
- package/src/shared/storage-file-mutex-review.test.ts +5 -7
- package/src/shared/test-open-files.test.ts +194 -0
- package/src/shared/test-open-files.ts +71 -0
- package/dist/index-bkg4hdyh.js +0 -3865
- package/dist/index-d9vfe7xq.js +0 -16
- package/dist/index-hsv31e69.js +0 -405
- package/dist/v2/server-d9vfe7xq.js +0 -16
- package/dist/v2/server-kgq2e2hh.js +0 -361
- package/dist/v2/server-rcchadw0.js +0 -3865
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
resolveLegacyConfigSources,
|
|
8
8
|
getProtectedTokensTierOverrides,
|
|
9
9
|
loadPluginConfigDetailed
|
|
10
|
-
} from "./server-
|
|
10
|
+
} from "./server-5p0bjk3y.js";
|
|
11
11
|
import {
|
|
12
12
|
getHarness2,
|
|
13
13
|
harnessOwnsOpenCodeStore2
|
|
@@ -54,10 +54,12 @@ import {
|
|
|
54
54
|
promptSurfaceConfigIdentity,
|
|
55
55
|
resolveModelConfigValue,
|
|
56
56
|
resolvePromptSurface,
|
|
57
|
+
normalizeProtectedToolName,
|
|
58
|
+
mergeProtectedTools,
|
|
57
59
|
DEFAULT_HISTORIAN_TIMEOUT_MS,
|
|
58
60
|
DEFAULT_LOCAL_EMBEDDING_MODEL,
|
|
59
61
|
DREAM_TASK_PROMOTION_DEFAULTS
|
|
60
|
-
} from "./server-
|
|
62
|
+
} from "./server-rz6g5xne.js";
|
|
61
63
|
import {
|
|
62
64
|
CANONICAL_DREAM_TASKS,
|
|
63
65
|
DREAM_TASK_CAPABILITIES,
|
|
@@ -175,6 +177,7 @@ import {
|
|
|
175
177
|
trimMemoriesToBudgetV2,
|
|
176
178
|
renderMemoryBlockV2,
|
|
177
179
|
stripMemoryMuralBlock,
|
|
180
|
+
servedHeadTexts,
|
|
178
181
|
materializeM0,
|
|
179
182
|
hydrateCachedM0Mural,
|
|
180
183
|
resetPrefixTrimFallbackState,
|
|
@@ -215,7 +218,7 @@ import {
|
|
|
215
218
|
startCompartmentAgent,
|
|
216
219
|
setRecompStarting2,
|
|
217
220
|
setRecompTerminal2
|
|
218
|
-
} from "./server-
|
|
221
|
+
} from "./server-96g41nad.js";
|
|
219
222
|
import {
|
|
220
223
|
resolveHistorianModel2
|
|
221
224
|
} from "./server-5kym00ag.js";
|
|
@@ -315,114 +318,9 @@ import {
|
|
|
315
318
|
formatChannel2Evaluation,
|
|
316
319
|
buildChannel2Reminder,
|
|
317
320
|
buildChannel1Reminder,
|
|
318
|
-
estimateEmergencyDropReclaimTokens,
|
|
319
|
-
planEmergencyDrop,
|
|
320
|
-
measureEmergencyTag,
|
|
321
|
-
queuePendingOp,
|
|
322
|
-
getPendingOps,
|
|
323
|
-
hasPendingDropOps,
|
|
324
|
-
getPendingOpsCount,
|
|
325
|
-
clearPendingOps,
|
|
326
|
-
removePendingOp,
|
|
327
|
-
updateTagByteSize2,
|
|
328
|
-
getRecentTagOwnerMessageIds2,
|
|
329
|
-
AGE_RECLAIM_MIN_TOKENS2,
|
|
330
|
-
getOldestActiveUnprotectedToolTags2,
|
|
331
|
-
getActiveToolTagsForAgeReclaim2,
|
|
332
|
-
getTriggerTagTokenUpperBound2,
|
|
333
|
-
getActiveTagTokenTotalsByMessage2,
|
|
334
|
-
updateTagTokenCount2,
|
|
335
|
-
tryGetReasoningTokenEstimatesByMessage2,
|
|
336
|
-
TagOwnerSummaryNotReady2,
|
|
337
|
-
cachedTagOwnerRatios2,
|
|
338
|
-
tagOwnerWarmupState2,
|
|
339
|
-
installTagOwnerDelta2,
|
|
340
|
-
installTagOwnerSummary2,
|
|
341
|
-
isTagOwnerSummaryReady2,
|
|
342
|
-
tagTokenCountIsNull2,
|
|
343
|
-
backfillTagTokenCounts2,
|
|
344
|
-
insertTag2,
|
|
345
|
-
updateTagStatus2,
|
|
346
|
-
markTagDropped2,
|
|
347
|
-
markWhitespaceAssistantTagInert2,
|
|
348
|
-
getInertWhitespaceAssistantTags2,
|
|
349
|
-
getInertWhitespaceAssistantTagsByNumbers2,
|
|
350
|
-
updateTagDropMode2,
|
|
351
|
-
updateCavemanDepth2,
|
|
352
|
-
updateTagMessageId2,
|
|
353
|
-
markTagsCompactedByMessageIds2,
|
|
354
|
-
getMaxTagNumberBySession2,
|
|
355
|
-
getTagNumberByMessageId2,
|
|
356
|
-
getAssignableTagNumberByMessageId2,
|
|
357
|
-
deriveTagLoadFloor2,
|
|
358
|
-
getTagsBySession2,
|
|
359
|
-
getActiveTagsBySession2,
|
|
360
|
-
getTailHygieneTags2,
|
|
361
|
-
getDroppedTagsBySession2,
|
|
362
|
-
getTagsByNumbers2,
|
|
363
|
-
getNewestToolTagNumbers2,
|
|
364
|
-
getDroppedTagsByNumbers2,
|
|
365
|
-
getMaxDroppedTagNumber2,
|
|
366
|
-
getTagById2,
|
|
367
|
-
getToolTagNumberByOwner2,
|
|
368
|
-
getNullOwnerToolTag2,
|
|
369
|
-
adoptNullOwnerToolTag2,
|
|
370
|
-
getCandidateToolOwners2,
|
|
371
|
-
pickNearestPriorOwner2
|
|
372
|
-
} from "./server-rcchadw0.js";
|
|
373
|
-
import {
|
|
374
|
-
textMentionsRecentCommit,
|
|
375
|
-
hasMeaningfulUserText2,
|
|
376
|
-
extractTexts2,
|
|
377
|
-
extractToolCallSummaries,
|
|
378
|
-
getTokenizerNativeMemoryStats,
|
|
379
|
-
preloadTokenizer,
|
|
380
|
-
estimateTokens,
|
|
381
|
-
estimateFixedPromptTokens,
|
|
382
|
-
normalizeText
|
|
383
|
-
} from "./server-3jc6qmdz.js";
|
|
384
|
-
import {
|
|
385
|
-
stableStringify,
|
|
386
|
-
getTableColumnNames,
|
|
387
|
-
getTemporalDecisions,
|
|
388
|
-
observeTemporalDecisions,
|
|
389
|
-
freezeTemporalDecisions,
|
|
390
|
-
tagRevisionKey,
|
|
391
|
-
tagIdentityRevisionKey
|
|
392
|
-
} from "./server-ww7xbxxf.js";
|
|
393
|
-
import {
|
|
394
|
-
resolveOpenCodeDbPath,
|
|
395
|
-
assertOpenCodeStoreGeneration,
|
|
396
|
-
openCodeDbPathExists,
|
|
397
|
-
recordOpenCodeDbReadFailure,
|
|
398
|
-
clearOpenCodeDbReadFailure,
|
|
399
|
-
claimOpenCodeDbDiagnosticOnce
|
|
400
|
-
} from "./server-2ra6pwf3.js";
|
|
401
|
-
import {
|
|
402
|
-
openCodeDbExists,
|
|
403
|
-
withReadOnlySessionDb,
|
|
404
|
-
latestPersistedMessageForRecovery,
|
|
405
|
-
latestRealUserTurnIdFromOpenCodeDb,
|
|
406
|
-
getMessageTimesFromOpenCodeDb,
|
|
407
|
-
findLastAssistantModelFromOpenCodeDb
|
|
408
|
-
} from "./server-7vrtk78d.js";
|
|
409
|
-
import {
|
|
410
|
-
askAnswerLines,
|
|
411
|
-
estimateTrueRawMessageTokens,
|
|
412
|
-
stripSystemInjection,
|
|
413
|
-
isTextPart,
|
|
414
|
-
isToolPartWithOutput,
|
|
415
|
-
isFilePart,
|
|
416
|
-
toolPartHasUserAnswer,
|
|
417
|
-
DreamTokenBudgetExceeded,
|
|
418
|
-
createDreamTokenBudget,
|
|
419
|
-
needsBlockedRead,
|
|
420
|
-
recordToolParameters,
|
|
421
|
-
createDroppedInputGuard,
|
|
422
|
-
assertExecutableToolInput,
|
|
423
|
-
isEditTool,
|
|
424
321
|
createFinalWireIncompleteLogger,
|
|
425
322
|
decodeMergedReasoningParts,
|
|
323
|
+
readFrozenMergedReasoningParts,
|
|
426
324
|
MAX_EXECUTE_THRESHOLD,
|
|
427
325
|
escalationBands,
|
|
428
326
|
HYGIENE_PROVIDER_UNITS_VERSION,
|
|
@@ -498,6 +396,9 @@ import {
|
|
|
498
396
|
compactionOffFrozenThinkingIds,
|
|
499
397
|
getThinkingBindingRecoveryTarget,
|
|
500
398
|
armThinkingBindingRecovery,
|
|
399
|
+
noteBindingRecoveryAwaitingClear,
|
|
400
|
+
bindingRecoveryAwaitingClear,
|
|
401
|
+
retryBindingRecoveryClear,
|
|
501
402
|
clearThinkingBindingRecoveryIf,
|
|
502
403
|
getMergedReasoningStrippedIds,
|
|
503
404
|
addMergedReasoningStrippedIds,
|
|
@@ -569,11 +470,125 @@ import {
|
|
|
569
470
|
opencodeReasoningBudgetCutoff,
|
|
570
471
|
describeFinalWireTail,
|
|
571
472
|
estimatePartImageTokens,
|
|
473
|
+
openCode2ThinkingPayload,
|
|
572
474
|
estimateMessageTokens,
|
|
573
475
|
wireContentBytes,
|
|
574
476
|
createFinalWireUsageTracker,
|
|
575
477
|
estimateFinalWireInputTokens,
|
|
576
478
|
estimateAppendedWireTokens,
|
|
479
|
+
estimateEmergencyDropReclaimTokens,
|
|
480
|
+
planEmergencyDrop,
|
|
481
|
+
measureEmergencyTag,
|
|
482
|
+
snapshotEmergencyServedMass,
|
|
483
|
+
tagsSinceReading,
|
|
484
|
+
emergencyServedMassRemovedSince,
|
|
485
|
+
queuePendingOp,
|
|
486
|
+
getPendingOps,
|
|
487
|
+
hasPendingDropOps,
|
|
488
|
+
getPendingOpsCount,
|
|
489
|
+
clearPendingOps,
|
|
490
|
+
removePendingOp,
|
|
491
|
+
updateTagByteSize2,
|
|
492
|
+
getRecentTagOwnerMessageIds2,
|
|
493
|
+
AGE_RECLAIM_MIN_TOKENS2,
|
|
494
|
+
getOldestActiveUnprotectedToolTags2,
|
|
495
|
+
getActiveToolTagsForAgeReclaim2,
|
|
496
|
+
getTriggerTagTokenUpperBound2,
|
|
497
|
+
getActiveTagTokenTotalsByMessage2,
|
|
498
|
+
updateTagTokenCount2,
|
|
499
|
+
tryGetReasoningTokenEstimatesByMessage2,
|
|
500
|
+
TagOwnerSummaryNotReady2,
|
|
501
|
+
cachedTagOwnerRatios2,
|
|
502
|
+
tagOwnerWarmupState2,
|
|
503
|
+
installTagOwnerDelta2,
|
|
504
|
+
installTagOwnerSummary2,
|
|
505
|
+
isTagOwnerSummaryReady2,
|
|
506
|
+
tagTokenCountIsNull2,
|
|
507
|
+
backfillTagTokenCounts2,
|
|
508
|
+
insertTag2,
|
|
509
|
+
updateTagStatus2,
|
|
510
|
+
markTagDropped2,
|
|
511
|
+
markWhitespaceAssistantTagInert2,
|
|
512
|
+
getInertWhitespaceAssistantTags2,
|
|
513
|
+
getInertWhitespaceAssistantTagsByNumbers2,
|
|
514
|
+
updateTagDropMode2,
|
|
515
|
+
updateCavemanDepth2,
|
|
516
|
+
updateTagMessageId2,
|
|
517
|
+
markTagsCompactedByMessageIds2,
|
|
518
|
+
getMaxTagNumberBySession2,
|
|
519
|
+
getTagNumberByMessageId2,
|
|
520
|
+
getAssignableTagNumberByMessageId2,
|
|
521
|
+
deriveTagLoadFloor2,
|
|
522
|
+
getTagsBySession2,
|
|
523
|
+
getActiveTagsBySession2,
|
|
524
|
+
getTailHygieneTags2,
|
|
525
|
+
getDroppedTagsBySession2,
|
|
526
|
+
getTagsByNumbers2,
|
|
527
|
+
getNewestToolTagNumbers2,
|
|
528
|
+
getDroppedTagsByNumbers2,
|
|
529
|
+
getMaxDroppedTagNumber2,
|
|
530
|
+
getTagById2,
|
|
531
|
+
getToolTagNumberByOwner2,
|
|
532
|
+
getNullOwnerToolTag2,
|
|
533
|
+
adoptNullOwnerToolTag2,
|
|
534
|
+
getCandidateToolOwners2,
|
|
535
|
+
pickNearestPriorOwner2
|
|
536
|
+
} from "./server-beydmd68.js";
|
|
537
|
+
import {
|
|
538
|
+
textMentionsRecentCommit,
|
|
539
|
+
hasMeaningfulUserText2,
|
|
540
|
+
extractTexts2,
|
|
541
|
+
extractToolCallSummaries,
|
|
542
|
+
getTokenizerNativeMemoryStats,
|
|
543
|
+
preloadTokenizer,
|
|
544
|
+
estimateTokens,
|
|
545
|
+
estimateFixedPromptTokens,
|
|
546
|
+
normalizeText
|
|
547
|
+
} from "./server-3jc6qmdz.js";
|
|
548
|
+
import {
|
|
549
|
+
BoundedSessionMap,
|
|
550
|
+
stableStringify,
|
|
551
|
+
recordToolDefinitionSet,
|
|
552
|
+
getCurrentToolSetHash,
|
|
553
|
+
getMeasuredToolDefinitionTokens,
|
|
554
|
+
getTableColumnNames,
|
|
555
|
+
getTemporalDecisions,
|
|
556
|
+
observeTemporalDecisions,
|
|
557
|
+
freezeTemporalDecisions,
|
|
558
|
+
tagRevisionKey,
|
|
559
|
+
tagIdentityRevisionKey
|
|
560
|
+
} from "./server-b0357as4.js";
|
|
561
|
+
import {
|
|
562
|
+
resolveOpenCodeDbPath,
|
|
563
|
+
assertOpenCodeStoreGeneration,
|
|
564
|
+
openCodeDbPathExists,
|
|
565
|
+
recordOpenCodeDbReadFailure,
|
|
566
|
+
clearOpenCodeDbReadFailure,
|
|
567
|
+
claimOpenCodeDbDiagnosticOnce
|
|
568
|
+
} from "./server-2ra6pwf3.js";
|
|
569
|
+
import {
|
|
570
|
+
openCodeDbExists,
|
|
571
|
+
withReadOnlySessionDb,
|
|
572
|
+
latestPersistedMessageForRecovery,
|
|
573
|
+
latestRealUserTurnIdFromOpenCodeDb,
|
|
574
|
+
getMessageTimesFromOpenCodeDb,
|
|
575
|
+
findLastAssistantModelFromOpenCodeDb
|
|
576
|
+
} from "./server-7vrtk78d.js";
|
|
577
|
+
import {
|
|
578
|
+
askAnswerLines,
|
|
579
|
+
estimateTrueRawMessageTokens,
|
|
580
|
+
stripSystemInjection,
|
|
581
|
+
isTextPart,
|
|
582
|
+
isToolPartWithOutput,
|
|
583
|
+
isFilePart,
|
|
584
|
+
toolPartHasUserAnswer,
|
|
585
|
+
DreamTokenBudgetExceeded,
|
|
586
|
+
createDreamTokenBudget,
|
|
587
|
+
needsBlockedRead,
|
|
588
|
+
recordToolParameters,
|
|
589
|
+
createDroppedInputGuard,
|
|
590
|
+
assertExecutableToolInput,
|
|
591
|
+
isEditTool,
|
|
577
592
|
SKELETON_REAL_INPUT_MAX_BYTES,
|
|
578
593
|
partHasCompletedResult,
|
|
579
594
|
extractToolCallObservation,
|
|
@@ -600,18 +615,12 @@ import {
|
|
|
600
615
|
readRawSessionMessageOrdinalById2,
|
|
601
616
|
readSessionChunk2,
|
|
602
617
|
readRawSessionSeedTail2
|
|
603
|
-
} from "./server-
|
|
604
|
-
import {
|
|
605
|
-
BoundedSessionMap,
|
|
606
|
-
recordToolDefinitionSet,
|
|
607
|
-
getCurrentToolSetHash,
|
|
608
|
-
getMeasuredToolDefinitionTokens
|
|
609
|
-
} from "./server-kgq2e2hh.js";
|
|
618
|
+
} from "./server-gge95a03.js";
|
|
610
619
|
import {
|
|
611
620
|
cleanSearchText,
|
|
612
621
|
matchedSearchSnippet,
|
|
613
622
|
getLastIndexedOrdinal
|
|
614
|
-
} from "./server-
|
|
623
|
+
} from "./server-jwydbwcx.js";
|
|
615
624
|
import"./server-966dq3pd.js";
|
|
616
625
|
import {
|
|
617
626
|
getMessageIndexEpoch,
|
|
@@ -638,7 +647,7 @@ import {
|
|
|
638
647
|
resolveMemoriesByIdsForSearch2,
|
|
639
648
|
unifiedSearch2,
|
|
640
649
|
formatSearchResults2
|
|
641
|
-
} from "./server-
|
|
650
|
+
} from "./server-7waad75d.js";
|
|
642
651
|
import {
|
|
643
652
|
embedPauseBySession,
|
|
644
653
|
embedRunStateBySession,
|
|
@@ -745,6 +754,16 @@ import {
|
|
|
745
754
|
noteLkgHealthyPrefix,
|
|
746
755
|
lkgRecoveryReplayUnproven,
|
|
747
756
|
lkgRecoveryEntryUnproven,
|
|
757
|
+
beginServedRequest,
|
|
758
|
+
noteServedPassPermission,
|
|
759
|
+
noteServedModel,
|
|
760
|
+
noteServedReplay,
|
|
761
|
+
noteServedHostInput,
|
|
762
|
+
noteServedRefusal,
|
|
763
|
+
countServedRefusal,
|
|
764
|
+
dropServedRecord,
|
|
765
|
+
forgetServedRecord,
|
|
766
|
+
commitServedRequest,
|
|
748
767
|
lkgInputIdentity,
|
|
749
768
|
beginLkgPass,
|
|
750
769
|
visitMessageContentFields,
|
|
@@ -753,6 +772,7 @@ import {
|
|
|
753
772
|
signatureForFields,
|
|
754
773
|
exactReusablePrefix,
|
|
755
774
|
incrementalLkgContentDigests,
|
|
775
|
+
lkgContentDigest,
|
|
756
776
|
lkgSlotRejection,
|
|
757
777
|
captureSlot,
|
|
758
778
|
getInMemorySlot,
|
|
@@ -773,7 +793,7 @@ import {
|
|
|
773
793
|
saveSourceContent,
|
|
774
794
|
replaceSourceContent,
|
|
775
795
|
getSourceContents
|
|
776
|
-
} from "./server-
|
|
796
|
+
} from "./server-7rmf6a57.js";
|
|
777
797
|
import {
|
|
778
798
|
startBootDeadline,
|
|
779
799
|
getUnconfirmedMigrationHolders,
|
|
@@ -789,7 +809,7 @@ import {
|
|
|
789
809
|
openDatabaseAsync,
|
|
790
810
|
isDatabasePersisted,
|
|
791
811
|
getDatabasePersistenceError
|
|
792
|
-
} from "./server-
|
|
812
|
+
} from "./server-0ayyh3mx.js";
|
|
793
813
|
import {
|
|
794
814
|
V2_MEMORY_CATEGORIES,
|
|
795
815
|
CATEGORY_PRIORITY
|
|
@@ -802,7 +822,7 @@ import {
|
|
|
802
822
|
resolveStoredPathWorkspaceIdentity,
|
|
803
823
|
storedPathBelongsToWorkspace,
|
|
804
824
|
computeWorkspaceEpochFingerprint
|
|
805
|
-
} from "./server-
|
|
825
|
+
} from "./server-6k0rnwbd.js";
|
|
806
826
|
import {
|
|
807
827
|
gaDatabasePath2,
|
|
808
828
|
RAW_MESSAGE_TYPES2,
|
|
@@ -837,7 +857,7 @@ import {
|
|
|
837
857
|
createPrimer,
|
|
838
858
|
updatePrimerSupport,
|
|
839
859
|
updatePrimerAnswer
|
|
840
|
-
} from "./server-
|
|
860
|
+
} from "./server-4x0xq8a1.js";
|
|
841
861
|
import {
|
|
842
862
|
deriveTriggerBudget2,
|
|
843
863
|
deriveHistorianChunkTokens2,
|
|
@@ -870,7 +890,7 @@ import {
|
|
|
870
890
|
embedSessionCompartmentChunks2,
|
|
871
891
|
getEmbeddingCoverageStatus2,
|
|
872
892
|
getAutoEmbeddingSessionCoverage2
|
|
873
|
-
} from "./server-
|
|
893
|
+
} from "./server-rpmkz5ta.js";
|
|
874
894
|
import {
|
|
875
895
|
GIT_SWEEP_LEASE_RENEWAL_MS,
|
|
876
896
|
acquireGitSweepLease,
|
|
@@ -890,10 +910,10 @@ import {
|
|
|
890
910
|
getCachedLocalEmbeddingPooling,
|
|
891
911
|
preflightLocalEmbeddingPooling,
|
|
892
912
|
getLocalEmbeddingNativeMemoryStats
|
|
893
|
-
} from "./server-
|
|
913
|
+
} from "./server-kwtnrhv3.js";
|
|
894
914
|
import {
|
|
895
915
|
cosineSimilarity
|
|
896
|
-
} from "./server-
|
|
916
|
+
} from "./server-ycvqg2s3.js";
|
|
897
917
|
import {
|
|
898
918
|
computeCueContentHash,
|
|
899
919
|
hasMuralCueColumns,
|
|
@@ -938,7 +958,7 @@ import {
|
|
|
938
958
|
readGitFileChangeTimesSince,
|
|
939
959
|
verificationFileExists,
|
|
940
960
|
normalizeVerificationFiles
|
|
941
|
-
} from "./server-
|
|
961
|
+
} from "./server-v817sf79.js";
|
|
942
962
|
import {
|
|
943
963
|
registerNotificationSink2,
|
|
944
964
|
pushNotification2,
|
|
@@ -975,14 +995,14 @@ import {
|
|
|
975
995
|
renderMessageByOrdinal2,
|
|
976
996
|
renderVerboseRangeForTool2,
|
|
977
997
|
renderItemByTag2
|
|
978
|
-
} from "./server-
|
|
979
|
-
import"./server-
|
|
998
|
+
} from "./server-avfc9ezb.js";
|
|
999
|
+
import"./server-52x68mj4.js";
|
|
980
1000
|
import {
|
|
981
1001
|
readV2ArchiveOffThread2
|
|
982
|
-
} from "./server-
|
|
1002
|
+
} from "./server-578pc4tf.js";
|
|
983
1003
|
import {
|
|
984
1004
|
renderSearchArchiveOffThread2
|
|
985
|
-
} from "./server-
|
|
1005
|
+
} from "./server-79tbtk5w.js";
|
|
986
1006
|
import {
|
|
987
1007
|
markHostInstructionRow,
|
|
988
1008
|
hostInstructionRow,
|
|
@@ -1008,10 +1028,6 @@ import {
|
|
|
1008
1028
|
import {
|
|
1009
1029
|
computeNormalizedHash
|
|
1010
1030
|
} from "./server-2bvekkfy.js";
|
|
1011
|
-
import {
|
|
1012
|
-
normalizeProtectedToolName,
|
|
1013
|
-
mergeProtectedTools
|
|
1014
|
-
} from "./server-d9vfe7xq.js";
|
|
1015
1031
|
import {
|
|
1016
1032
|
canonicalModelIdentity,
|
|
1017
1033
|
piModelRefToCanonical,
|
|
@@ -2607,7 +2623,8 @@ var canonicalReasons = new Set([
|
|
|
2607
2623
|
"coverage_fold",
|
|
2608
2624
|
"profile_transition",
|
|
2609
2625
|
"host_compaction",
|
|
2610
|
-
"tag_identity_repair"
|
|
2626
|
+
"tag_identity_repair",
|
|
2627
|
+
"latest_turn_thinking_removed"
|
|
2611
2628
|
]);
|
|
2612
2629
|
var piReasonAliases = {
|
|
2613
2630
|
project_memory_change: "project_memory_epoch",
|
|
@@ -2647,11 +2664,12 @@ function normalizeMaterializeReason(harness, reason, rematerialized) {
|
|
|
2647
2664
|
function writeRustTransformDecision(args) {
|
|
2648
2665
|
const rawDecision = args.decision.trim();
|
|
2649
2666
|
const decisionUpper = rawDecision.toUpperCase();
|
|
2650
|
-
const
|
|
2667
|
+
const scheduled = decisionUpper === "HARD" || decisionUpper === "MIGRATE_HARD" ? { decision: "execute", materialized: true, bustedThisPass: true } : decisionUpper === "SOFT" || decisionUpper === "EXECUTE" || args.materializeReason === "ttl_idle" ? { decision: "execute", materialized: false, bustedThisPass: true } : decisionUpper === "SOFT+" ? { decision: "defer", materialized: false, bustedThisPass: false } : {
|
|
2651
2668
|
decision: rawDecision.toLowerCase() || "unknown",
|
|
2652
2669
|
materialized: false,
|
|
2653
2670
|
bustedThisPass: false
|
|
2654
2671
|
};
|
|
2672
|
+
const mapped = args.materializeReason === "latest_turn_thinking_removed" ? { ...scheduled, bustedThisPass: true } : scheduled;
|
|
2655
2673
|
pendingDecisionBySession.set(args.sessionId, {
|
|
2656
2674
|
tsMs: args.tsMs ?? Date.now(),
|
|
2657
2675
|
decision: mapped.decision,
|
|
@@ -7198,6 +7216,66 @@ function latestAssistantTurnStart(messages) {
|
|
|
7198
7216
|
function latestAssistantTurnMessages(messages) {
|
|
7199
7217
|
return new Set(messages.slice(latestAssistantTurnStart(messages)));
|
|
7200
7218
|
}
|
|
7219
|
+
function isSentAssistantMessage(message) {
|
|
7220
|
+
if (!isRecord(message) || role(message) !== "assistant")
|
|
7221
|
+
return false;
|
|
7222
|
+
const parts = content(message);
|
|
7223
|
+
if (!Array.isArray(parts) || parts.length === 0)
|
|
7224
|
+
return false;
|
|
7225
|
+
if (message.stopReason === "error" || message.stopReason === "aborted")
|
|
7226
|
+
return false;
|
|
7227
|
+
const error = isRecord(message.info) ? message.info.error : undefined;
|
|
7228
|
+
if (error === undefined || error === null)
|
|
7229
|
+
return true;
|
|
7230
|
+
return isRecord(error) && error.name === "MessageAbortedError" && parts.some((part) => isRecord(part) && part.type !== "step-start" && part.type !== "reasoning");
|
|
7231
|
+
}
|
|
7232
|
+
var PI_USER_ON_WIRE_ROLES = new Set([
|
|
7233
|
+
"user",
|
|
7234
|
+
"developer",
|
|
7235
|
+
"custom",
|
|
7236
|
+
"hookMessage",
|
|
7237
|
+
"bashExecution",
|
|
7238
|
+
"pythonExecution",
|
|
7239
|
+
"fileMention",
|
|
7240
|
+
"branchSummary",
|
|
7241
|
+
"compactionSummary"
|
|
7242
|
+
]);
|
|
7243
|
+
var TOOL_RESULT_TYPES = new Set(["tool_result", "toolResult", "tool-result"]);
|
|
7244
|
+
function isUserMessageOnWire(message) {
|
|
7245
|
+
if (!isRecord(message))
|
|
7246
|
+
return false;
|
|
7247
|
+
if (isRecord(message.info)) {
|
|
7248
|
+
if (message.info.role !== "user" || !Array.isArray(message.parts))
|
|
7249
|
+
return false;
|
|
7250
|
+
return message.parts.some((part) => isRecord(part) && part.ignored !== true && !TOOL_RESULT_TYPES.has(String(part.type)) && !(part.type === "text" && part.text === ""));
|
|
7251
|
+
}
|
|
7252
|
+
if (!PI_USER_ON_WIRE_ROLES.has(String(message.role)))
|
|
7253
|
+
return false;
|
|
7254
|
+
if (message.excludeFromContext === true)
|
|
7255
|
+
return false;
|
|
7256
|
+
if (message.role !== "user")
|
|
7257
|
+
return true;
|
|
7258
|
+
if (typeof message.content === "string")
|
|
7259
|
+
return message.content.length > 0;
|
|
7260
|
+
return Array.isArray(message.content) && message.content.some((block) => !isRecord(block) || !TOOL_RESULT_TYPES.has(String(block.type)));
|
|
7261
|
+
}
|
|
7262
|
+
function providerLatestTurn(messages) {
|
|
7263
|
+
let last = messages.length - 1;
|
|
7264
|
+
while (last >= 0 && !isSentAssistantMessage(messages[last]))
|
|
7265
|
+
last -= 1;
|
|
7266
|
+
if (last < 0)
|
|
7267
|
+
return;
|
|
7268
|
+
let start = last;
|
|
7269
|
+
while (start > 0 && !isUserMessageOnWire(messages[start - 1]))
|
|
7270
|
+
start -= 1;
|
|
7271
|
+
let first = start;
|
|
7272
|
+
while (first < last && !isSentAssistantMessage(messages[first]))
|
|
7273
|
+
first += 1;
|
|
7274
|
+
let end = last + 1;
|
|
7275
|
+
while (end < messages.length && !isUserMessageOnWire(messages[end]))
|
|
7276
|
+
end += 1;
|
|
7277
|
+
return { start, first, last, end };
|
|
7278
|
+
}
|
|
7201
7279
|
function isAnthropicThinkingPart(part, familyRoute) {
|
|
7202
7280
|
return isRecord(part) && THINKING_TYPES.has(String(part.type ?? part.kind)) && (familyRoute || isRecord(part.metadata) && isRecord(part.metadata.anthropic));
|
|
7203
7281
|
}
|
|
@@ -7286,18 +7364,113 @@ function retainedActiveThinkingParts(args) {
|
|
|
7286
7364
|
|
|
7287
7365
|
// src/hooks/magic-context/latest-thinking-recovery.ts
|
|
7288
7366
|
var LATEST_THINKING_RESTORE = "latest_thinking_original";
|
|
7367
|
+
var TURN_STATE = `${LATEST_THINKING_RESTORE}_turn:`;
|
|
7289
7368
|
var knownRejectedSessions = new Set;
|
|
7290
|
-
|
|
7291
|
-
|
|
7292
|
-
|
|
7293
|
-
var
|
|
7294
|
-
var
|
|
7295
|
-
function
|
|
7369
|
+
function isLatestThinkingRecoveryTarget(target) {
|
|
7370
|
+
return typeof target === "string" && target.startsWith(LATEST_THINKING_RESTORE);
|
|
7371
|
+
}
|
|
7372
|
+
var REFUSE_AT_REJECTION = 3;
|
|
7373
|
+
var STAGES = new Set(["armed", "restoring", "remove", "removed", "refused"]);
|
|
7374
|
+
function readState2(target) {
|
|
7375
|
+
if (!target.startsWith(TURN_STATE))
|
|
7376
|
+
return;
|
|
7377
|
+
try {
|
|
7378
|
+
const value = JSON.parse(target.slice(TURN_STATE.length));
|
|
7379
|
+
if (!isRecord(value) || !STAGES.has(String(value.stage)) || typeof value.first !== "string" || typeof value.last !== "string" || typeof value.rejections !== "number")
|
|
7380
|
+
return;
|
|
7381
|
+
return {
|
|
7382
|
+
stage: value.stage,
|
|
7383
|
+
first: value.first,
|
|
7384
|
+
last: value.last,
|
|
7385
|
+
rejections: value.rejections,
|
|
7386
|
+
...typeof value.pass === "string" ? { pass: value.pass } : {},
|
|
7387
|
+
...typeof value.model === "string" ? { model: value.model } : {},
|
|
7388
|
+
...typeof value.provider === "string" ? { provider: value.provider } : {},
|
|
7389
|
+
...value.accepted === true ? { accepted: true } : {}
|
|
7390
|
+
};
|
|
7391
|
+
} catch {
|
|
7392
|
+
return;
|
|
7393
|
+
}
|
|
7394
|
+
}
|
|
7395
|
+
function encodeState(state) {
|
|
7396
|
+
return TURN_STATE + JSON.stringify({
|
|
7397
|
+
stage: state.stage,
|
|
7398
|
+
first: state.first,
|
|
7399
|
+
last: state.last,
|
|
7400
|
+
rejections: state.rejections,
|
|
7401
|
+
...state.pass ? { pass: state.pass } : {},
|
|
7402
|
+
...state.model ? { model: state.model } : {},
|
|
7403
|
+
...state.provider ? { provider: state.provider } : {},
|
|
7404
|
+
...state.accepted ? { accepted: true } : {}
|
|
7405
|
+
});
|
|
7406
|
+
}
|
|
7407
|
+
function identifyTurn(messages, id) {
|
|
7408
|
+
const turn = providerLatestTurn(messages);
|
|
7409
|
+
if (!turn)
|
|
7410
|
+
return;
|
|
7411
|
+
const first = id(messages[turn.first], turn.first);
|
|
7412
|
+
const last = id(messages[turn.last], turn.last);
|
|
7413
|
+
return first && last ? { turn, bound: { first, last } } : undefined;
|
|
7414
|
+
}
|
|
7415
|
+
var lastPassTurn = new Map;
|
|
7416
|
+
var PROCESS_TOKEN = Math.random().toString(36).slice(2, 10);
|
|
7417
|
+
var passCounter = 0;
|
|
7418
|
+
var LATEST_THINKING_UNSAFE = "ANTHROPIC_LATEST_TURN_EDIT_UNSAFE: The provider keeps rejecting the thinking of this conversation's latest assistant turn, even after Magic Context restored or removed it. Sending a new message does not help, because the provider checks that same turn again. Switch the model once, or run /clear, to continue.";
|
|
7419
|
+
var LATEST_THINKING_NOT_SAVED = "Magic Context could not save the change this request needs after the provider rejected the thinking of the latest assistant turn (its database was busy or changed at the same moment). Nothing was sent. Send your message again.";
|
|
7420
|
+
function escalate(state, rejections) {
|
|
7421
|
+
switch (state.stage) {
|
|
7422
|
+
case "armed":
|
|
7423
|
+
return "armed";
|
|
7424
|
+
case "restoring":
|
|
7425
|
+
case "remove":
|
|
7426
|
+
return "remove";
|
|
7427
|
+
case "removed":
|
|
7428
|
+
if (state.accepted)
|
|
7429
|
+
return "remove";
|
|
7430
|
+
return rejections >= REFUSE_AT_REJECTION ? "refused" : "removed";
|
|
7431
|
+
case "refused":
|
|
7432
|
+
return "refused";
|
|
7433
|
+
}
|
|
7434
|
+
}
|
|
7435
|
+
function armLatestThinkingRecovery(db, sessionId, modelID) {
|
|
7296
7436
|
knownRejectedSessions.add(sessionId);
|
|
7297
7437
|
ensureSessionMetaRow(db, sessionId);
|
|
7298
7438
|
const current = getThinkingBindingRecoveryTarget(db, sessionId);
|
|
7299
|
-
const
|
|
7300
|
-
const
|
|
7439
|
+
const state = current ? readState2(current) : undefined;
|
|
7440
|
+
const pass = lastPassTurn.get(sessionId);
|
|
7441
|
+
let next;
|
|
7442
|
+
if (state) {
|
|
7443
|
+
if (pass !== undefined && state.pass === pass.pass)
|
|
7444
|
+
return;
|
|
7445
|
+
const rejections = state.accepted ? 1 : state.rejections + 1;
|
|
7446
|
+
const stage = escalate(state, rejections);
|
|
7447
|
+
const last = pass?.first === state.first ? pass.last : state.last;
|
|
7448
|
+
next = encodeState({
|
|
7449
|
+
...state,
|
|
7450
|
+
stage,
|
|
7451
|
+
last,
|
|
7452
|
+
rejections,
|
|
7453
|
+
pass: pass?.pass,
|
|
7454
|
+
accepted: false
|
|
7455
|
+
});
|
|
7456
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: provider rejected the bound turn again (rejection ${rejections}, first=${state.first} last=${last}); ${state.stage} -> ${stage}`);
|
|
7457
|
+
} else if (pass) {
|
|
7458
|
+
const model = pass.model ?? modelID;
|
|
7459
|
+
const provider = pass.model ? pass.provider : undefined;
|
|
7460
|
+
next = encodeState({
|
|
7461
|
+
stage: "armed",
|
|
7462
|
+
first: pass.first,
|
|
7463
|
+
last: pass.last,
|
|
7464
|
+
rejections: 1,
|
|
7465
|
+
pass: pass.pass,
|
|
7466
|
+
...model ? { model } : {},
|
|
7467
|
+
...provider ? { provider } : {}
|
|
7468
|
+
});
|
|
7469
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: armed for the provider's latest turn (first=${pass.first} last=${pass.last} model=${provider ? `${provider}/` : ""}${model ?? "unknown"})`);
|
|
7470
|
+
} else {
|
|
7471
|
+
next = LATEST_THINKING_RESTORE;
|
|
7472
|
+
sessionLog2(sessionId, "latest-turn thinking recovery: rejection not bound, no pass in this process built the rejected request");
|
|
7473
|
+
}
|
|
7301
7474
|
db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ?").run(next, sessionId);
|
|
7302
7475
|
}
|
|
7303
7476
|
function clone(value) {
|
|
@@ -7320,66 +7493,246 @@ function replayableOriginal(part) {
|
|
|
7320
7493
|
const signature = part.signature ?? part.thinkingSignature ?? metadata.signature ?? part.data ?? metadata.redactedData;
|
|
7321
7494
|
return typeof signature === "string" && signature.length > 0 && part.text !== "[cleared]" && part.thinking !== "[cleared]";
|
|
7322
7495
|
}
|
|
7496
|
+
var NO_RECOVERY = { restore: false, ended: false };
|
|
7497
|
+
var LATEST_TURN_THINKING_REMOVED_REASON = "latest_turn_thinking_removed";
|
|
7498
|
+
function replaceTarget(db, sessionId, expected, next) {
|
|
7499
|
+
return db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(next, sessionId, expected).changes > 0;
|
|
7500
|
+
}
|
|
7501
|
+
function decisionMessageId(decision) {
|
|
7502
|
+
if (decision === "binding_mismatch_order:end" || decision === TOOL_SWEEP_SCOPED_MARKER)
|
|
7503
|
+
return;
|
|
7504
|
+
return decodeMergedReasoningParts(decision)?.[0] ?? (decision.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX) ? decision.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length) : decision);
|
|
7505
|
+
}
|
|
7506
|
+
function sentAssistantIds(args, turn) {
|
|
7507
|
+
const ids = [];
|
|
7508
|
+
for (let index = turn.start;index < turn.end; index += 1) {
|
|
7509
|
+
const message = args.messages[index];
|
|
7510
|
+
if (!isSentAssistantMessage(message))
|
|
7511
|
+
continue;
|
|
7512
|
+
const id = args.id(message, index);
|
|
7513
|
+
if (id)
|
|
7514
|
+
ids.push(id);
|
|
7515
|
+
}
|
|
7516
|
+
return ids;
|
|
7517
|
+
}
|
|
7518
|
+
function magicContextEditedTurn(args, turn, modelID) {
|
|
7519
|
+
const ids = new Set(sentAssistantIds(args, turn));
|
|
7520
|
+
for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
7521
|
+
const id = decisionMessageId(decision);
|
|
7522
|
+
if (id !== undefined && ids.has(id))
|
|
7523
|
+
return true;
|
|
7524
|
+
}
|
|
7525
|
+
try {
|
|
7526
|
+
for (const id of getReasoningRemovalState(args.db, args.sessionId).messageIds) {
|
|
7527
|
+
if (ids.has(id))
|
|
7528
|
+
return true;
|
|
7529
|
+
}
|
|
7530
|
+
} catch {}
|
|
7531
|
+
return !isPrefixBoundThinkingModel(undefined, modelID) && clearedByWatermark(args, turn);
|
|
7532
|
+
}
|
|
7533
|
+
function clearedByWatermark(args, turn) {
|
|
7534
|
+
try {
|
|
7535
|
+
const row = args.db.prepare("SELECT cleared_reasoning_through_tag AS watermark FROM session_meta WHERE session_id = ?").get(args.sessionId);
|
|
7536
|
+
const watermark = row?.watermark ?? 0;
|
|
7537
|
+
if (!(watermark > 0))
|
|
7538
|
+
return false;
|
|
7539
|
+
const textTags = args.db.prepare("SELECT MAX(tag_number) AS n FROM tags WHERE session_id = ? AND message_id >= ? AND message_id < ?");
|
|
7540
|
+
const toolTags = args.db.prepare("SELECT MAX(tag_number) AS n FROM tags WHERE session_id = ? AND type = 'tool' AND tool_owner_message_id = ?");
|
|
7541
|
+
for (let index = turn.start;index < turn.end; index += 1) {
|
|
7542
|
+
const message = args.messages[index];
|
|
7543
|
+
if (!isSentAssistantMessage(message))
|
|
7544
|
+
continue;
|
|
7545
|
+
if (!args.parts(message).some(isThinkingPart2))
|
|
7546
|
+
continue;
|
|
7547
|
+
const id = args.id(message, index);
|
|
7548
|
+
if (!id)
|
|
7549
|
+
continue;
|
|
7550
|
+
const text = textTags.get(args.sessionId, `${id}:`, `${id};`);
|
|
7551
|
+
const tool = toolTags.get(args.sessionId, id);
|
|
7552
|
+
const newest = Math.max(text?.n ?? 0, tool?.n ?? 0);
|
|
7553
|
+
if (newest > 0 && newest <= watermark)
|
|
7554
|
+
return true;
|
|
7555
|
+
}
|
|
7556
|
+
} catch {}
|
|
7557
|
+
return false;
|
|
7558
|
+
}
|
|
7559
|
+
function restoreBlocker(args, turn) {
|
|
7560
|
+
if (turn.start === 0)
|
|
7561
|
+
return "no-turn-start";
|
|
7562
|
+
const turnMessages = args.messages.slice(turn.start, turn.end);
|
|
7563
|
+
if (!turnMessages.some((message) => args.parts(message).some(replayableOriginal)))
|
|
7564
|
+
return "missing-thinking-original";
|
|
7565
|
+
const ids = new Map(args.messages.map((message, index) => [args.id(message, index), index]));
|
|
7566
|
+
for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
7567
|
+
const id = decisionMessageId(decision);
|
|
7568
|
+
if (id === undefined)
|
|
7569
|
+
continue;
|
|
7570
|
+
const index = ids.get(id);
|
|
7571
|
+
if (index === undefined || index >= turn.start && !args.parts(args.messages[index]).some(replayableOriginal))
|
|
7572
|
+
return `missing-original:${id}`;
|
|
7573
|
+
}
|
|
7574
|
+
return;
|
|
7575
|
+
}
|
|
7576
|
+
function refuse(sessionId, why) {
|
|
7577
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: refused locally (${why})`);
|
|
7578
|
+
throw contextRefusalError(LATEST_THINKING_UNSAFE);
|
|
7579
|
+
}
|
|
7580
|
+
function refuseUnsaved(sessionId, why) {
|
|
7581
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: refused locally (${why})`);
|
|
7582
|
+
throw contextRefusalError(LATEST_THINKING_NOT_SAVED);
|
|
7583
|
+
}
|
|
7584
|
+
function frozenBindingIds(args) {
|
|
7585
|
+
const frozen = new Set;
|
|
7586
|
+
for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
7587
|
+
if (decision.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX))
|
|
7588
|
+
frozen.add(decision.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length));
|
|
7589
|
+
}
|
|
7590
|
+
return frozen;
|
|
7591
|
+
}
|
|
7592
|
+
function frozenTurnIds(args, turn) {
|
|
7593
|
+
const frozen = frozenBindingIds(args);
|
|
7594
|
+
return sentAssistantIds(args, turn).filter((id) => frozen.has(id));
|
|
7595
|
+
}
|
|
7596
|
+
function persistBindingRemoval(db, sessionId, ids) {
|
|
7597
|
+
return addMergedReasoningStrippedIds(db, sessionId, ids.map(thinkingBindingRecoveryFrozenId));
|
|
7598
|
+
}
|
|
7599
|
+
function removeTurnThinking(args, target, state, turn, current) {
|
|
7600
|
+
const frozen = frozenBindingIds(args);
|
|
7601
|
+
const ids = [];
|
|
7602
|
+
let parts = 0;
|
|
7603
|
+
for (let index = turn.start;index < turn.end; index += 1) {
|
|
7604
|
+
const message = args.messages[index];
|
|
7605
|
+
if (!isSentAssistantMessage(message))
|
|
7606
|
+
continue;
|
|
7607
|
+
const thinking = args.parts(message).filter(isThinkingPart2).length;
|
|
7608
|
+
if (thinking === 0)
|
|
7609
|
+
continue;
|
|
7610
|
+
const id = args.id(message, index);
|
|
7611
|
+
if (!id)
|
|
7612
|
+
refuse(args.sessionId, "a thinking message of the turn has no stable id");
|
|
7613
|
+
if (frozen.has(id))
|
|
7614
|
+
continue;
|
|
7615
|
+
ids.push(id);
|
|
7616
|
+
parts += thinking;
|
|
7617
|
+
}
|
|
7618
|
+
if (ids.length === 0) {
|
|
7619
|
+
replaceTarget(args.db, args.sessionId, target, encodeState({ ...state, stage: "refused", last: current.last }));
|
|
7620
|
+
refuse(args.sessionId, "the rejected turn has no thinking left to remove");
|
|
7621
|
+
}
|
|
7622
|
+
const persist = args.persistRemoval ?? ((next) => persistBindingRemoval(args.db, args.sessionId, next));
|
|
7623
|
+
let persisted = false;
|
|
7624
|
+
try {
|
|
7625
|
+
args.db.transaction(() => {
|
|
7626
|
+
if (!persist(ids))
|
|
7627
|
+
throw new Error("thinking removal was not persisted");
|
|
7628
|
+
const next = encodeState({ ...state, stage: "removed", last: current.last });
|
|
7629
|
+
if (!replaceTarget(args.db, args.sessionId, target, next))
|
|
7630
|
+
throw new Error("recovery state changed concurrently");
|
|
7631
|
+
}).immediate();
|
|
7632
|
+
persisted = true;
|
|
7633
|
+
} catch (error) {
|
|
7634
|
+
sessionLog2(args.sessionId, "latest-turn thinking recovery: removal write failed:", error);
|
|
7635
|
+
}
|
|
7636
|
+
if (!persisted)
|
|
7637
|
+
refuseUnsaved(args.sessionId, "the thinking removal could not be saved");
|
|
7638
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: removed thinking from the bound turn (parts=${parts} messages=${ids.length} first=${state.first} last=${current.last})`);
|
|
7639
|
+
return {
|
|
7640
|
+
restore: false,
|
|
7641
|
+
ended: false,
|
|
7642
|
+
removedThisPass: true,
|
|
7643
|
+
removedIds: frozenTurnIds(args, turn)
|
|
7644
|
+
};
|
|
7645
|
+
}
|
|
7323
7646
|
function prepareLatestThinkingRecovery(args) {
|
|
7324
|
-
const
|
|
7325
|
-
|
|
7326
|
-
|
|
7327
|
-
|
|
7647
|
+
const identified = identifyTurn(args.messages, args.id);
|
|
7648
|
+
if (identified)
|
|
7649
|
+
lastPassTurn.set(args.sessionId, {
|
|
7650
|
+
...identified.bound,
|
|
7651
|
+
pass: `${PROCESS_TOKEN}:${++passCounter}`,
|
|
7652
|
+
...args.modelID ? { model: args.modelID } : {},
|
|
7653
|
+
...args.modelID && args.providerID ? { provider: args.providerID } : {}
|
|
7654
|
+
});
|
|
7328
7655
|
else
|
|
7329
|
-
|
|
7656
|
+
lastPassTurn.delete(args.sessionId);
|
|
7330
7657
|
let target;
|
|
7331
7658
|
try {
|
|
7332
7659
|
target = getThinkingBindingRecoveryTarget(args.db, args.sessionId);
|
|
7333
7660
|
} catch (error) {
|
|
7334
7661
|
if (knownRejectedSessions.has(args.sessionId))
|
|
7335
|
-
|
|
7336
|
-
return
|
|
7662
|
+
refuseUnsaved(args.sessionId, "the recovery state could not be read");
|
|
7663
|
+
return NO_RECOVERY;
|
|
7337
7664
|
}
|
|
7338
7665
|
if (!target || !target.startsWith(LATEST_THINKING_RESTORE)) {
|
|
7339
7666
|
knownRejectedSessions.delete(args.sessionId);
|
|
7340
|
-
return
|
|
7667
|
+
return NO_RECOVERY;
|
|
7341
7668
|
}
|
|
7342
|
-
const
|
|
7343
|
-
if (
|
|
7344
|
-
args.db
|
|
7669
|
+
const state = readState2(target);
|
|
7670
|
+
if (!state) {
|
|
7671
|
+
replaceTarget(args.db, args.sessionId, target, "");
|
|
7345
7672
|
knownRejectedSessions.delete(args.sessionId);
|
|
7346
|
-
|
|
7673
|
+
sessionLog2(args.sessionId, "latest-turn thinking recovery: cleared a rejection that names no turn");
|
|
7674
|
+
return NO_RECOVERY;
|
|
7347
7675
|
}
|
|
7348
|
-
|
|
7349
|
-
|
|
7350
|
-
if (savedAnchor !== undefined && savedAnchor !== anchor) {
|
|
7351
|
-
args.db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(args.sessionId, target);
|
|
7676
|
+
const unbind = (why) => {
|
|
7677
|
+
replaceTarget(args.db, args.sessionId, target, "");
|
|
7352
7678
|
knownRejectedSessions.delete(args.sessionId);
|
|
7353
|
-
|
|
7679
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: unbound because ${why} (stage=${state.stage} first=${state.first} last=${state.last})`);
|
|
7680
|
+
return { restore: false, ended: state.stage === "restoring" };
|
|
7681
|
+
};
|
|
7682
|
+
if (args.modelID && state.model && args.modelID.toLowerCase() !== state.model.toLowerCase())
|
|
7683
|
+
return unbind(`the request now goes to ${args.modelID}`);
|
|
7684
|
+
if (args.providerID && state.provider && args.providerID.toLowerCase() !== state.provider.toLowerCase())
|
|
7685
|
+
return unbind(`the request now goes through ${args.providerID}`);
|
|
7686
|
+
const current = identified?.bound;
|
|
7687
|
+
if (!identified || !current || current.first !== state.first)
|
|
7688
|
+
return unbind(`a newer turn was accepted (now first=${current?.first ?? "none"} last=${current?.last ?? "none"})`);
|
|
7689
|
+
const turn = identified.turn;
|
|
7690
|
+
if (current.last !== state.last && state.stage !== "restoring") {
|
|
7691
|
+
if (state.stage !== "removed")
|
|
7692
|
+
return unbind(`a newer message of the turn was accepted (now last=${current.last})`);
|
|
7693
|
+
replaceTarget(args.db, args.sessionId, target, encodeState({ ...state, last: current.last, accepted: true }));
|
|
7694
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: a request without the turn's removed thinking was accepted (first=${state.first} last=${current.last})`);
|
|
7695
|
+
return { ...NO_RECOVERY, removedIds: frozenTurnIds(args, identified.turn) };
|
|
7354
7696
|
}
|
|
7355
|
-
|
|
7356
|
-
|
|
7357
|
-
|
|
7358
|
-
|
|
7359
|
-
|
|
7360
|
-
|
|
7361
|
-
|
|
7362
|
-
|
|
7363
|
-
|
|
7364
|
-
|
|
7365
|
-
|
|
7366
|
-
|
|
7367
|
-
|
|
7368
|
-
|
|
7369
|
-
|
|
7370
|
-
|
|
7697
|
+
knownRejectedSessions.add(args.sessionId);
|
|
7698
|
+
switch (state.stage) {
|
|
7699
|
+
case "refused":
|
|
7700
|
+
return refuse(args.sessionId, `the provider rejected the turn first=${state.first} ${state.rejections} times`);
|
|
7701
|
+
case "removed":
|
|
7702
|
+
return { ...NO_RECOVERY, removedIds: frozenTurnIds(args, turn) };
|
|
7703
|
+
case "restoring": {
|
|
7704
|
+
const blocker = restoreBlocker(args, turn);
|
|
7705
|
+
if (blocker === undefined)
|
|
7706
|
+
return { restore: true, ended: false };
|
|
7707
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: restore no longer possible (${blocker}); removing the turn's thinking instead`);
|
|
7708
|
+
return removeTurnThinking(args, target, state, turn, current);
|
|
7709
|
+
}
|
|
7710
|
+
case "armed": {
|
|
7711
|
+
if (magicContextEditedTurn(args, turn, args.modelID)) {
|
|
7712
|
+
const blocker = restoreBlocker(args, turn);
|
|
7713
|
+
if (blocker === undefined) {
|
|
7714
|
+
replaceTarget(args.db, args.sessionId, target, encodeState({ ...state, stage: "restoring", last: current.last }));
|
|
7715
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: restore applied to the bound turn (first=${state.first} last=${current.last})`);
|
|
7716
|
+
return { restore: true, ended: false };
|
|
7717
|
+
}
|
|
7718
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: restore unavailable (${blocker}); removing the turn's thinking instead`);
|
|
7719
|
+
}
|
|
7720
|
+
return removeTurnThinking(args, target, state, turn, current);
|
|
7721
|
+
}
|
|
7722
|
+
case "remove":
|
|
7723
|
+
return removeTurnThinking(args, target, state, turn, current);
|
|
7371
7724
|
}
|
|
7372
|
-
return { restore: true, ended: false };
|
|
7373
7725
|
}
|
|
7374
7726
|
function endLatestThinkingRecoveryAfterReset(db, sessionId) {
|
|
7375
7727
|
const target = getThinkingBindingRecoveryTarget(db, sessionId);
|
|
7376
7728
|
if (target?.startsWith(LATEST_THINKING_RESTORE)) {
|
|
7377
7729
|
db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(sessionId, target);
|
|
7730
|
+
sessionLog2(sessionId, "latest-turn thinking recovery: ended after a signed-thinking reset removed the turn's thinking");
|
|
7378
7731
|
}
|
|
7379
7732
|
knownRejectedSessions.delete(sessionId);
|
|
7380
7733
|
}
|
|
7381
7734
|
function captureOriginalTurn(messages, parts, setParts) {
|
|
7382
|
-
const start = Math.max(0, latestAssistantTurnStart(messages) - 1);
|
|
7735
|
+
const start = Math.max(0, (providerLatestTurn(messages)?.start ?? latestAssistantTurnStart(messages)) - 1);
|
|
7383
7736
|
const originals = messages.slice(start).map((message) => ({ message, parts: clone(parts(message)) }));
|
|
7384
7737
|
const before = messages.slice(0, start);
|
|
7385
7738
|
return (target = messages) => {
|
|
@@ -7392,23 +7745,34 @@ function captureOriginalTurn(messages, parts, setParts) {
|
|
|
7392
7745
|
target.push(...prefix, ...originals.map((original) => original.message));
|
|
7393
7746
|
};
|
|
7394
7747
|
}
|
|
7748
|
+
function restoredTurnMessages(messages, activeTurn) {
|
|
7749
|
+
const turn = providerLatestTurn(messages);
|
|
7750
|
+
return turn ? new Set(messages.slice(turn.start)) : new Set(activeTurn);
|
|
7751
|
+
}
|
|
7395
7752
|
function captureLatestTurnOriginals(messages) {
|
|
7396
7753
|
return captureOriginalTurn(messages, (message) => message.parts, (message, parts) => {
|
|
7397
7754
|
message.parts = parts;
|
|
7398
7755
|
});
|
|
7399
7756
|
}
|
|
7400
7757
|
function armBindingRecoverySafely(db, sessionId) {
|
|
7401
|
-
|
|
7402
|
-
|
|
7403
|
-
|
|
7404
|
-
|
|
7758
|
+
const target = getThinkingBindingRecoveryTarget(db, sessionId);
|
|
7759
|
+
if (target?.startsWith(LATEST_THINKING_RESTORE)) {
|
|
7760
|
+
const stage = readState2(target)?.stage;
|
|
7761
|
+
if (stage !== "removed" && stage !== "refused") {
|
|
7762
|
+
armLatestThinkingRecovery(db, sessionId);
|
|
7763
|
+
return;
|
|
7764
|
+
}
|
|
7765
|
+
knownRejectedSessions.delete(sessionId);
|
|
7766
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: binding rejection handed to the binding recovery (stage=${stage})`);
|
|
7767
|
+
}
|
|
7768
|
+
armThinkingBindingRecovery(db, sessionId);
|
|
7405
7769
|
}
|
|
7406
7770
|
function armLatestThinkingRecoveryFromError(args) {
|
|
7407
7771
|
if (!detectLatestTurnThinkingMismatch(args.error))
|
|
7408
7772
|
return false;
|
|
7409
7773
|
if (!isAnthropicFamilyRoute(args.providerID, args.modelID))
|
|
7410
7774
|
return true;
|
|
7411
|
-
armLatestThinkingRecovery(args.db, args.sessionId);
|
|
7775
|
+
armLatestThinkingRecovery(args.db, args.sessionId, args.modelID);
|
|
7412
7776
|
dropSlot(args.sessionId, "latest-thinking-recovery-arm");
|
|
7413
7777
|
return true;
|
|
7414
7778
|
}
|
|
@@ -7573,15 +7937,15 @@ function isHostInstructionRetentionOn(db, sessionId) {
|
|
|
7573
7937
|
const lane = readReplayEnvelope(db, sessionId)[NAMESPACE2];
|
|
7574
7938
|
return typeof lane === "object" && lane !== null && lane.on === true;
|
|
7575
7939
|
}
|
|
7576
|
-
function
|
|
7577
|
-
|
|
7578
|
-
|
|
7579
|
-
|
|
7580
|
-
return false;
|
|
7940
|
+
function recordHostInstructionDecisions(doc, decisions) {
|
|
7941
|
+
let changed = decisions.record?.(doc) ?? false;
|
|
7942
|
+
const lane = doc[NAMESPACE2];
|
|
7943
|
+
if (decisions.retention && !(typeof lane === "object" && lane !== null && lane.on === true)) {
|
|
7581
7944
|
doc.version = 2;
|
|
7582
7945
|
doc[NAMESPACE2] = { on: true };
|
|
7583
|
-
|
|
7584
|
-
}
|
|
7946
|
+
changed = true;
|
|
7947
|
+
}
|
|
7948
|
+
return changed;
|
|
7585
7949
|
}
|
|
7586
7950
|
|
|
7587
7951
|
// src/hooks/magic-context/apply-operations.ts
|
|
@@ -8418,6 +8782,10 @@ function replayCavemanCompression(sessionId, db, targets, tags) {
|
|
|
8418
8782
|
}
|
|
8419
8783
|
|
|
8420
8784
|
// src/hooks/magic-context/heuristic-cleanup.ts
|
|
8785
|
+
var NOTHING_SERVED_BEFORE_PASS = {
|
|
8786
|
+
tags: new Map,
|
|
8787
|
+
reasoning: new Map
|
|
8788
|
+
};
|
|
8421
8789
|
var DEDUP_SAFE_TOOLS = new Set([
|
|
8422
8790
|
"grep",
|
|
8423
8791
|
"read",
|
|
@@ -8454,8 +8822,12 @@ function applyHeuristicCleanup(sessionId, db, targets, messageTagNumbers, config
|
|
|
8454
8822
|
const candidateTags = tags.filter((t) => t.status === "active" && t.type === "tool" && targets.get(t.tagNumber)?.canDrop?.());
|
|
8455
8823
|
const recentTags = new Set(candidateTags.slice().sort((a, b) => b.tagNumber - a.tagNumber).slice(0, 20).map((tag) => tag.tagNumber));
|
|
8456
8824
|
const calibration = sessionDecisionCalibration(db, sessionId);
|
|
8457
|
-
const activeTags = tags.filter((t) => t.status === "active").map((tag) =>
|
|
8825
|
+
const activeTags = tags.filter((t) => t.status === "active").map((tag) => {
|
|
8826
|
+
const measured = measureEmergencyTag(tag, targets.get(tag.tagNumber), calibration, targets.get(tag.tagNumber)?.requiresToolArcSkeleton === true || (emergency.usagePercentage ?? 0) < 95 && recentTags.has(tag.tagNumber) && hasSmallToolInput(targets.get(tag.tagNumber)));
|
|
8827
|
+
return emergency.sinceReading?.has(tag.tagNumber) ? { ...measured, sinceReading: true } : measured;
|
|
8828
|
+
});
|
|
8458
8829
|
const measuredByTag = new Map(activeTags.map((tag) => [tag.tagNumber, tag]));
|
|
8830
|
+
const removedThisPassTokens = emergencyServedMassRemovedSince(emergency.servedBeforePass ?? NOTHING_SERVED_BEFORE_PASS, targets, calibration, measuredByTag);
|
|
8459
8831
|
const droppableTags = candidateTags.flatMap((tag) => {
|
|
8460
8832
|
const measured = measuredByTag.get(tag.tagNumber);
|
|
8461
8833
|
return measured ? [measured] : [];
|
|
@@ -8466,6 +8838,7 @@ function applyHeuristicCleanup(sessionId, db, targets, messageTagNumbers, config
|
|
|
8466
8838
|
maxTag,
|
|
8467
8839
|
protectedCutoff: config.protectedCutoff,
|
|
8468
8840
|
currentTotalInputTokens: emergency.currentTotalInputTokens,
|
|
8841
|
+
removedThisPassTokens,
|
|
8469
8842
|
ceilingTokens: emergency.ceilingTokens,
|
|
8470
8843
|
usagePercentage: emergency.usagePercentage,
|
|
8471
8844
|
priorInputSample,
|
|
@@ -8851,15 +9224,26 @@ function projectStructuralSentinels(args) {
|
|
|
8851
9224
|
}
|
|
8852
9225
|
|
|
8853
9226
|
// src/hooks/magic-context/routine-cleanup-decision.ts
|
|
8854
|
-
function
|
|
9227
|
+
function forceBandOf(args) {
|
|
8855
9228
|
const emergencyDropEligible = !args.compactionOff && args.percentage >= args.forceMaterializationPercentage;
|
|
8856
9229
|
const forceRideWaitsOnLocalCount = args.fromEstimate && args.percentage < 95;
|
|
8857
9230
|
return {
|
|
8858
|
-
forceMaterialization: args.fullFeatureMode && emergencyDropEligible,
|
|
8859
9231
|
emergencyDropEligible,
|
|
8860
9232
|
forceRideWaitsOnLocalCount,
|
|
8861
|
-
forceBandConfirmed: emergencyDropEligible && !forceRideWaitsOnLocalCount
|
|
8862
|
-
|
|
9233
|
+
forceBandConfirmed: emergencyDropEligible && !forceRideWaitsOnLocalCount
|
|
9234
|
+
};
|
|
9235
|
+
}
|
|
9236
|
+
function forceBandConfirmed(args) {
|
|
9237
|
+
return forceBandOf(args).forceBandConfirmed;
|
|
9238
|
+
}
|
|
9239
|
+
function pressureBands(args) {
|
|
9240
|
+
const band = forceBandOf(args);
|
|
9241
|
+
return {
|
|
9242
|
+
forceMaterialization: args.fullFeatureMode && band.emergencyDropEligible,
|
|
9243
|
+
emergencyDropEligible: band.emergencyDropEligible,
|
|
9244
|
+
forceRideWaitsOnLocalCount: band.forceRideWaitsOnLocalCount,
|
|
9245
|
+
forceBandConfirmed: band.forceBandConfirmed,
|
|
9246
|
+
executePressureEligible: args.schedulerDecision === "execute" || band.emergencyDropEligible
|
|
8863
9247
|
};
|
|
8864
9248
|
}
|
|
8865
9249
|
function forceRide(args) {
|
|
@@ -10166,6 +10550,38 @@ function proactiveStripStartIndex(args) {
|
|
|
10166
10550
|
return divergence;
|
|
10167
10551
|
return divergence ?? lastServed.messages.length;
|
|
10168
10552
|
}
|
|
10553
|
+
function messagesAfterReplayedThinkingStrips(args, owners, compactionOff, compactionOffFrozenThinking) {
|
|
10554
|
+
const mergedIds = compactionOff ? new Set : new Set(getMergedReasoningStrippedIds(args.db, args.sessionId));
|
|
10555
|
+
const bindingIds = compactionOff ? new Set(compactionOffFrozenThinking) : new Set([...mergedIds].filter((id) => id.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX)).map((id) => id.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length)));
|
|
10556
|
+
const mergedReplays = args.resolvedProviderID === "anthropic";
|
|
10557
|
+
const exactParts = mergedReplays ? readFrozenMergedReasoningParts(mergedIds) : new Map;
|
|
10558
|
+
const reasoningType = (part) => isRecord(part) && ["reasoning", "thinking", "redacted_thinking"].includes(String(part.type));
|
|
10559
|
+
const copies = [];
|
|
10560
|
+
for (const message of new Set(owners)) {
|
|
10561
|
+
const id = typeof message.info.id === "string" ? message.info.id : undefined;
|
|
10562
|
+
if (id === undefined || args.restoreThinkingMessageIds?.has(id)) {
|
|
10563
|
+
copies.push(message);
|
|
10564
|
+
continue;
|
|
10565
|
+
}
|
|
10566
|
+
const legacy = mergedReplays && mergedIds.has(id);
|
|
10567
|
+
const whole = bindingIds.has(id) || legacy;
|
|
10568
|
+
const exact = exactParts.get(id);
|
|
10569
|
+
copies.push({
|
|
10570
|
+
...message,
|
|
10571
|
+
parts: message.parts.filter((part, index) => {
|
|
10572
|
+
if (!reasoningType(part))
|
|
10573
|
+
return true;
|
|
10574
|
+
if (whole)
|
|
10575
|
+
return false;
|
|
10576
|
+
if (!exact)
|
|
10577
|
+
return true;
|
|
10578
|
+
const partId = isRecord(part) && typeof part.id === "string" ? part.id : undefined;
|
|
10579
|
+
return !exact.includes(index) && !(partId !== undefined && exact.includes(partId));
|
|
10580
|
+
})
|
|
10581
|
+
});
|
|
10582
|
+
}
|
|
10583
|
+
return copies;
|
|
10584
|
+
}
|
|
10169
10585
|
function servesThinkingBlock(messages, providerID, modelID) {
|
|
10170
10586
|
const familyRoute = isAnthropicFamilyRoute(providerID, modelID);
|
|
10171
10587
|
for (const message of messages) {
|
|
@@ -10181,6 +10597,8 @@ function servesThinkingBlock(messages, providerID, modelID) {
|
|
|
10181
10597
|
const records = isRecord(part.metadata) ? Object.values(part.metadata) : [];
|
|
10182
10598
|
if (records.some((record) => isRecord(record) && record.redactedData !== undefined))
|
|
10183
10599
|
return true;
|
|
10600
|
+
if (openCode2ThinkingPayload(part) !== undefined)
|
|
10601
|
+
return true;
|
|
10184
10602
|
}
|
|
10185
10603
|
}
|
|
10186
10604
|
return false;
|
|
@@ -10370,7 +10788,7 @@ function applyRustModeThinkingStrips(args, hostEditBeforeNewestThinking) {
|
|
|
10370
10788
|
recoveryMessageIds.add(messageId);
|
|
10371
10789
|
}
|
|
10372
10790
|
const flagTarget = !args.activeThinkingTurn && args.thinkingBindingRecoveryEnabledForModel ? getThinkingBindingRecoveryTarget(args.db, args.sessionId) : null;
|
|
10373
|
-
if (flagTarget) {
|
|
10791
|
+
if (flagTarget && !isLatestThinkingRecoveryTarget(flagTarget)) {
|
|
10374
10792
|
thinkingBindingRecovery = freezeAllReasoningForBindingRecovery({
|
|
10375
10793
|
db: args.db,
|
|
10376
10794
|
sessionId: args.sessionId,
|
|
@@ -10701,6 +11119,9 @@ function legacyPublishedHeadChanged(args) {
|
|
|
10701
11119
|
const served = args.readLastServedMessages();
|
|
10702
11120
|
if (served === null)
|
|
10703
11121
|
return true;
|
|
11122
|
+
return legacyHeadDiffersFrom(args, served);
|
|
11123
|
+
}
|
|
11124
|
+
function legacyHeadDiffersFrom(args, served) {
|
|
10704
11125
|
const previous = served[0];
|
|
10705
11126
|
if (!Array.isArray(previous?.parts) || !args.pendingCompartmentInjection)
|
|
10706
11127
|
return false;
|
|
@@ -10714,6 +11135,17 @@ ${args.pendingCompartmentInjection.block}
|
|
|
10714
11135
|
|
|
10715
11136
|
`);
|
|
10716
11137
|
}
|
|
11138
|
+
function frozenRecoveryHeadDiffers(args, m0M1Enabled, frozen) {
|
|
11139
|
+
if (m0M1Enabled)
|
|
11140
|
+
return !servedPrefixMatches({
|
|
11141
|
+
messages: frozen,
|
|
11142
|
+
...servedHeadTexts(args.sessionMeta),
|
|
11143
|
+
muralDataUrl: args.sessionMeta.cachedM0MuralDataUrl ?? null
|
|
11144
|
+
});
|
|
11145
|
+
if ((args.pendingCompartmentInjection?.compartmentCount ?? 0) > 0)
|
|
11146
|
+
return frozen === null || legacyHeadDiffersFrom(args, frozen);
|
|
11147
|
+
return false;
|
|
11148
|
+
}
|
|
10717
11149
|
async function runPostTransformPhase(args) {
|
|
10718
11150
|
const tPostprocessSetup = performance.now();
|
|
10719
11151
|
const compactionOff = args.compactionOff === true;
|
|
@@ -10799,9 +11231,9 @@ async function runPostTransformPhase(args) {
|
|
|
10799
11231
|
let freezeM0M1 = args.freezeM0M1 === true || activeThinkingPrefixHold;
|
|
10800
11232
|
let rewritingSignedPrefix = false;
|
|
10801
11233
|
let thinkingReleasedForFit = false;
|
|
10802
|
-
const releaseThinkingForRewrite = (forFit = false, stripInCompactionOff = false) => {
|
|
11234
|
+
const releaseThinkingForRewrite = (forFit = false, stripInCompactionOff = false, saved) => {
|
|
10803
11235
|
const stripOffWire = compactionOff && stripInCompactionOff;
|
|
10804
|
-
const stripped = freezeReasoningOnBustingPass({
|
|
11236
|
+
const stripped = saved ?? freezeReasoningOnBustingPass({
|
|
10805
11237
|
db: args.db,
|
|
10806
11238
|
sessionId: args.sessionId,
|
|
10807
11239
|
messages: args.messages,
|
|
@@ -10892,9 +11324,37 @@ async function runPostTransformPhase(args) {
|
|
|
10892
11324
|
m1Bytes: args.sessionMeta.cachedM1Bytes ?? null,
|
|
10893
11325
|
muralDataUrl: args.sessionMeta.cachedM0MuralDataUrl ?? null
|
|
10894
11326
|
};
|
|
11327
|
+
const compareRenderedHead = (rendered) => {
|
|
11328
|
+
const servedMatches = () => servedPrefixMatches({
|
|
11329
|
+
messages: servedBeforeFirstRender,
|
|
11330
|
+
m0Text: rendered.m0Bytes.toString(),
|
|
11331
|
+
m1Text: rendered.m1Bytes.toString(),
|
|
11332
|
+
muralDataUrl: rendered.muralDataUrl
|
|
11333
|
+
});
|
|
11334
|
+
return {
|
|
11335
|
+
bustsPrefix: activeThinkingPrefixHold ? !servedMatches() : foldBustsServedPrefix(foldDueDecision.reason, servedPrefixBeforeFold, rendered),
|
|
11336
|
+
changesHead: firstRenderBust ? !servedMatches() : foldChangesServedPrefix(servedPrefixBeforeFold, rendered)
|
|
11337
|
+
};
|
|
11338
|
+
};
|
|
11339
|
+
const compactionOffRenderStrip = (db, head) => {
|
|
11340
|
+
const due = compactionOff && (activeThinkingPrefixHold ? firstRenderBust && head.bustsPrefix : args.thinkingBindingRecoveryEnabledForModel === true && head.changesHead);
|
|
11341
|
+
if (!due)
|
|
11342
|
+
return;
|
|
11343
|
+
const strip = freezeReasoningOnBustingPass({
|
|
11344
|
+
db,
|
|
11345
|
+
sessionId: args.sessionId,
|
|
11346
|
+
messages: args.messages,
|
|
11347
|
+
alreadyFrozen: bindingThinking,
|
|
11348
|
+
compactionOff: true
|
|
11349
|
+
});
|
|
11350
|
+
if (strip.persistenceFailed)
|
|
11351
|
+
throw new Error("Cannot persist signed thinking omission with the compaction-off fold");
|
|
11352
|
+
return strip;
|
|
11353
|
+
};
|
|
10895
11354
|
if ((foldDueDecision.value || softRefreshOpportunity || firstRenderBust && activeThinkingPrefixHold) && m0M1EnabledForFold && args.m0M1) {
|
|
10896
11355
|
let committedFoldBustsServedPrefix;
|
|
10897
11356
|
let committedFoldChangesHead;
|
|
11357
|
+
let compactionOffFoldStrip;
|
|
10898
11358
|
try {
|
|
10899
11359
|
const previousM1 = args.sessionMeta.cachedM1Bytes?.toString("utf8");
|
|
10900
11360
|
const foldResult = injectM0M1({
|
|
@@ -10918,18 +11378,9 @@ async function runPostTransformPhase(args) {
|
|
|
10918
11378
|
onFoldPrepare: () => {
|
|
10919
11379
|
const conversions = prepareLegacyToolSkeletonConversions(args.db, args.sessionId, args.targets);
|
|
10920
11380
|
return (db, rendered) => {
|
|
10921
|
-
const
|
|
10922
|
-
|
|
10923
|
-
|
|
10924
|
-
m1Text: rendered.m1Bytes.toString(),
|
|
10925
|
-
muralDataUrl: rendered.muralDataUrl
|
|
10926
|
-
}) : foldBustsServedPrefix(foldDueDecision.reason, servedPrefixBeforeFold, rendered);
|
|
10927
|
-
committedFoldChangesHead = firstRenderBust ? !servedPrefixMatches({
|
|
10928
|
-
messages: servedBeforeFirstRender,
|
|
10929
|
-
m0Text: rendered.m0Bytes.toString(),
|
|
10930
|
-
m1Text: rendered.m1Bytes.toString(),
|
|
10931
|
-
muralDataUrl: rendered.muralDataUrl
|
|
10932
|
-
}) : foldChangesServedPrefix(servedPrefixBeforeFold, rendered);
|
|
11381
|
+
const head = compareRenderedHead(rendered);
|
|
11382
|
+
const bustsPrefix = head.bustsPrefix;
|
|
11383
|
+
committedFoldChangesHead = head.changesHead;
|
|
10933
11384
|
if (bustsPrefix) {
|
|
10934
11385
|
if (!conversions.isCurrent(db)) {
|
|
10935
11386
|
throw new MaterializeContentionError({
|
|
@@ -10942,15 +11393,16 @@ async function runPostTransformPhase(args) {
|
|
|
10942
11393
|
}
|
|
10943
11394
|
}
|
|
10944
11395
|
committedFoldBustsServedPrefix = bustsPrefix;
|
|
11396
|
+
compactionOffFoldStrip = compactionOffRenderStrip(db, head);
|
|
10945
11397
|
};
|
|
10946
11398
|
}
|
|
10947
11399
|
});
|
|
10948
11400
|
preparedPrefix = foldResult;
|
|
10949
11401
|
if (activeThinkingPrefixHold && firstRenderBust && committedFoldBustsServedPrefix) {
|
|
10950
|
-
releaseThinkingForRewrite(false, true);
|
|
11402
|
+
releaseThinkingForRewrite(false, true, compactionOffFoldStrip);
|
|
10951
11403
|
} else if (compactionOff && !activeThinkingPrefixHold && args.thinkingBindingRecoveryEnabledForModel === true && committedFoldChangesHead) {
|
|
10952
11404
|
sessionLog2(args.sessionId, "compaction-off fold changed the head: stripping signed thinking");
|
|
10953
|
-
releaseThinkingForRewrite(false, true);
|
|
11405
|
+
releaseThinkingForRewrite(false, true, compactionOffFoldStrip);
|
|
10954
11406
|
}
|
|
10955
11407
|
prefixPreflightFailed = foldResult.materializationContentionRetryExhausted === true;
|
|
10956
11408
|
foldExecutedThisPass = foldExecutesThisPass(foldDueDecision.value || softRefreshOpportunity, foldResult.m0RematerializedThisPass);
|
|
@@ -10998,8 +11450,7 @@ async function runPostTransformPhase(args) {
|
|
|
10998
11450
|
}
|
|
10999
11451
|
logTransformTiming(args.sessionId, "pp.prefixPreflight", tPostprocessSetup, `foldExecuted=${foldExecutedThisPass} m1Refreshed=${publishedM1RefreshedThisPass}`);
|
|
11000
11452
|
const tPassDecisions = performance.now();
|
|
11001
|
-
|
|
11002
|
-
if (activeThinkingPrefixHold && (args.forceSignedRebuildForFit || args.contextUsage.percentage >= 95 && frontToolCandidates.length > 0 && frontToolCandidates.every((tag) => newTargets.get(tag.tagNumber)?.thinkingRewriteProtected === true))) {
|
|
11453
|
+
if (activeThinkingPrefixHold && args.forceSignedRebuildForFit) {
|
|
11003
11454
|
releaseThinkingForRewrite(true);
|
|
11004
11455
|
}
|
|
11005
11456
|
if (activeThinkingPrefixHold) {
|
|
@@ -11070,9 +11521,17 @@ async function runPostTransformPhase(args) {
|
|
|
11070
11521
|
if (servedShapeRepair.needsRebuild && !isCacheBustingPass)
|
|
11071
11522
|
throw new Error("Served-shape repair requires a rebuilding pass");
|
|
11072
11523
|
servedShapeRepair.apply(isCacheBustingPass);
|
|
11524
|
+
const releasedFrozenHeadChanged = isCacheBustingPass && !activeThinkingPrefixHold && args.frozenRecoveryRequest !== undefined && frozenRecoveryHeadDiffers(args, m0M1EnabledForFold, args.frozenRecoveryRequest());
|
|
11525
|
+
if (releasedFrozenHeadChanged)
|
|
11526
|
+
sessionLog2(args.sessionId, "frozen replay release: the history head differs from the replay's; counting it as a head change");
|
|
11527
|
+
const restartHeadChanged = !compactionOff && args.thinkingBindingRecoveryEnabledForModel === true && args.restartedLastServedRequest !== undefined && frozenRecoveryHeadDiffers(args, m0M1EnabledForFold, args.restartedLastServedRequest());
|
|
11528
|
+
if (restartHeadChanged) {
|
|
11529
|
+
sessionLog2(args.sessionId, "restart: the history head differs from the saved last-good request's; stripping signed thinking");
|
|
11530
|
+
releaseThinkingForRewrite();
|
|
11531
|
+
}
|
|
11073
11532
|
let unheldSignedTurnBust = false;
|
|
11074
11533
|
if (isCacheBustingPass && !activeThinkingPrefixHold && activeThinkingTurn && args.thinkingBindingRecoveryEnabledForModel === true) {
|
|
11075
|
-
if (foldBustsServedPrefixThisPass || firstRenderBust || publishedM1RefreshedThisPass || hostCheckpointRide)
|
|
11534
|
+
if (foldBustsServedPrefixThisPass || firstRenderBust || publishedM1RefreshedThisPass || hostCheckpointRide || releasedFrozenHeadChanged)
|
|
11076
11535
|
releaseThinkingForRewrite();
|
|
11077
11536
|
else {
|
|
11078
11537
|
unheldSignedTurnBust = true;
|
|
@@ -11087,6 +11546,15 @@ async function runPostTransformPhase(args) {
|
|
|
11087
11546
|
const recoveredShapeRewriteProof = recoveryHeadChangedThisPass ? "head_bytes" : recoveryExternalFoldCause ?? (recoveryHeadlessRebuild ? "headless_rebuild" : null);
|
|
11088
11547
|
const canNormalizeRecoveredShape = isCacheBustingPass && !activeThinkingPrefixHold && recoveredShapeRewriteProof !== null;
|
|
11089
11548
|
sessionLog2(args.sessionId, `rewrite permission: allowed=${isCacheBustingPass} ${reclaimRideLabel(rideSignals)} served_shape_repair=${servedShapeRepair.needsRebuild} signed_prefix_release=${rewritingSignedPrefix} fold_prefix_loss=${foldBustsServedPrefixThisPass} first_render=${firstRenderBust} cache_expired=${args.m0M1?.hardSignals?.cacheExpired === true} thinking_hold=${activeThinkingPrefixHold} recovery_has_head=${recoveryHasHistoryHead} recovery_head_changed=${recoveryHeadChangedThisPass} recovery_headless_rebuild=${recoveryHeadlessRebuild} proven_external_fold=${recoveryExternalFoldCause ?? "none"} recovered_shape_proof=${recoveredShapeRewriteProof ?? "none"}`);
|
|
11549
|
+
noteServedPassPermission(args.sessionId, {
|
|
11550
|
+
permitted: isCacheBustingPass,
|
|
11551
|
+
rides: reclaimRideLabel(rideSignals),
|
|
11552
|
+
signedThinkingHold: activeThinkingPrefixHold,
|
|
11553
|
+
firstRender: firstRenderBust,
|
|
11554
|
+
hostCheckpointHead: hostCheckpointRide,
|
|
11555
|
+
emergency: forceBandConfirmed,
|
|
11556
|
+
schedulerDecision: args.schedulerDecision
|
|
11557
|
+
});
|
|
11090
11558
|
let recoveryTailNormalizedThisPass = false;
|
|
11091
11559
|
if (args.normalizeRecoveryTail && canNormalizeRecoveredShape) {
|
|
11092
11560
|
args.normalizeRecoveryTail();
|
|
@@ -11256,6 +11724,23 @@ async function runPostTransformPhase(args) {
|
|
|
11256
11724
|
}
|
|
11257
11725
|
}
|
|
11258
11726
|
let autoReclaimDidMutateThisPass = false;
|
|
11727
|
+
const emergencyPlannerMayRun = shouldRunHeuristics && forceBandConfirmed && args.emergencyCeilingTokens !== undefined && args.emergencyCeilingTokens > 0;
|
|
11728
|
+
const tagsNewerThanReading = emergencyPlannerMayRun ? tagsSinceReading(args.messages, newTargets) : undefined;
|
|
11729
|
+
let servedBeforeRemovals;
|
|
11730
|
+
if (emergencyPlannerMayRun && shouldApplyPendingOps && pendingOps.length > 0) {
|
|
11731
|
+
const queued = new Set(pendingOps.map((op) => op.tagId));
|
|
11732
|
+
const owners = new Set;
|
|
11733
|
+
for (const tagNumber of queued) {
|
|
11734
|
+
const target = newTargets.get(tagNumber);
|
|
11735
|
+
if (!target?.dropReasoningParts?.length)
|
|
11736
|
+
continue;
|
|
11737
|
+
for (const { message } of target.mutationParts ?? [])
|
|
11738
|
+
owners.add(message);
|
|
11739
|
+
if (target.message)
|
|
11740
|
+
owners.add(target.message);
|
|
11741
|
+
}
|
|
11742
|
+
servedBeforeRemovals = snapshotEmergencyServedMass(args.tags.filter((tag) => queued.has(tag.tagNumber) && !tagsNewerThanReading?.has(tag.tagNumber)), newTargets, sessionDecisionCalibration(args.db, args.sessionId), messagesAfterReplayedThinkingStrips(args, owners, compactionOff, compactionOffFrozenThinking));
|
|
11743
|
+
}
|
|
11259
11744
|
logTransformTiming(args.sessionId, "pp.passDecisions", tPassDecisions, `pendingOps=${pendingOps.length}`);
|
|
11260
11745
|
try {
|
|
11261
11746
|
if (shouldApplyPendingOps) {
|
|
@@ -11307,7 +11792,9 @@ async function runPostTransformPhase(args) {
|
|
|
11307
11792
|
currentTotalInputTokens: args.contextUsage.inputTokens,
|
|
11308
11793
|
ceilingTokens: args.emergencyCeilingTokens,
|
|
11309
11794
|
usagePercentage: args.contextUsage.percentage,
|
|
11310
|
-
passAlreadyPriced: emergencyRewriteAlreadyPriced
|
|
11795
|
+
passAlreadyPriced: emergencyRewriteAlreadyPriced,
|
|
11796
|
+
servedBeforePass: servedBeforeRemovals,
|
|
11797
|
+
sinceReading: tagsNewerThanReading
|
|
11311
11798
|
} : undefined,
|
|
11312
11799
|
routine: routineCleanupApplied,
|
|
11313
11800
|
caveman: cavemanConfig
|
|
@@ -11622,6 +12109,7 @@ async function runPostTransformPhase(args) {
|
|
|
11622
12109
|
preparedPrefix = prepareCachedM0M1Replay(args.db, args.sessionId);
|
|
11623
12110
|
}
|
|
11624
12111
|
const tInjectM0M1 = performance.now();
|
|
12112
|
+
let finalRenderStrip;
|
|
11625
12113
|
try {
|
|
11626
12114
|
const messagesBeforeInjection = args.messages.slice();
|
|
11627
12115
|
const result = injectM0M1({
|
|
@@ -11643,8 +12131,17 @@ async function runPostTransformPhase(args) {
|
|
|
11643
12131
|
allowFreshContentionFallback: forceMaterialization || emergencyDropEligible,
|
|
11644
12132
|
hardSignals: args.m0M1.hardSignals,
|
|
11645
12133
|
muralEnabled: args.m0M1.muralEnabled,
|
|
11646
|
-
compactionOff
|
|
12134
|
+
compactionOff,
|
|
12135
|
+
...compactionOff ? {
|
|
12136
|
+
onFoldPrepare: () => (db, rendered) => {
|
|
12137
|
+
finalRenderStrip = compactionOffRenderStrip(db, compareRenderedHead(rendered));
|
|
12138
|
+
}
|
|
12139
|
+
} : {}
|
|
11647
12140
|
});
|
|
12141
|
+
if (finalRenderStrip?.strip) {
|
|
12142
|
+
sessionLog2(args.sessionId, "compaction-off render changed the head: stripping signed thinking");
|
|
12143
|
+
releaseThinkingForRewrite(false, true, finalRenderStrip);
|
|
12144
|
+
}
|
|
11648
12145
|
deliveredPrefix = result;
|
|
11649
12146
|
if (result.prefixTrimStatus === "applied") {
|
|
11650
12147
|
const retainedMessages = new Set(args.messages);
|
|
@@ -11747,10 +12244,12 @@ async function runPostTransformPhase(args) {
|
|
|
11747
12244
|
const historyWasConsumedThisPass = (!m0M1Enabled || deliveredPrefix?.injected === true && !deliveredPrefix.materializationContentionRetryExhausted) && args.historyRebuiltThisPass && (args.canConsumeDeferredLate || args.phaseJustAwaitedPublication || explicitRebuildHappened) && materializationSatisfied;
|
|
11748
12245
|
let suppressV12HistoryDrain = false;
|
|
11749
12246
|
let persistedCompactionMarkerState = replaySnapshot?.compactionMarker ?? null;
|
|
12247
|
+
let markerDrainChangedServedRow = false;
|
|
11750
12248
|
if (replaySnapshot?.pendingCompactionMarker && (args.compactionMarkerStrategy ?? defaultCompactionMarkerStrategy).applyDeferred === applyDeferredCompactionMarker)
|
|
11751
12249
|
startCompactionMarkerCandidatePreparation(args.sessionId);
|
|
11752
|
-
|
|
11753
|
-
|
|
12250
|
+
const servedHeadIsCurrent = !m0M1Enabled || deliveredPrefix?.injected === true && !deliveredPrefix.materializationContentionRetryExhausted;
|
|
12251
|
+
if (isCacheBustingPass || historyWasConsumedThisPass) {
|
|
12252
|
+
const pending = servedHeadIsCurrent ? replaySnapshot?.pendingCompactionMarker ?? null : null;
|
|
11754
12253
|
if (pending) {
|
|
11755
12254
|
const pendingCovered = pendingMarkerCoveredByConsumedBoundary(pending, args.pendingCompartmentInjection);
|
|
11756
12255
|
const trimWasProven = !m0M1Enabled || deliveredPrefixWasTrimmedThroughPendingBoundary(deliveredPrefix, args.prefixTrimSourceOrder, pending) || sourceAlreadyReflectsCoveringMarker(args.sessionId, args.prefixTrimSourceOrder, persistedCompactionMarkerState, pending);
|
|
@@ -11760,6 +12259,8 @@ async function runPostTransformPhase(args) {
|
|
|
11760
12259
|
} else if (!trimWasProven) {
|
|
11761
12260
|
suppressV12HistoryDrain = true;
|
|
11762
12261
|
sessionLog2(args.sessionId, `compaction-marker drain: refusing ordinal ${pending.ordinal} because prefix trim through ${args.pendingCompartmentInjection?.compartmentEndMessageId ?? "<none>"} was not proven; preserving deferred history refresh signal`);
|
|
12262
|
+
} else if (!isCacheBustingPass) {
|
|
12263
|
+
sessionLog2(args.sessionId, `compaction-marker drain: pass has no rewrite permission; ordinal ${pending.ordinal} waits for a pass with rewrite permission`);
|
|
11763
12264
|
} else {
|
|
11764
12265
|
const tMarkerDrain = performance.now();
|
|
11765
12266
|
const strategy = args.compactionMarkerStrategy ?? defaultCompactionMarkerStrategy;
|
|
@@ -11768,13 +12269,13 @@ async function runPostTransformPhase(args) {
|
|
|
11768
12269
|
logTransformTiming(args.sessionId, "pp.markerDrain", tMarkerDrain, `outcome=${outcome.kind}`);
|
|
11769
12270
|
switch (outcome.kind) {
|
|
11770
12271
|
case "deferred":
|
|
11771
|
-
|
|
11772
|
-
sessionLog2(args.sessionId, "compaction-marker drain: candidate preparation deferred; preserving deferred history refresh signal");
|
|
12272
|
+
sessionLog2(args.sessionId, "compaction-marker drain: candidate preparation deferred; pending marker kept for the next pass with rewrite permission");
|
|
11773
12273
|
break;
|
|
11774
12274
|
case "applied":
|
|
11775
12275
|
case "already-current":
|
|
11776
12276
|
case "stale-skip":
|
|
11777
12277
|
persistedCompactionMarkerState = getPersistedCompactionMarkerState(args.db, args.sessionId);
|
|
12278
|
+
markerDrainChangedServedRow = (persistedCompactionMarkerState?.summaryMessageId ?? null) !== (replaySnapshot?.compactionMarker?.summaryMessageId ?? null);
|
|
11778
12279
|
if (clearPendingCompactionMarkerAfterSuccessfulDrain({
|
|
11779
12280
|
db: args.db,
|
|
11780
12281
|
sessionId: args.sessionId,
|
|
@@ -11785,6 +12286,10 @@ async function runPostTransformPhase(args) {
|
|
|
11785
12286
|
}
|
|
11786
12287
|
break;
|
|
11787
12288
|
case "retryable-failure":
|
|
12289
|
+
if (outcome.cut === "definitely-no-cut") {
|
|
12290
|
+
sessionLog2(args.sessionId, `compaction-marker drain: marker unchanged (reason=${isSqliteLockContentionError(outcome.error) ? "busy-writer" : "left-unchanged"}); serving rebuilt history and keeping the pending marker for the next pass with rewrite permission:`, outcome.error);
|
|
12291
|
+
break;
|
|
12292
|
+
}
|
|
11788
12293
|
failPass("compaction-marker-drain-failure", outcome.error);
|
|
11789
12294
|
sessionLog2(args.sessionId, "compaction-marker drain: retryable failure; preserving deferred history refresh signal", outcome.error);
|
|
11790
12295
|
suppressV12HistoryDrain = true;
|
|
@@ -11955,7 +12460,7 @@ async function runPostTransformPhase(args) {
|
|
|
11955
12460
|
}
|
|
11956
12461
|
const materializeReason = m0MaterializeReason ?? (explicitMaterializedSuccessfully ? pendingOrigin : null);
|
|
11957
12462
|
const materialized = m0RematerializedThisPass || explicitMaterializedSuccessfully || deferredMaterializedSuccessfully;
|
|
11958
|
-
let bustedThisPass = firstApplicationEdits.any || firstRenderBust || hostCheckpointRide || pendingOpsDidMutate || heuristicOrReasoningDidMutate || autoReclaimDidMutateThisPass || convertedToolSkeletonsDidMutate || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass;
|
|
12463
|
+
let bustedThisPass = firstApplicationEdits.any || firstRenderBust || hostCheckpointRide || pendingOpsDidMutate || heuristicOrReasoningDidMutate || autoReclaimDidMutateThisPass || convertedToolSkeletonsDidMutate || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass || markerDrainChangedServedRow;
|
|
11959
12464
|
const proactiveThinkingStripPermitted = isCacheBustingPass && !activeThinkingPrefixHold;
|
|
11960
12465
|
const tFrozenDecisions = performance.now();
|
|
11961
12466
|
if (reasoningMutationTargetUnknown) {
|
|
@@ -11989,7 +12494,7 @@ async function runPostTransformPhase(args) {
|
|
|
11989
12494
|
}
|
|
11990
12495
|
}
|
|
11991
12496
|
const flagTarget = !activeThinkingTurn && args.thinkingBindingRecoveryEnabledForModel ? replaySnapshot?.thinkingBindingRecoveryTarget ?? null : null;
|
|
11992
|
-
if (flagTarget) {
|
|
12497
|
+
if (flagTarget && !isLatestThinkingRecoveryTarget(flagTarget) && flagTarget !== args.appliedBindingRecoveryTarget) {
|
|
11993
12498
|
thinkingBindingRecovery = freezeAllReasoningForBindingRecovery({
|
|
11994
12499
|
db: args.db,
|
|
11995
12500
|
sessionId: args.sessionId,
|
|
@@ -12161,7 +12666,7 @@ async function runPostTransformPhase(args) {
|
|
|
12161
12666
|
}
|
|
12162
12667
|
}
|
|
12163
12668
|
}
|
|
12164
|
-
const prefixEditBesidesReasoningTrim = firstRenderBust || materializationRequested || explicitMaterializedSuccessfully || deferredMaterializedSuccessfully || foldBustsServedPrefixThisPass || publishedM1RefreshedThisPass || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass || pendingOpsDidMutate || heuristicOrReasoningEditBesidesTrim || emergency || autoReclaimDidMutateThisPass || convertedToolSkeletonsDidMutate || deferredClearedMarkerRetires || noteNudgeAppendedThisPass || todoAnchorMovedThisPass || autoSearchHintAppendedThisPass || dropModeSwitchesThisPass || recoveryTailNormalizedThisPass || firstApplicationEdits.beforeNewerThinking;
|
|
12669
|
+
const prefixEditBesidesReasoningTrim = firstRenderBust || materializationRequested || explicitMaterializedSuccessfully || deferredMaterializedSuccessfully || foldBustsServedPrefixThisPass || publishedM1RefreshedThisPass || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass || markerDrainChangedServedRow || pendingOpsDidMutate || heuristicOrReasoningEditBesidesTrim || emergency || autoReclaimDidMutateThisPass || convertedToolSkeletonsDidMutate || deferredClearedMarkerRetires || noteNudgeAppendedThisPass || todoAnchorMovedThisPass || autoSearchHintAppendedThisPass || dropModeSwitchesThisPass || recoveryTailNormalizedThisPass || releasedFrozenHeadChanged || firstApplicationEdits.beforeNewerThinking;
|
|
12165
12670
|
let proactiveThinkingStrip = null;
|
|
12166
12671
|
if (!compactionOff && args.thinkingBindingRecoveryEnabledForModel === true && proactiveThinkingStripPermitted && prefixEditBesidesReasoningTrim) {
|
|
12167
12672
|
const outcome = freezeReasoningOnBustingPass({
|
|
@@ -12186,9 +12691,10 @@ async function runPostTransformPhase(args) {
|
|
|
12186
12691
|
failPass("proactive-thinking-strip-persistence-failure");
|
|
12187
12692
|
}
|
|
12188
12693
|
}
|
|
12189
|
-
hostRowReclaim
|
|
12190
|
-
|
|
12191
|
-
|
|
12694
|
+
const pendingHostInstructionDecisions = hostRowReclaim || retainCoveredInstructions && !coveredRetentionOn ? {
|
|
12695
|
+
reclaim: hostRowReclaim,
|
|
12696
|
+
retention: retainCoveredInstructions && !coveredRetentionOn
|
|
12697
|
+
} : undefined;
|
|
12192
12698
|
let settledDroppedReasoning = 0;
|
|
12193
12699
|
if (!canUseEmptySentinels) {
|
|
12194
12700
|
let mode = "legacy";
|
|
@@ -12376,7 +12882,9 @@ async function runPostTransformPhase(args) {
|
|
|
12376
12882
|
prefixTrimRefusal: deliveredPrefix?.prefixTrimRefusal ?? null,
|
|
12377
12883
|
thinkingBindingRecovery,
|
|
12378
12884
|
proactiveThinkingStrip,
|
|
12379
|
-
thinkingReleasedForFit
|
|
12885
|
+
thinkingReleasedForFit,
|
|
12886
|
+
pendingHostInstructionDecisions,
|
|
12887
|
+
restartHeadChanged
|
|
12380
12888
|
};
|
|
12381
12889
|
}
|
|
12382
12890
|
function checkM0MutationDriftAndSignal(args) {
|
|
@@ -13195,6 +13703,111 @@ function createPassOutcome() {
|
|
|
13195
13703
|
};
|
|
13196
13704
|
}
|
|
13197
13705
|
|
|
13706
|
+
// src/hooks/magic-context/signed-thinking-hold.ts
|
|
13707
|
+
var HEAVY_REASONING_TOKENS = 1500;
|
|
13708
|
+
var HEAVY_REASONING_WINDOW_STEPS = 15;
|
|
13709
|
+
var HOLD_CAP_POINTS = 10;
|
|
13710
|
+
var REASONING_TYPES = new Set(["reasoning", "thinking"]);
|
|
13711
|
+
function role2(message) {
|
|
13712
|
+
if (!isRecord(message))
|
|
13713
|
+
return;
|
|
13714
|
+
return isRecord(message.info) ? message.info.role : message.role;
|
|
13715
|
+
}
|
|
13716
|
+
function parts(message) {
|
|
13717
|
+
if (!isRecord(message))
|
|
13718
|
+
return [];
|
|
13719
|
+
if (Array.isArray(message.parts))
|
|
13720
|
+
return message.parts;
|
|
13721
|
+
return Array.isArray(message.content) ? message.content : [];
|
|
13722
|
+
}
|
|
13723
|
+
function recordedReasoningTokens(message) {
|
|
13724
|
+
if (!isRecord(message))
|
|
13725
|
+
return;
|
|
13726
|
+
const info = isRecord(message.info) ? message.info : undefined;
|
|
13727
|
+
const candidates = [];
|
|
13728
|
+
if (info && isRecord(info.tokens))
|
|
13729
|
+
candidates.push(info.tokens.reasoning);
|
|
13730
|
+
if (isRecord(message.usage)) {
|
|
13731
|
+
candidates.push(message.usage.reasoning, message.usage.reasoningTokens);
|
|
13732
|
+
}
|
|
13733
|
+
for (const value of candidates) {
|
|
13734
|
+
if (typeof value === "number" && Number.isFinite(value) && value > 0)
|
|
13735
|
+
return value;
|
|
13736
|
+
}
|
|
13737
|
+
return;
|
|
13738
|
+
}
|
|
13739
|
+
function stepReasoningTokens(message, estimateTextTokens) {
|
|
13740
|
+
let text = "";
|
|
13741
|
+
let opaque = false;
|
|
13742
|
+
for (const part of parts(message)) {
|
|
13743
|
+
if (!isRecord(part))
|
|
13744
|
+
continue;
|
|
13745
|
+
const type = String(part.type ?? part.kind);
|
|
13746
|
+
if (type === "redacted_thinking" || part.redacted === true) {
|
|
13747
|
+
opaque = true;
|
|
13748
|
+
continue;
|
|
13749
|
+
}
|
|
13750
|
+
if (!REASONING_TYPES.has(type))
|
|
13751
|
+
continue;
|
|
13752
|
+
const body = typeof part.thinking === "string" ? part.thinking : typeof part.text === "string" ? part.text : "";
|
|
13753
|
+
if (body.length > 0)
|
|
13754
|
+
text += body;
|
|
13755
|
+
else
|
|
13756
|
+
opaque = true;
|
|
13757
|
+
}
|
|
13758
|
+
if (!text && !opaque)
|
|
13759
|
+
return 0;
|
|
13760
|
+
return reasoningStepCost(recordedReasoningTokens(message), text ? estimateTextTokens(text) : 0, opaque);
|
|
13761
|
+
}
|
|
13762
|
+
function decideSignedThinkingHold(args) {
|
|
13763
|
+
const capPercentage = args.executeThresholdPercentage + HOLD_CAP_POINTS;
|
|
13764
|
+
let heavyStepsBack = null;
|
|
13765
|
+
let heavyStepTokens = 0;
|
|
13766
|
+
const start = latestAssistantTurnStart(args.messages);
|
|
13767
|
+
let stepsBack = 0;
|
|
13768
|
+
for (let index = args.messages.length - 1;index >= start; index--) {
|
|
13769
|
+
const message = args.messages[index];
|
|
13770
|
+
if (role2(message) !== "assistant" || parts(message).length === 0)
|
|
13771
|
+
continue;
|
|
13772
|
+
stepsBack++;
|
|
13773
|
+
if (stepsBack > HEAVY_REASONING_WINDOW_STEPS)
|
|
13774
|
+
break;
|
|
13775
|
+
const tokens = stepReasoningTokens(message, args.estimateTextTokens);
|
|
13776
|
+
if (tokens > HEAVY_REASONING_TOKENS) {
|
|
13777
|
+
heavyStepsBack = stepsBack;
|
|
13778
|
+
heavyStepTokens = tokens;
|
|
13779
|
+
break;
|
|
13780
|
+
}
|
|
13781
|
+
}
|
|
13782
|
+
if (heavyStepsBack === null)
|
|
13783
|
+
return {
|
|
13784
|
+
held: false,
|
|
13785
|
+
reason: "no_recent_heavy_reasoning",
|
|
13786
|
+
heavyStepsBack,
|
|
13787
|
+
heavyStepTokens,
|
|
13788
|
+
capPercentage
|
|
13789
|
+
};
|
|
13790
|
+
const ended = readingEndsHold({
|
|
13791
|
+
usagePercentage: args.usagePercentage,
|
|
13792
|
+
capPercentage,
|
|
13793
|
+
forceBandPressure: args.forceBandPressure
|
|
13794
|
+
});
|
|
13795
|
+
if (ended !== null)
|
|
13796
|
+
return { held: false, reason: ended, heavyStepsBack, heavyStepTokens, capPercentage };
|
|
13797
|
+
return {
|
|
13798
|
+
held: true,
|
|
13799
|
+
reason: "heavy_reasoning",
|
|
13800
|
+
heavyStepsBack,
|
|
13801
|
+
heavyStepTokens,
|
|
13802
|
+
capPercentage
|
|
13803
|
+
};
|
|
13804
|
+
}
|
|
13805
|
+
function readingEndsHold(args) {
|
|
13806
|
+
if (!(args.usagePercentage < args.capPercentage))
|
|
13807
|
+
return "above_cap";
|
|
13808
|
+
return args.forceBandPressure ? "force_band" : null;
|
|
13809
|
+
}
|
|
13810
|
+
|
|
13198
13811
|
// src/hooks/magic-context/priced-pass-sizing.ts
|
|
13199
13812
|
var REASONING_PART_TYPES = new Set(["reasoning", "thinking", "redacted_thinking"]);
|
|
13200
13813
|
var WIDEST_PRICED_PASS_PLAN = {
|
|
@@ -13211,6 +13824,11 @@ function planPricedPass(input, usage) {
|
|
|
13211
13824
|
schedulerDecision: input.schedulerDecision
|
|
13212
13825
|
});
|
|
13213
13826
|
const emergencySample = () => getEmergencyInputSample(input.db, input.sessionId);
|
|
13827
|
+
const signedThinkingHold = input.signedThinkingHold && (input.signedThinkingHoldCapPercentage === undefined ? !bands.forceBandConfirmed : readingEndsHold({
|
|
13828
|
+
usagePercentage: usage.percentage,
|
|
13829
|
+
capPercentage: input.signedThinkingHoldCapPercentage,
|
|
13830
|
+
forceBandPressure: bands.forceBandConfirmed
|
|
13831
|
+
}) === null);
|
|
13214
13832
|
const rides = {
|
|
13215
13833
|
hardFold: input.folds || input.firstRender,
|
|
13216
13834
|
force: forceRide({
|
|
@@ -13226,11 +13844,11 @@ function planPricedPass(input, usage) {
|
|
|
13226
13844
|
servedShapeRepair: false
|
|
13227
13845
|
};
|
|
13228
13846
|
const drainAllowed = !input.compactionOff && reclaimRidePermitted(rides, {
|
|
13229
|
-
signedThinkingHold
|
|
13847
|
+
signedThinkingHold,
|
|
13230
13848
|
firstRender: input.firstRender,
|
|
13231
13849
|
emergency: bands.forceBandConfirmed
|
|
13232
13850
|
});
|
|
13233
|
-
const materializationRequested = !
|
|
13851
|
+
const materializationRequested = !signedThinkingHold && input.materializationRequested;
|
|
13234
13852
|
const heuristics = heuristicsRunOnPass({
|
|
13235
13853
|
compactionOff: input.compactionOff,
|
|
13236
13854
|
drainAllowed,
|
|
@@ -13257,8 +13875,8 @@ function planPricedPass(input, usage) {
|
|
|
13257
13875
|
rewriteAlreadyPriced: input.folds || input.firstRender || input.historyRebuilt
|
|
13258
13876
|
});
|
|
13259
13877
|
return {
|
|
13260
|
-
editsWholePrefix: drainAllowed && !
|
|
13261
|
-
clearsReasoning: routine && !
|
|
13878
|
+
editsWholePrefix: drainAllowed && !signedThinkingHold,
|
|
13879
|
+
clearsReasoning: routine && !signedThinkingHold
|
|
13262
13880
|
};
|
|
13263
13881
|
}
|
|
13264
13882
|
function sameSizingPlan(input, a, b) {
|
|
@@ -17735,12 +18353,15 @@ function createRustModeTransform(deps, options) {
|
|
|
17735
18353
|
}
|
|
17736
18354
|
const inputCount = messages.length;
|
|
17737
18355
|
const inputHasActiveThinking = hasActiveAnthropicThinkingTurn(messages, "anthropic");
|
|
18356
|
+
const rustRecoveryModel = modelFromMessages(messages) ?? deps.liveModelBySession?.get(sessionId);
|
|
17738
18357
|
const thinkingRecovery = prepareLatestThinkingRecovery({
|
|
17739
18358
|
db: deps.db,
|
|
17740
18359
|
sessionId,
|
|
17741
18360
|
messages,
|
|
17742
18361
|
id: (message) => message?.info.id,
|
|
17743
|
-
parts: (message) => message?.parts ?? []
|
|
18362
|
+
parts: (message) => message?.parts ?? [],
|
|
18363
|
+
modelID: rustRecoveryModel?.modelID,
|
|
18364
|
+
providerID: rustRecoveryModel?.providerID
|
|
17744
18365
|
});
|
|
17745
18366
|
const restoreLatestTurnOriginals = thinkingRecovery.restore ? captureLatestTurnOriginals(messages) : undefined;
|
|
17746
18367
|
let requestInputTokens = 0;
|
|
@@ -17987,7 +18608,7 @@ function createRustModeTransform(deps, options) {
|
|
|
17987
18608
|
writeRustTransformDecision({
|
|
17988
18609
|
sessionId,
|
|
17989
18610
|
decision,
|
|
17990
|
-
materializeReason: materializeReason === "none" ?
|
|
18611
|
+
materializeReason: thinkingRecovery.removedThisPass && (materializeReason === "none" || materializeReason === "ttl_idle") ? LATEST_TURN_THINKING_REMOVED_REASON : materializeReason !== "none" ? materializeReason : null,
|
|
17991
18612
|
inputTokens: requestInputTokens,
|
|
17992
18613
|
tsMs: passObservedAtMs,
|
|
17993
18614
|
lkgFrozenReleaseReason: applied && served && frozenReleaseReason ? `${frozenReleaseReason};first_changed=${frozenReleaseFirstChanged}` : undefined
|
|
@@ -18891,7 +19512,7 @@ function createRustModeTransform(deps, options) {
|
|
|
18891
19512
|
const activeThinkingTurn = inputHasActiveThinking && isAnthropicFamilyRoute(model?.providerID, model?.modelID);
|
|
18892
19513
|
const postprocess = runRustModePostprocess({
|
|
18893
19514
|
activeThinkingTurn,
|
|
18894
|
-
protectedThinkingMessages: thinkingRecovery.restore ? protectedThinkingMessages : undefined,
|
|
19515
|
+
protectedThinkingMessages: thinkingRecovery.restore ? restoredTurnMessages(appliedMessages, protectedThinkingMessages) : undefined,
|
|
18895
19516
|
restoreLatestTurnOriginals: () => restoreLatestTurnOriginals?.(appliedMessages),
|
|
18896
19517
|
db: deps.db,
|
|
18897
19518
|
sessionId,
|
|
@@ -19051,7 +19672,7 @@ function createRustModeTransform(deps, options) {
|
|
|
19051
19672
|
}
|
|
19052
19673
|
}
|
|
19053
19674
|
const endRecoveryAfterResetCapture = () => {
|
|
19054
|
-
if (signedThinkingReset
|
|
19675
|
+
if (signedThinkingReset) {
|
|
19055
19676
|
endLatestThinkingRecoveryAfterReset(deps.db, sessionId);
|
|
19056
19677
|
}
|
|
19057
19678
|
};
|
|
@@ -19500,101 +20121,6 @@ function takeSignedThinkingFitSnapshot(args) {
|
|
|
19500
20121
|
}
|
|
19501
20122
|
var snapshotObserver;
|
|
19502
20123
|
|
|
19503
|
-
// src/hooks/magic-context/signed-thinking-hold.ts
|
|
19504
|
-
var HEAVY_REASONING_TOKENS = 1500;
|
|
19505
|
-
var HEAVY_REASONING_WINDOW_STEPS = 15;
|
|
19506
|
-
var HOLD_CAP_POINTS = 10;
|
|
19507
|
-
var REASONING_TYPES = new Set(["reasoning", "thinking"]);
|
|
19508
|
-
function role2(message) {
|
|
19509
|
-
if (!isRecord(message))
|
|
19510
|
-
return;
|
|
19511
|
-
return isRecord(message.info) ? message.info.role : message.role;
|
|
19512
|
-
}
|
|
19513
|
-
function parts(message) {
|
|
19514
|
-
if (!isRecord(message))
|
|
19515
|
-
return [];
|
|
19516
|
-
if (Array.isArray(message.parts))
|
|
19517
|
-
return message.parts;
|
|
19518
|
-
return Array.isArray(message.content) ? message.content : [];
|
|
19519
|
-
}
|
|
19520
|
-
function recordedReasoningTokens(message) {
|
|
19521
|
-
if (!isRecord(message))
|
|
19522
|
-
return;
|
|
19523
|
-
const info = isRecord(message.info) ? message.info : undefined;
|
|
19524
|
-
const candidates = [];
|
|
19525
|
-
if (info && isRecord(info.tokens))
|
|
19526
|
-
candidates.push(info.tokens.reasoning);
|
|
19527
|
-
if (isRecord(message.usage)) {
|
|
19528
|
-
candidates.push(message.usage.reasoning, message.usage.reasoningTokens);
|
|
19529
|
-
}
|
|
19530
|
-
for (const value of candidates) {
|
|
19531
|
-
if (typeof value === "number" && Number.isFinite(value) && value > 0)
|
|
19532
|
-
return value;
|
|
19533
|
-
}
|
|
19534
|
-
return;
|
|
19535
|
-
}
|
|
19536
|
-
function stepReasoningTokens(message, estimateTextTokens) {
|
|
19537
|
-
let text = "";
|
|
19538
|
-
let opaque = false;
|
|
19539
|
-
for (const part of parts(message)) {
|
|
19540
|
-
if (!isRecord(part))
|
|
19541
|
-
continue;
|
|
19542
|
-
const type = String(part.type ?? part.kind);
|
|
19543
|
-
if (type === "redacted_thinking" || part.redacted === true) {
|
|
19544
|
-
opaque = true;
|
|
19545
|
-
continue;
|
|
19546
|
-
}
|
|
19547
|
-
if (!REASONING_TYPES.has(type))
|
|
19548
|
-
continue;
|
|
19549
|
-
const body = typeof part.thinking === "string" ? part.thinking : typeof part.text === "string" ? part.text : "";
|
|
19550
|
-
if (body.length > 0)
|
|
19551
|
-
text += body;
|
|
19552
|
-
else
|
|
19553
|
-
opaque = true;
|
|
19554
|
-
}
|
|
19555
|
-
if (!text && !opaque)
|
|
19556
|
-
return 0;
|
|
19557
|
-
return reasoningStepCost(recordedReasoningTokens(message), text ? estimateTextTokens(text) : 0, opaque);
|
|
19558
|
-
}
|
|
19559
|
-
function decideSignedThinkingHold(args) {
|
|
19560
|
-
const capPercentage = args.executeThresholdPercentage + HOLD_CAP_POINTS;
|
|
19561
|
-
let heavyStepsBack = null;
|
|
19562
|
-
let heavyStepTokens = 0;
|
|
19563
|
-
const start = latestAssistantTurnStart(args.messages);
|
|
19564
|
-
let stepsBack = 0;
|
|
19565
|
-
for (let index = args.messages.length - 1;index >= start; index--) {
|
|
19566
|
-
const message = args.messages[index];
|
|
19567
|
-
if (role2(message) !== "assistant" || parts(message).length === 0)
|
|
19568
|
-
continue;
|
|
19569
|
-
stepsBack++;
|
|
19570
|
-
if (stepsBack > HEAVY_REASONING_WINDOW_STEPS)
|
|
19571
|
-
break;
|
|
19572
|
-
const tokens = stepReasoningTokens(message, args.estimateTextTokens);
|
|
19573
|
-
if (tokens > HEAVY_REASONING_TOKENS) {
|
|
19574
|
-
heavyStepsBack = stepsBack;
|
|
19575
|
-
heavyStepTokens = tokens;
|
|
19576
|
-
break;
|
|
19577
|
-
}
|
|
19578
|
-
}
|
|
19579
|
-
if (heavyStepsBack === null)
|
|
19580
|
-
return {
|
|
19581
|
-
held: false,
|
|
19582
|
-
reason: "no_recent_heavy_reasoning",
|
|
19583
|
-
heavyStepsBack,
|
|
19584
|
-
heavyStepTokens,
|
|
19585
|
-
capPercentage
|
|
19586
|
-
};
|
|
19587
|
-
if (!(args.usagePercentage < capPercentage))
|
|
19588
|
-
return { held: false, reason: "above_cap", heavyStepsBack, heavyStepTokens, capPercentage };
|
|
19589
|
-
return {
|
|
19590
|
-
held: true,
|
|
19591
|
-
reason: "heavy_reasoning",
|
|
19592
|
-
heavyStepsBack,
|
|
19593
|
-
heavyStepTokens,
|
|
19594
|
-
capPercentage
|
|
19595
|
-
};
|
|
19596
|
-
}
|
|
19597
|
-
|
|
19598
20124
|
// src/hooks/magic-context/temporal-served-projection.ts
|
|
19599
20125
|
function readLkgTemporalDecisions(db, sessionId, runtime) {
|
|
19600
20126
|
const slot = getInMemorySlot(sessionId) ?? loadPersistedLkgSlot(db, sessionId);
|
|
@@ -20122,6 +20648,14 @@ function historyBoundaryRefusalCause(trimRefusal, boundaryInStore) {
|
|
|
20122
20648
|
return trimRefusal ?? undefined;
|
|
20123
20649
|
}
|
|
20124
20650
|
// src/hooks/magic-context/transform.ts
|
|
20651
|
+
function afterCapture(sessionId, statement, run) {
|
|
20652
|
+
try {
|
|
20653
|
+
return run();
|
|
20654
|
+
} catch (error) {
|
|
20655
|
+
sessionLog2(sessionId, `${statement} failed after the request was decided; serving the pass:`, error);
|
|
20656
|
+
return;
|
|
20657
|
+
}
|
|
20658
|
+
}
|
|
20125
20659
|
var MESSAGE_TOKENS_CACHE_MAX = 100;
|
|
20126
20660
|
var messageTokensBySession = new BoundedSessionMap(MESSAGE_TOKENS_CACHE_MAX);
|
|
20127
20661
|
function getMessageTokensCache(sessionId) {
|
|
@@ -20447,12 +20981,21 @@ function createTransform(deps) {
|
|
|
20447
20981
|
}
|
|
20448
20982
|
}
|
|
20449
20983
|
const activeThinkingModel = findLastAssistantModel(messages) ?? deps.liveModelBySession?.get(sessionId);
|
|
20984
|
+
const thinkingRecoveryModel = findNewestUserModel(messages) ?? deps.liveModelBySession?.get(sessionId);
|
|
20985
|
+
try {
|
|
20986
|
+
retryBindingRecoveryClear(db, sessionId);
|
|
20987
|
+
} catch (error) {
|
|
20988
|
+
sessionLog2(sessionId, "thinking binding recovery: retried clear failed:", error);
|
|
20989
|
+
}
|
|
20990
|
+
const appliedBindingRecoveryTarget = bindingRecoveryAwaitingClear(sessionId);
|
|
20450
20991
|
const thinkingRecovery = prepareLatestThinkingRecovery({
|
|
20451
20992
|
db,
|
|
20452
20993
|
sessionId,
|
|
20453
20994
|
messages,
|
|
20454
20995
|
id: (message) => message?.info.id,
|
|
20455
|
-
parts: (message) => message?.parts ?? []
|
|
20996
|
+
parts: (message) => message?.parts ?? [],
|
|
20997
|
+
modelID: thinkingRecoveryModel?.modelID,
|
|
20998
|
+
providerID: thinkingRecoveryModel?.providerID
|
|
20456
20999
|
});
|
|
20457
21000
|
if (thinkingRecovery.ended)
|
|
20458
21001
|
deps.pendingMaterializationSessions?.add(sessionId);
|
|
@@ -20606,6 +21149,7 @@ function createTransform(deps) {
|
|
|
20606
21149
|
deps.liveModelBySession?.set(sessionId, recovered);
|
|
20607
21150
|
}
|
|
20608
21151
|
}
|
|
21152
|
+
noteServedModel(sessionId, modelForBudget);
|
|
20609
21153
|
const resolvedProviderID = modelForBudget?.providerID;
|
|
20610
21154
|
activeThinkingTurn ||= hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID);
|
|
20611
21155
|
const signedThinkingPrefixBound = activeThinkingTurn && (isPrefixBoundThinkingModel(activeThinkingModel?.providerID, activeThinkingModel?.modelID) || isPrefixBoundThinkingModel(resolvedProviderID, modelForBudget?.modelID));
|
|
@@ -20678,6 +21222,12 @@ function createTransform(deps) {
|
|
|
20678
21222
|
messages,
|
|
20679
21223
|
usagePercentage: contextUsageEarly.percentage,
|
|
20680
21224
|
executeThresholdPercentage: effectiveExecuteThresholdPercentage,
|
|
21225
|
+
forceBandPressure: forceBandConfirmed({
|
|
21226
|
+
percentage: contextUsageEarly.percentage,
|
|
21227
|
+
fromEstimate: hostOverWindow,
|
|
21228
|
+
forceMaterializationPercentage,
|
|
21229
|
+
compactionOff
|
|
21230
|
+
}),
|
|
20681
21231
|
estimateTextTokens: (text) => {
|
|
20682
21232
|
holdProseRatio ??= sessionDecisionCalibration(db, sessionId).proseRatio;
|
|
20683
21233
|
return estimateTokens(text) * holdProseRatio;
|
|
@@ -21330,6 +21880,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21330
21880
|
schedulerDecision,
|
|
21331
21881
|
forceMaterializationPercentage,
|
|
21332
21882
|
signedThinkingHold: activeThinkingPrefixHold,
|
|
21883
|
+
signedThinkingHoldCapPercentage: !compactionOff && signedThinkingHold?.held === true ? signedThinkingHold.capPercentage : undefined,
|
|
21333
21884
|
firstRender: servesHead && !(sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) && !hasCompleteCachedM0M1(db, sessionId),
|
|
21334
21885
|
folds: protectionFoldWillBust,
|
|
21335
21886
|
explicitFlush: hasPendingMaterializationOrigin(deps.pendingMaterializationSessions, sessionId, "user_flush"),
|
|
@@ -21444,6 +21995,20 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21444
21995
|
sessionLog2(sessionId, `transform: unknown provider usage; using ${reading.usedProviderInput ? "provider-proven input" : "wire estimate"} for priced pass inputTokens=${contextUsage.inputTokens} percentage=${contextUsage.percentage.toFixed(1)} trusted=${pressureEstimate.trusted} wireTokens=${pressureEstimate.tokens} pressureTokens=${pressureEstimate.pressureTokens}${reading.grewPastSavedReading ? ` grewPastSavedReading=${savedProviderReading?.percentage.toFixed(1)}` : ""} ${sizedPlan}`);
|
|
21445
21996
|
}
|
|
21446
21997
|
}
|
|
21998
|
+
const sizedHoldEnd = activeThinkingPrefixHold && !compactionOff && signedThinkingHold?.held === true ? readingEndsHold({
|
|
21999
|
+
usagePercentage: contextUsage.percentage,
|
|
22000
|
+
capPercentage: signedThinkingHold.capPercentage,
|
|
22001
|
+
forceBandPressure: forceBandConfirmed({
|
|
22002
|
+
percentage: contextUsage.percentage,
|
|
22003
|
+
fromEstimate: contextUsageFromEstimate,
|
|
22004
|
+
forceMaterializationPercentage,
|
|
22005
|
+
compactionOff
|
|
22006
|
+
})
|
|
22007
|
+
}) : null;
|
|
22008
|
+
if (sizedHoldEnd !== null && signedThinkingHold) {
|
|
22009
|
+
activeThinkingPrefixHold = false;
|
|
22010
|
+
sessionLog2(sessionId, `signed thinking hold: held=false reason=${sizedHoldEnd} heavyStepsBack=${signedThinkingHold.heavyStepsBack ?? "none"} heavyStepTokens=${signedThinkingHold.heavyStepTokens} usage=${contextUsage.percentage.toFixed(1)}% cap=${signedThinkingHold.capPercentage}% (sized reading${contextUsageFromEstimate ? ", local count" : ""})`);
|
|
22011
|
+
}
|
|
21447
22012
|
const protectionUsableSoft = windowGeometry?.usableSoft ?? boundaryContextLimit;
|
|
21448
22013
|
const protectionFloor = resolveEpochFloorForPass(db, sessionId, {
|
|
21449
22014
|
configuredOverride: deps.protectedTokens,
|
|
@@ -21468,6 +22033,22 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21468
22033
|
opencode2: deps.storeGeneration === "v2",
|
|
21469
22034
|
structuralSentinelUpgradeFailed,
|
|
21470
22035
|
releaseRecoveryPrefix: releaseRecoveryReplay,
|
|
22036
|
+
frozenRecoveryRequest: recovery.prefix ? () => {
|
|
22037
|
+
try {
|
|
22038
|
+
const frozen = JSON.parse(recovery.prefix?.json ?? "null");
|
|
22039
|
+
return Array.isArray(frozen) ? frozen : null;
|
|
22040
|
+
} catch {
|
|
22041
|
+
return null;
|
|
22042
|
+
}
|
|
22043
|
+
} : undefined,
|
|
22044
|
+
restartedLastServedRequest: recovery.restartedSlotJson !== undefined ? () => {
|
|
22045
|
+
try {
|
|
22046
|
+
const saved = JSON.parse(recovery.restartedSlotJson ?? "");
|
|
22047
|
+
return Array.isArray(saved) ? saved : null;
|
|
22048
|
+
} catch {
|
|
22049
|
+
return null;
|
|
22050
|
+
}
|
|
22051
|
+
} : undefined,
|
|
21471
22052
|
normalizeRecoveryTail,
|
|
21472
22053
|
compactionMarkerStrategy: deps.compactionMarkerStrategy ?? defaultCompactionMarkerStrategy,
|
|
21473
22054
|
sessionId,
|
|
@@ -21549,10 +22130,11 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21549
22130
|
protectedTools: deps.protectedTools,
|
|
21550
22131
|
resolvedProviderID,
|
|
21551
22132
|
activeThinkingTurn,
|
|
21552
|
-
protectedThinkingMessages: thinkingRecovery.restore ? protectedThinkingMessages : undefined,
|
|
21553
|
-
restoreThinkingMessageIds: thinkingRecovery.restore ? new Set([...protectedThinkingMessages].flatMap((message) => typeof message.info.id === "string" ? [message.info.id] : [])) : undefined,
|
|
22133
|
+
protectedThinkingMessages: thinkingRecovery.restore ? restoredTurnMessages(messages, protectedThinkingMessages) : undefined,
|
|
22134
|
+
restoreThinkingMessageIds: thinkingRecovery.restore ? new Set([...restoredTurnMessages(messages, protectedThinkingMessages)].flatMap((message) => typeof message.info.id === "string" ? [message.info.id] : [])) : undefined,
|
|
21554
22135
|
restoreLatestTurnOriginals,
|
|
21555
22136
|
resolvedModelID: modelForBudget?.modelID,
|
|
22137
|
+
appliedBindingRecoveryTarget,
|
|
21556
22138
|
thinkingBindingRecoveryEnabledForModel: isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID),
|
|
21557
22139
|
trailingBlankSourceDecisions,
|
|
21558
22140
|
passOutcome,
|
|
@@ -21587,7 +22169,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21587
22169
|
const suffix = recoveryTailSources.flatMap(({ identity, pristineSystem }) => pristineSystem ? [pristineSystem] : renderedById.get(identity) ?? []);
|
|
21588
22170
|
messages.splice(0, messages.length, ...JSON.parse(recovery.prefix.json), ...suffix);
|
|
21589
22171
|
}
|
|
21590
|
-
const recoveryReleaseReason = recovery.rebuildReason ?? (recoveryNormalized ? "recovery_tail_normalized" : recoveryReleased ? "recovery_prefix_released" : undefined);
|
|
22172
|
+
const recoveryReleaseReason = recovery.rebuildReason ?? (recoveryNormalized ? "recovery_tail_normalized" : recoveryReleased ? "recovery_prefix_released" : postTransformResult.restartHeadChanged ? "lkg_restart_head_changed" : undefined);
|
|
21591
22173
|
if (recoveryReleaseReason)
|
|
21592
22174
|
postTransformResult.bustedThisPass = true;
|
|
21593
22175
|
passOutcome.markFinalized();
|
|
@@ -21853,11 +22435,25 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21853
22435
|
if (!finalWireEstimate) {
|
|
21854
22436
|
sessionLog2(sessionId, `transform: final-wire telemetry estimate=unavailable trusted=false conversation=unknown tools=unknown system=unknown toolDefinitions=unknown tail=${finalWireTail}`);
|
|
21855
22437
|
}
|
|
22438
|
+
const instructionDecisions = postTransformResult.pendingHostInstructionDecisions;
|
|
22439
|
+
const reclaim = instructionDecisions?.reclaim;
|
|
22440
|
+
const decisionsDue = instructionDecisions !== undefined && (instructionDecisions.retention || reclaim?.hasDecisions === true);
|
|
21856
22441
|
if (!compactionOff) {
|
|
21857
22442
|
const stillUntagged = untaggedReplayTailServed && !recoveryNormalized ? [...untaggedReplayIds] : [];
|
|
21858
|
-
|
|
22443
|
+
const untaggedChanged = JSON.stringify([...new Set(stillUntagged)].sort()) !== JSON.stringify([...new Set(persistedUntaggedInputIds)].sort());
|
|
22444
|
+
if ((untaggedChanged || decisionsDue) && !persistLkgUntaggedInputIds(db, sessionId, untaggedChanged ? stillUntagged : undefined, decisionsDue ? (doc) => recordHostInstructionDecisions(doc, {
|
|
22445
|
+
retention: instructionDecisions?.retention === true,
|
|
22446
|
+
record: reclaim ? (target) => reclaim.record(target) : undefined
|
|
22447
|
+
}) : undefined)) {
|
|
22448
|
+
if (decisionsDue) {
|
|
22449
|
+
const failure = new Error("Cannot persist the last-good records with this pass's instruction-row decisions");
|
|
22450
|
+
sessionLog2(sessionId, "transform refused degraded pass site=host-instruction-retention-persistence-failure:", failure);
|
|
22451
|
+
failPass("host-instruction-retention-persistence-failure", failure);
|
|
22452
|
+
}
|
|
21859
22453
|
throw new Error("Cannot persist the last-good untagged-message record");
|
|
22454
|
+
}
|
|
21860
22455
|
}
|
|
22456
|
+
reclaim?.markRetired();
|
|
21861
22457
|
const signedThinkingServed = isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID) && servesThinkingBlock(messages, modelForBudget?.providerID, modelForBudget?.modelID);
|
|
21862
22458
|
finishSystemDateRefresh(deps.historyRefreshSessions, dateRequest, postTransformResult.bustedThisPass && !activeThinkingPrefixHold && !signedThinkingServed || postTransformResult.thinkingReleasedForFit === true, signedThinkingServed);
|
|
21863
22459
|
if (activeThinkingPrefixHold && !postTransformResult.thinkingReleasedForFit && sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) {
|
|
@@ -21878,8 +22474,10 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21878
22474
|
agentName: notificationParams?.agent
|
|
21879
22475
|
});
|
|
21880
22476
|
if (captured) {
|
|
21881
|
-
|
|
21882
|
-
|
|
22477
|
+
afterCapture(sessionId, "deferred last-good save", () => {
|
|
22478
|
+
const capturedSlot = getInMemorySlot(sessionId);
|
|
22479
|
+
if (!capturedSlot)
|
|
22480
|
+
return;
|
|
21883
22481
|
const revision = lkgDirtyRevision(sessionId) ?? dirtyLkgRecoveryRevision(sessionId, capturedSlot);
|
|
21884
22482
|
const fence = {
|
|
21885
22483
|
ownDirtyRevision: revision,
|
|
@@ -21899,7 +22497,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21899
22497
|
sessionLog2(sessionId, "Last-good deferred publication remains uncertified:", error);
|
|
21900
22498
|
}
|
|
21901
22499
|
}));
|
|
21902
|
-
}
|
|
22500
|
+
});
|
|
21903
22501
|
noteLkgHealthyPrefix(sessionId, lkgInput, messages, !!recoveryReleaseReason);
|
|
21904
22502
|
}
|
|
21905
22503
|
if (!captured) {
|
|
@@ -21913,94 +22511,98 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
21913
22511
|
}
|
|
21914
22512
|
sessionLog2(sessionId, `lkg_capture_declined degradations=${passOutcome.degradations.map((item) => item.site).join(",")}`);
|
|
21915
22513
|
}
|
|
21916
|
-
|
|
21917
|
-
|
|
21918
|
-
|
|
21919
|
-
|
|
21920
|
-
|
|
21921
|
-
|
|
21922
|
-
|
|
21923
|
-
|
|
21924
|
-
|
|
21925
|
-
|
|
21926
|
-
|
|
21927
|
-
|
|
21928
|
-
|
|
21929
|
-
|
|
21930
|
-
|
|
21931
|
-
|
|
21932
|
-
|
|
21933
|
-
|
|
21934
|
-
|
|
21935
|
-
|
|
21936
|
-
|
|
21937
|
-
|
|
21938
|
-
|
|
21939
|
-
|
|
21940
|
-
|
|
21941
|
-
|
|
21942
|
-
|
|
21943
|
-
|
|
21944
|
-
|
|
21945
|
-
|
|
21946
|
-
|
|
21947
|
-
|
|
21948
|
-
|
|
21949
|
-
|
|
21950
|
-
|
|
21951
|
-
|
|
21952
|
-
|
|
21953
|
-
|
|
21954
|
-
|
|
21955
|
-
const msgTokens = getMessageTokensCache(sessionId);
|
|
21956
|
-
let storedByMessage = new Map;
|
|
21957
|
-
const uncachedMessageIds = messages.flatMap((message) => {
|
|
21958
|
-
const messageId = message.info.id;
|
|
21959
|
-
return messageId !== undefined && !msgTokens.has(messageId) ? [messageId] : [];
|
|
22514
|
+
afterCapture(sessionId, "transform decision record", () => {
|
|
22515
|
+
if (postTransformResult.bustedThisPass || hardCacheExpired || thinkingRecovery.removedThisPass) {
|
|
22516
|
+
recordPendingTransformDecision(sessionId, {
|
|
22517
|
+
tsMs: Date.now(),
|
|
22518
|
+
decision: schedulerDecision,
|
|
22519
|
+
materialized: postTransformResult.materialized,
|
|
22520
|
+
materializeReason: normalizeMaterializeReason("opencode", postTransformResult.materializeReason ?? (thinkingRecovery.removedThisPass ? LATEST_TURN_THINKING_REMOVED_REASON : hardCacheExpired ? "ttl_idle" : null), postTransformResult.materialized),
|
|
22521
|
+
systemHashPrev: postTransformResult.systemHashPrev,
|
|
22522
|
+
systemHashNew: postTransformResult.systemHashNew,
|
|
22523
|
+
m0ToolSetHashPrev: postTransformResult.m0ToolSetHashPrev,
|
|
22524
|
+
m0ToolSetHashNew: postTransformResult.m0ToolSetHashNew,
|
|
22525
|
+
m0ModelKeyPrev: postTransformResult.m0ModelKeyPrev,
|
|
22526
|
+
m0ModelKeyNew: postTransformResult.m0ModelKeyNew,
|
|
22527
|
+
emergency: postTransformResult.emergency,
|
|
22528
|
+
droppedTokens: postTransformResult.droppedTokens,
|
|
22529
|
+
droppedCount: postTransformResult.droppedCount,
|
|
22530
|
+
inputTokens: contextUsage.inputTokens,
|
|
22531
|
+
bustedThisPass: true,
|
|
22532
|
+
lkgFrozenReleaseReason: recoveryReleaseReason
|
|
22533
|
+
});
|
|
22534
|
+
} else {
|
|
22535
|
+
noteOpenCodeUnbustedPass(sessionId, {
|
|
22536
|
+
tsMs: Date.now(),
|
|
22537
|
+
decision: schedulerDecision,
|
|
22538
|
+
materialized: postTransformResult.materialized,
|
|
22539
|
+
materializeReason: normalizeMaterializeReason("opencode", postTransformResult.materializeReason, postTransformResult.materialized),
|
|
22540
|
+
systemHashPrev: postTransformResult.systemHashPrev,
|
|
22541
|
+
systemHashNew: postTransformResult.systemHashNew,
|
|
22542
|
+
m0ToolSetHashPrev: postTransformResult.m0ToolSetHashPrev,
|
|
22543
|
+
m0ToolSetHashNew: postTransformResult.m0ToolSetHashNew,
|
|
22544
|
+
m0ModelKeyPrev: postTransformResult.m0ModelKeyPrev,
|
|
22545
|
+
m0ModelKeyNew: postTransformResult.m0ModelKeyNew,
|
|
22546
|
+
emergency: postTransformResult.emergency,
|
|
22547
|
+
droppedTokens: postTransformResult.droppedTokens,
|
|
22548
|
+
droppedCount: postTransformResult.droppedCount,
|
|
22549
|
+
inputTokens: contextUsage.inputTokens,
|
|
22550
|
+
bustedThisPass: false
|
|
22551
|
+
});
|
|
22552
|
+
}
|
|
21960
22553
|
});
|
|
21961
|
-
|
|
21962
|
-
|
|
21963
|
-
|
|
21964
|
-
|
|
21965
|
-
|
|
21966
|
-
|
|
21967
|
-
|
|
21968
|
-
|
|
21969
|
-
|
|
21970
|
-
|
|
21971
|
-
|
|
21972
|
-
|
|
21973
|
-
|
|
21974
|
-
if (cached) {
|
|
21975
|
-
conversationTokens += cached.conversation;
|
|
21976
|
-
toolCallTokens += cached.toolCall;
|
|
21977
|
-
continue;
|
|
22554
|
+
logTransformTiming(sessionId, "postTransformPhase", tPostProcess);
|
|
22555
|
+
afterCapture(sessionId, "conversation token estimate", () => {
|
|
22556
|
+
const msgTokens = getMessageTokensCache(sessionId);
|
|
22557
|
+
let storedByMessage = new Map;
|
|
22558
|
+
const uncachedMessageIds = messages.flatMap((message) => {
|
|
22559
|
+
const messageId = message.info.id;
|
|
22560
|
+
return messageId !== undefined && !msgTokens.has(messageId) ? [messageId] : [];
|
|
22561
|
+
});
|
|
22562
|
+
if (uncachedMessageIds.length > 0) {
|
|
22563
|
+
try {
|
|
22564
|
+
storedByMessage = omitIncompleteFileTokenTotals(db, sessionId, messages.flatMap((message) => message.info.id ? [{ id: message.info.id, parts: message.parts }] : []), getActiveTagTokenTotalsByMessage2(db, sessionId, uncachedMessageIds));
|
|
22565
|
+
} catch {
|
|
22566
|
+
storedByMessage = new Map;
|
|
21978
22567
|
}
|
|
21979
|
-
|
|
21980
|
-
|
|
21981
|
-
|
|
21982
|
-
|
|
21983
|
-
|
|
21984
|
-
|
|
21985
|
-
|
|
21986
|
-
|
|
21987
|
-
|
|
22568
|
+
}
|
|
22569
|
+
let conversationTokens = 0;
|
|
22570
|
+
let toolCallTokens = 0;
|
|
22571
|
+
for (const message of messages) {
|
|
22572
|
+
const mid = message.info.id;
|
|
22573
|
+
if (mid) {
|
|
22574
|
+
const cached = msgTokens.get(mid);
|
|
22575
|
+
if (cached) {
|
|
22576
|
+
conversationTokens += cached.conversation;
|
|
22577
|
+
toolCallTokens += cached.toolCall;
|
|
22578
|
+
continue;
|
|
22579
|
+
}
|
|
22580
|
+
const stored = storedByMessage.get(mid);
|
|
22581
|
+
if (stored && !stored.hasNull) {
|
|
22582
|
+
conversationTokens += stored.conversation;
|
|
22583
|
+
toolCallTokens += stored.toolCall;
|
|
22584
|
+
msgTokens.set(mid, {
|
|
22585
|
+
conversation: stored.conversation,
|
|
22586
|
+
toolCall: stored.toolCall
|
|
22587
|
+
});
|
|
22588
|
+
continue;
|
|
22589
|
+
}
|
|
21988
22590
|
}
|
|
22591
|
+
const estimated = estimateMessageTokens(message);
|
|
22592
|
+
if (mid)
|
|
22593
|
+
msgTokens.set(mid, estimated);
|
|
22594
|
+
conversationTokens += estimated.conversation;
|
|
22595
|
+
toolCallTokens += estimated.toolCall;
|
|
21989
22596
|
}
|
|
21990
|
-
|
|
21991
|
-
|
|
21992
|
-
|
|
21993
|
-
|
|
21994
|
-
|
|
21995
|
-
|
|
21996
|
-
|
|
21997
|
-
updateSessionMeta(db, sessionId, { conversationTokens, toolCallTokens });
|
|
21998
|
-
} catch (error) {
|
|
21999
|
-
const code = error?.code;
|
|
22000
|
-
if (code !== "SQLITE_BUSY") {
|
|
22001
|
-
sessionLog2(sessionId, "conversation_tokens UPDATE failed:", error);
|
|
22597
|
+
try {
|
|
22598
|
+
updateSessionMeta(db, sessionId, { conversationTokens, toolCallTokens });
|
|
22599
|
+
} catch (error) {
|
|
22600
|
+
const code = error?.code;
|
|
22601
|
+
if (code !== "SQLITE_BUSY") {
|
|
22602
|
+
sessionLog2(sessionId, "conversation_tokens UPDATE failed:", error);
|
|
22603
|
+
}
|
|
22002
22604
|
}
|
|
22003
|
-
}
|
|
22605
|
+
});
|
|
22004
22606
|
const channelBaseline = deps.channel1StateBySession?.get(sessionId);
|
|
22005
22607
|
if (ctxReduceCallable && !compactionOff && channelBaseline) {
|
|
22006
22608
|
try {
|
|
@@ -22039,14 +22641,16 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
22039
22641
|
}
|
|
22040
22642
|
const elapsed = (performance.now() - startTime).toFixed(1);
|
|
22041
22643
|
sessionLog2(sessionId, `transform completed in ${elapsed}ms (${messages.length} messages, ${targets.size} targets, watermark: ${watermark})`);
|
|
22042
|
-
withoutSqliteTransformPass2(() => deps.maybeAutoEmbedSession?.(sessionId));
|
|
22644
|
+
afterCapture(sessionId, "auto-embed scheduling", () => withoutSqliteTransformPass2(() => deps.maybeAutoEmbedSession?.(sessionId)));
|
|
22043
22645
|
const bindingRecovery = postTransformResult.thinkingBindingRecovery;
|
|
22044
22646
|
if (bindingRecovery) {
|
|
22045
|
-
const cleared = clearThinkingBindingRecoveryIf(db, sessionId, bindingRecovery.flagTarget);
|
|
22046
|
-
|
|
22647
|
+
const cleared = afterCapture(sessionId, "thinking binding recovery clear", () => clearThinkingBindingRecoveryIf(db, sessionId, bindingRecovery.flagTarget));
|
|
22648
|
+
if (cleared === undefined)
|
|
22649
|
+
noteBindingRecoveryAwaitingClear(sessionId, bindingRecovery.flagTarget);
|
|
22650
|
+
sessionLog2(sessionId, `thinking binding recovery: stripped bound reasoning from ${bindingRecovery.messageIds.length} assistant(s) [${bindingRecovery.messageIds.join(",")}]; flag=${cleared === undefined ? "kept" : cleared ? "cleared" : "rearmed"}`);
|
|
22047
22651
|
}
|
|
22048
22652
|
if (passOutcome.captureEligible)
|
|
22049
|
-
finalWireUsage.capture(sessionId, {
|
|
22653
|
+
afterCapture(sessionId, "final wire usage capture", () => finalWireUsage.capture(sessionId, {
|
|
22050
22654
|
messages,
|
|
22051
22655
|
systemPromptTokens: sessionMeta.systemPromptTokens,
|
|
22052
22656
|
providerID: modelForBudget?.providerID,
|
|
@@ -22054,8 +22658,8 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
22054
22658
|
agentName: notificationParams.agent,
|
|
22055
22659
|
sessionId,
|
|
22056
22660
|
systemPromptHash: sessionMeta.systemPromptHash
|
|
22057
|
-
});
|
|
22058
|
-
deps.onPassPermission?.(sessionId, postTransformResult.prefixMutationPermitted);
|
|
22661
|
+
}));
|
|
22662
|
+
afterCapture(sessionId, "pass permission report", () => deps.onPassPermission?.(sessionId, postTransformResult.prefixMutationPermitted));
|
|
22059
22663
|
};
|
|
22060
22664
|
const timedTransform = (input, output) => withTransformTimingSummary(async () => {
|
|
22061
22665
|
const sessionId = findSessionId(output.messages);
|
|
@@ -22362,6 +22966,7 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
22362
22966
|
} else {
|
|
22363
22967
|
const inputMessages = output.messages;
|
|
22364
22968
|
const keys = resolveLkgModelKeys(inputMessages);
|
|
22969
|
+
const hostTailDigests = rust ? [] : entry.pristineTail.map(lkgContentDigest);
|
|
22365
22970
|
const replay = replayLkg({
|
|
22366
22971
|
sessionId,
|
|
22367
22972
|
messages: inputMessages,
|
|
@@ -22428,6 +23033,7 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
22428
23033
|
entry,
|
|
22429
23034
|
messages: replay.messages,
|
|
22430
23035
|
...keys,
|
|
23036
|
+
hostTailDigests,
|
|
22431
23037
|
db
|
|
22432
23038
|
}))
|
|
22433
23039
|
return false;
|
|
@@ -22435,6 +23041,7 @@ function tryMessagesTransformLkgReplay(args) {
|
|
|
22435
23041
|
args.onLkgReplay?.();
|
|
22436
23042
|
noteExternalLkgReplay(rust, sessionId, inputMessages, replay.messages);
|
|
22437
23043
|
replaceMessagesInPlace2(output, replay.messages);
|
|
23044
|
+
noteServedReplay(sessionId);
|
|
22438
23045
|
sessionLog2(sessionId, "lkg_replay_served");
|
|
22439
23046
|
return true;
|
|
22440
23047
|
} else {
|
|
@@ -22461,6 +23068,8 @@ function createMessagesTransformHandler(args) {
|
|
|
22461
23068
|
const isInternalChild = typeof sessionId === "string" && sessionId.length > 0 && args.internalChildSessions?.has(sessionId) === true;
|
|
22462
23069
|
const compactionOffInputSnapshot = args.compactionOff ? [...output.messages] : null;
|
|
22463
23070
|
const restoreCompactionOffInput = () => {
|
|
23071
|
+
if (compactionOffInputSnapshot && sessionId)
|
|
23072
|
+
noteServedHostInput(sessionId);
|
|
22464
23073
|
if (compactionOffInputSnapshot && output.messages !== compactionOffInputSnapshot) {
|
|
22465
23074
|
output.messages.splice(0, output.messages.length, ...compactionOffInputSnapshot);
|
|
22466
23075
|
}
|
|
@@ -22541,6 +23150,8 @@ function createMessagesTransformHandler(args) {
|
|
|
22541
23150
|
tryReopen: args.tryReopenStorage
|
|
22542
23151
|
});
|
|
22543
23152
|
}
|
|
23153
|
+
if (sessionId)
|
|
23154
|
+
noteServedHostInput(sessionId);
|
|
22544
23155
|
return output.messages;
|
|
22545
23156
|
}
|
|
22546
23157
|
}
|
|
@@ -22627,7 +23238,42 @@ function createMessagesTransformHandler(args) {
|
|
|
22627
23238
|
restoreCompactionOffInput();
|
|
22628
23239
|
return output.messages;
|
|
22629
23240
|
};
|
|
23241
|
+
const finishServedRequest = (sessionId, output, returned) => {
|
|
23242
|
+
try {
|
|
23243
|
+
if (!returned)
|
|
23244
|
+
countServedRefusal(sessionId);
|
|
23245
|
+
else if (resolveRust(sessionId))
|
|
23246
|
+
forgetServedRecord(sessionId);
|
|
23247
|
+
else {
|
|
23248
|
+
const keys = resolveLkgModelKeys(output.messages);
|
|
23249
|
+
commitServedRequest({
|
|
23250
|
+
sessionId,
|
|
23251
|
+
host: "opencode",
|
|
23252
|
+
messages: output.messages,
|
|
23253
|
+
providerID: keys.providerKey,
|
|
23254
|
+
modelID: keys.modelKey && keys.providerKey ? keys.modelKey.slice(keys.providerKey.length + 1) : keys.modelKey,
|
|
23255
|
+
compactionOff: args.compactionOff === true
|
|
23256
|
+
});
|
|
23257
|
+
}
|
|
23258
|
+
} catch (error) {
|
|
23259
|
+
sessionLog2(sessionId, "served check skipped:", error);
|
|
23260
|
+
}
|
|
23261
|
+
};
|
|
22630
23262
|
return (input, output) => withSqliteTransformPass2(async () => {
|
|
23263
|
+
const servedSessionId = args.recordServed === false ? null : resolveSessionId2(output);
|
|
23264
|
+
if (servedSessionId)
|
|
23265
|
+
beginServedRequest(servedSessionId);
|
|
23266
|
+
let returned = false;
|
|
23267
|
+
try {
|
|
23268
|
+
const served = await servePass(input, output);
|
|
23269
|
+
returned = true;
|
|
23270
|
+
return served;
|
|
23271
|
+
} finally {
|
|
23272
|
+
if (servedSessionId)
|
|
23273
|
+
finishServedRequest(servedSessionId, output, returned);
|
|
23274
|
+
}
|
|
23275
|
+
});
|
|
23276
|
+
async function servePass(input, output) {
|
|
22631
23277
|
const tail = output.messages.at(-1);
|
|
22632
23278
|
if (tail?.info.role === "user" && tail.info.id && !tail.info.summary && tail.parts.length === 0) {
|
|
22633
23279
|
throw new IncompleteUserMessageError;
|
|
@@ -22641,7 +23287,7 @@ function createMessagesTransformHandler(args) {
|
|
|
22641
23287
|
preserveUserTerminatedTail(output.messages, inputMessages);
|
|
22642
23288
|
reportAssistantTerminatedTail(output.messages, inputTailRole, resolveSessionId2(output));
|
|
22643
23289
|
}
|
|
22644
|
-
}
|
|
23290
|
+
}
|
|
22645
23291
|
}
|
|
22646
23292
|
function resolveSessionId2(output) {
|
|
22647
23293
|
for (const message of output.messages) {
|
|
@@ -23779,7 +24425,7 @@ var storedCarry = object({
|
|
|
23779
24425
|
})
|
|
23780
24426
|
]))
|
|
23781
24427
|
});
|
|
23782
|
-
function
|
|
24428
|
+
function readState3(db, sessionId) {
|
|
23783
24429
|
const row = db.prepare("SELECT deferred_execute_state, new_work_tokens, total_input_tokens FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
23784
24430
|
let root = {};
|
|
23785
24431
|
try {
|
|
@@ -23802,7 +24448,7 @@ function matchesStoredState(state, source, carry, metrics) {
|
|
|
23802
24448
|
});
|
|
23803
24449
|
}
|
|
23804
24450
|
function readSessionWorkMetricsCarry(db, sessionId, source) {
|
|
23805
|
-
const parsed = storedCarry.safeParse(
|
|
24451
|
+
const parsed = storedCarry.safeParse(readState3(db, sessionId).root[STATE_KEY]);
|
|
23806
24452
|
if (!parsed.success || parsed.data.source !== source)
|
|
23807
24453
|
return;
|
|
23808
24454
|
return {
|
|
@@ -23817,10 +24463,10 @@ function setSessionWorkMetricsCarry(db, sessionId, source, carry, metrics) {
|
|
|
23817
24463
|
newWorkTokens: Math.max(0, Math.floor(metrics.newWorkTokens)),
|
|
23818
24464
|
totalInputTokens: Math.max(0, Math.floor(metrics.totalInputTokens))
|
|
23819
24465
|
};
|
|
23820
|
-
if (matchesStoredState(
|
|
24466
|
+
if (matchesStoredState(readState3(db, sessionId), source, carry, normalized))
|
|
23821
24467
|
return;
|
|
23822
24468
|
db.transaction(() => {
|
|
23823
|
-
const state =
|
|
24469
|
+
const state = readState3(db, sessionId);
|
|
23824
24470
|
if (matchesStoredState(state, source, carry, normalized))
|
|
23825
24471
|
return;
|
|
23826
24472
|
ensureSessionMetaRow(db, sessionId);
|
|
@@ -25403,7 +26049,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
25403
26049
|
const db = readDatabase();
|
|
25404
26050
|
if (!db)
|
|
25405
26051
|
return { ok: false, error: "db unavailable" };
|
|
25406
|
-
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-
|
|
26052
|
+
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-cdkfynz4.js"));
|
|
25407
26053
|
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-95p89k7q.js"));
|
|
25408
26054
|
log2(`[rpc] recomp requested for session ${sessionId}`);
|
|
25409
26055
|
if (!args.client && !args.hiddenCompletionExecutor) {
|
|
@@ -25488,7 +26134,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
25488
26134
|
const db = readDatabase();
|
|
25489
26135
|
if (!db)
|
|
25490
26136
|
return { ok: false, error: "db unavailable" };
|
|
25491
|
-
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-
|
|
26137
|
+
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-xnqq81c4.js"));
|
|
25492
26138
|
const model = liveSessionState.liveModelBySession.get(sessionId);
|
|
25493
26139
|
const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
|
|
25494
26140
|
const ctx = {
|
|
@@ -26863,22 +27509,24 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
|
|
|
26863
27509
|
}
|
|
26864
27510
|
return {
|
|
26865
27511
|
edits,
|
|
26866
|
-
|
|
26867
|
-
|
|
26868
|
-
|
|
26869
|
-
|
|
26870
|
-
|
|
26871
|
-
|
|
26872
|
-
|
|
26873
|
-
|
|
26874
|
-
|
|
26875
|
-
|
|
26876
|
-
|
|
26877
|
-
|
|
26878
|
-
|
|
26879
|
-
|
|
26880
|
-
|
|
26881
|
-
|
|
27512
|
+
hasDecisions: newlyRetired.size > 0 || switchCovered,
|
|
27513
|
+
record(doc) {
|
|
27514
|
+
if (newlyRetired.size === 0 && !switchCovered)
|
|
27515
|
+
return false;
|
|
27516
|
+
const current = decode(doc[namespace]);
|
|
27517
|
+
if ([...newlyRetired].every((id) => current.has(id)) && (!switchCovered || coveredOn(doc[coveredNamespace])))
|
|
27518
|
+
return false;
|
|
27519
|
+
for (const id of folded)
|
|
27520
|
+
current.delete(id);
|
|
27521
|
+
for (const id of newlyRetired)
|
|
27522
|
+
current.add(id);
|
|
27523
|
+
doc.version = 2;
|
|
27524
|
+
doc[namespace] = [...current];
|
|
27525
|
+
if (switchCovered)
|
|
27526
|
+
doc[coveredNamespace] = { on: true };
|
|
27527
|
+
return true;
|
|
27528
|
+
},
|
|
27529
|
+
markRetired() {
|
|
26882
27530
|
for (const { message, row } of rows) {
|
|
26883
27531
|
if (omits(message, row.id))
|
|
26884
27532
|
markRetiredInstructionRow(message.info);
|
|
@@ -55836,6 +56484,7 @@ async function cacheV2SessionDirectory(session, sessionID, directories) {
|
|
|
55836
56484
|
function refuseBeforeProvider(session, sessionID, arm, cause) {
|
|
55837
56485
|
const detail = cause instanceof Error ? `${cause.name}: ${cause.message}` : cause === undefined ? "" : String(cause);
|
|
55838
56486
|
sessionLog2(sessionID, `v2 refusal: interrupting the turn before the provider request arm=${arm}${detail ? ` cause=${JSON.stringify(detail.slice(0, 500))}` : ""}`);
|
|
56487
|
+
noteServedRefusal(sessionID);
|
|
55839
56488
|
return interruptBeforeProvider(session, sessionID);
|
|
55840
56489
|
}
|
|
55841
56490
|
function createHostSeams(context, readAllForConversion, reconciliationSource, liveModels) {
|
|
@@ -56509,6 +57158,23 @@ async function registerContext(context) {
|
|
|
56509
57158
|
log2("[magic-context] v2 thinking binding recovery arm failed", armError);
|
|
56510
57159
|
}
|
|
56511
57160
|
};
|
|
57161
|
+
const armLatestThinkingFromEvent = (sessionID, error) => {
|
|
57162
|
+
if (error === undefined || !db || compactionOff)
|
|
57163
|
+
return false;
|
|
57164
|
+
const model = liveModels.get(sessionID);
|
|
57165
|
+
try {
|
|
57166
|
+
return armLatestThinkingRecoveryFromError({
|
|
57167
|
+
db,
|
|
57168
|
+
sessionId: sessionID,
|
|
57169
|
+
error,
|
|
57170
|
+
providerID: model?.providerID,
|
|
57171
|
+
modelID: model?.modelID
|
|
57172
|
+
});
|
|
57173
|
+
} catch (armError) {
|
|
57174
|
+
log2("[magic-context] v2 latest-thinking recovery arm failed", armError);
|
|
57175
|
+
return false;
|
|
57176
|
+
}
|
|
57177
|
+
};
|
|
56512
57178
|
const usageController = new AbortController;
|
|
56513
57179
|
const usageDone = (async () => {
|
|
56514
57180
|
let retry = 0;
|
|
@@ -56561,7 +57227,7 @@ async function registerContext(context) {
|
|
|
56561
57227
|
if (typeof messageID === "string")
|
|
56562
57228
|
messageTimesCache.deleteMessage(sessionID, messageID);
|
|
56563
57229
|
}
|
|
56564
|
-
if (event.type === "session.step.failed")
|
|
57230
|
+
if (event.type === "session.step.failed" && !armLatestThinkingFromEvent(sessionID, event.data.error))
|
|
56565
57231
|
armBindingRecoveryFromEvent(sessionID, event.data.error, "session.step.failed");
|
|
56566
57232
|
if (event.type === "session.error" || event.type === "session.execution.failed") {
|
|
56567
57233
|
hostFoldIdle?.active(sessionID);
|
|
@@ -56569,20 +57235,7 @@ async function registerContext(context) {
|
|
|
56569
57235
|
if (error !== undefined)
|
|
56570
57236
|
hiddenSessionErrors.set(sessionID, error);
|
|
56571
57237
|
if (error !== undefined && db && !compactionOff) {
|
|
56572
|
-
|
|
56573
|
-
let latestTurnRejection = false;
|
|
56574
|
-
try {
|
|
56575
|
-
latestTurnRejection = armLatestThinkingRecoveryFromError({
|
|
56576
|
-
db,
|
|
56577
|
-
sessionId: sessionID,
|
|
56578
|
-
error,
|
|
56579
|
-
providerID: model?.providerID,
|
|
56580
|
-
modelID: model?.modelID
|
|
56581
|
-
});
|
|
56582
|
-
} catch (armError) {
|
|
56583
|
-
log2("[magic-context] v2 latest-thinking recovery arm failed", armError);
|
|
56584
|
-
}
|
|
56585
|
-
if (!latestTurnRejection)
|
|
57238
|
+
if (!armLatestThinkingFromEvent(sessionID, error))
|
|
56586
57239
|
armBindingRecoveryFromEvent(sessionID, error, event.type);
|
|
56587
57240
|
}
|
|
56588
57241
|
continue;
|
|
@@ -56591,6 +57244,7 @@ async function registerContext(context) {
|
|
|
56591
57244
|
overflowRecovery.forget(sessionID);
|
|
56592
57245
|
hostFoldIdle?.active(sessionID);
|
|
56593
57246
|
clearLkgMeasuredRequest(sessionID);
|
|
57247
|
+
dropServedRecord(sessionID, "session_deleted");
|
|
56594
57248
|
deletedSessions.add(sessionID);
|
|
56595
57249
|
const failures = [];
|
|
56596
57250
|
try {
|
|
@@ -57366,6 +58020,7 @@ async function registerContext(context) {
|
|
|
57366
58020
|
await createMessagesTransformHandler({
|
|
57367
58021
|
magicContext: { "experimental.chat.messages.transform": transform },
|
|
57368
58022
|
compactionOff,
|
|
58023
|
+
recordServed: false,
|
|
57369
58024
|
replayFits,
|
|
57370
58025
|
onLkgReplay: restoreLkgSystem,
|
|
57371
58026
|
rustReplayParticipant: () => transform?.getRustReplayParticipant() ?? null
|
|
@@ -57441,6 +58096,7 @@ async function registerContext(context) {
|
|
|
57441
58096
|
throw new StorageBusyRefusalError(error, "v2-context");
|
|
57442
58097
|
const { mapped } = input;
|
|
57443
58098
|
await createMessagesTransformHandler({
|
|
58099
|
+
recordServed: false,
|
|
57444
58100
|
replayFits,
|
|
57445
58101
|
onLkgReplay: restoreLkgSystem,
|
|
57446
58102
|
rustReplayParticipant: () => transform?.getRustReplayParticipant() ?? null,
|
|
@@ -57484,6 +58140,26 @@ async function registerContext(context) {
|
|
|
57484
58140
|
}
|
|
57485
58141
|
}
|
|
57486
58142
|
};
|
|
58143
|
+
const finishServedRequest = (draft, returned) => {
|
|
58144
|
+
try {
|
|
58145
|
+
const sessionID = draft.sessionID;
|
|
58146
|
+
if (!returned)
|
|
58147
|
+
countServedRefusal(sessionID);
|
|
58148
|
+
else if (rustModeModuleClient || deletedSessions.has(sessionID) || hiddenChildHook.owns(sessionID))
|
|
58149
|
+
forgetServedRecord(sessionID);
|
|
58150
|
+
else
|
|
58151
|
+
commitServedRequest({
|
|
58152
|
+
sessionId: sessionID,
|
|
58153
|
+
host: "opencode2",
|
|
58154
|
+
messages: draft.messages,
|
|
58155
|
+
providerID: draft.model.providerID,
|
|
58156
|
+
modelID: draft.model.id,
|
|
58157
|
+
compactionOff
|
|
58158
|
+
});
|
|
58159
|
+
} catch (error) {
|
|
58160
|
+
sessionLog2(draft.sessionID, "served check skipped:", error);
|
|
58161
|
+
}
|
|
58162
|
+
};
|
|
57487
58163
|
const refuseOversizedCheckpoint = async (draft) => {
|
|
57488
58164
|
const hasCheckpoint = draft.messages.some((message) => message.content.some((part) => part.type === "text" && typeof part.text === "string" && part.text.startsWith("<conversation-checkpoint>")));
|
|
57489
58165
|
const limit = draft.model.limit?.input ?? draft.model.limit?.context;
|
|
@@ -57506,6 +58182,8 @@ async function registerContext(context) {
|
|
|
57506
58182
|
await context.session.hook("context", (draft) => withSqliteTransformPass2(async () => {
|
|
57507
58183
|
hostFoldIdle?.active(draft.sessionID);
|
|
57508
58184
|
const anchor = generateReplayAnchor(draft.messages);
|
|
58185
|
+
beginServedRequest(draft.sessionID);
|
|
58186
|
+
let returned = false;
|
|
57509
58187
|
try {
|
|
57510
58188
|
await runManagedContext(draft);
|
|
57511
58189
|
if (!compactionOff)
|
|
@@ -57519,6 +58197,7 @@ async function registerContext(context) {
|
|
|
57519
58197
|
hostFoldIdle.idle(draft.sessionID, meta.cacheTtl, meta.lastResponseTime);
|
|
57520
58198
|
}
|
|
57521
58199
|
}
|
|
58200
|
+
returned = true;
|
|
57522
58201
|
} finally {
|
|
57523
58202
|
admissionRebuildPasses.delete(draft.sessionID);
|
|
57524
58203
|
nativeFoldReplay?.cancelLegacyUpgrade(draft.sessionID);
|
|
@@ -57526,6 +58205,7 @@ async function registerContext(context) {
|
|
|
57526
58205
|
checkpointInputEstimates.delete(draft.sessionID);
|
|
57527
58206
|
checkpointPassPermissions.delete(draft.sessionID);
|
|
57528
58207
|
foldedInstructionIDs.delete(draft.sessionID);
|
|
58208
|
+
finishServedRequest(draft, returned);
|
|
57529
58209
|
}
|
|
57530
58210
|
if (!compactionOff)
|
|
57531
58211
|
generateReplay.capture(draft, anchor);
|