@cortexkit/opencode-magic-context 0.49.17 → 0.49.18
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-yhetp0kn.js → context-m897gfp9.js} +20 -11
- package/dist/features/magic-context/storage-host-instruction-retention.d.ts +11 -0
- package/dist/features/magic-context/storage-host-instruction-retention.d.ts.map +1 -0
- package/dist/hooks/magic-context/cache-busting-signals.d.ts +22 -1
- package/dist/hooks/magic-context/cache-busting-signals.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-trigger.d.ts +4 -2
- package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
- package/dist/hooks/magic-context/file-token-coverage.d.ts +11 -0
- package/dist/hooks/magic-context/file-token-coverage.d.ts.map +1 -0
- package/dist/hooks/magic-context/final-wire-token-estimate.d.ts +9 -0
- package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
- package/dist/hooks/magic-context/host-served-rows.d.ts +25 -0
- package/dist/hooks/magic-context/host-served-rows.d.ts.map +1 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts +7 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-slot.d.ts +1 -1
- package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
- package/dist/hooks/magic-context/pass-outcome.d.ts +2 -0
- package/dist/hooks/magic-context/pass-outcome.d.ts.map +1 -1
- package/dist/hooks/magic-context/protected-tail-boundary.d.ts +2 -1
- package/dist/hooks/magic-context/protected-tail-boundary.d.ts.map +1 -1
- package/dist/hooks/magic-context/signed-thinking-hold.d.ts +59 -0
- package/dist/hooks/magic-context/signed-thinking-hold.d.ts.map +1 -0
- package/dist/hooks/magic-context/tag-content-primitives.d.ts.map +1 -1
- package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts +6 -0
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-context-state.d.ts +19 -0
- package/dist/hooks/magic-context/transform-context-state.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +19 -0
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/{index-5a1ex6x8.js → index-24jbw52d.js} +3 -3
- package/dist/{index-kmdj7dsq.js → index-6s5941tm.js} +1 -1
- package/dist/{index-aabzay3h.js → index-936py2wm.js} +207 -35
- package/dist/{index-hqhm3wke.js → index-cf74k5ak.js} +2 -2
- package/dist/{index-4yt7dtf4.js → index-e4xv8890.js} +90 -35
- package/dist/{index-fb2qxs2y.js → index-fgncb0ng.js} +1 -1
- package/dist/{index-nkpmm9q8.js → index-r4nkrs05.js} +2 -2
- package/dist/{index-p7m7j0cp.js → index-rmwykbbb.js} +38 -7
- package/dist/{index-a7c4r5re.js → index-s1ex9y6p.js} +55 -17
- package/dist/{index-vrzjhftj.js → index-s7j8tvhv.js} +2 -2
- package/dist/{index-cwzfcbtq.js → index-x4njr8df.js} +10 -1
- package/dist/index.js +14 -14
- package/dist/{message-index-dprebmtt.js → message-index-66jv6fh4.js} +3 -3
- package/dist/{message-index-bounded-1633vc7f.js → message-index-bounded-n1frdn85.js} +3 -3
- package/dist/migration-worker.js +1 -1
- package/dist/raw-ordinal-warmup-worker.js +4 -4
- package/dist/{read-session-chunk-4zp09ejb.js → read-session-chunk-v06g3vka.js} +2 -2
- package/dist/{recomp-orchestrator-z3ecszx6.js → recomp-orchestrator-ghpk2dtq.js} +6 -6
- package/dist/{search-archive-znyy44ve.js → search-archive-4d53y23e.js} +3 -3
- package/dist/{search-6mee3vty.js → search-nkf271d4.js} +4 -4
- package/dist/{storage-tags-8qns3012.js → storage-tags-r7k9tjcv.js} +1 -1
- package/dist/{transform-postprocess-phase-3ydzxa62.js → transform-postprocess-phase-zpgav0h7.js} +6 -6
- package/dist/v2/auto-search-worker.js +1 -1
- package/dist/v2/chunk-embedding-write-worker.js +1 -1
- package/dist/v2/{context-jn3zpeqh.js → context-f2xh7ba4.js} +302 -68
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/payload.d.ts.map +1 -1
- package/dist/v2/{message-index-pxehjpzx.js → message-index-48f7hw7a.js} +3 -3
- package/dist/v2/{message-index-bounded-hpejqyd8.js → message-index-bounded-w3hfm29z.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-zdppn4bj.js → read-session-chunk-zpgmxwte.js} +2 -2
- package/dist/v2/{recomp-orchestrator-cmqnfpp3.js → recomp-orchestrator-4vfxej9t.js} +5 -5
- package/dist/v2/{search-archive-gfh11vs0.js → search-archive-vv48s2aa.js} +3 -3
- package/dist/v2/{search-66842dya.js → search-kza414f0.js} +4 -4
- package/dist/v2/{server-vsw8tmm6.js → server-1nyybqan.js} +2 -2
- package/dist/v2/{server-zyzawhdw.js → server-27gq4mfz.js} +2 -2
- package/dist/v2/{server-3rhpvy84.js → server-2ehj0bw7.js} +10 -1
- package/dist/v2/{server-gtfhttbr.js → server-a2eqhkxr.js} +1 -1
- package/dist/v2/{server-fw7wrk01.js → server-bfpda1tb.js} +55 -17
- package/dist/v2/{server-ec4ca92p.js → server-qv7f0hhe.js} +1 -1
- package/dist/v2/{server-kh7dpa1a.js → server-xhab8jx8.js} +38 -7
- package/dist/v2/server.js +2 -2
- package/dist/v2/{storage-tags-1h8k6ra9.js → storage-tags-3wdb8zph.js} +1 -1
- package/dist/v2/store-reader.d.ts +6 -0
- package/dist/v2/store-reader.d.ts.map +1 -1
- package/dist/v2/{wrapup-orchestrator-xs8redz9.js → wrapup-orchestrator-psqz7yh0.js} +5 -5
- package/dist/{wrapup-orchestrator-j7d7ry5b.js → wrapup-orchestrator-s9zc5b00.js} +7 -7
- package/package.json +1 -1
|
@@ -267,6 +267,7 @@ import {
|
|
|
267
267
|
peekNoteNudgeText,
|
|
268
268
|
markNoteNudgeDelivered,
|
|
269
269
|
clearNoteNudgeTriggerAndCooldown,
|
|
270
|
+
omitIncompleteFileTokenTotals,
|
|
270
271
|
RECOVERY_NO_HEAD_LIMIT,
|
|
271
272
|
deriveProtectedTailTokenTarget,
|
|
272
273
|
selectPerRunCap,
|
|
@@ -279,7 +280,7 @@ import {
|
|
|
279
280
|
startCompartmentAgent,
|
|
280
281
|
setRecompStarting2,
|
|
281
282
|
setRecompTerminal2
|
|
282
|
-
} from "./server-
|
|
283
|
+
} from "./server-bfpda1tb.js";
|
|
283
284
|
import {
|
|
284
285
|
resolveHistorianModel2
|
|
285
286
|
} from "./server-8cd2j99z.js";
|
|
@@ -304,7 +305,7 @@ import {
|
|
|
304
305
|
openDatabaseAsync,
|
|
305
306
|
isDatabasePersisted,
|
|
306
307
|
getDatabasePersistenceError
|
|
307
|
-
} from "./server-
|
|
308
|
+
} from "./server-a2eqhkxr.js";
|
|
308
309
|
import {
|
|
309
310
|
pruneMissingProjectIdentities,
|
|
310
311
|
setHomeProjectPermission,
|
|
@@ -331,12 +332,15 @@ import {
|
|
|
331
332
|
clearCachedM0,
|
|
332
333
|
expandToolPart,
|
|
333
334
|
markHostUnservedRow,
|
|
335
|
+
markCoveredInstructionRow,
|
|
336
|
+
isCoveredInstructionRow,
|
|
337
|
+
takeCoveredInstructionRows,
|
|
338
|
+
cloneKeepingCoveredInstructionMarks,
|
|
334
339
|
estimateTrueRawMessageTokens,
|
|
335
340
|
stripSystemInjection,
|
|
336
341
|
isTextPart,
|
|
337
342
|
isToolPartWithOutput,
|
|
338
343
|
isFilePart,
|
|
339
|
-
buildFileSourceContent,
|
|
340
344
|
toolPartHasUserAnswer,
|
|
341
345
|
DreamTokenBudgetExceeded,
|
|
342
346
|
createDreamTokenBudget,
|
|
@@ -474,6 +478,7 @@ import {
|
|
|
474
478
|
projectOpencodeReasoningBudgetCutoff,
|
|
475
479
|
DEFAULT_KEEP_REASONING_TOKENS,
|
|
476
480
|
resolveKeepReasoningTokens,
|
|
481
|
+
reasoningStepCost,
|
|
477
482
|
reasoningBudgetCutoff,
|
|
478
483
|
reasoningTextAndOpaque,
|
|
479
484
|
opencodeReasoningBudgetCutoff,
|
|
@@ -510,7 +515,7 @@ import {
|
|
|
510
515
|
readRawSessionMessageById2,
|
|
511
516
|
readSessionChunk2,
|
|
512
517
|
readRawSessionSeedTail2
|
|
513
|
-
} from "./server-
|
|
518
|
+
} from "./server-xhab8jx8.js";
|
|
514
519
|
import {
|
|
515
520
|
embedPauseBySession,
|
|
516
521
|
embedRunStateBySession,
|
|
@@ -616,7 +621,7 @@ import {
|
|
|
616
621
|
isMessageIndexReconciledThrough2,
|
|
617
622
|
indexMessagesAfterOrdinal2,
|
|
618
623
|
sweepOrphanedOpenCodeMessageIndexesCooperatively2
|
|
619
|
-
} from "./server-
|
|
624
|
+
} from "./server-2ehj0bw7.js";
|
|
620
625
|
import {
|
|
621
626
|
stableStringify,
|
|
622
627
|
getTemporalDecisions,
|
|
@@ -719,7 +724,7 @@ import {
|
|
|
719
724
|
adoptNullOwnerToolTag2,
|
|
720
725
|
getCandidateToolOwners2,
|
|
721
726
|
pickNearestPriorOwner2
|
|
722
|
-
} from "./server-
|
|
727
|
+
} from "./server-27gq4mfz.js";
|
|
723
728
|
import {
|
|
724
729
|
resolveOpenCodeDbPath,
|
|
725
730
|
assertOpenCodeStoreGeneration,
|
|
@@ -888,14 +893,14 @@ import {
|
|
|
888
893
|
resolveMemoriesByIdsForSearch2,
|
|
889
894
|
unifiedSearch2,
|
|
890
895
|
formatSearchResults2
|
|
891
|
-
} from "./server-
|
|
896
|
+
} from "./server-1nyybqan.js";
|
|
892
897
|
import {
|
|
893
898
|
resolvePromptContext2
|
|
894
899
|
} from "./server-fmsr7v69.js";
|
|
895
900
|
import"./server-kaqs6h31.js";
|
|
896
901
|
import {
|
|
897
902
|
renderSearchArchiveOffThread2
|
|
898
|
-
} from "./server-
|
|
903
|
+
} from "./server-qv7f0hhe.js";
|
|
899
904
|
import {
|
|
900
905
|
compareSemverCore
|
|
901
906
|
} from "./server-84w6rvvf.js";
|
|
@@ -5804,6 +5809,12 @@ function canConsumeDeferredOnThisPass(args) {
|
|
|
5804
5809
|
function hasReclaimRide(signals) {
|
|
5805
5810
|
return signals.hardFold || signals.force || signals.explicitFlush || signals.publishedHistory || signals.subagentExecute === true;
|
|
5806
5811
|
}
|
|
5812
|
+
function prefixMutationPermitted(gate) {
|
|
5813
|
+
return !gate.signedThinkingHold || gate.firstRender || gate.idleExpiry || gate.emergency;
|
|
5814
|
+
}
|
|
5815
|
+
function reclaimRidePermitted(signals, gate) {
|
|
5816
|
+
return prefixMutationPermitted(gate) && hasReclaimRide(signals);
|
|
5817
|
+
}
|
|
5807
5818
|
var RECLAIM_RIDE_NAMES = [
|
|
5808
5819
|
"hardFold",
|
|
5809
5820
|
"force",
|
|
@@ -6099,8 +6110,9 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
|
|
|
6099
6110
|
const canClearReasoning = reasoningProjection?.canClearReasoning ?? modelAcceptsEmptyContent(reasoningProjection?.providerID);
|
|
6100
6111
|
const projectedPostDropPercentage = estimateProjectedPostDropPercentage(db, sessionId, usage, preloadedActiveTags ?? getActiveTagsBySession2(db, sessionId), keepReasoningTokens, sessionMeta.clearedReasoningThroughTag, canClearReasoning, reasoningProjection?.budgetCutoff, eligiblePendingDropTagIds);
|
|
6101
6112
|
const relativePostDropTarget = executeThresholdPercentage * POST_DROP_TARGET_RATIO;
|
|
6113
|
+
const ridePermitted = reclaimRide !== undefined && (reclaimRide.permission ? reclaimRidePermitted(reclaimRide, reclaimRide.permission) : hasReclaimRide(reclaimRide));
|
|
6102
6114
|
const rideLabel = reclaimRide ? reclaimRideLabel(reclaimRide) : "ride=none";
|
|
6103
|
-
const dropsCanLand =
|
|
6115
|
+
const dropsCanLand = ridePermitted;
|
|
6104
6116
|
const forceMaterializationPercentage = escalationBands(executeThresholdPercentage).forceMaterializationPercentage;
|
|
6105
6117
|
if (usage.percentage >= forceMaterializationPercentage) {
|
|
6106
6118
|
if (dropsCanLand && projectedPostDropPercentage !== null && projectedPostDropPercentage <= relativePostDropTarget) {
|
|
@@ -7023,6 +7035,27 @@ function resolveHistoryBudgetTokens(historyBudgetPercentage, contextUsage, execu
|
|
|
7023
7035
|
}) / 100) * historyBudgetPercentage);
|
|
7024
7036
|
}
|
|
7025
7037
|
|
|
7038
|
+
// src/features/magic-context/storage-host-instruction-retention.ts
|
|
7039
|
+
var NAMESPACE = "hostInstructionRetention";
|
|
7040
|
+
var enabled = true;
|
|
7041
|
+
function hostInstructionRetentionEnabled() {
|
|
7042
|
+
return enabled;
|
|
7043
|
+
}
|
|
7044
|
+
function isHostInstructionRetentionOn(db, sessionId) {
|
|
7045
|
+
const lane = readReplayEnvelope(db, sessionId)[NAMESPACE];
|
|
7046
|
+
return typeof lane === "object" && lane !== null && lane.on === true;
|
|
7047
|
+
}
|
|
7048
|
+
function markHostInstructionRetention(db, sessionId) {
|
|
7049
|
+
return updateReplayDocument(db, sessionId, (doc) => {
|
|
7050
|
+
const lane = doc[NAMESPACE];
|
|
7051
|
+
if (typeof lane === "object" && lane !== null && lane.on === true)
|
|
7052
|
+
return false;
|
|
7053
|
+
doc.version = 2;
|
|
7054
|
+
doc[NAMESPACE] = { on: true };
|
|
7055
|
+
return true;
|
|
7056
|
+
});
|
|
7057
|
+
}
|
|
7058
|
+
|
|
7026
7059
|
// src/hooks/magic-context/pending-drop-eligibility.ts
|
|
7027
7060
|
function pendingDropVeto(tagNumber, target, protectedTagIds) {
|
|
7028
7061
|
if (protectedTagIds.has(tagNumber))
|
|
@@ -7646,7 +7679,7 @@ function foldExecutesThisPass(foldDue, materialized) {
|
|
|
7646
7679
|
}
|
|
7647
7680
|
|
|
7648
7681
|
// src/features/magic-context/storage-caveman-rules.ts
|
|
7649
|
-
var
|
|
7682
|
+
var NAMESPACE2 = "caveman";
|
|
7650
7683
|
var CURRENT_RULES_VERSION = 2;
|
|
7651
7684
|
var ORIGINAL_RULES = {
|
|
7652
7685
|
currentRules: false,
|
|
@@ -7665,7 +7698,7 @@ function parseState(lane) {
|
|
|
7665
7698
|
}
|
|
7666
7699
|
function getCavemanReplayState(db, sessionId) {
|
|
7667
7700
|
try {
|
|
7668
|
-
return parseState(readReplayEnvelope(db, sessionId)[
|
|
7701
|
+
return parseState(readReplayEnvelope(db, sessionId)[NAMESPACE2]);
|
|
7669
7702
|
} catch (error) {
|
|
7670
7703
|
if (error instanceof ReplayDocumentError)
|
|
7671
7704
|
return ORIGINAL_RULES;
|
|
@@ -7675,11 +7708,11 @@ function getCavemanReplayState(db, sessionId) {
|
|
|
7675
7708
|
function recordCavemanCurrentRules(db, sessionId, englishWordRules, legacyReasoningTags) {
|
|
7676
7709
|
const tags = [...new Set(legacyReasoningTags)].sort((a, b) => a - b);
|
|
7677
7710
|
const persisted = updateReplayDocument(db, sessionId, (doc) => {
|
|
7678
|
-
const current = parseState(doc[
|
|
7711
|
+
const current = parseState(doc[NAMESPACE2]);
|
|
7679
7712
|
if (current.currentRules && current.englishWordRules === englishWordRules)
|
|
7680
7713
|
return false;
|
|
7681
7714
|
doc.version = 2;
|
|
7682
|
-
doc[
|
|
7715
|
+
doc[NAMESPACE2] = {
|
|
7683
7716
|
rules: CURRENT_RULES_VERSION,
|
|
7684
7717
|
legacyReasoningTags: current.currentRules ? [...current.legacyReasoningTags].sort((a, b) => a - b) : tags,
|
|
7685
7718
|
...englishWordRules ? {} : { englishWordRules: false }
|
|
@@ -9160,25 +9193,12 @@ function tagMessages(sessionId, messages, tagger, db, options = {}) {
|
|
|
9160
9193
|
const filePart = part;
|
|
9161
9194
|
const messageParts = message.parts;
|
|
9162
9195
|
const contentId = `${messageId}:file${partIndex}`;
|
|
9163
|
-
const existingTagId = resolver.resolve(messageId, "file", contentId, fileOrdinal);
|
|
9164
|
-
|
|
9165
|
-
|
|
9166
|
-
|
|
9167
|
-
|
|
9168
|
-
|
|
9169
|
-
}));
|
|
9170
|
-
accAssignTag += performance.now() - _tAssignFile;
|
|
9171
|
-
if (existingTagId === undefined) {
|
|
9172
|
-
const sourceContent = buildFileSourceContent(message.parts);
|
|
9173
|
-
if (sourceContent) {
|
|
9174
|
-
const _tSaveFile = performance.now();
|
|
9175
|
-
if (options.refreshSourceContents)
|
|
9176
|
-
replaceSourceContent(db, sessionId, tagId, sourceContent);
|
|
9177
|
-
else
|
|
9178
|
-
saveSourceContent(db, sessionId, tagId, sourceContent);
|
|
9179
|
-
accSaveSource += performance.now() - _tSaveFile;
|
|
9180
|
-
}
|
|
9181
|
-
}
|
|
9196
|
+
const existingTagId = resolver.resolve(messageId, "file", contentId, fileOrdinal) ?? getTagNumberByMessageId2(db, sessionId, contentId) ?? undefined;
|
|
9197
|
+
fileOrdinal += 1;
|
|
9198
|
+
if (existingTagId === undefined)
|
|
9199
|
+
continue;
|
|
9200
|
+
const tagId = existingTagId;
|
|
9201
|
+
tagger.bindTag(sessionId, contentId, tagId);
|
|
9182
9202
|
messageTagNumbers.set(message, Math.max(messageTagNumbers.get(message) ?? 0, tagId));
|
|
9183
9203
|
targets.set(tagId, {
|
|
9184
9204
|
message,
|
|
@@ -9200,7 +9220,6 @@ function tagMessages(sessionId, messages, tagger, db, options = {}) {
|
|
|
9200
9220
|
return true;
|
|
9201
9221
|
}
|
|
9202
9222
|
});
|
|
9203
|
-
fileOrdinal += 1;
|
|
9204
9223
|
}
|
|
9205
9224
|
}
|
|
9206
9225
|
if (message.info.role === "assistant" && !messageHasTextPart) {
|
|
@@ -9964,7 +9983,7 @@ async function runPostTransformPhase(args) {
|
|
|
9964
9983
|
routinePressureAppliedBySession.set(args.sessionId, true);
|
|
9965
9984
|
}
|
|
9966
9985
|
const routinePressureAlreadyApplied = args.fullFeatureMode && executePressureEligible && routinePressureAppliedBySession.get(args.sessionId) === true;
|
|
9967
|
-
if (args.contextUsage.percentage > 0 && args.contextUsage.percentage < args.forceMaterializationPercentage - 5 && getEmergencyInputSample(args.db, args.sessionId) > 0) {
|
|
9986
|
+
if (args.contextUsageFromEstimate !== true && args.contextUsage.percentage > 0 && args.contextUsage.percentage < args.forceMaterializationPercentage - 5 && getEmergencyInputSample(args.db, args.sessionId) > 0) {
|
|
9968
9987
|
clearEmergencyDropSample(args.db, args.sessionId);
|
|
9969
9988
|
}
|
|
9970
9989
|
const activeCompartmentRun = args.canRunCompartments ? getActiveCompartmentRun(args.sessionId) : undefined;
|
|
@@ -9994,7 +10013,7 @@ async function runPostTransformPhase(args) {
|
|
|
9994
10013
|
if (tag && tag > 0)
|
|
9995
10014
|
safeReasoningCutoff = Math.min(safeReasoningCutoff, tag - 1);
|
|
9996
10015
|
}
|
|
9997
|
-
let activeThinkingPrefixHold = args.activeThinkingPrefixHold === true
|
|
10016
|
+
let activeThinkingPrefixHold = args.activeThinkingPrefixHold === true;
|
|
9998
10017
|
let freezeM0M1 = args.freezeM0M1 === true || activeThinkingPrefixHold;
|
|
9999
10018
|
let rewritingSignedPrefix = false;
|
|
10000
10019
|
let thinkingReleasedForFit = false;
|
|
@@ -10016,7 +10035,7 @@ async function runPostTransformPhase(args) {
|
|
|
10016
10035
|
rewritingSignedPrefix = true;
|
|
10017
10036
|
thinkingReleasedForFit ||= forFit;
|
|
10018
10037
|
};
|
|
10019
|
-
if (activeThinkingPrefixHold && args.
|
|
10038
|
+
if (args.forceSignedRebuildForFit && (activeThinkingPrefixHold || activeThinkingTurn && args.thinkingBindingRecoveryEnabledForModel === true)) {
|
|
10020
10039
|
releaseThinkingForRewrite(true);
|
|
10021
10040
|
}
|
|
10022
10041
|
const foldDueDecision = m0M1EnabledForFold && args.m0M1 && !freezeM0M1 ? mustMaterialize({
|
|
@@ -10153,7 +10172,7 @@ async function runPostTransformPhase(args) {
|
|
|
10153
10172
|
const shouldReadPendingOps = !compactionOff && (materializationRequested || publishedM1RefreshedThisPass || args.schedulerDecision === "execute" || forceMaterialization || foldExecutedThisPass || firstRenderBust || compartmentRunning);
|
|
10154
10173
|
const pendingOps = shouldReadPendingOps ? getPendingOps(args.db, args.sessionId) : [];
|
|
10155
10174
|
const hasPendingUserOps = pendingOps.length > 0;
|
|
10156
|
-
if (args.schedulerDecision === "execute" && pendingOps.some((op) => newTargets.get(op.tagId)?.thinkingDropProtected))
|
|
10175
|
+
if (args.schedulerDecision === "execute" && args.thinkingBindingRecoveryEnabledForModel !== true && pendingOps.some((op) => newTargets.get(op.tagId)?.thinkingDropProtected))
|
|
10157
10176
|
requestPendingMaterialization(args.pendingMaterializationSessions, args.sessionId, "thinking_hold");
|
|
10158
10177
|
const formatPendingOpsDepth = () => {
|
|
10159
10178
|
const depth = getPendingOpsCount(args.db, args.sessionId);
|
|
@@ -10164,16 +10183,34 @@ async function runPostTransformPhase(args) {
|
|
|
10164
10183
|
const rideSignals = {
|
|
10165
10184
|
subagentExecute: !args.fullFeatureMode && args.schedulerDecision === "execute",
|
|
10166
10185
|
hardFold: rewritingSignedPrefix || foldBustsServedPrefixThisPass || firstRenderBust || idleExpiryRebuild,
|
|
10167
|
-
force: emergencyDropEligible && (args.contextUsage.percentage >= 95 || getEmergencyInputSample(args.db, args.sessionId) === 0),
|
|
10186
|
+
force: emergencyDropEligible && (args.contextUsage.percentage >= 95 || args.contextUsageFromEstimate !== true && getEmergencyInputSample(args.db, args.sessionId) === 0),
|
|
10168
10187
|
explicitFlush: isExplicitFlush && hasPendingMaterializationOrigin(args.pendingMaterializationSessions, args.sessionId, "user_flush"),
|
|
10169
10188
|
publishedHistory: !prefixPreflightFailed && (publishedM1RefreshedThisPass || !m0M1EnabledForFold && (args.pendingCompartmentInjection?.compartmentCount ?? 0) > 0 && legacyPublishedHeadChanged(args))
|
|
10170
10189
|
};
|
|
10171
|
-
const publishedWorkDrainAllowed = !compactionOff && (
|
|
10190
|
+
const publishedWorkDrainAllowed = !compactionOff && reclaimRidePermitted(rideSignals, {
|
|
10191
|
+
signedThinkingHold: activeThinkingPrefixHold,
|
|
10192
|
+
firstRender: firstRenderBust,
|
|
10193
|
+
idleExpiry: idleExpiryRebuild,
|
|
10194
|
+
emergency: emergencyDropEligible
|
|
10195
|
+
});
|
|
10172
10196
|
const shouldApplyPendingOps = publishedWorkDrainAllowed;
|
|
10173
10197
|
const shouldRunHeuristics = publishedWorkDrainAllowed && (rideSignals.publishedHistory || materializationRequested || forceMaterialization || foldBustsServedPrefixThisPass || firstRenderBust || heldIdleExpiryRebuild || emergencyDropEligible || args.schedulerDecision === "execute" && (!alreadyRanThisTurn || !args.fullFeatureMode));
|
|
10174
10198
|
const isCacheBustingPass = publishedWorkDrainAllowed;
|
|
10175
|
-
|
|
10199
|
+
let unheldSignedTurnBust = false;
|
|
10200
|
+
if (isCacheBustingPass && !activeThinkingPrefixHold && activeThinkingTurn && args.thinkingBindingRecoveryEnabledForModel === true) {
|
|
10201
|
+
if (foldBustsServedPrefixThisPass || firstRenderBust || publishedM1RefreshedThisPass)
|
|
10202
|
+
releaseThinkingForRewrite();
|
|
10203
|
+
else {
|
|
10204
|
+
unheldSignedTurnBust = true;
|
|
10205
|
+
retainedThinking.clear();
|
|
10206
|
+
protectedThinkingMessages.clear();
|
|
10207
|
+
newTargets = args.targets;
|
|
10208
|
+
}
|
|
10209
|
+
}
|
|
10210
|
+
let recoveryTailNormalizedThisPass = false;
|
|
10211
|
+
if (args.normalizeRecoveryTail && isCacheBustingPass && !activeThinkingPrefixHold) {
|
|
10176
10212
|
args.normalizeRecoveryTail();
|
|
10213
|
+
recoveryTailNormalizedThisPass = true;
|
|
10177
10214
|
args.tags = getTagsBySession2(args.db, args.sessionId);
|
|
10178
10215
|
newTargets = protectNewTagMutations(args.messages, args.targets, retainedThinking, args.thinkingBindingRecoveryEnabledForModel === true);
|
|
10179
10216
|
}
|
|
@@ -10644,6 +10681,26 @@ async function runPostTransformPhase(args) {
|
|
|
10644
10681
|
}
|
|
10645
10682
|
}
|
|
10646
10683
|
const m0M1Enabled = m0M1EnabledForFold;
|
|
10684
|
+
if (m0M1Enabled && args.m0M1 && !compactionOff && args.opencode2) {
|
|
10685
|
+
const covered = args.coveredHostInstructions ?? [];
|
|
10686
|
+
if (covered.length > 0 || canEditWholePrefix) {
|
|
10687
|
+
let retain = false;
|
|
10688
|
+
if (hostInstructionRetentionEnabled()) {
|
|
10689
|
+
try {
|
|
10690
|
+
retain = isHostInstructionRetentionOn(args.db, args.sessionId);
|
|
10691
|
+
} catch (error) {
|
|
10692
|
+
failPass("host-instruction-retention-read-failure", error);
|
|
10693
|
+
}
|
|
10694
|
+
if (!retain && canEditWholePrefix) {
|
|
10695
|
+
if (!markHostInstructionRetention(args.db, args.sessionId))
|
|
10696
|
+
failPass("host-instruction-retention-persistence-failure");
|
|
10697
|
+
retain = true;
|
|
10698
|
+
}
|
|
10699
|
+
}
|
|
10700
|
+
if (retain && covered.length > 0)
|
|
10701
|
+
args.messages.unshift(...covered);
|
|
10702
|
+
}
|
|
10703
|
+
}
|
|
10647
10704
|
if (m0M1Enabled && args.m0M1) {
|
|
10648
10705
|
if (freezeM0M1 && !preparedPrefix) {
|
|
10649
10706
|
preparedPrefix = prepareCachedM0M1Replay(args.db, args.sessionId);
|
|
@@ -11166,7 +11223,7 @@ async function runPostTransformPhase(args) {
|
|
|
11166
11223
|
}
|
|
11167
11224
|
}
|
|
11168
11225
|
}
|
|
11169
|
-
const prefixEditBesidesReasoningTrim = firstRenderBust || heldIdleExpiryRebuild || materializationRequested || explicitMaterializedSuccessfully || deferredMaterializedSuccessfully || foldBustsServedPrefixThisPass || publishedM1RefreshedThisPass || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass || pendingOpsDidMutate || heuristicOrReasoningEditBesidesTrim || emergency || autoReclaimDidMutateThisPass || convertedToolSkeletonsDidMutate || deferredClearedMarkerRetires || noteNudgeAppendedThisPass || todoAnchorMovedThisPass || autoSearchHintAppendedThisPass || dropModeSwitchesThisPass || firstApplicationEdits.beforeNewerThinking;
|
|
11226
|
+
const prefixEditBesidesReasoningTrim = firstRenderBust || heldIdleExpiryRebuild || materializationRequested || explicitMaterializedSuccessfully || deferredMaterializedSuccessfully || foldBustsServedPrefixThisPass || publishedM1RefreshedThisPass || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass || pendingOpsDidMutate || heuristicOrReasoningEditBesidesTrim || emergency || autoReclaimDidMutateThisPass || convertedToolSkeletonsDidMutate || deferredClearedMarkerRetires || noteNudgeAppendedThisPass || todoAnchorMovedThisPass || autoSearchHintAppendedThisPass || dropModeSwitchesThisPass || recoveryTailNormalizedThisPass || firstApplicationEdits.beforeNewerThinking;
|
|
11170
11227
|
let proactiveThinkingStrip = null;
|
|
11171
11228
|
if (!compactionOff && args.thinkingBindingRecoveryEnabledForModel === true && proactiveThinkingStripPermitted && prefixEditBesidesReasoningTrim) {
|
|
11172
11229
|
const outcome = freezeReasoningOnBustingPass({
|
|
@@ -11183,7 +11240,11 @@ async function runPostTransformPhase(args) {
|
|
|
11183
11240
|
mergedReasoningStrippedIds.add(thinkingBindingRecoveryFrozenId(messageId));
|
|
11184
11241
|
}
|
|
11185
11242
|
bustedThisPass = true;
|
|
11243
|
+
if (unheldSignedTurnBust)
|
|
11244
|
+
rewritingSignedPrefix = true;
|
|
11186
11245
|
} else if (outcome.persistenceFailed) {
|
|
11246
|
+
if (unheldSignedTurnBust)
|
|
11247
|
+
throw new Error("Cannot persist signed thinking omission after a mid-turn edit");
|
|
11187
11248
|
failPass("proactive-thinking-strip-persistence-failure");
|
|
11188
11249
|
}
|
|
11189
11250
|
}
|
|
@@ -11342,7 +11403,8 @@ async function runPostTransformPhase(args) {
|
|
|
11342
11403
|
prefixTrimStatus: deliveredPrefix?.prefixTrimStatus ?? null,
|
|
11343
11404
|
thinkingBindingRecovery,
|
|
11344
11405
|
proactiveThinkingStrip,
|
|
11345
|
-
thinkingReleasedForFit
|
|
11406
|
+
thinkingReleasedForFit,
|
|
11407
|
+
openTurnSignedThinkingKept: args.thinkingBindingRecoveryEnabledForModel === true && activeThinkingTurn && !rewritingSignedPrefix
|
|
11346
11408
|
};
|
|
11347
11409
|
}
|
|
11348
11410
|
function checkM0MutationDriftAndSignal(args) {
|
|
@@ -11981,7 +12043,9 @@ var PASS_DEGRADATION_EFFECTS = {
|
|
|
11981
12043
|
"trailing-blank-decision-exception": "changes-request",
|
|
11982
12044
|
"proactive-thinking-strip-persistence-failure": "changes-request",
|
|
11983
12045
|
"reasoning-removal-read-failure": "changes-request",
|
|
11984
|
-
"reasoning-removal-persistence-failure": "changes-request"
|
|
12046
|
+
"reasoning-removal-persistence-failure": "changes-request",
|
|
12047
|
+
"host-instruction-retention-read-failure": "changes-request",
|
|
12048
|
+
"host-instruction-retention-persistence-failure": "changes-request"
|
|
11985
12049
|
};
|
|
11986
12050
|
function degradationChangesRequest(site) {
|
|
11987
12051
|
return PASS_DEGRADATION_EFFECTS[site] === "changes-request";
|
|
@@ -14711,6 +14775,24 @@ function contextUsagePassSnapshot(sessionMeta) {
|
|
|
14711
14775
|
} : null
|
|
14712
14776
|
};
|
|
14713
14777
|
}
|
|
14778
|
+
function savedProviderReadingForPass(input) {
|
|
14779
|
+
const persisted = input.persisted;
|
|
14780
|
+
if (!persisted)
|
|
14781
|
+
return null;
|
|
14782
|
+
const { percentage, inputTokens } = persisted.usage;
|
|
14783
|
+
if (!Number.isFinite(percentage) || percentage <= 0 || !Number.isFinite(inputTokens) || inputTokens <= 0) {
|
|
14784
|
+
return null;
|
|
14785
|
+
}
|
|
14786
|
+
if (!(input.lastResponseTime > 0) || input.cacheExpired)
|
|
14787
|
+
return null;
|
|
14788
|
+
if (persisted.lastObservedModelKey === null || input.currentModelKey === undefined || input.currentModelKey.length === 0 || piModelRefToCanonical(persisted.lastObservedModelKey) !== piModelRefToCanonical(input.currentModelKey)) {
|
|
14789
|
+
return null;
|
|
14790
|
+
}
|
|
14791
|
+
if (typeof input.contextLimit !== "number" || !(input.contextLimit > 0) || persisted.lastUsageContextLimit !== input.contextLimit) {
|
|
14792
|
+
return null;
|
|
14793
|
+
}
|
|
14794
|
+
return { percentage, inputTokens };
|
|
14795
|
+
}
|
|
14714
14796
|
function resolveUnknownUsageFromWireEstimate(input) {
|
|
14715
14797
|
if (input.usage.inputTokens > 0 || !input.pricedPass)
|
|
14716
14798
|
return input.usage;
|
|
@@ -17918,6 +18000,101 @@ function createRustModeTransform(deps, options) {
|
|
|
17918
18000
|
return adapter;
|
|
17919
18001
|
}
|
|
17920
18002
|
|
|
18003
|
+
// src/hooks/magic-context/signed-thinking-hold.ts
|
|
18004
|
+
var HEAVY_REASONING_TOKENS = 1500;
|
|
18005
|
+
var HEAVY_REASONING_WINDOW_STEPS = 15;
|
|
18006
|
+
var HOLD_CAP_POINTS = 10;
|
|
18007
|
+
var REASONING_TYPES = new Set(["reasoning", "thinking"]);
|
|
18008
|
+
function role2(message) {
|
|
18009
|
+
if (!isRecord(message))
|
|
18010
|
+
return;
|
|
18011
|
+
return isRecord(message.info) ? message.info.role : message.role;
|
|
18012
|
+
}
|
|
18013
|
+
function parts(message) {
|
|
18014
|
+
if (!isRecord(message))
|
|
18015
|
+
return [];
|
|
18016
|
+
if (Array.isArray(message.parts))
|
|
18017
|
+
return message.parts;
|
|
18018
|
+
return Array.isArray(message.content) ? message.content : [];
|
|
18019
|
+
}
|
|
18020
|
+
function recordedReasoningTokens(message) {
|
|
18021
|
+
if (!isRecord(message))
|
|
18022
|
+
return;
|
|
18023
|
+
const info = isRecord(message.info) ? message.info : undefined;
|
|
18024
|
+
const candidates = [];
|
|
18025
|
+
if (info && isRecord(info.tokens))
|
|
18026
|
+
candidates.push(info.tokens.reasoning);
|
|
18027
|
+
if (isRecord(message.usage)) {
|
|
18028
|
+
candidates.push(message.usage.reasoning, message.usage.reasoningTokens);
|
|
18029
|
+
}
|
|
18030
|
+
for (const value of candidates) {
|
|
18031
|
+
if (typeof value === "number" && Number.isFinite(value) && value > 0)
|
|
18032
|
+
return value;
|
|
18033
|
+
}
|
|
18034
|
+
return;
|
|
18035
|
+
}
|
|
18036
|
+
function stepReasoningTokens(message, estimateTextTokens) {
|
|
18037
|
+
let text = "";
|
|
18038
|
+
let opaque = false;
|
|
18039
|
+
for (const part of parts(message)) {
|
|
18040
|
+
if (!isRecord(part))
|
|
18041
|
+
continue;
|
|
18042
|
+
const type = String(part.type ?? part.kind);
|
|
18043
|
+
if (type === "redacted_thinking" || part.redacted === true) {
|
|
18044
|
+
opaque = true;
|
|
18045
|
+
continue;
|
|
18046
|
+
}
|
|
18047
|
+
if (!REASONING_TYPES.has(type))
|
|
18048
|
+
continue;
|
|
18049
|
+
const body = typeof part.thinking === "string" ? part.thinking : typeof part.text === "string" ? part.text : "";
|
|
18050
|
+
if (body.length > 0)
|
|
18051
|
+
text += body;
|
|
18052
|
+
else
|
|
18053
|
+
opaque = true;
|
|
18054
|
+
}
|
|
18055
|
+
if (!text && !opaque)
|
|
18056
|
+
return 0;
|
|
18057
|
+
return reasoningStepCost(recordedReasoningTokens(message), text ? estimateTextTokens(text) : 0, opaque);
|
|
18058
|
+
}
|
|
18059
|
+
function decideSignedThinkingHold(args) {
|
|
18060
|
+
const capPercentage = args.executeThresholdPercentage + HOLD_CAP_POINTS;
|
|
18061
|
+
let heavyStepsBack = null;
|
|
18062
|
+
let heavyStepTokens = 0;
|
|
18063
|
+
const start = latestAssistantTurnStart(args.messages);
|
|
18064
|
+
let stepsBack = 0;
|
|
18065
|
+
for (let index = args.messages.length - 1;index >= start; index--) {
|
|
18066
|
+
const message = args.messages[index];
|
|
18067
|
+
if (role2(message) !== "assistant" || parts(message).length === 0)
|
|
18068
|
+
continue;
|
|
18069
|
+
stepsBack++;
|
|
18070
|
+
if (stepsBack > HEAVY_REASONING_WINDOW_STEPS)
|
|
18071
|
+
break;
|
|
18072
|
+
const tokens = stepReasoningTokens(message, args.estimateTextTokens);
|
|
18073
|
+
if (tokens > HEAVY_REASONING_TOKENS) {
|
|
18074
|
+
heavyStepsBack = stepsBack;
|
|
18075
|
+
heavyStepTokens = tokens;
|
|
18076
|
+
break;
|
|
18077
|
+
}
|
|
18078
|
+
}
|
|
18079
|
+
if (heavyStepsBack === null)
|
|
18080
|
+
return {
|
|
18081
|
+
held: false,
|
|
18082
|
+
reason: "no_recent_heavy_reasoning",
|
|
18083
|
+
heavyStepsBack,
|
|
18084
|
+
heavyStepTokens,
|
|
18085
|
+
capPercentage
|
|
18086
|
+
};
|
|
18087
|
+
if (!(args.usagePercentage < capPercentage))
|
|
18088
|
+
return { held: false, reason: "above_cap", heavyStepsBack, heavyStepTokens, capPercentage };
|
|
18089
|
+
return {
|
|
18090
|
+
held: true,
|
|
18091
|
+
reason: "heavy_reasoning",
|
|
18092
|
+
heavyStepsBack,
|
|
18093
|
+
heavyStepTokens,
|
|
18094
|
+
capPercentage
|
|
18095
|
+
};
|
|
18096
|
+
}
|
|
18097
|
+
|
|
17921
18098
|
// src/hooks/magic-context/temporal-served-projection.ts
|
|
17922
18099
|
function readLkgTemporalDecisions(db, sessionId, runtime) {
|
|
17923
18100
|
const slot = getInMemorySlot(sessionId) ?? loadPersistedLkgSlot(db, sessionId);
|
|
@@ -18141,7 +18318,7 @@ async function runCompartmentPhaseImpl(args) {
|
|
|
18141
18318
|
justAwaitedPublication = activeRun.published;
|
|
18142
18319
|
published = published || activeRun.published;
|
|
18143
18320
|
const historyReprepareShouldBust = activeRun.published && args.deferredHistoryRefreshSessions.has(args.sessionId);
|
|
18144
|
-
pendingCompartmentInjection = prepareCompartmentInjection(args.db, args.resolvedSessionId, args.messages, historyReprepareShouldBust, args.projectPath, args.injectionBudgetTokens, args.experimentalTemporalAwareness);
|
|
18321
|
+
pendingCompartmentInjection = prepareCompartmentInjection(args.db, args.resolvedSessionId, args.messages, historyReprepareShouldBust, args.coveredInstructions, args.projectPath, args.injectionBudgetTokens, args.experimentalTemporalAwareness);
|
|
18145
18322
|
if (historyReprepareShouldBust) {
|
|
18146
18323
|
rebuiltHistoryThisPass = true;
|
|
18147
18324
|
}
|
|
@@ -18432,7 +18609,8 @@ function createTransform(deps) {
|
|
|
18432
18609
|
const startTime = performance.now();
|
|
18433
18610
|
const historianRun = deps.resolveHistorianRun?.();
|
|
18434
18611
|
const messages = output.messages;
|
|
18435
|
-
const originalForThinkingFit = messages.some((message) => message.parts.some((part) => isRecord(part) && ["reasoning", "thinking", "redacted_thinking"].includes(String(part.type)))) ?
|
|
18612
|
+
const originalForThinkingFit = messages.some((message) => message.parts.some((part) => isRecord(part) && ["reasoning", "thinking", "redacted_thinking"].includes(String(part.type)))) ? cloneKeepingCoveredInstructionMarks(messages) : null;
|
|
18613
|
+
const coveredHostInstructions = takeCoveredInstructionRows(messages);
|
|
18436
18614
|
const passOutcome = createPassOutcome();
|
|
18437
18615
|
const tSessionId = performance.now();
|
|
18438
18616
|
const sessionId = findSessionId(messages);
|
|
@@ -18630,8 +18808,8 @@ function createTransform(deps) {
|
|
|
18630
18808
|
return true;
|
|
18631
18809
|
}
|
|
18632
18810
|
})();
|
|
18633
|
-
let activeThinkingPrefixHold =
|
|
18634
|
-
let freezeM0M1 = unresolvedDirectoryHold
|
|
18811
|
+
let activeThinkingPrefixHold = false;
|
|
18812
|
+
let freezeM0M1 = unresolvedDirectoryHold;
|
|
18635
18813
|
const compartmentDirectory = sessionDirectory;
|
|
18636
18814
|
const historianRunnable = deps.historianRunnable !== false;
|
|
18637
18815
|
const canRunCompartments = fullFeatureMode && !compactionOff && historianRunnable && (deps.client !== undefined || deps.hiddenCompletionExecutor !== undefined) && compartmentDirectory.length > 0;
|
|
@@ -18759,13 +18937,7 @@ function createTransform(deps) {
|
|
|
18759
18937
|
}
|
|
18760
18938
|
const resolvedProviderID = modelForBudget?.providerID;
|
|
18761
18939
|
activeThinkingTurn ||= hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID);
|
|
18762
|
-
|
|
18763
|
-
freezeM0M1 ||= activeThinkingPrefixHold;
|
|
18764
|
-
if (freezeM0M1 && prefixHoldLogTurnIds.get(sessionId) !== currentTurnId) {
|
|
18765
|
-
prefixHoldLogTurnIds.set(sessionId, currentTurnId);
|
|
18766
|
-
const reason = activeThinkingPrefixHold ? "active thinking turn (prefix-bound model)" : "session directory unresolved";
|
|
18767
|
-
sessionLog2(sessionId, `m[0]/m[1] frozen: ${reason}; replaying the frozen prefix and deferring any rebuild`);
|
|
18768
|
-
}
|
|
18940
|
+
const signedThinkingPrefixBound = activeThinkingTurn && (isPrefixBoundThinkingModel(activeThinkingModel?.providerID, activeThinkingModel?.modelID) || isPrefixBoundThinkingModel(resolvedProviderID, modelForBudget?.modelID));
|
|
18769
18941
|
const canUseEmptySentinels = modelAcceptsEmptyContent(resolvedProviderID);
|
|
18770
18942
|
const protectedThinkingMessages = activeThinkingTurn || isAnthropicFamilyRoute(resolvedProviderID, modelForBudget?.modelID) ? latestAssistantTurnMessages(messages) : new Set;
|
|
18771
18943
|
const resolvedContextLimit = modelForBudget ? resolveTrustedContextLimit(modelForBudget.providerID, modelForBudget.modelID, {
|
|
@@ -18819,6 +18991,29 @@ function createTransform(deps) {
|
|
|
18819
18991
|
const effectiveExecuteThresholdPercentage = executeThresholdDetail.percentage;
|
|
18820
18992
|
sessionLog2(sessionId, `transform threshold: model=${currentModelKeyForBoundary ?? "unknown"} matchedModel=${executeThresholdDetail.matchedKey ?? "scalar"} mode=${executeThresholdDetail.mode} threshold=${effectiveExecuteThresholdPercentage}% proactiveFloor=${getProactiveCompartmentTriggerPercentage(effectiveExecuteThresholdPercentage)}%`);
|
|
18821
18993
|
const { forceMaterializationPercentage } = escalationBands(effectiveExecuteThresholdPercentage);
|
|
18994
|
+
let holdProseRatio;
|
|
18995
|
+
const signedThinkingHold = signedThinkingPrefixBound ? decideSignedThinkingHold({
|
|
18996
|
+
messages,
|
|
18997
|
+
usagePercentage: contextUsageEarly.percentage,
|
|
18998
|
+
executeThresholdPercentage: effectiveExecuteThresholdPercentage,
|
|
18999
|
+
estimateTextTokens: (text) => {
|
|
19000
|
+
holdProseRatio ??= sessionDecisionCalibration(db, sessionId).proseRatio;
|
|
19001
|
+
return estimateTokens(text) * holdProseRatio;
|
|
19002
|
+
}
|
|
19003
|
+
}) : null;
|
|
19004
|
+
activeThinkingPrefixHold = signedThinkingPrefixBound && (compactionOff || signedThinkingHold?.held === true);
|
|
19005
|
+
freezeM0M1 ||= activeThinkingPrefixHold;
|
|
19006
|
+
const prefixHoldLogKey = signedThinkingHold ? `${currentTurnId}:${signedThinkingHold.reason}:${signedThinkingHold.heavyStepsBack ?? "none"}` : freezeM0M1 ? `${currentTurnId}:directory` : null;
|
|
19007
|
+
if (prefixHoldLogKey !== null && prefixHoldLogTurnIds.get(sessionId) !== prefixHoldLogKey) {
|
|
19008
|
+
prefixHoldLogTurnIds.set(sessionId, prefixHoldLogKey);
|
|
19009
|
+
if (signedThinkingHold) {
|
|
19010
|
+
sessionLog2(sessionId, `signed thinking hold: held=${signedThinkingHold.held} reason=${signedThinkingHold.reason} heavyStepsBack=${signedThinkingHold.heavyStepsBack ?? "none"} heavyStepTokens=${signedThinkingHold.heavyStepTokens} usage=${contextUsageEarly.percentage.toFixed(1)}% cap=${signedThinkingHold.capPercentage}%`);
|
|
19011
|
+
}
|
|
19012
|
+
if (freezeM0M1) {
|
|
19013
|
+
const reason = activeThinkingPrefixHold ? compactionOff ? "active thinking turn in compaction-off mode (prefix-bound model)" : "recent heavy reasoning in the active thinking turn (prefix-bound model)" : "session directory unresolved";
|
|
19014
|
+
sessionLog2(sessionId, `m[0]/m[1] frozen: ${reason}; replaying the frozen prefix and deferring any rebuild`);
|
|
19015
|
+
}
|
|
19016
|
+
}
|
|
18822
19017
|
const persistedUsageFreshForBoundary = persistedUsageBeforeResets && Date.now() - persistedUsageBeforeResets.updatedAt <= 10 * 60 * 1000 && (persistedUsageBeforeResets.lastObservedModelKey === null || currentModelKeyForBoundary === undefined || piModelRefToCanonical(persistedUsageBeforeResets.lastObservedModelKey) === piModelRefToCanonical(currentModelKeyForBoundary)) && (resolvedContextLimit === undefined || persistedUsageBeforeResets.lastUsageContextLimit === 0 || persistedUsageBeforeResets.lastUsageContextLimit === resolvedContextLimit) ? persistedUsageBeforeResets.usage : null;
|
|
18823
19018
|
const boundaryUsageForProtectedTail = persistedUsageFreshForBoundary ?? contextUsageEarly;
|
|
18824
19019
|
const boundaryUsageSource = persistedUsageFreshForBoundary ? "persisted" : "live";
|
|
@@ -19005,8 +19200,14 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19005
19200
|
}, {
|
|
19006
19201
|
hardFold: false,
|
|
19007
19202
|
force: contextUsageEarly.percentage >= forceMaterializationPercentage && (contextUsageEarly.percentage >= 95 || getEmergencyInputSample(db, sessionId) === 0),
|
|
19008
|
-
explicitFlush: deps.pendingMaterializationSessions
|
|
19009
|
-
publishedHistory: isCacheBusting
|
|
19203
|
+
explicitFlush: hasPendingMaterializationOrigin(deps.pendingMaterializationSessions, sessionId, "user_flush"),
|
|
19204
|
+
publishedHistory: isCacheBusting,
|
|
19205
|
+
permission: {
|
|
19206
|
+
signedThinkingHold: activeThinkingPrefixHold,
|
|
19207
|
+
firstRender: false,
|
|
19208
|
+
idleExpiry: false,
|
|
19209
|
+
emergency: contextUsageEarly.percentage >= forceMaterializationPercentage
|
|
19210
|
+
}
|
|
19010
19211
|
}, pendingDropEligibility.read(sessionId, dropProjectionKey()));
|
|
19011
19212
|
if (triggerResult.shouldFire) {
|
|
19012
19213
|
sessionLog2(sessionId, `compartment trigger: firing (reason=${triggerResult.reason})`);
|
|
@@ -19026,7 +19227,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19026
19227
|
const messagesBeforeInitialPrepare = isCacheBusting && deferredHistoryWasPendingAtPassStart ? [...messages] : null;
|
|
19027
19228
|
if (fullFeatureMode && !compactionOff) {
|
|
19028
19229
|
const tInj = performance.now();
|
|
19029
|
-
pendingCompartmentInjection = prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, projectIdentity, deps.memoryConfig?.injectionBudgetTokens, deps.experimentalTemporalAwareness);
|
|
19230
|
+
pendingCompartmentInjection = prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, coveredHostInstructions, projectIdentity, deps.memoryConfig?.injectionBudgetTokens, deps.experimentalTemporalAwareness);
|
|
19030
19231
|
if (messagesBeforeInitialPrepare) {
|
|
19031
19232
|
const skippedVisibleMessages = pendingCompartmentInjection?.skippedVisibleMessages ?? 0;
|
|
19032
19233
|
trimmedMessagesAtCompactionBoundary = messagesBeforeInitialPrepare.slice(0, skippedVisibleMessages);
|
|
@@ -19200,6 +19401,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19200
19401
|
fallbackModels: historianRun?.fallbackModels ?? deps.fallbackModels,
|
|
19201
19402
|
compartmentDirectory,
|
|
19202
19403
|
messages,
|
|
19404
|
+
coveredInstructions: coveredHostInstructions,
|
|
19203
19405
|
pendingCompartmentInjection,
|
|
19204
19406
|
fallbackModelId,
|
|
19205
19407
|
projectPath: projectIdentity,
|
|
@@ -19271,30 +19473,53 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19271
19473
|
bustReason: calibrationBustReason,
|
|
19272
19474
|
onAdopt: (message) => sessionLog2(sessionId, message)
|
|
19273
19475
|
});
|
|
19476
|
+
let contextUsageFromEstimate = false;
|
|
19274
19477
|
if (contextUsage.inputTokens <= 0 && protectionCacheBustingPass) {
|
|
19478
|
+
const overflowRecoveryPass = usagePercentageSynthetic || emergencyRecoveryArmed;
|
|
19479
|
+
const savedProviderReading = overflowRecoveryPass ? null : savedProviderReadingForPass({
|
|
19480
|
+
persisted: persistedUsageBeforeResets,
|
|
19481
|
+
currentModelKey: currentModelKeyForBoundary ?? (hardModelKey || undefined),
|
|
19482
|
+
contextLimit: resolvedContextLimit,
|
|
19483
|
+
lastResponseTime: sessionMeta.lastResponseTime,
|
|
19484
|
+
cacheExpired: hardCacheExpired
|
|
19485
|
+
});
|
|
19486
|
+
let pressureEstimate;
|
|
19275
19487
|
try {
|
|
19276
|
-
|
|
19488
|
+
pressureEstimate = estimateFinalWireInputTokens({
|
|
19277
19489
|
messages,
|
|
19278
19490
|
systemPromptTokens: sessionMeta.systemPromptTokens,
|
|
19279
19491
|
providerID: modelForBudget?.providerID,
|
|
19280
19492
|
modelID: modelForBudget?.modelID,
|
|
19281
19493
|
agentName: notificationParams.agent
|
|
19282
19494
|
});
|
|
19495
|
+
} catch (error) {
|
|
19496
|
+
sessionLog2(sessionId, `transform: wire-estimate pressure fallback unavailable: ${getErrorMessage(error)}`);
|
|
19497
|
+
}
|
|
19498
|
+
const usableHard = windowGeometry?.usableHard;
|
|
19499
|
+
const countPercentage = pressureEstimate?.pressureTokens !== undefined && Number.isFinite(pressureEstimate.pressureTokens) && typeof usableHard === "number" && usableHard > 0 ? pressureEstimate.pressureTokens / usableHard * 100 : 0;
|
|
19500
|
+
const grewPastSavedReading = savedProviderReading !== null && countPercentage >= 95 && countPercentage > savedProviderReading.percentage;
|
|
19501
|
+
if (savedProviderReading && !grewPastSavedReading) {
|
|
19502
|
+
contextUsage = {
|
|
19503
|
+
inputTokens: savedProviderReading.inputTokens,
|
|
19504
|
+
percentage: Math.max(contextUsage.percentage, savedProviderReading.percentage)
|
|
19505
|
+
};
|
|
19506
|
+
sessionLog2(sessionId, `transform: unknown provider usage; using saved provider reading for priced pass inputTokens=${contextUsage.inputTokens} percentage=${contextUsage.percentage.toFixed(1)} countPercentage=${countPercentage.toFixed(1)}`);
|
|
19507
|
+
} else if (pressureEstimate) {
|
|
19508
|
+
const percentageBeforeEstimate = contextUsage.percentage;
|
|
19283
19509
|
contextUsage = resolveUnknownUsageFromWireEstimate({
|
|
19284
19510
|
usage: contextUsage,
|
|
19285
19511
|
pricedPass: true,
|
|
19286
|
-
wireEstimateTokens: pressureEstimate.tokens,
|
|
19512
|
+
wireEstimateTokens: overflowRecoveryPass ? pressureEstimate.tokens : pressureEstimate.pressureTokens,
|
|
19287
19513
|
wireEstimateTrusted: pressureEstimate.trusted,
|
|
19288
19514
|
providerProvenInputTokens: providerProvenInputForRecovery,
|
|
19289
19515
|
providerProvenLimitTokens: providerProvenLimitForRecovery,
|
|
19290
|
-
usableHardLimit:
|
|
19516
|
+
usableHardLimit: usableHard
|
|
19291
19517
|
});
|
|
19292
19518
|
if (contextUsage.inputTokens > 0) {
|
|
19293
19519
|
const usedProviderInput = !pressureEstimate.trusted && providerProvenLimitForRecovery !== undefined && providerProvenInputForRecovery !== undefined && contextUsage.inputTokens >= providerProvenInputForRecovery;
|
|
19294
|
-
|
|
19520
|
+
contextUsageFromEstimate = !overflowRecoveryPass && !usedProviderInput && !usagePercentageSynthetic && contextUsage.percentage > percentageBeforeEstimate;
|
|
19521
|
+
sessionLog2(sessionId, `transform: unknown provider usage; using ${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}${grewPastSavedReading ? ` grewPastSavedReading=${savedProviderReading?.percentage.toFixed(1)}` : ""}`);
|
|
19295
19522
|
}
|
|
19296
|
-
} catch (error) {
|
|
19297
|
-
sessionLog2(sessionId, `transform: wire-estimate pressure fallback unavailable: ${getErrorMessage(error)}`);
|
|
19298
19523
|
}
|
|
19299
19524
|
}
|
|
19300
19525
|
const protectionUsableSoft = windowGeometry?.usableSoft ?? boundaryContextLimit;
|
|
@@ -19335,6 +19560,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19335
19560
|
activeAgent,
|
|
19336
19561
|
batch,
|
|
19337
19562
|
contextUsage,
|
|
19563
|
+
contextUsageFromEstimate,
|
|
19338
19564
|
usableWindow: resolvedContextLimit ?? 0,
|
|
19339
19565
|
schedulerDecision,
|
|
19340
19566
|
schedulerDeferReason,
|
|
@@ -19380,6 +19606,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19380
19606
|
emergencyCeilingTokens,
|
|
19381
19607
|
pendingCompartmentInjection,
|
|
19382
19608
|
prefixTrimSourceOrder,
|
|
19609
|
+
coveredHostInstructions,
|
|
19383
19610
|
hiddenMessagesAtCompactionSeam,
|
|
19384
19611
|
trimmedMessagesAtCompactionBoundary,
|
|
19385
19612
|
didMutateFromFlushedStatuses,
|
|
@@ -19580,7 +19807,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19580
19807
|
if (!finalWireEstimate) {
|
|
19581
19808
|
sessionLog2(sessionId, `transform: final-wire telemetry estimate=unavailable trusted=false conversation=unknown tools=unknown system=unknown toolDefinitions=unknown tail=${finalWireTail}`);
|
|
19582
19809
|
}
|
|
19583
|
-
finishSystemDateRefresh(deps.historyRefreshSessions, dateRequest, postTransformResult.bustedThisPass && !activeThinkingPrefixHold || postTransformResult.thinkingReleasedForFit === true);
|
|
19810
|
+
finishSystemDateRefresh(deps.historyRefreshSessions, dateRequest, postTransformResult.bustedThisPass && !activeThinkingPrefixHold && postTransformResult.openTurnSignedThinkingKept !== true || postTransformResult.thinkingReleasedForFit === true);
|
|
19584
19811
|
if (activeThinkingPrefixHold && !postTransformResult.thinkingReleasedForFit && sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) {
|
|
19585
19812
|
recordHeldHeadForRequest(sessionId, currentLkgRequestIdentity(sessionId), (ownsHistory) => deferDeliveredSystemRefresh(deps, sessionId, ownsHistory));
|
|
19586
19813
|
}
|
|
@@ -19681,7 +19908,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
19681
19908
|
});
|
|
19682
19909
|
if (uncachedMessageIds.length > 0) {
|
|
19683
19910
|
try {
|
|
19684
|
-
storedByMessage = getActiveTagTokenTotalsByMessage2(db, sessionId, uncachedMessageIds);
|
|
19911
|
+
storedByMessage = omitIncompleteFileTokenTotals(db, sessionId, messages.flatMap((message) => message.info.id ? [{ id: message.info.id, parts: message.parts }] : []), getActiveTagTokenTotalsByMessage2(db, sessionId, uncachedMessageIds));
|
|
19685
19912
|
} catch {
|
|
19686
19913
|
storedByMessage = new Map;
|
|
19687
19914
|
}
|
|
@@ -22999,7 +23226,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
22999
23226
|
const db = readDatabase();
|
|
23000
23227
|
if (!db)
|
|
23001
23228
|
return { ok: false, error: "db unavailable" };
|
|
23002
|
-
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-
|
|
23229
|
+
const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-4vfxej9t.js"));
|
|
23003
23230
|
const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-3pxn658x.js"));
|
|
23004
23231
|
log2(`[rpc] recomp requested for session ${sessionId}`);
|
|
23005
23232
|
if (!args.client && !args.hiddenCompletionExecutor) {
|
|
@@ -23084,7 +23311,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
23084
23311
|
const db = readDatabase();
|
|
23085
23312
|
if (!db)
|
|
23086
23313
|
return { ok: false, error: "db unavailable" };
|
|
23087
|
-
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-
|
|
23314
|
+
const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-psqz7yh0.js"));
|
|
23088
23315
|
const model = liveSessionState.liveModelBySession.get(sessionId);
|
|
23089
23316
|
const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
|
|
23090
23317
|
const ctx = {
|
|
@@ -24706,6 +24933,8 @@ function adaptPayload(draft, admittedIDs = new Set, messageTimes = new Map) {
|
|
|
24706
24933
|
parts
|
|
24707
24934
|
};
|
|
24708
24935
|
originals.set(mapped, message);
|
|
24936
|
+
if (isCoveredInstructionRow(message))
|
|
24937
|
+
markCoveredInstructionRow(mapped.info);
|
|
24709
24938
|
if (typeof message.id !== "string")
|
|
24710
24939
|
bridgesByCarrier.set(mapped, byCallID);
|
|
24711
24940
|
messages.push(mapped);
|
|
@@ -51796,6 +52025,11 @@ async function applyV2SystemPrompt(systemPrompt, draft) {
|
|
|
51796
52025
|
text
|
|
51797
52026
|
})));
|
|
51798
52027
|
}
|
|
52028
|
+
function coveredInstructionRows(reader, sessionID, throughSeq, model) {
|
|
52029
|
+
if (throughSeq < 0)
|
|
52030
|
+
return [];
|
|
52031
|
+
return reader.instructionRowsThrough(sessionID, throughSeq).flatMap((row) => restoreRow(row, model)).map((message) => markCoveredInstructionRow(message));
|
|
52032
|
+
}
|
|
51799
52033
|
async function registerContext(context) {
|
|
51800
52034
|
const directory = context.location.directory;
|
|
51801
52035
|
const config = loadPluginConfigDetailed(directory).config;
|
|
@@ -52791,7 +53025,7 @@ async function registerContext(context) {
|
|
|
52791
53025
|
asset: hostMediaAsset,
|
|
52792
53026
|
unavailable: (detail) => sessionLog2(draft.sessionID, `v2 restore: attachment replaced by a note row=${detail.rowID} name=${JSON.stringify(detail.name ?? null)} mediaType=${detail.mediaType} reason=${JSON.stringify(detail.reason)}`)
|
|
52793
53027
|
} : undefined));
|
|
52794
|
-
draft.messages.splice(0, draft.messages.length, ...restored, ...draft.messages.filter((message) => message !== incoming));
|
|
53028
|
+
draft.messages.splice(0, draft.messages.length, ...rustModeModuleClient ? [] : coveredInstructionRows(reader, draft.sessionID, Math.min(boundary, cut.seq), draft.model), ...restored, ...draft.messages.filter((message) => message !== incoming));
|
|
52795
53029
|
}
|
|
52796
53030
|
if (config.temporal_awareness === true)
|
|
52797
53031
|
messageTimes = reader.messageTimes(draft.sessionID, draft.messages.flatMap((message) => message.id ? [message.id] : []));
|