@cortexkit/opencode-magic-context 0.49.45 → 0.49.46
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 +1 -1
- package/dist/chunk-embedding-write-worker.js +1 -1
- package/dist/{context-y85dvs6j.js → context-cb51adcz.js} +362 -103
- package/dist/{derive-budgets-htj16n4x.js → derive-budgets-nkw09vq7.js} +1 -1
- package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts +21 -0
- package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
- package/dist/hooks/magic-context/priced-pass-sizing.d.ts +132 -0
- package/dist/hooks/magic-context/priced-pass-sizing.d.ts.map +1 -0
- package/dist/hooks/magic-context/reasoning-budget.d.ts.map +1 -1
- package/dist/hooks/magic-context/recovery-fit.d.ts +51 -0
- package/dist/hooks/magic-context/recovery-fit.d.ts.map +1 -0
- package/dist/hooks/magic-context/routine-cleanup-decision.d.ts +109 -0
- package/dist/hooks/magic-context/routine-cleanup-decision.d.ts.map +1 -0
- package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts +24 -0
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-context-state.d.ts +2 -1
- package/dist/hooks/magic-context/transform-context-state.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +15 -2
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts +10 -2
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/{index-tvd2j34s.js → index-44pp3vrj.js} +1 -1
- package/dist/{index-xejh7cqv.js → index-55ngkbqa.js} +28 -9
- package/dist/{index-980brvjr.js → index-5jk4h64j.js} +3 -3
- package/dist/{index-dnqqqc5f.js → index-8cfnaagj.js} +10 -2
- package/dist/{index-7na94cjf.js → index-a4t7pdmm.js} +3 -3
- package/dist/{index-z8dacvkt.js → index-b0xt5qz9.js} +1 -1
- package/dist/{index-bzq05g00.js → index-etn2hmb5.js} +1 -1
- package/dist/{index-rk5hyc41.js → index-gaxktvxm.js} +2 -2
- package/dist/{index-dcdvyaeh.js → index-kevd267m.js} +3 -3
- package/dist/{index-gf1vx3bn.js → index-kw7azjmy.js} +2 -2
- package/dist/{index-jwa5t1s4.js → index-n9q8c1dr.js} +2 -2
- package/dist/{index-qdx8dq60.js → index-pwfmcg4e.js} +4 -4
- package/dist/{index-fs3zfby1.js → index-snztv1f0.js} +608 -96
- package/dist/{index-0a79y98x.js → index-tajstyw4.js} +161 -81
- package/dist/{index-gxqr0sbd.js → index-x53gnmce.js} +10 -10
- package/dist/{index-wwg1je98.js → index-xgnh498s.js} +3 -2
- package/dist/index.js +19 -19
- package/dist/{message-index-bounded-d8xt6q5c.js → message-index-bounded-3qpg8dq5.js} +3 -3
- package/dist/migration-worker.js +1 -1
- package/dist/raw-ordinal-warmup-worker.js +4 -4
- package/dist/{read-session-chunk-k3fqshw8.js → read-session-chunk-7h9f32sz.js} +2 -2
- package/dist/{recomp-orchestrator-y75thsc3.js → recomp-orchestrator-qnactdw7.js} +8 -8
- package/dist/{render-3psbedzk.js → render-da999saz.js} +6 -6
- package/dist/{search-hd16c8gq.js → search-0a3hh5x6.js} +5 -5
- package/dist/{search-archive-rvr7j5gx.js → search-archive-0z9cxv8e.js} +4 -4
- package/dist/shared/window-geometry.d.ts +5 -0
- package/dist/shared/window-geometry.d.ts.map +1 -1
- package/dist/{storage-tags-ye9aqrqy.js → storage-tags-q8erkn48.js} +3 -1
- package/dist/tools/parameter-descriptions.d.ts +6 -6
- package/dist/tools/parameter-descriptions.d.ts.map +1 -1
- package/dist/{transform-postprocess-phase-1rzxmkhb.js → transform-postprocess-phase-k9d1r13f.js} +9 -9
- package/dist/v2/auto-search-worker.js +1 -1
- package/dist/v2/chunk-embedding-write-worker.js +1 -1
- package/dist/v2/{context-0e946t63.js → context-jtqj5e1r.js} +1077 -245
- package/dist/v2/{derive-budgets-sa0v7bz0.js → derive-budgets-b5cgrtp8.js} +2 -2
- package/dist/v2/fold/code-mode-catalog.d.ts +11 -3
- package/dist/v2/fold/code-mode-catalog.d.ts.map +1 -1
- package/dist/v2/fold/instruction-supersession.d.ts +13 -2
- package/dist/v2/fold/instruction-supersession.d.ts.map +1 -1
- package/dist/v2/fold/native-replay.d.ts +5 -0
- package/dist/v2/fold/native-replay.d.ts.map +1 -1
- package/dist/v2/fold/owner.d.ts +14 -0
- package/dist/v2/fold/owner.d.ts.map +1 -1
- package/dist/v2/fold/summary.d.ts +35 -0
- package/dist/v2/fold/summary.d.ts.map +1 -1
- package/dist/v2/hooks/context.d.ts +2 -1
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/lkg-system.d.ts +3 -0
- package/dist/v2/hooks/lkg-system.d.ts.map +1 -1
- package/dist/v2/{message-index-bounded-wt64v2rn.js → message-index-bounded-60tdhht5.js} +3 -3
- package/dist/v2/migration-worker.js +1 -1
- package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
- package/dist/v2/{read-session-chunk-4b31z6bz.js → read-session-chunk-9tmsxwb2.js} +2 -2
- package/dist/v2/{recomp-orchestrator-6qrm2nea.js → recomp-orchestrator-7y8smqqp.js} +9 -9
- package/dist/v2/{render-f8mw16pp.js → render-j0y57skn.js} +6 -6
- package/dist/v2/{search-archive-7d0xdp54.js → search-archive-1e2tr8eq.js} +4 -4
- package/dist/v2/{search-ecjd7e50.js → search-qhd2m8kn.js} +4 -4
- package/dist/v2/{server-ftyc8awt.js → server-3rp821fw.js} +1 -1
- package/dist/v2/{server-39kzpp8q.js → server-4m71jpaj.js} +2 -2
- package/dist/v2/{server-vnpnmrsv.js → server-5dtrzs6j.js} +3 -2
- package/dist/v2/{server-0ymsgh0j.js → server-5vy0xt3p.js} +1 -1
- package/dist/v2/{server-sd8hvzte.js → server-af1rmkyn.js} +1 -1
- package/dist/v2/{server-zqzh2ybj.js → server-ahy062xr.js} +30 -11
- package/dist/v2/{server-wbxbk3za.js → server-ht0dyq9r.js} +2 -2
- package/dist/v2/{server-2qyfev3b.js → server-rjn4msjj.js} +2 -2
- package/dist/v2/{server-an1ff8d8.js → server-rshcp4gy.js} +3 -3
- package/dist/v2/{server-hq7fdqfm.js → server-sscb1r3e.js} +2 -2
- package/dist/v2/{server-gwqfwtzq.js → server-t4hk02v1.js} +10 -10
- package/dist/v2/{server-vjhk8v41.js → server-wa4qhryh.js} +1 -1
- package/dist/v2/{server-qxzbmtqt.js → server-zt1m5rwj.js} +10 -2
- package/dist/v2/server.js +4 -4
- package/dist/v2/{storage-tags-8nttt1sk.js → storage-tags-ztar1k0g.js} +3 -1
- package/dist/v2/{v2-archive-reader-53kp5mme.js → v2-archive-reader-tme5988n.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-bng0dfxy.js → wrapup-orchestrator-k7m16xze.js} +9 -9
- package/dist/{v2-archive-reader-0fcxs5e9.js → v2-archive-reader-dq5ebwe6.js} +1 -1
- package/dist/{wrapup-orchestrator-r5cqgyrg.js → wrapup-orchestrator-4pqwet8p.js} +9 -9
- package/package.json +1 -1
- package/src/agents/smart-notes-dreamer-gate.golden.json +169 -169
- package/src/shared/prompt-surface-a1-golden.md +4 -4
- package/src/shared/window-geometry.test.ts +85 -0
- package/src/shared/window-geometry.ts +29 -2
|
@@ -164,6 +164,9 @@ import {
|
|
|
164
164
|
renderMemoryBlockV2,
|
|
165
165
|
findHostCompactionWindow,
|
|
166
166
|
capturePrefixTrimSourceOrder,
|
|
167
|
+
headMessagesForSizing,
|
|
168
|
+
rawTailAfterNewestCompartment,
|
|
169
|
+
hasCompleteCachedM0M1,
|
|
167
170
|
resolveHiddenCompletionExecutor,
|
|
168
171
|
createV1HiddenCompletionExecutor,
|
|
169
172
|
readCoordinateGeneration,
|
|
@@ -191,7 +194,7 @@ import {
|
|
|
191
194
|
snapRangeToCompartments,
|
|
192
195
|
getActiveCompartmentRun,
|
|
193
196
|
startCompartmentAgent
|
|
194
|
-
} from "./index-
|
|
197
|
+
} from "./index-55ngkbqa.js";
|
|
195
198
|
import {
|
|
196
199
|
hasTrustedAbsoluteWall,
|
|
197
200
|
applyProvenInputFloor,
|
|
@@ -203,7 +206,7 @@ import {
|
|
|
203
206
|
deriveTriggerBudget2,
|
|
204
207
|
resolveKnownHistorianContextLimit2,
|
|
205
208
|
resolveHistorianProducerLimits2
|
|
206
|
-
} from "./index-
|
|
209
|
+
} from "./index-8cfnaagj.js";
|
|
207
210
|
import {
|
|
208
211
|
resolveModelCalibration,
|
|
209
212
|
calibrateBuckets,
|
|
@@ -244,6 +247,7 @@ import {
|
|
|
244
247
|
getTriggerTagTokenUpperBound2,
|
|
245
248
|
getActiveTagTokenTotalsByMessage2,
|
|
246
249
|
tryGetReasoningTokenEstimatesByMessage2,
|
|
250
|
+
TagOwnerSummaryNotReady2,
|
|
247
251
|
isTagOwnerSummaryReady2,
|
|
248
252
|
updateTagStatus2,
|
|
249
253
|
getInertWhitespaceAssistantTagsByNumbers2,
|
|
@@ -254,7 +258,7 @@ import {
|
|
|
254
258
|
getTagsByNumbers2,
|
|
255
259
|
getDroppedTagsByNumbers2,
|
|
256
260
|
getMaxDroppedTagNumber2
|
|
257
|
-
} from "./index-
|
|
261
|
+
} from "./index-x53gnmce.js";
|
|
258
262
|
import {
|
|
259
263
|
observeTemporalDecisions,
|
|
260
264
|
stableStringify
|
|
@@ -358,6 +362,7 @@ import {
|
|
|
358
362
|
getPersistedCompactionMarkerState,
|
|
359
363
|
setPersistedCompactionMarkerState,
|
|
360
364
|
getStrippedPlaceholderIds,
|
|
365
|
+
THINKING_BINDING_RECOVERY_FROZEN_PREFIX,
|
|
361
366
|
thinkingBindingRecoveryFrozenId,
|
|
362
367
|
getThinkingBindingRecoveryTarget,
|
|
363
368
|
armThinkingBindingRecovery,
|
|
@@ -371,6 +376,7 @@ import {
|
|
|
371
376
|
clearPendingCompactionMarkerStateIf,
|
|
372
377
|
getObservedEpochFloor,
|
|
373
378
|
resolveEpochFloorForPass,
|
|
379
|
+
getReasoningRemovalState,
|
|
374
380
|
detectLatestTurnThinkingMismatch,
|
|
375
381
|
isPrefixBoundThinkingModel,
|
|
376
382
|
detectOverflow,
|
|
@@ -383,10 +389,12 @@ import {
|
|
|
383
389
|
stripClearedReasoning,
|
|
384
390
|
findReasoningBearingAssistantIds,
|
|
385
391
|
snapshotTrailingBlankSourceDecisions,
|
|
392
|
+
stripReasoningFromAssistantIds,
|
|
386
393
|
projectOpencodeReasoningBudgetCutoff,
|
|
387
394
|
resolveKeepReasoningTokens,
|
|
388
395
|
reasoningStepCost,
|
|
389
396
|
reasoningBudgetCutoff,
|
|
397
|
+
opencodeReasoningBudgetCutoff,
|
|
390
398
|
describeFinalWireTail,
|
|
391
399
|
estimateMessageTokens,
|
|
392
400
|
wireContentBytes,
|
|
@@ -416,7 +424,7 @@ import {
|
|
|
416
424
|
readRawSessionMessageById2,
|
|
417
425
|
readSessionChunk2,
|
|
418
426
|
readRawSessionSeedTail2
|
|
419
|
-
} from "./index-
|
|
427
|
+
} from "./index-xgnh498s.js";
|
|
420
428
|
import {
|
|
421
429
|
BoundedSessionMap,
|
|
422
430
|
getMeasuredToolDefinitionTokens
|
|
@@ -446,7 +454,7 @@ import {
|
|
|
446
454
|
runSqliteOptimize,
|
|
447
455
|
openDatabase,
|
|
448
456
|
openCurrentDatabase
|
|
449
|
-
} from "./index-
|
|
457
|
+
} from "./index-b0xt5qz9.js";
|
|
450
458
|
import {
|
|
451
459
|
unescapeXml,
|
|
452
460
|
resolveWorkspaceShareCategories,
|
|
@@ -555,10 +563,10 @@ import {
|
|
|
555
563
|
GLOBAL_USER_PROFILE_PROJECT_PATH,
|
|
556
564
|
getProjectState,
|
|
557
565
|
bumpProjectUserProfileVersion
|
|
558
|
-
} from "./index-
|
|
566
|
+
} from "./index-n9q8c1dr.js";
|
|
559
567
|
import {
|
|
560
568
|
getLastIndexedOrdinal
|
|
561
|
-
} from "./index-
|
|
569
|
+
} from "./index-etn2hmb5.js";
|
|
562
570
|
import {
|
|
563
571
|
SESSION_NOTE_CONDITION_ERROR,
|
|
564
572
|
getNoteByIdInScope,
|
|
@@ -692,13 +700,13 @@ import {
|
|
|
692
700
|
resolveMemoriesByIdsForSearch2,
|
|
693
701
|
unifiedSearch2,
|
|
694
702
|
formatSearchResults2
|
|
695
|
-
} from "./index-
|
|
703
|
+
} from "./index-5jk4h64j.js";
|
|
696
704
|
import {
|
|
697
705
|
scheduleReconciliation,
|
|
698
706
|
scheduleIncrementalIndex,
|
|
699
707
|
getMessageIndexQueueHeapStats,
|
|
700
708
|
clearSessionTracking
|
|
701
|
-
} from "./index-
|
|
709
|
+
} from "./index-44pp3vrj.js";
|
|
702
710
|
import {
|
|
703
711
|
flushIgnoredMessages2,
|
|
704
712
|
clearIgnoredMessages2,
|
|
@@ -708,7 +716,7 @@ import {
|
|
|
708
716
|
import {
|
|
709
717
|
setRecompStarting2,
|
|
710
718
|
setRecompTerminal2
|
|
711
|
-
} from "./index-
|
|
719
|
+
} from "./index-kevd267m.js";
|
|
712
720
|
import {
|
|
713
721
|
makeToolCompositeKey,
|
|
714
722
|
searchMessageHistoryOffThread,
|
|
@@ -746,12 +754,23 @@ import {
|
|
|
746
754
|
outgoingContextRefusal,
|
|
747
755
|
signedTurnContextRefusal,
|
|
748
756
|
EmergencyFailClosedError,
|
|
757
|
+
removeReasoningParts,
|
|
749
758
|
latestAssistantTurnStart,
|
|
750
759
|
latestAssistantTurnMessages,
|
|
751
760
|
hasActiveAnthropicThinkingTurn,
|
|
761
|
+
retainedActiveThinkingParts,
|
|
752
762
|
replayCavemanCompression,
|
|
753
763
|
DegradedPassRefusalError,
|
|
754
764
|
degradedPassError,
|
|
765
|
+
hostInstructionRetentionEnabled,
|
|
766
|
+
isHostInstructionRetentionOn,
|
|
767
|
+
pressureBands,
|
|
768
|
+
forceRide,
|
|
769
|
+
heuristicsRunOnPass,
|
|
770
|
+
routineCleanupRunsOnPass,
|
|
771
|
+
heuristicsAlreadyRanThisTurn,
|
|
772
|
+
routinePressureAlreadyApplied,
|
|
773
|
+
safeReasoningCutoff,
|
|
755
774
|
isStructuralNoiseSentinel,
|
|
756
775
|
stripStructuralNoise,
|
|
757
776
|
prepareStructuralSentinelChoices,
|
|
@@ -773,7 +792,7 @@ import {
|
|
|
773
792
|
abortSessionFailClosed2,
|
|
774
793
|
evaluateEmergencyFailClosed2,
|
|
775
794
|
runPostTransformPhase2
|
|
776
|
-
} from "./index-
|
|
795
|
+
} from "./index-tajstyw4.js";
|
|
777
796
|
import {
|
|
778
797
|
ANNOUNCEMENT_VERSION2,
|
|
779
798
|
ANNOUNCEMENT_FEATURES2,
|
|
@@ -788,13 +807,13 @@ import {
|
|
|
788
807
|
renderMessageByOrdinal2,
|
|
789
808
|
renderVerboseRangeForTool2,
|
|
790
809
|
renderItemByTag2
|
|
791
|
-
} from "./index-
|
|
810
|
+
} from "./index-kw7azjmy.js";
|
|
792
811
|
import {
|
|
793
812
|
readV2ArchiveOffThread2
|
|
794
|
-
} from "./index-
|
|
813
|
+
} from "./index-a4t7pdmm.js";
|
|
795
814
|
import {
|
|
796
815
|
renderSearchArchiveOffThread2
|
|
797
|
-
} from "./index-
|
|
816
|
+
} from "./index-gaxktvxm.js";
|
|
798
817
|
import {
|
|
799
818
|
COMPACTION_ENABLED_PATH,
|
|
800
819
|
isDreamerRunnable,
|
|
@@ -16352,7 +16371,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
16352
16371
|
return { count: buildCompartmentCount(db, sessionId, moduleStatus) };
|
|
16353
16372
|
});
|
|
16354
16373
|
const buildManagedCtx = async (db) => {
|
|
16355
|
-
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-
|
|
16374
|
+
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-nkw09vq7.js"));
|
|
16356
16375
|
const { resolveHistorianModel } = await importPluginModule(() => import("./model-resolution-280gmqvd.js"));
|
|
16357
16376
|
const { userObservationCollectionEnabled, userObservationsRequested } = await importPluginModule(() => import("./task-config-t6bpyka7.js"));
|
|
16358
16377
|
const DEFAULT_HISTORIAN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
@@ -16404,7 +16423,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
16404
16423
|
const db = readDatabase();
|
|
16405
16424
|
if (!db)
|
|
16406
16425
|
return { ok: false, error: "db unavailable" };
|
|
16407
|
-
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-
|
|
16426
|
+
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-qnactdw7.js"));
|
|
16408
16427
|
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-j93pn2hn.js"));
|
|
16409
16428
|
log2(`[rpc] recomp requested for session ${sessionId}`);
|
|
16410
16429
|
if (!args.client && !args.hiddenCompletionExecutor) {
|
|
@@ -16489,7 +16508,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
16489
16508
|
const db = readDatabase();
|
|
16490
16509
|
if (!db)
|
|
16491
16510
|
return { ok: false, error: "db unavailable" };
|
|
16492
|
-
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-
|
|
16511
|
+
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-4pqwet8p.js"));
|
|
16493
16512
|
const model = liveSessionState.liveModelBySession.get(sessionId);
|
|
16494
16513
|
const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
|
|
16495
16514
|
const ctx = {
|
|
@@ -17497,6 +17516,192 @@ function createPassOutcome() {
|
|
|
17497
17516
|
};
|
|
17498
17517
|
}
|
|
17499
17518
|
|
|
17519
|
+
// src/hooks/magic-context/priced-pass-sizing.ts
|
|
17520
|
+
var REASONING_PART_TYPES = new Set(["reasoning", "thinking", "redacted_thinking"]);
|
|
17521
|
+
var WIDEST_PRICED_PASS_PLAN = {
|
|
17522
|
+
editsWholePrefix: true,
|
|
17523
|
+
clearsReasoning: false
|
|
17524
|
+
};
|
|
17525
|
+
function planPricedPass(input, usage) {
|
|
17526
|
+
const bands = pressureBands({
|
|
17527
|
+
percentage: usage.percentage,
|
|
17528
|
+
fromEstimate: usage.fromEstimate,
|
|
17529
|
+
forceMaterializationPercentage: input.forceMaterializationPercentage,
|
|
17530
|
+
compactionOff: input.compactionOff,
|
|
17531
|
+
fullFeatureMode: input.fullFeatureMode,
|
|
17532
|
+
schedulerDecision: input.schedulerDecision
|
|
17533
|
+
});
|
|
17534
|
+
const emergencySample = () => getEmergencyInputSample(input.db, input.sessionId);
|
|
17535
|
+
const rides = {
|
|
17536
|
+
hardFold: input.folds || input.firstRender,
|
|
17537
|
+
force: forceRide({
|
|
17538
|
+
bands,
|
|
17539
|
+
percentage: usage.percentage,
|
|
17540
|
+
fromEstimate: usage.fromEstimate,
|
|
17541
|
+
emergencySample
|
|
17542
|
+
}),
|
|
17543
|
+
explicitFlush: input.explicitFlush,
|
|
17544
|
+
publishedHistory: false,
|
|
17545
|
+
subagentExecute: !input.fullFeatureMode && input.schedulerDecision === "execute",
|
|
17546
|
+
executeReclaim: false,
|
|
17547
|
+
servedShapeRepair: false
|
|
17548
|
+
};
|
|
17549
|
+
const drainAllowed = !input.compactionOff && reclaimRidePermitted(rides, {
|
|
17550
|
+
signedThinkingHold: input.signedThinkingHold,
|
|
17551
|
+
firstRender: input.firstRender,
|
|
17552
|
+
emergency: bands.forceBandConfirmed
|
|
17553
|
+
});
|
|
17554
|
+
const materializationRequested = !input.signedThinkingHold && input.materializationRequested;
|
|
17555
|
+
const heuristics = heuristicsRunOnPass({
|
|
17556
|
+
compactionOff: input.compactionOff,
|
|
17557
|
+
drainAllowed,
|
|
17558
|
+
rides,
|
|
17559
|
+
materializationRequested,
|
|
17560
|
+
bands,
|
|
17561
|
+
foldBustsServedPrefix: input.folds,
|
|
17562
|
+
firstRender: input.firstRender,
|
|
17563
|
+
schedulerDecision: input.schedulerDecision,
|
|
17564
|
+
alreadyRanThisTurn: input.alreadyRanThisTurn,
|
|
17565
|
+
fullFeatureMode: input.fullFeatureMode
|
|
17566
|
+
});
|
|
17567
|
+
const routine = heuristics && routineCleanupRunsOnPass({
|
|
17568
|
+
bands,
|
|
17569
|
+
percentage: usage.percentage,
|
|
17570
|
+
emergencySample,
|
|
17571
|
+
fullFeatureMode: input.fullFeatureMode,
|
|
17572
|
+
routinePressureAlreadyApplied: routinePressureAlreadyApplied(input.sessionId, {
|
|
17573
|
+
fullFeatureMode: input.fullFeatureMode,
|
|
17574
|
+
executePressureEligible: bands.executePressureEligible,
|
|
17575
|
+
alreadyRanThisTurn: input.alreadyRanThisTurn
|
|
17576
|
+
}),
|
|
17577
|
+
materializationRequested,
|
|
17578
|
+
rewriteAlreadyPriced: input.folds || input.firstRender || input.historyRebuilt
|
|
17579
|
+
});
|
|
17580
|
+
return {
|
|
17581
|
+
editsWholePrefix: drainAllowed && !input.signedThinkingHold,
|
|
17582
|
+
clearsReasoning: routine && !input.signedThinkingHold
|
|
17583
|
+
};
|
|
17584
|
+
}
|
|
17585
|
+
function sameSizingPlan(input, a, b) {
|
|
17586
|
+
const rowsDiffer = a.editsWholePrefix !== b.editsWholePrefix && input.coveredInstructions.length > 0 && hostInstructionRetentionEnabled() && !isHostInstructionRetentionOn(input.db, input.sessionId);
|
|
17587
|
+
const reasoningDiffers = a.clearsReasoning !== b.clearsReasoning && input.reasoning !== undefined;
|
|
17588
|
+
return !rowsDiffer && !reasoningDiffers;
|
|
17589
|
+
}
|
|
17590
|
+
function protectedThinkingMessagesForSizing(args) {
|
|
17591
|
+
if (!args.activeThinkingTurn)
|
|
17592
|
+
return new Set;
|
|
17593
|
+
const mergedIds = getMergedReasoningStrippedIds(args.db, args.sessionId);
|
|
17594
|
+
const bindingIds = new Set([...mergedIds].filter((id) => id.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX)).map((id) => id.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length)));
|
|
17595
|
+
const retained = retainedActiveThinkingParts({
|
|
17596
|
+
messages: [...args.messages],
|
|
17597
|
+
providerID: args.providerID,
|
|
17598
|
+
modelID: args.modelID,
|
|
17599
|
+
mergedIds,
|
|
17600
|
+
bindingIds,
|
|
17601
|
+
removedIds: getReasoningRemovalState(args.db, args.sessionId).messageIds
|
|
17602
|
+
});
|
|
17603
|
+
return new Set(args.messages.filter((message) => message.parts.some((part) => retained.has(part))));
|
|
17604
|
+
}
|
|
17605
|
+
function servedRequestForSizing(input, plan) {
|
|
17606
|
+
const head = input.head ? headMessagesForSizing(input.head, input.headFolds) : [];
|
|
17607
|
+
const instructions = input.coveredInstructions.length > 0 && hostInstructionRetentionEnabled() && (plan.editsWholePrefix || isHostInstructionRetentionOn(input.db, input.sessionId)) ? input.coveredInstructions : [];
|
|
17608
|
+
const removals = replayedReasoningRemovals(input);
|
|
17609
|
+
const cutoff = plan.clearsReasoning && input.reasoning ? Math.min(safeReasoningCutoff(input.messageTagNumbers, input.reasoning.protectedThinkingMessages), clearedReasoningCutoff(input, input.reasoning, removals.messageIds)) : 0;
|
|
17610
|
+
let conversation = withoutReplayedRemovals(input.messages, removals, input);
|
|
17611
|
+
if (cutoff > 0)
|
|
17612
|
+
conversation = conversation.map((message, index) => withoutClearedReasoning(message, input.messages[index] ?? message, input, cutoff));
|
|
17613
|
+
return [...head, ...instructions, ...conversation];
|
|
17614
|
+
}
|
|
17615
|
+
function replayedReasoningRemovals(input) {
|
|
17616
|
+
const bindingIds = new Set;
|
|
17617
|
+
if (input.replayedRemovals.bindingStrips)
|
|
17618
|
+
for (const id of getMergedReasoningStrippedIds(input.db, input.sessionId)) {
|
|
17619
|
+
if (!id.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX))
|
|
17620
|
+
continue;
|
|
17621
|
+
const messageId = id.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length);
|
|
17622
|
+
if (messageId.length > 0)
|
|
17623
|
+
bindingIds.add(messageId);
|
|
17624
|
+
}
|
|
17625
|
+
return {
|
|
17626
|
+
messageIds: input.replayedRemovals.wholePartRemoval ? getReasoningRemovalState(input.db, input.sessionId).messageIds : new Set,
|
|
17627
|
+
bindingIds
|
|
17628
|
+
};
|
|
17629
|
+
}
|
|
17630
|
+
function withoutReplayedRemovals(messages, removals, input) {
|
|
17631
|
+
if (removals.messageIds.size === 0 && removals.bindingIds.size === 0)
|
|
17632
|
+
return [...messages];
|
|
17633
|
+
const copies = messages.map((message) => {
|
|
17634
|
+
const id = message.info.id;
|
|
17635
|
+
return typeof id === "string" && (removals.messageIds.has(id) || removals.bindingIds.has(id)) ? countingCopy(message) : message;
|
|
17636
|
+
});
|
|
17637
|
+
const providerID = input.replayedRemovals.providerID;
|
|
17638
|
+
stripReasoningFromAssistantIds(copies, providerID, removals.bindingIds);
|
|
17639
|
+
removeReasoningParts(copies, removals.messageIds, providerID);
|
|
17640
|
+
return copies;
|
|
17641
|
+
}
|
|
17642
|
+
function countingCopy(message) {
|
|
17643
|
+
return {
|
|
17644
|
+
...message,
|
|
17645
|
+
parts: message.parts.map((part) => {
|
|
17646
|
+
if (!isRecord(part) || !isRecord(part.metadata))
|
|
17647
|
+
return part;
|
|
17648
|
+
return {
|
|
17649
|
+
...part,
|
|
17650
|
+
metadata: {
|
|
17651
|
+
...part.metadata,
|
|
17652
|
+
...isRecord(part.metadata.openrouter) ? { openrouter: { ...part.metadata.openrouter } } : {}
|
|
17653
|
+
}
|
|
17654
|
+
};
|
|
17655
|
+
})
|
|
17656
|
+
};
|
|
17657
|
+
}
|
|
17658
|
+
function clearedReasoningCutoff(input, reasoning, removedIds) {
|
|
17659
|
+
try {
|
|
17660
|
+
return projectOpencodeReasoningBudgetCutoff(input.db, input.sessionId, [...input.messages], reasoning.keepTokens, reasoning.clearedThroughTag, reasoning.proseRatio);
|
|
17661
|
+
} catch (error) {
|
|
17662
|
+
if (!(error instanceof TagOwnerSummaryNotReady2))
|
|
17663
|
+
throw error;
|
|
17664
|
+
}
|
|
17665
|
+
const gone = new Set(removedIds);
|
|
17666
|
+
for (const [message, tag] of input.messageTagNumbers) {
|
|
17667
|
+
if (tag > 0 && tag <= reasoning.clearedThroughTag && typeof message.info.id === "string")
|
|
17668
|
+
gone.add(message.info.id);
|
|
17669
|
+
}
|
|
17670
|
+
const frozenMergedIds = getMergedReasoningStrippedIds(input.db, input.sessionId);
|
|
17671
|
+
return opencodeReasoningBudgetCutoff({
|
|
17672
|
+
messages: [...input.messages],
|
|
17673
|
+
messageTagNumbers: input.messageTagNumbers,
|
|
17674
|
+
budget: reasoning.keepTokens,
|
|
17675
|
+
alreadyRemoved: gone,
|
|
17676
|
+
proseRatio: reasoning.proseRatio,
|
|
17677
|
+
frozenMergedIds,
|
|
17678
|
+
alsoGone: new Set([...frozenMergedIds].filter((id) => id.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX)).map((id) => id.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length)))
|
|
17679
|
+
});
|
|
17680
|
+
}
|
|
17681
|
+
function withoutClearedReasoning(message, original, input, cutoff) {
|
|
17682
|
+
const tag = input.messageTagNumbers.get(original) ?? 0;
|
|
17683
|
+
if (tag === 0 || tag > cutoff)
|
|
17684
|
+
return message;
|
|
17685
|
+
const parts = message.parts.filter((part) => !isReasoningPart(part));
|
|
17686
|
+
return parts.length === message.parts.length ? message : { ...message, parts };
|
|
17687
|
+
}
|
|
17688
|
+
function isReasoningPart(part) {
|
|
17689
|
+
return typeof part === "object" && part !== null && REASONING_PART_TYPES.has(String(part.type));
|
|
17690
|
+
}
|
|
17691
|
+
|
|
17692
|
+
// src/hooks/magic-context/recovery-fit.ts
|
|
17693
|
+
var RECOVERY_REFUSAL_NOTICE = "Magic Context is still summarizing older history so this conversation fits the model's context window. Send your message again to continue.";
|
|
17694
|
+
var RECOVERY_NO_HISTORY_REFUSAL_NOTICE = "This conversation no longer fits the model's context window, and Magic Context has no more older history it can summarize. Switch to a model with a larger context window to continue.";
|
|
17695
|
+
function recoveryLineTokens(windowTokens) {
|
|
17696
|
+
return Math.floor(windowTokens * BLOCK_UNTIL_DONE_PERCENTAGE / 100);
|
|
17697
|
+
}
|
|
17698
|
+
function recoveryAdmissionLimitTokens(windowTokens, historyRemains) {
|
|
17699
|
+
return historyRemains ? recoveryLineTokens(windowTokens) : Math.floor(windowTokens);
|
|
17700
|
+
}
|
|
17701
|
+
function recoveryRefusalNotice(historyRemains) {
|
|
17702
|
+
return historyRemains ? RECOVERY_REFUSAL_NOTICE : RECOVERY_NO_HISTORY_REFUSAL_NOTICE;
|
|
17703
|
+
}
|
|
17704
|
+
|
|
17500
17705
|
// src/hooks/magic-context/release-recovery-prefix.ts
|
|
17501
17706
|
function groups(messages) {
|
|
17502
17707
|
const result = new Map;
|
|
@@ -20453,7 +20658,7 @@ function resolveUnknownUsageFromWireEstimate(input) {
|
|
|
20453
20658
|
const providerLimit = input.providerProvenLimitTokens;
|
|
20454
20659
|
const canUseProviderMass = input.wireEstimateTrusted === false && typeof providerTokens === "number" && Number.isFinite(providerTokens) && providerTokens > 0 && typeof providerLimit === "number" && Number.isFinite(providerLimit) && providerLimit > 0;
|
|
20455
20660
|
const tokens = canUseProviderMass ? Math.max(wireTokens, providerTokens) : wireTokens;
|
|
20456
|
-
const limit = input.
|
|
20661
|
+
const limit = input.windowTokens;
|
|
20457
20662
|
const estimatedPercentage = typeof limit === "number" && Number.isFinite(limit) && limit > 0 ? tokens / limit * 100 : input.usage.percentage;
|
|
20458
20663
|
return {
|
|
20459
20664
|
inputTokens: tokens,
|
|
@@ -21155,7 +21360,7 @@ function transformGeometryForWire(geometry) {
|
|
|
21155
21360
|
return;
|
|
21156
21361
|
const { window, reserve } = geometry.derivation;
|
|
21157
21362
|
let derivation;
|
|
21158
|
-
if (geometry.geometry === "separate" && geometry.usableSoft <
|
|
21363
|
+
if (geometry.geometry === "separate" && geometry.usableSoft < window) {
|
|
21159
21364
|
derivation = `s1-pre-carve/input=${geometry.usableSoft}`;
|
|
21160
21365
|
} else if (geometry.geometry === "separate") {
|
|
21161
21366
|
derivation = `s1-separate/context=${window}`;
|
|
@@ -23988,6 +24193,7 @@ function readServedTemporalDecisions(db, sessionId, runtime, messageIds) {
|
|
|
23988
24193
|
|
|
23989
24194
|
// src/hooks/magic-context/transform-compartment-phase.ts
|
|
23990
24195
|
var HISTORIAN_INLINE_JOIN_BUDGET_MS = 60000;
|
|
24196
|
+
var CHAINED_RECOVERY_RUN_MIN_BUDGET_MS = 15000;
|
|
23991
24197
|
function resolveHistorianInlineJoinBudget(configuredTimeoutMs) {
|
|
23992
24198
|
const requested = configuredTimeoutMs ?? HISTORIAN_INLINE_JOIN_BUDGET_MS;
|
|
23993
24199
|
return Math.max(0, Math.min(requested, HISTORIAN_INLINE_JOIN_BUDGET_MS));
|
|
@@ -24049,6 +24255,7 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
24049
24255
|
let rebuiltHistoryThisPass = false;
|
|
24050
24256
|
let historianJoinTimedOut = false;
|
|
24051
24257
|
let historianJoinBudgetMs = null;
|
|
24258
|
+
let chainedRecoveryRuns = 0;
|
|
24052
24259
|
const historianRunnable = args.historianRunnable !== false;
|
|
24053
24260
|
if (args.compactionOff) {
|
|
24054
24261
|
if (args.sessionMeta.compartmentInProgress) {
|
|
@@ -24064,7 +24271,9 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
24064
24271
|
justAwaitedPublication,
|
|
24065
24272
|
rebuiltHistoryThisPass,
|
|
24066
24273
|
historianJoinTimedOut,
|
|
24067
|
-
historianJoinBudgetMs
|
|
24274
|
+
historianJoinBudgetMs,
|
|
24275
|
+
chainedRecoveryRuns,
|
|
24276
|
+
recoveryHistoryRemains: false
|
|
24068
24277
|
};
|
|
24069
24278
|
}
|
|
24070
24279
|
let rawEligibility = args.preResolvedBoundarySnapshot ? {
|
|
@@ -24112,7 +24321,7 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
24112
24321
|
const snapshot = getBoundarySnapshotForCompartment();
|
|
24113
24322
|
return snapshot !== null && hasRunnableCompartmentWindow(snapshot);
|
|
24114
24323
|
}
|
|
24115
|
-
async function awaitCompartmentRun(activeRun, reason) {
|
|
24324
|
+
async function awaitCompartmentRun(activeRun, reason, join = fullInlineJoinWindow()) {
|
|
24116
24325
|
await Promise.resolve();
|
|
24117
24326
|
if (activeRun.inlineJoinTimedOutBudgetMs !== undefined && !activeRun.settled) {
|
|
24118
24327
|
historianJoinTimedOut = true;
|
|
@@ -24121,8 +24330,8 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
24121
24330
|
return "timed_out";
|
|
24122
24331
|
}
|
|
24123
24332
|
sessionLog2(args.sessionId, reason);
|
|
24124
|
-
const timeoutMs =
|
|
24125
|
-
historianJoinBudgetMs =
|
|
24333
|
+
const timeoutMs = join.timeoutMs;
|
|
24334
|
+
historianJoinBudgetMs = join.budgetMs;
|
|
24126
24335
|
let timer;
|
|
24127
24336
|
const timeout = new Promise((resolve) => {
|
|
24128
24337
|
timer = setTimeout(() => resolve("timeout"), timeoutMs);
|
|
@@ -24135,20 +24344,145 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
24135
24344
|
clearTimeout(timer);
|
|
24136
24345
|
}
|
|
24137
24346
|
if (result === "timeout") {
|
|
24138
|
-
activeRun.inlineJoinTimedOutBudgetMs =
|
|
24347
|
+
activeRun.inlineJoinTimedOutBudgetMs = join.budgetMs;
|
|
24139
24348
|
historianJoinTimedOut = true;
|
|
24140
24349
|
sessionLog2(args.sessionId, `transform: compartment await timed out after ${timeoutMs}ms — proceeding without waiting`);
|
|
24141
24350
|
return "timed_out";
|
|
24142
24351
|
}
|
|
24143
|
-
|
|
24144
|
-
justAwaitedPublication = activeRun.published;
|
|
24352
|
+
justAwaitedPublication = justAwaitedPublication || activeRun.published;
|
|
24145
24353
|
published = published || activeRun.published;
|
|
24146
|
-
|
|
24354
|
+
return "completed";
|
|
24355
|
+
}
|
|
24356
|
+
function refreshCompartmentCoverage() {
|
|
24357
|
+
sessionLog2(args.sessionId, "transform: compartment agent completed, refreshing compartment coverage");
|
|
24358
|
+
const historyReprepareShouldBust = published && args.deferredHistoryRefreshSessions.has(args.sessionId);
|
|
24147
24359
|
pendingCompartmentInjection = prepareCompartmentInjection(args.db, args.resolvedSessionId, args.messages, historyReprepareShouldBust, args.coveredInstructions, args.projectPath, args.injectionBudgetTokens, args.experimentalTemporalAwareness);
|
|
24148
24360
|
if (historyReprepareShouldBust) {
|
|
24149
24361
|
rebuiltHistoryThisPass = true;
|
|
24150
24362
|
}
|
|
24151
|
-
|
|
24363
|
+
}
|
|
24364
|
+
function fullInlineJoinWindow() {
|
|
24365
|
+
const budgetMs = resolveHistorianInlineJoinBudget(args.historianTimeoutMs);
|
|
24366
|
+
return { timeoutMs: budgetMs, budgetMs };
|
|
24367
|
+
}
|
|
24368
|
+
function historianRunDeps(boundarySnapshot) {
|
|
24369
|
+
return {
|
|
24370
|
+
client: args.client,
|
|
24371
|
+
hiddenCompletionExecutor: args.hiddenCompletionExecutor,
|
|
24372
|
+
compactionMarkerStrategy: args.compactionMarkerStrategy,
|
|
24373
|
+
db: args.db,
|
|
24374
|
+
sessionId: args.sessionId,
|
|
24375
|
+
historianChunkTokens: args.historianChunkTokens,
|
|
24376
|
+
boundarySnapshot,
|
|
24377
|
+
currentContextLimit: args.boundaryContextLimit,
|
|
24378
|
+
historyBudgetTokens: args.historyBudgetTokens,
|
|
24379
|
+
historianTimeoutMs: args.historianTimeoutMs,
|
|
24380
|
+
model: args.historianModel,
|
|
24381
|
+
historianContextLimit: args.historianContextLimit,
|
|
24382
|
+
historianMaxOutputTokens: args.historianMaxOutputTokens,
|
|
24383
|
+
fallbackModels: args.fallbackModels,
|
|
24384
|
+
directory: args.compartmentDirectory,
|
|
24385
|
+
fallbackModelId: args.fallbackModelId,
|
|
24386
|
+
ensureProjectRegistered: args.ensureProjectRegistered,
|
|
24387
|
+
getNotificationParams: args.getNotificationParams,
|
|
24388
|
+
experimentalUserMemories: args.experimentalUserMemories,
|
|
24389
|
+
userObservationsRequested: args.userObservationsRequested,
|
|
24390
|
+
historianTwoPass: args.historianTwoPass,
|
|
24391
|
+
historianExpandTools: args.historianExpandTools,
|
|
24392
|
+
memoryEnabled: args.memoryEnabled,
|
|
24393
|
+
autoPromote: args.autoPromote,
|
|
24394
|
+
onCompartmentStatePublished: args.onCompartmentStatePublished,
|
|
24395
|
+
preserveInjectionCacheUntilConsumed: true
|
|
24396
|
+
};
|
|
24397
|
+
}
|
|
24398
|
+
function resolveNextRecoveryBoundary() {
|
|
24399
|
+
rawEligibility = null;
|
|
24400
|
+
cachedBoundarySnapshot = null;
|
|
24401
|
+
if (!hasNewRawHistoryForCompartment())
|
|
24402
|
+
return null;
|
|
24403
|
+
const resolve = args.resolveRecoveryBoundary ?? resolveBoundarySnapshot;
|
|
24404
|
+
let snapshot = resolve();
|
|
24405
|
+
if (!hasRunnableCompartmentWindow(snapshot)) {
|
|
24406
|
+
snapshot = resolve(args.contextUsage.percentage >= BLOCK_UNTIL_DONE_PERCENTAGE ? 0.25 : 0.5);
|
|
24407
|
+
}
|
|
24408
|
+
cachedBoundarySnapshot = snapshot;
|
|
24409
|
+
return hasRunnableCompartmentWindow(snapshot) ? snapshot : null;
|
|
24410
|
+
}
|
|
24411
|
+
async function chainRecoveryRuns(firstRun, project, deadline, budgetMs) {
|
|
24412
|
+
let lastRun = firstRun;
|
|
24413
|
+
const minimumRunBudgetMs = Math.min(CHAINED_RECOVERY_RUN_MIN_BUDGET_MS, budgetMs / 4);
|
|
24414
|
+
for (;; ) {
|
|
24415
|
+
if (!lastRun.published) {
|
|
24416
|
+
sessionLog2(args.sessionId, `transform: recovery chain stops: the last historian run published nothing (${chainedRecoveryRuns} chained runs)`);
|
|
24417
|
+
return "stopped";
|
|
24418
|
+
}
|
|
24419
|
+
let fit;
|
|
24420
|
+
try {
|
|
24421
|
+
fit = project();
|
|
24422
|
+
} catch (error) {
|
|
24423
|
+
sessionLog2(args.sessionId, "transform: recovery chain stops: the request could not be counted:", error);
|
|
24424
|
+
return "stopped";
|
|
24425
|
+
}
|
|
24426
|
+
if (!fit)
|
|
24427
|
+
return "stopped";
|
|
24428
|
+
if (Number.isFinite(fit.tokens) && fit.tokens <= fit.lineTokens) {
|
|
24429
|
+
sessionLog2(args.sessionId, `transform: recovery chain done: the request is about ${fit.tokens} tokens, under the 95% line ${fit.lineTokens} (${chainedRecoveryRuns} chained runs)`);
|
|
24430
|
+
return "stopped";
|
|
24431
|
+
}
|
|
24432
|
+
const remainingMs = deadline - Date.now();
|
|
24433
|
+
if (remainingMs < minimumRunBudgetMs) {
|
|
24434
|
+
sessionLog2(args.sessionId, `transform: recovery chain stops: ${Math.max(0, remainingMs)}ms of the ${budgetMs}ms inline join budget is left, under the ${minimumRunBudgetMs}ms a chained run needs; the request is still about ${fit.tokens} tokens, over the 95% line ${fit.lineTokens}`);
|
|
24435
|
+
return "stopped";
|
|
24436
|
+
}
|
|
24437
|
+
const boundary = resolveNextRecoveryBoundary();
|
|
24438
|
+
if (!boundary) {
|
|
24439
|
+
sessionLog2(args.sessionId, `transform: recovery chain stops: no eligible history before the protected tail; the request is still about ${fit.tokens} tokens, over the 95% line ${fit.lineTokens}`);
|
|
24440
|
+
return "stopped";
|
|
24441
|
+
}
|
|
24442
|
+
if (isHistorianDrainBudgetSpent({
|
|
24443
|
+
db: args.db,
|
|
24444
|
+
sessionId: args.sessionId,
|
|
24445
|
+
contextLimit: args.boundaryContextLimit,
|
|
24446
|
+
executeThresholdPercentage: args.boundaryExecuteThresholdPercentage,
|
|
24447
|
+
usagePercentage: args.boundaryUsage.percentage
|
|
24448
|
+
})) {
|
|
24449
|
+
sessionLog2(args.sessionId, `transform: recovery chain stops: the historian's drain budget is spent; the request is still about ${fit.tokens} tokens, over the 95% line ${fit.lineTokens}`);
|
|
24450
|
+
return "stopped";
|
|
24451
|
+
}
|
|
24452
|
+
startCompartmentAgent(historianRunDeps(boundary));
|
|
24453
|
+
const nextRun = getActiveCompartmentRun(args.sessionId);
|
|
24454
|
+
if (!nextRun || nextRun === lastRun) {
|
|
24455
|
+
sessionLog2(args.sessionId, "transform: recovery chain stops: the next historian run did not start");
|
|
24456
|
+
return "stopped";
|
|
24457
|
+
}
|
|
24458
|
+
chainedRecoveryRuns += 1;
|
|
24459
|
+
const result = await awaitCompartmentRun(nextRun, `transform: recovery request still about ${fit.tokens} tokens, over the 95% line ${fit.lineTokens}; blocking for historian run ${chainedRecoveryRuns + 1} on the next chunk`, { timeoutMs: remainingMs, budgetMs });
|
|
24460
|
+
if (result === "timed_out")
|
|
24461
|
+
return "timed_out";
|
|
24462
|
+
lastRun = nextRun;
|
|
24463
|
+
}
|
|
24464
|
+
}
|
|
24465
|
+
function recoveryHistoryRemainsAfterJoins() {
|
|
24466
|
+
if (!historianRunnable || !args.canRunCompartments)
|
|
24467
|
+
return false;
|
|
24468
|
+
if (getActiveCompartmentRun(args.sessionId))
|
|
24469
|
+
return true;
|
|
24470
|
+
if (!args.client && !args.hiddenCompletionExecutor)
|
|
24471
|
+
return false;
|
|
24472
|
+
try {
|
|
24473
|
+
if (resolveNextRecoveryBoundary() === null)
|
|
24474
|
+
return false;
|
|
24475
|
+
} catch (error) {
|
|
24476
|
+
sessionLog2(args.sessionId, "transform: recovery history check failed; keeping the 95% line:", error);
|
|
24477
|
+
return true;
|
|
24478
|
+
}
|
|
24479
|
+
return !isHistorianDrainBudgetSpent({
|
|
24480
|
+
db: args.db,
|
|
24481
|
+
sessionId: args.sessionId,
|
|
24482
|
+
contextLimit: args.boundaryContextLimit,
|
|
24483
|
+
executeThresholdPercentage: args.boundaryExecuteThresholdPercentage,
|
|
24484
|
+
usagePercentage: args.boundaryUsage.percentage
|
|
24485
|
+
});
|
|
24152
24486
|
}
|
|
24153
24487
|
if ((!historianRunnable || !args.canRunCompartments && !getActiveCompartmentRun(args.sessionId)) && args.sessionMeta.compartmentInProgress) {
|
|
24154
24488
|
sessionLog2(args.sessionId, "transform: historian unavailable; clearing stale compartmentInProgress flag");
|
|
@@ -24208,34 +24542,7 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
24208
24542
|
let activeRun = getActiveCompartmentRun(args.sessionId);
|
|
24209
24543
|
if (!activeRun && hasEligibleHistoryForCompartment() && (args.client || args.hiddenCompletionExecutor)) {
|
|
24210
24544
|
sessionLog2(args.sessionId, `transform: 95% reached (${args.contextUsage.percentage.toFixed(1)}%), force-starting compartment agent and blocking`);
|
|
24211
|
-
startCompartmentAgent(
|
|
24212
|
-
client: args.client,
|
|
24213
|
-
hiddenCompletionExecutor: args.hiddenCompletionExecutor,
|
|
24214
|
-
compactionMarkerStrategy: args.compactionMarkerStrategy,
|
|
24215
|
-
db: args.db,
|
|
24216
|
-
sessionId: args.sessionId,
|
|
24217
|
-
historianChunkTokens: args.historianChunkTokens,
|
|
24218
|
-
boundarySnapshot: getBoundarySnapshotForCompartment() ?? undefined,
|
|
24219
|
-
currentContextLimit: args.boundaryContextLimit,
|
|
24220
|
-
historyBudgetTokens: args.historyBudgetTokens,
|
|
24221
|
-
historianTimeoutMs: args.historianTimeoutMs,
|
|
24222
|
-
model: args.historianModel,
|
|
24223
|
-
historianContextLimit: args.historianContextLimit,
|
|
24224
|
-
historianMaxOutputTokens: args.historianMaxOutputTokens,
|
|
24225
|
-
fallbackModels: args.fallbackModels,
|
|
24226
|
-
directory: args.compartmentDirectory,
|
|
24227
|
-
fallbackModelId: args.fallbackModelId,
|
|
24228
|
-
ensureProjectRegistered: args.ensureProjectRegistered,
|
|
24229
|
-
getNotificationParams: args.getNotificationParams,
|
|
24230
|
-
experimentalUserMemories: args.experimentalUserMemories,
|
|
24231
|
-
userObservationsRequested: args.userObservationsRequested,
|
|
24232
|
-
historianTwoPass: args.historianTwoPass,
|
|
24233
|
-
historianExpandTools: args.historianExpandTools,
|
|
24234
|
-
memoryEnabled: args.memoryEnabled,
|
|
24235
|
-
autoPromote: args.autoPromote,
|
|
24236
|
-
onCompartmentStatePublished: args.onCompartmentStatePublished,
|
|
24237
|
-
preserveInjectionCacheUntilConsumed: true
|
|
24238
|
-
});
|
|
24545
|
+
startCompartmentAgent(historianRunDeps(getBoundarySnapshotForCompartment() ?? undefined));
|
|
24239
24546
|
activeRun = getActiveCompartmentRun(args.sessionId);
|
|
24240
24547
|
} else if (!activeRun && hasEligibleHistoryForCompartment()) {
|
|
24241
24548
|
sessionLog2(args.sessionId, "transform: cannot force-start compartment agent without client");
|
|
@@ -24246,15 +24553,24 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
24246
24553
|
const notifParams = args.getNotificationParams?.() ?? {};
|
|
24247
24554
|
withoutSqliteTransformPass2(() => sendStatusNotification2(args.client, args.sessionId, `⏳ Context at ${args.contextUsage.percentage.toFixed(0)}% — Magic Context is comparting history before continuing. This may take up to ${HISTORIAN_INLINE_JOIN_BUDGET_MS / 1000} seconds.`, notifParams));
|
|
24248
24555
|
}
|
|
24249
|
-
const
|
|
24556
|
+
const join = fullInlineJoinWindow();
|
|
24557
|
+
const joinDeadline = Date.now() + join.budgetMs;
|
|
24558
|
+
const awaitResult = await awaitCompartmentRun(activeRun, `transform: blocking at ${args.contextUsage.percentage.toFixed(1)}% until compartment agent completes`, join);
|
|
24250
24559
|
if (awaitResult === "completed") {
|
|
24251
24560
|
awaitedCompartmentRun = true;
|
|
24252
24561
|
compartmentInProgress = false;
|
|
24562
|
+
if (args.projectRecoveryRequest) {
|
|
24563
|
+
const chain = await chainRecoveryRuns(activeRun, args.projectRecoveryRequest, joinDeadline, join.budgetMs);
|
|
24564
|
+
if (chain === "timed_out")
|
|
24565
|
+
compartmentInProgress = true;
|
|
24566
|
+
}
|
|
24567
|
+
refreshCompartmentCoverage();
|
|
24253
24568
|
} else {
|
|
24254
24569
|
sessionLog2(args.sessionId, "transform: historian join timed out — reclaim and final fit checks continue; historian keeps running in the background");
|
|
24255
24570
|
}
|
|
24256
24571
|
}
|
|
24257
24572
|
}
|
|
24573
|
+
const recoveryHistoryRemains = args.projectRecoveryRequest !== undefined && recoveryHistoryRemainsAfterJoins();
|
|
24258
24574
|
return {
|
|
24259
24575
|
pendingCompartmentInjection,
|
|
24260
24576
|
awaitedCompartmentRun,
|
|
@@ -24263,7 +24579,9 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
24263
24579
|
justAwaitedPublication,
|
|
24264
24580
|
rebuiltHistoryThisPass,
|
|
24265
24581
|
historianJoinTimedOut,
|
|
24266
|
-
historianJoinBudgetMs
|
|
24582
|
+
historianJoinBudgetMs,
|
|
24583
|
+
chainedRecoveryRuns,
|
|
24584
|
+
recoveryHistoryRemains
|
|
24267
24585
|
};
|
|
24268
24586
|
}
|
|
24269
24587
|
|
|
@@ -24812,6 +25130,7 @@ function createTransform(deps) {
|
|
|
24812
25130
|
sessionID: sessionId
|
|
24813
25131
|
}) : undefined;
|
|
24814
25132
|
const hostEstimate = deps.hostInputEstimate?.(sessionId);
|
|
25133
|
+
const recoveryHostAddedTokens = typeof hostEstimate?.hostAddedTokens === "number" && Number.isFinite(hostEstimate.hostAddedTokens) && hostEstimate.hostAddedTokens > 0 ? hostEstimate.hostAddedTokens : 0;
|
|
24815
25134
|
const hostOverWindow = fullFeatureMode && !compactionOff && resolvedContextLimit !== undefined && resolvedContextLimit > 0 && hostEstimate !== undefined && Number.isFinite(hostEstimate.tokens) && Number.isFinite(hostEstimate.pressureTokens) && hostEstimate.tokens > resolvedContextLimit;
|
|
24816
25135
|
if (hostOverWindow) {
|
|
24817
25136
|
contextUsageEarly = {
|
|
@@ -25301,6 +25620,50 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
25301
25620
|
const watermark = getMaxDroppedTagNumber2(db, sessionId);
|
|
25302
25621
|
let contextUsage = contextUsageEarly;
|
|
25303
25622
|
const rawGetNotifParams = runNotificationParams;
|
|
25623
|
+
const pricedPassSizingInputFor = (messagesToSize, options) => {
|
|
25624
|
+
const servesHead = (!!projectIdentity || !!sessionDirectory) && (fullFeatureMode || compactionOff);
|
|
25625
|
+
const prefixBoundModel = isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID);
|
|
25626
|
+
return {
|
|
25627
|
+
db,
|
|
25628
|
+
sessionId,
|
|
25629
|
+
messages: messagesToSize,
|
|
25630
|
+
messageTagNumbers,
|
|
25631
|
+
head: servesHead ? {
|
|
25632
|
+
db,
|
|
25633
|
+
sessionId,
|
|
25634
|
+
state: options.meta,
|
|
25635
|
+
projectDirectory: sessionDirectory,
|
|
25636
|
+
...renderOptions,
|
|
25637
|
+
hardSignals: options.hardSignals,
|
|
25638
|
+
compactionOff
|
|
25639
|
+
} : undefined,
|
|
25640
|
+
headFolds: options.headFolds,
|
|
25641
|
+
coveredInstructions: deps.storeGeneration === "v2" && servesHead && !compactionOff ? coveredHostInstructions : [],
|
|
25642
|
+
replayedRemovals: {
|
|
25643
|
+
providerID: resolvedProviderID,
|
|
25644
|
+
wholePartRemoval: (!canUseEmptySentinels || prefixBoundModel) && !compactionOff,
|
|
25645
|
+
bindingStrips: !compactionOff
|
|
25646
|
+
},
|
|
25647
|
+
reasoning: options.reasoning
|
|
25648
|
+
};
|
|
25649
|
+
};
|
|
25650
|
+
const recoveryChainWindow = windowGeometry?.usableHard ?? resolvedContextLimit;
|
|
25651
|
+
const recoveryChainMeta = sessionMeta;
|
|
25652
|
+
const projectRecoveryRequest = fullFeatureMode && !compactionOff && emergencyRecoveryArmed && emergencyRecoveryOrigin !== null && typeof recoveryChainWindow === "number" && recoveryChainWindow > 0 ? () => {
|
|
25653
|
+
const served = servedRequestForSizing(pricedPassSizingInputFor(rawTailAfterNewestCompartment(db, sessionId, messages), { meta: recoveryChainMeta, headFolds: true, reasoning: undefined }), { editsWholePrefix: !activeThinkingPrefixHold, clearsReasoning: false });
|
|
25654
|
+
const estimate = estimateFinalWireInputTokens({
|
|
25655
|
+
messages: served,
|
|
25656
|
+
systemPromptTokens: recoveryChainMeta.systemPromptTokens,
|
|
25657
|
+
providerID: modelForBudget?.providerID,
|
|
25658
|
+
modelID: modelForBudget?.modelID,
|
|
25659
|
+
agentName: notificationParams.agent,
|
|
25660
|
+
sessionId
|
|
25661
|
+
});
|
|
25662
|
+
return {
|
|
25663
|
+
tokens: (estimate.pressureTokens ?? estimate.tokens) + recoveryHostAddedTokens,
|
|
25664
|
+
lineTokens: recoveryLineTokens(recoveryChainWindow)
|
|
25665
|
+
};
|
|
25666
|
+
} : undefined;
|
|
25304
25667
|
const tCompartmentPhase = performance.now();
|
|
25305
25668
|
const compartmentPhase = await runCompartmentPhase({
|
|
25306
25669
|
hiddenCompletionExecutor: deps.hiddenCompletionExecutor,
|
|
@@ -25316,6 +25679,17 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
25316
25679
|
boundaryUsage: boundaryUsageForProtectedTail,
|
|
25317
25680
|
boundaryUsageSource,
|
|
25318
25681
|
preResolvedBoundarySnapshot: triggerBoundarySnapshot,
|
|
25682
|
+
projectRecoveryRequest,
|
|
25683
|
+
resolveRecoveryBoundary: (emergencyTailScale) => host.hostProtectedTailBoundary({
|
|
25684
|
+
db,
|
|
25685
|
+
sessionId: resolvedSessionId,
|
|
25686
|
+
mode: "transform-force",
|
|
25687
|
+
contextLimit: boundaryContextLimit,
|
|
25688
|
+
executeThresholdPercentage: boundaryExecuteThreshold,
|
|
25689
|
+
usage: boundaryUsageForProtectedTail,
|
|
25690
|
+
usageSource: boundaryUsageSource,
|
|
25691
|
+
emergencyTailScale
|
|
25692
|
+
}),
|
|
25319
25693
|
client: deps.client,
|
|
25320
25694
|
db,
|
|
25321
25695
|
sessionId,
|
|
@@ -25419,44 +25793,149 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
25419
25793
|
contextLimit: resolvedContextLimit,
|
|
25420
25794
|
lastResponseTime: sessionMeta.lastResponseTime
|
|
25421
25795
|
});
|
|
25422
|
-
|
|
25796
|
+
const servesHead = (!!projectIdentity || !!sessionDirectory) && (fullFeatureMode || compactionOff);
|
|
25797
|
+
const prefixBoundModel = isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID);
|
|
25798
|
+
let sizingInput;
|
|
25799
|
+
let planInput;
|
|
25423
25800
|
try {
|
|
25424
|
-
|
|
25425
|
-
|
|
25426
|
-
|
|
25427
|
-
|
|
25428
|
-
|
|
25429
|
-
|
|
25430
|
-
|
|
25801
|
+
sizingInput = pricedPassSizingInputFor(messages, {
|
|
25802
|
+
meta: sessionMeta,
|
|
25803
|
+
hardSignals: m0HardSignals,
|
|
25804
|
+
headFolds: protectionFoldWillBust,
|
|
25805
|
+
reasoning: !compactionOff && !activeThinkingPrefixHold && resolvedProviderID !== undefined && !prefixBoundModel ? {
|
|
25806
|
+
keepTokens: resolveKeepReasoningTokens(deps.keepReasoningTokens, currentModelKeyForBoundary),
|
|
25807
|
+
clearedThroughTag: sessionMeta.clearedReasoningThroughTag,
|
|
25808
|
+
proseRatio: sessionDecisionCalibration(db, sessionId).proseRatio,
|
|
25809
|
+
protectedThinkingMessages: protectedThinkingMessagesForSizing({
|
|
25810
|
+
db,
|
|
25811
|
+
sessionId,
|
|
25812
|
+
messages,
|
|
25813
|
+
activeThinkingTurn,
|
|
25814
|
+
providerID: resolvedProviderID,
|
|
25815
|
+
modelID: modelForBudget?.modelID
|
|
25816
|
+
})
|
|
25817
|
+
} : undefined
|
|
25431
25818
|
});
|
|
25819
|
+
planInput = {
|
|
25820
|
+
db,
|
|
25821
|
+
sessionId,
|
|
25822
|
+
compactionOff,
|
|
25823
|
+
fullFeatureMode,
|
|
25824
|
+
schedulerDecision,
|
|
25825
|
+
forceMaterializationPercentage,
|
|
25826
|
+
signedThinkingHold: activeThinkingPrefixHold,
|
|
25827
|
+
firstRender: servesHead && !(sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) && !hasCompleteCachedM0M1(db, sessionId),
|
|
25828
|
+
folds: protectionFoldWillBust,
|
|
25829
|
+
explicitFlush: hasPendingMaterializationOrigin(deps.pendingMaterializationSessions, sessionId, "user_flush"),
|
|
25830
|
+
materializationRequested: deps.pendingMaterializationSessions.has(sessionId) || canConsumeDeferredLate && deferredMaterializationSessions.has(sessionId),
|
|
25831
|
+
historyRebuilt: historyRebuiltThisPass || pendingCompartmentInjection?.rebuiltFromDb === true || rebuiltHistoryFromInitialPrepare,
|
|
25832
|
+
alreadyRanThisTurn: heuristicsAlreadyRanThisTurn(deps.lastHeuristicsTurnId, sessionId, currentTurnId)
|
|
25833
|
+
};
|
|
25432
25834
|
} catch (error) {
|
|
25433
|
-
|
|
25434
|
-
|
|
25435
|
-
|
|
25436
|
-
const
|
|
25437
|
-
|
|
25438
|
-
|
|
25439
|
-
|
|
25440
|
-
|
|
25441
|
-
|
|
25835
|
+
sizingInput = undefined;
|
|
25836
|
+
sessionLog2(sessionId, `transform: priced-pass sizing counts the array without the parts the pass adds: ${getErrorMessage(error)}`);
|
|
25837
|
+
}
|
|
25838
|
+
const countRequest = (plan) => {
|
|
25839
|
+
let sizingMessages = messages;
|
|
25840
|
+
if (sizingInput) {
|
|
25841
|
+
try {
|
|
25842
|
+
sizingMessages = servedRequestForSizing(sizingInput, plan);
|
|
25843
|
+
} catch (error) {
|
|
25844
|
+
sessionLog2(sessionId, `transform: priced-pass sizing counts the array without the parts the pass adds: ${getErrorMessage(error)}`);
|
|
25845
|
+
}
|
|
25846
|
+
}
|
|
25847
|
+
try {
|
|
25848
|
+
return estimateFinalWireInputTokens({
|
|
25849
|
+
messages: sizingMessages,
|
|
25850
|
+
systemPromptTokens: sessionMeta.systemPromptTokens,
|
|
25851
|
+
providerID: modelForBudget?.providerID,
|
|
25852
|
+
modelID: modelForBudget?.modelID,
|
|
25853
|
+
agentName: notificationParams.agent,
|
|
25854
|
+
sessionId
|
|
25855
|
+
});
|
|
25856
|
+
} catch (error) {
|
|
25857
|
+
sessionLog2(sessionId, `transform: wire-estimate pressure fallback unavailable: ${getErrorMessage(error)}`);
|
|
25858
|
+
return;
|
|
25859
|
+
}
|
|
25860
|
+
};
|
|
25861
|
+
const usageBeforeSizing = contextUsage;
|
|
25862
|
+
const readingFrom = (pressureEstimate) => {
|
|
25863
|
+
const countPercentage = pressureEstimate?.pressureTokens !== undefined && Number.isFinite(pressureEstimate.pressureTokens) && typeof localReadingWindow === "number" && localReadingWindow > 0 ? pressureEstimate.pressureTokens / localReadingWindow * 100 : 0;
|
|
25864
|
+
const grewPastSavedReading = savedProviderReading !== null && countPercentage >= 95 && countPercentage > savedProviderReading.percentage;
|
|
25865
|
+
const unchanged = {
|
|
25866
|
+
source: "none",
|
|
25867
|
+
usage: usageBeforeSizing,
|
|
25868
|
+
fromEstimate: hostOverWindow,
|
|
25869
|
+
countPercentage,
|
|
25870
|
+
grewPastSavedReading,
|
|
25871
|
+
pressureEstimate,
|
|
25872
|
+
usedProviderInput: false
|
|
25442
25873
|
};
|
|
25443
|
-
|
|
25444
|
-
|
|
25445
|
-
|
|
25446
|
-
|
|
25447
|
-
|
|
25874
|
+
if (savedProviderReading && !grewPastSavedReading) {
|
|
25875
|
+
return {
|
|
25876
|
+
...unchanged,
|
|
25877
|
+
source: "saved",
|
|
25878
|
+
usage: {
|
|
25879
|
+
inputTokens: savedProviderReading.inputTokens,
|
|
25880
|
+
percentage: Math.max(usageBeforeSizing.percentage, savedProviderReading.percentage)
|
|
25881
|
+
}
|
|
25882
|
+
};
|
|
25883
|
+
}
|
|
25884
|
+
if (!pressureEstimate)
|
|
25885
|
+
return unchanged;
|
|
25886
|
+
const usage = resolveUnknownUsageFromWireEstimate({
|
|
25887
|
+
usage: usageBeforeSizing,
|
|
25448
25888
|
pricedPass: true,
|
|
25449
25889
|
wireEstimateTokens: overflowRecoveryPass ? pressureEstimate.tokens : pressureEstimate.pressureTokens,
|
|
25450
25890
|
wireEstimateTrusted: pressureEstimate.trusted,
|
|
25451
25891
|
providerProvenInputTokens: providerProvenInputForRecovery,
|
|
25452
25892
|
providerProvenLimitTokens: providerProvenLimitForRecovery,
|
|
25453
|
-
|
|
25893
|
+
windowTokens: localReadingWindow
|
|
25454
25894
|
});
|
|
25455
|
-
if (
|
|
25456
|
-
|
|
25457
|
-
|
|
25458
|
-
|
|
25895
|
+
if (usage.inputTokens <= 0)
|
|
25896
|
+
return { ...unchanged, usage };
|
|
25897
|
+
const usedProviderInput = !pressureEstimate.trusted && providerProvenLimitForRecovery !== undefined && providerProvenInputForRecovery !== undefined && usage.inputTokens >= providerProvenInputForRecovery;
|
|
25898
|
+
return {
|
|
25899
|
+
...unchanged,
|
|
25900
|
+
source: "estimate",
|
|
25901
|
+
usage,
|
|
25902
|
+
usedProviderInput,
|
|
25903
|
+
fromEstimate: !overflowRecoveryPass && !usedProviderInput && !usagePercentageSynthetic && usage.percentage > usageBeforeSizing.percentage
|
|
25904
|
+
};
|
|
25905
|
+
};
|
|
25906
|
+
const planAt = (usage) => {
|
|
25907
|
+
if (!sizingInput || !planInput)
|
|
25908
|
+
return;
|
|
25909
|
+
try {
|
|
25910
|
+
return planPricedPass(planInput, usage);
|
|
25911
|
+
} catch (error) {
|
|
25912
|
+
sessionLog2(sessionId, `transform: priced-pass sizing counts the widest request: ${getErrorMessage(error)}`);
|
|
25913
|
+
return;
|
|
25459
25914
|
}
|
|
25915
|
+
};
|
|
25916
|
+
let plan = planAt({
|
|
25917
|
+
percentage: usageBeforeSizing.percentage,
|
|
25918
|
+
fromEstimate: hostOverWindow
|
|
25919
|
+
}) ?? WIDEST_PRICED_PASS_PLAN;
|
|
25920
|
+
let reading = readingFrom(countRequest(plan));
|
|
25921
|
+
for (let attempt = 0;sizingInput && plan !== WIDEST_PRICED_PASS_PLAN; attempt++) {
|
|
25922
|
+
const next = planAt({
|
|
25923
|
+
percentage: reading.usage.percentage,
|
|
25924
|
+
fromEstimate: reading.fromEstimate
|
|
25925
|
+
});
|
|
25926
|
+
if (next && sameSizingPlan(sizingInput, next, plan))
|
|
25927
|
+
break;
|
|
25928
|
+
plan = next && attempt === 0 ? next : WIDEST_PRICED_PASS_PLAN;
|
|
25929
|
+
reading = readingFrom(countRequest(plan));
|
|
25930
|
+
}
|
|
25931
|
+
const sizedPlan = `sizedPlan=${plan.clearsReasoning ? "clears_reasoning" : "keeps_reasoning"}${plan.editsWholePrefix ? "+covered_rows" : ""}`;
|
|
25932
|
+
contextUsage = reading.usage;
|
|
25933
|
+
if (reading.source === "saved") {
|
|
25934
|
+
sessionLog2(sessionId, `transform: unknown provider usage; using saved provider reading for priced pass inputTokens=${contextUsage.inputTokens} percentage=${contextUsage.percentage.toFixed(1)} countPercentage=${reading.countPercentage.toFixed(1)} ${sizedPlan}`);
|
|
25935
|
+
} else if (reading.source === "estimate" && reading.pressureEstimate) {
|
|
25936
|
+
const pressureEstimate = reading.pressureEstimate;
|
|
25937
|
+
contextUsageFromEstimate = reading.fromEstimate;
|
|
25938
|
+
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}`);
|
|
25460
25939
|
}
|
|
25461
25940
|
}
|
|
25462
25941
|
const protectionUsableSoft = windowGeometry?.usableSoft ?? boundaryContextLimit;
|
|
@@ -25638,8 +26117,9 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
25638
26117
|
logIncompleteFinalWire(finalWireEstimate, messages);
|
|
25639
26118
|
sessionLog2(sessionId, `transform: final-wire telemetry estimate=${finalWireEstimate.tokens} trusted=${finalWireEstimate.trusted} conversation=${finalWireEstimate.messageTokens.conversation} tools=${finalWireEstimate.messageTokens.toolCall} system=${finalWireEstimate.systemTokens} toolDefinitions=${finalWireEstimate.toolDefinitionTokens ?? "unknown"} tail=${finalWireTail}`);
|
|
25640
26119
|
}
|
|
26120
|
+
const recoveryAdmissionPass = emergencyRecoveryArmed && emergencyRecoveryOrigin !== null && emergencyUsagePercentage >= 95;
|
|
25641
26121
|
let servedPressureTokens;
|
|
25642
|
-
if (providerReadingMissing) {
|
|
26122
|
+
if (providerReadingMissing || recoveryAdmissionPass) {
|
|
25643
26123
|
servedPressureTokens = finalWireEstimate?.pressureTokens;
|
|
25644
26124
|
if (servedPressureTokens === undefined) {
|
|
25645
26125
|
try {
|
|
@@ -25656,12 +26136,13 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
25656
26136
|
}
|
|
25657
26137
|
}
|
|
25658
26138
|
}
|
|
26139
|
+
const recoveryAdmissionTokens = recoveryAdmissionPass && servedPressureTokens !== undefined ? servedPressureTokens + recoveryHostAddedTokens : undefined;
|
|
25659
26140
|
localWireReadings.record({
|
|
25660
26141
|
sessionId,
|
|
25661
26142
|
providerReadingMissing,
|
|
25662
26143
|
modelKey: localReadingModelKey,
|
|
25663
26144
|
usableWindow: localReadingWindow,
|
|
25664
|
-
pressureTokens: servedPressureTokens
|
|
26145
|
+
pressureTokens: providerReadingMissing ? servedPressureTokens : undefined
|
|
25665
26146
|
});
|
|
25666
26147
|
if ((finalWireEstimate?.refusalGrade || finalWireEstimate?.refusalBasis === "byte-bound" && finalWireEstimate.refusalTokens !== undefined) && boundaryContextLimit > 0 && (finalWireEstimate.refusalTokens ?? finalWireEstimate.tokens) > boundaryContextLimit) {
|
|
25667
26148
|
const signedFitRetryWanted = !thinkingFitRetries.has(sessionId) && activeThinkingPrefixHold && hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID);
|
|
@@ -25716,6 +26197,21 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
25716
26197
|
unmanagedOverWindowSessions.delete(sessionId);
|
|
25717
26198
|
sessionLog2(sessionId, `over-window first pass reduced: the request is about ${servedTokens} tokens (history started at ${unmanagedOverWindowPass.tokens}), under the ${unmanagedOverWindowPass.limit}-token window`);
|
|
25718
26199
|
}
|
|
26200
|
+
const currentModelKeyForRecovery = deps.getModelKey?.(sessionId);
|
|
26201
|
+
const keepRecoveryArmed = () => {
|
|
26202
|
+
if (!emergencyRecoveryArmed || emergencyRecoveryOrigin === null)
|
|
26203
|
+
return;
|
|
26204
|
+
try {
|
|
26205
|
+
if (getOverflowState(db, sessionId).needsEmergencyRecovery)
|
|
26206
|
+
return;
|
|
26207
|
+
recordOverflowDetected(db, sessionId, undefined, currentModelKeyForRecovery, emergencyRecoveryOrigin);
|
|
26208
|
+
} catch (error) {
|
|
26209
|
+
throw new EmergencyFailClosedError("Emergency recovery re-arm failed", {
|
|
26210
|
+
cause: error
|
|
26211
|
+
});
|
|
26212
|
+
}
|
|
26213
|
+
sessionLog2(sessionId, `transform: recovery was cleared during a pass that is not sent; armed again (${emergencyRecoveryOrigin}) for the next turn`);
|
|
26214
|
+
};
|
|
25719
26215
|
const timedOutHistorianFailure = compartmentPhase.historianJoinTimedOut ? historianJoinFailClosedMessage({
|
|
25720
26216
|
timedOut: true,
|
|
25721
26217
|
budgetMs: compartmentPhase.historianJoinBudgetMs,
|
|
@@ -25725,14 +26221,21 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
25725
26221
|
}) : null;
|
|
25726
26222
|
if (timedOutHistorianFailure) {
|
|
25727
26223
|
sessionLog2(sessionId, `transform: ${timedOutHistorianFailure}; finalEstimate=${finalWireEstimate?.tokens ?? "unavailable"} estimateTrusted=${finalWireEstimate?.trusted ?? false} contextLimit=${boundaryContextLimit} emergencyReclaimed=${postTransformResult.emergencyReclaimedTokens}`);
|
|
26224
|
+
keepRecoveryArmed();
|
|
25728
26225
|
throw new EmergencyFailClosedError(timedOutHistorianFailure);
|
|
25729
26226
|
}
|
|
25730
26227
|
if (compartmentPhase.historianJoinTimedOut) {
|
|
25731
26228
|
sessionLog2(sessionId, `transform: proceeding after bounded historian join; trusted final-wire ${finalWireEstimate?.tokens} fits context limit ${boundaryContextLimit} after emergency reclaim=${postTransformResult.emergencyReclaimedTokens}`);
|
|
25732
26229
|
}
|
|
25733
|
-
const currentModelKeyForRecovery = deps.getModelKey?.(sessionId);
|
|
25734
26230
|
const overflowStateForFinalWire = getOverflowState(db, sessionId, currentModelKeyForRecovery);
|
|
25735
26231
|
const providerProvenLimitTokens = typeof currentModelKeyForRecovery === "string" && currentModelKeyForRecovery.length > 0 && overflowStateForFinalWire.detectedContextLimit > 0 && piModelRefToCanonical(overflowStateForFinalWire.detectedContextLimitModelKey ?? "") === piModelRefToCanonical(currentModelKeyForRecovery) ? overflowStateForFinalWire.detectedContextLimit : undefined;
|
|
26232
|
+
const recoveryWindowTokens = windowGeometry?.usableHard ?? resolvedContextLimit;
|
|
26233
|
+
const recoveryHistoryRemains = compartmentPhase.recoveryHistoryRemains;
|
|
26234
|
+
const recoveryServedRequest = recoveryAdmissionTokens !== undefined && typeof recoveryWindowTokens === "number" && recoveryWindowTokens > 0 ? {
|
|
26235
|
+
tokens: recoveryAdmissionTokens,
|
|
26236
|
+
lineTokens: recoveryAdmissionLimitTokens(recoveryWindowTokens, recoveryHistoryRemains),
|
|
26237
|
+
historyRemains: recoveryHistoryRemains
|
|
26238
|
+
} : undefined;
|
|
25736
26239
|
const emergencyFailClosed = evaluateEmergencyFailClosed2({
|
|
25737
26240
|
usagePercentage: emergencyUsagePercentage,
|
|
25738
26241
|
emergencyRecoveryArmed,
|
|
@@ -25741,18 +26244,27 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
25741
26244
|
finalWireEstimate,
|
|
25742
26245
|
providerProvenLimitTokens,
|
|
25743
26246
|
contextLimitTokens: boundaryContextLimit,
|
|
25744
|
-
protectedToolTokens: protectedToolTokenCount(getActiveTagsBySession2(db, sessionId), deps.protectedTools, resolveDecisionCalibration(modelForBudget?.providerID, modelForBudget?.modelID))
|
|
26247
|
+
protectedToolTokens: protectedToolTokenCount(getActiveTagsBySession2(db, sessionId), deps.protectedTools, resolveDecisionCalibration(modelForBudget?.providerID, modelForBudget?.modelID)),
|
|
26248
|
+
recoveryServedRequest
|
|
25745
26249
|
});
|
|
25746
26250
|
if (emergencyFailClosed.disarm) {
|
|
25747
26251
|
clearEmergencyRecovery(db, sessionId);
|
|
25748
26252
|
sessionLog2(sessionId, `emergency disarm: trusted final-wire ${emergencyFailClosed.disarm.finalWireTokens} under limit ${emergencyFailClosed.disarm.provenLimitTokens}`);
|
|
26253
|
+
} else if (recoveryAdmissionPass && !emergencyFailClosed.shouldAbort && recoveryServedRequest !== undefined) {
|
|
26254
|
+
clearEmergencyRecovery(db, sessionId);
|
|
26255
|
+
sessionLog2(sessionId, `transform: recovery request admitted: about ${recoveryServedRequest.tokens} tokens, within ${recoveryServedRequest.lineTokens} of ${recoveryWindowTokens}; ${emergencyRecoveryOrigin} recovery ends`);
|
|
25749
26256
|
}
|
|
25750
26257
|
if (emergencyFailClosed.shouldAbort) {
|
|
26258
|
+
keepRecoveryArmed();
|
|
25751
26259
|
if (emergencyFailClosed.refusalMessage) {
|
|
25752
26260
|
throw contextRefusalError(emergencyFailClosed.refusalMessage);
|
|
25753
26261
|
}
|
|
26262
|
+
const recoveryOverLimit = emergencyFailClosed.reason === "recovery-request-over-limit" && recoveryServedRequest !== undefined;
|
|
26263
|
+
if (recoveryOverLimit) {
|
|
26264
|
+
sessionLog2(sessionId, recoveryServedRequest.historyRemains ? `transform: recovery request still over the window: about ${recoveryServedRequest.tokens} tokens against the 95% line ${recoveryServedRequest.lineTokens} of ${recoveryWindowTokens}; not sending it, recovery stays armed for the next turn` : `transform: recovery request still over the window: about ${recoveryServedRequest.tokens} tokens against the whole window ${recoveryServedRequest.lineTokens}, with no older history left to summarize; not sending it`);
|
|
26265
|
+
}
|
|
25754
26266
|
try {
|
|
25755
|
-
await host.hostRefusalNotice(deps.client, sessionId, EMERGENCY_REFUSAL_NOTICE, notificationParams);
|
|
26267
|
+
await host.hostRefusalNotice(deps.client, sessionId, recoveryOverLimit ? recoveryRefusalNotice(recoveryServedRequest.historyRemains) : EMERGENCY_REFUSAL_NOTICE, notificationParams);
|
|
25756
26268
|
} catch (error) {
|
|
25757
26269
|
throw new EmergencyFailClosedError("Emergency recovery notification failed", {
|
|
25758
26270
|
cause: error
|
|
@@ -29259,9 +29771,9 @@ var FULL_PARAMETER_DESCRIPTIONS = {
|
|
|
29259
29771
|
},
|
|
29260
29772
|
ctx_memory: {
|
|
29261
29773
|
action: "write | update | archive | merge | get",
|
|
29262
|
-
content: "The memory text — one standalone fact (write, update, merge).",
|
|
29263
|
-
category: "Kind of fact
|
|
29264
|
-
ids: "Memory ids from <project-memory>: one for update, one or more for archive, two or more for merge, 1–20 for get.",
|
|
29774
|
+
content: "The memory text — one standalone fact (write, update, merge). Archive and get take an empty string.",
|
|
29775
|
+
category: "Kind of fact: the new fact's kind for write; on update/merge, the memory's current category to keep it. Archive and get ignore it.",
|
|
29776
|
+
ids: "Memory ids from <project-memory>: one for update, one or more for archive, two or more for merge, 1–20 for get. Write takes an empty list.",
|
|
29265
29777
|
reason: "Why it is being archived (optional)."
|
|
29266
29778
|
},
|
|
29267
29779
|
ctx_search: {
|
|
@@ -29294,9 +29806,9 @@ var LIGHT_PARAMETER_DESCRIPTIONS = {
|
|
|
29294
29806
|
},
|
|
29295
29807
|
ctx_memory: {
|
|
29296
29808
|
action: "write | update | archive | merge | get",
|
|
29297
|
-
content: "One standalone fact (write, update, merge).",
|
|
29298
|
-
category: "Kind of fact (
|
|
29299
|
-
ids: "Ids from <project-memory>: one for update, 1+ for archive, 2+ for merge, 1–20 for get.",
|
|
29809
|
+
content: "One standalone fact (write, update, merge). Archive and get: empty string.",
|
|
29810
|
+
category: "Kind of fact (write; on update/merge pass the current category to keep it). Archive and get ignore it.",
|
|
29811
|
+
ids: "Ids from <project-memory>: one for update, 1+ for archive, 2+ for merge, 1–20 for get. Write: empty list.",
|
|
29300
29812
|
reason: "Why it is archived (optional)."
|
|
29301
29813
|
},
|
|
29302
29814
|
ctx_search: {
|