@cortexkit/pi-magic-context 0.49.51 → 0.49.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auto-search-worker.js +3 -3
- package/dist/chunk-embedding-write-worker.js +1 -1
- package/dist/{embedding-backfill-fbhpk2yy.js → embedding-backfill-ad4k8e3f.js} +2 -2
- package/dist/{index-babadndp.js → index-1tk6065b.js} +32 -16
- package/dist/{index-r6dj8rm9.js → index-2yjpxzga.js} +9 -5
- package/dist/{index-jexm22qn.js → index-4cmj48mq.js} +3 -3
- package/dist/{index-4j5442b0.js → index-8cgk0pyh.js} +52 -15
- package/dist/{index-1cvyaw9a.js → index-8d2z6503.js} +1 -1
- package/dist/{index-sm51c9bc.js → index-a70dwgff.js} +8 -8
- package/dist/{index-jy9fq8gp.js → index-f07s5m8x.js} +504 -9
- package/dist/{index-ch3rvpjg.js → index-nevbaezn.js} +7 -6
- package/dist/{index-ty2m0s0s.js → index-njd3qa8e.js} +1 -1
- package/dist/{index-ywvhr524.js → index-snrkpmpf.js} +1 -1
- package/dist/{index-06rdy9h6.js → index-tv9pqeek.js} +1 -1
- package/dist/index.js +669 -144
- package/dist/{message-index-bounded-wg71m86d.js → message-index-bounded-hwatm90p.js} +2 -2
- package/dist/migration-worker.js +1 -1
- package/dist/{project-embedding-registry-hpca84nz.js → project-embedding-registry-d67axw7r.js} +3 -1
- package/dist/raw-ordinal-warmup-worker.js +3 -3
- package/dist/{read-session-chunk-dmpabgvh.js → read-session-chunk-mj91mv8r.js} +1 -1
- package/dist/{render-71rpjt3g.js → render-js5tkc4g.js} +4 -4
- package/dist/{search-archive-w12r0c45.js → search-archive-159s0qp9.js} +4 -4
- package/dist/{search-7w8m1snz.js → search-hyc5s9t0.js} +6 -6
- package/dist/subagent-entry.js +11 -11
- package/dist/tag-snapshot-worker-pi.js +1 -1
- package/dist/{v2-archive-reader-5n1w78zj.js → v2-archive-reader-5sc0rsh9.js} +1 -1
- package/package.json +3 -1
package/dist/index.js
CHANGED
|
@@ -153,7 +153,7 @@ import {
|
|
|
153
153
|
registerTodoStateLifecycle,
|
|
154
154
|
syncCtxMemoryToolEnabled,
|
|
155
155
|
registerMagicContextTools
|
|
156
|
-
} from "./index-
|
|
156
|
+
} from "./index-a70dwgff.js";
|
|
157
157
|
import"./index-4knyh1kt.js";
|
|
158
158
|
import {
|
|
159
159
|
canonicalModelIdentity,
|
|
@@ -319,6 +319,7 @@ import {
|
|
|
319
319
|
createDroppedInputGuard,
|
|
320
320
|
isEditTool,
|
|
321
321
|
applyEditMarkerToInput,
|
|
322
|
+
getReasoningRemovalState,
|
|
322
323
|
modelAcceptsEmptyContent,
|
|
323
324
|
isAnthropicFamilyRoute,
|
|
324
325
|
variantChangeBustsProviderCache,
|
|
@@ -351,12 +352,13 @@ import {
|
|
|
351
352
|
getCachedAbsoluteMessageCount2,
|
|
352
353
|
primeInMemoryTailRawMessageCache2,
|
|
353
354
|
readRawSessionMessageIdOrdinalsForRange2,
|
|
355
|
+
hasRawSessionMessageById2,
|
|
354
356
|
compareRawSessionMessageOrder2,
|
|
355
357
|
getRawSessionMessageCount2,
|
|
356
358
|
getRawSessionTagKeysThrough2,
|
|
357
359
|
getLegacyProtectedTailStartOrdinal2,
|
|
358
360
|
readSessionChunk2
|
|
359
|
-
} from "./index-
|
|
361
|
+
} from "./index-8cgk0pyh.js";
|
|
360
362
|
import {
|
|
361
363
|
UNKNOWN_FIT_RATIO,
|
|
362
364
|
hasMeasuredDecisionCalibration,
|
|
@@ -495,7 +497,7 @@ import {
|
|
|
495
497
|
openCurrentDatabase,
|
|
496
498
|
openDatabaseAsync,
|
|
497
499
|
closeDatabase
|
|
498
|
-
} from "./index-
|
|
500
|
+
} from "./index-tv9pqeek.js";
|
|
499
501
|
import {
|
|
500
502
|
LkgRecoveryFenceError,
|
|
501
503
|
clearLkgFenceProcessState,
|
|
@@ -561,6 +563,12 @@ import {
|
|
|
561
563
|
drainStaleLkgSlots,
|
|
562
564
|
createDbLkgPersistence,
|
|
563
565
|
replayLkg,
|
|
566
|
+
beginServedRequest,
|
|
567
|
+
noteServedPassPermission,
|
|
568
|
+
noteServedReplay,
|
|
569
|
+
countServedRefusal,
|
|
570
|
+
dropServedRecord,
|
|
571
|
+
commitServedRequest,
|
|
564
572
|
registerLkgPersistence,
|
|
565
573
|
LKG_SNAPSHOT_ARRAY,
|
|
566
574
|
LKG_SNAPSHOT_OBJECT,
|
|
@@ -612,7 +620,7 @@ import {
|
|
|
612
620
|
getSourceContents,
|
|
613
621
|
recordSubagentInvocation,
|
|
614
622
|
getLatestHistorianInvocationId
|
|
615
|
-
} from "./index-
|
|
623
|
+
} from "./index-f07s5m8x.js";
|
|
616
624
|
import {
|
|
617
625
|
resolveOpenCodeDbPath,
|
|
618
626
|
assertOpenCodeStoreGeneration,
|
|
@@ -670,7 +678,7 @@ import {
|
|
|
670
678
|
clearCompressionDepthRange,
|
|
671
679
|
cleanSearchText,
|
|
672
680
|
matchedSearchSnippet
|
|
673
|
-
} from "./index-
|
|
681
|
+
} from "./index-snrkpmpf.js";
|
|
674
682
|
import {
|
|
675
683
|
rememberV1HiddenRun
|
|
676
684
|
} from "./index-6x556c2q.js";
|
|
@@ -759,16 +767,16 @@ import {
|
|
|
759
767
|
getProjectEmbeddingMaxInputTokens2,
|
|
760
768
|
embedTextForProject2,
|
|
761
769
|
embedBatchForProject2,
|
|
762
|
-
|
|
770
|
+
embedItemsWindowBounded2,
|
|
763
771
|
embedUnembeddedMemoriesForProject2,
|
|
764
772
|
drainCommitBacklogForProject2,
|
|
765
773
|
embedSessionCompartmentChunks2,
|
|
766
774
|
getEmbeddingCoverageStatus2,
|
|
767
775
|
getAutoEmbeddingSessionCoverage2
|
|
768
|
-
} from "./index-
|
|
776
|
+
} from "./index-2yjpxzga.js";
|
|
769
777
|
import {
|
|
770
778
|
cosineSimilarity
|
|
771
|
-
} from "./index-
|
|
779
|
+
} from "./index-njd3qa8e.js";
|
|
772
780
|
import {
|
|
773
781
|
USER_FACING_FAILURES,
|
|
774
782
|
renderUserFacingFailure,
|
|
@@ -802,7 +810,7 @@ import {
|
|
|
802
810
|
scheduleClearAndReindex,
|
|
803
811
|
clearSessionTracking,
|
|
804
812
|
createAutoSearchDiagnostics
|
|
805
|
-
} from "./index-
|
|
813
|
+
} from "./index-1tk6065b.js";
|
|
806
814
|
import"./index-xssjy4z9.js";
|
|
807
815
|
import {
|
|
808
816
|
DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
|
|
@@ -832,9 +840,9 @@ import {
|
|
|
832
840
|
ensurePiTagSnapshotReady
|
|
833
841
|
} from "./index-pkg07s54.js";
|
|
834
842
|
import"./index-yjgkjkjs.js";
|
|
835
|
-
import"./index-
|
|
836
|
-
import"./index-
|
|
837
|
-
import"./index-
|
|
843
|
+
import"./index-8d2z6503.js";
|
|
844
|
+
import"./index-4cmj48mq.js";
|
|
845
|
+
import"./index-nevbaezn.js";
|
|
838
846
|
import {
|
|
839
847
|
__toESM
|
|
840
848
|
} from "./index-22jkk6wg.js";
|
|
@@ -3589,7 +3597,7 @@ function startHostStallProfilerSwitch() {
|
|
|
3589
3597
|
// package.json
|
|
3590
3598
|
var package_default = {
|
|
3591
3599
|
name: "@cortexkit/pi-magic-context",
|
|
3592
|
-
version: "0.49.
|
|
3600
|
+
version: "0.49.53",
|
|
3593
3601
|
type: "module",
|
|
3594
3602
|
description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
|
|
3595
3603
|
main: "dist/index.js",
|
|
@@ -3657,6 +3665,7 @@ var package_default = {
|
|
|
3657
3665
|
"omp-coding-agent-18126": "npm:@oh-my-pi/pi-coding-agent@18.12.6",
|
|
3658
3666
|
"omp-coding-agent-18132": "npm:@oh-my-pi/pi-coding-agent@18.13.2",
|
|
3659
3667
|
"omp-coding-agent-18186": "npm:@oh-my-pi/pi-coding-agent@18.18.6",
|
|
3668
|
+
"omp-coding-agent-18190": "npm:@oh-my-pi/pi-coding-agent@18.19.0",
|
|
3660
3669
|
"omp-pi-ai-171": "npm:@oh-my-pi/pi-ai@17.1.7",
|
|
3661
3670
|
"omp-pi-ai-1889": "npm:@oh-my-pi/pi-ai@18.8.9",
|
|
3662
3671
|
"omp-pi-ai-1811": "npm:@oh-my-pi/pi-ai@18.11.3",
|
|
@@ -3667,6 +3676,7 @@ var package_default = {
|
|
|
3667
3676
|
"omp-pi-ai-18180": "npm:@oh-my-pi/pi-ai@18.18.0",
|
|
3668
3677
|
"omp-pi-ai-18181": "npm:@oh-my-pi/pi-ai@18.18.1",
|
|
3669
3678
|
"omp-pi-ai-18186": "npm:@oh-my-pi/pi-ai@18.18.6",
|
|
3679
|
+
"omp-pi-ai-18190": "npm:@oh-my-pi/pi-ai@18.19.0",
|
|
3670
3680
|
"pi-agent-core-087": "npm:@earendil-works/pi-agent-core@0.87.1",
|
|
3671
3681
|
"pi-ai-086": "npm:@earendil-works/pi-ai@0.86.0",
|
|
3672
3682
|
"pi-ai-087": "npm:@earendil-works/pi-ai@0.87.1",
|
|
@@ -24666,7 +24676,8 @@ var canonicalReasons = new Set([
|
|
|
24666
24676
|
"coverage_fold",
|
|
24667
24677
|
"profile_transition",
|
|
24668
24678
|
"host_compaction",
|
|
24669
|
-
"tag_identity_repair"
|
|
24679
|
+
"tag_identity_repair",
|
|
24680
|
+
"latest_turn_thinking_removed"
|
|
24670
24681
|
]);
|
|
24671
24682
|
var piReasonAliases = {
|
|
24672
24683
|
project_memory_change: "project_memory_epoch",
|
|
@@ -27182,6 +27193,66 @@ function latestAssistantTurnStart(messages) {
|
|
|
27182
27193
|
function latestAssistantTurnMessages(messages) {
|
|
27183
27194
|
return new Set(messages.slice(latestAssistantTurnStart(messages)));
|
|
27184
27195
|
}
|
|
27196
|
+
function isSentAssistantMessage(message) {
|
|
27197
|
+
if (!isRecord(message) || role(message) !== "assistant")
|
|
27198
|
+
return false;
|
|
27199
|
+
const parts = content(message);
|
|
27200
|
+
if (!Array.isArray(parts) || parts.length === 0)
|
|
27201
|
+
return false;
|
|
27202
|
+
if (message.stopReason === "error" || message.stopReason === "aborted")
|
|
27203
|
+
return false;
|
|
27204
|
+
const error = isRecord(message.info) ? message.info.error : undefined;
|
|
27205
|
+
if (error === undefined || error === null)
|
|
27206
|
+
return true;
|
|
27207
|
+
return isRecord(error) && error.name === "MessageAbortedError" && parts.some((part) => isRecord(part) && part.type !== "step-start" && part.type !== "reasoning");
|
|
27208
|
+
}
|
|
27209
|
+
var PI_USER_ON_WIRE_ROLES = new Set([
|
|
27210
|
+
"user",
|
|
27211
|
+
"developer",
|
|
27212
|
+
"custom",
|
|
27213
|
+
"hookMessage",
|
|
27214
|
+
"bashExecution",
|
|
27215
|
+
"pythonExecution",
|
|
27216
|
+
"fileMention",
|
|
27217
|
+
"branchSummary",
|
|
27218
|
+
"compactionSummary"
|
|
27219
|
+
]);
|
|
27220
|
+
var TOOL_RESULT_TYPES = new Set(["tool_result", "toolResult", "tool-result"]);
|
|
27221
|
+
function isUserMessageOnWire(message) {
|
|
27222
|
+
if (!isRecord(message))
|
|
27223
|
+
return false;
|
|
27224
|
+
if (isRecord(message.info)) {
|
|
27225
|
+
if (message.info.role !== "user" || !Array.isArray(message.parts))
|
|
27226
|
+
return false;
|
|
27227
|
+
return message.parts.some((part) => isRecord(part) && part.ignored !== true && !TOOL_RESULT_TYPES.has(String(part.type)) && !(part.type === "text" && part.text === ""));
|
|
27228
|
+
}
|
|
27229
|
+
if (!PI_USER_ON_WIRE_ROLES.has(String(message.role)))
|
|
27230
|
+
return false;
|
|
27231
|
+
if (message.excludeFromContext === true)
|
|
27232
|
+
return false;
|
|
27233
|
+
if (message.role !== "user")
|
|
27234
|
+
return true;
|
|
27235
|
+
if (typeof message.content === "string")
|
|
27236
|
+
return message.content.length > 0;
|
|
27237
|
+
return Array.isArray(message.content) && message.content.some((block) => !isRecord(block) || !TOOL_RESULT_TYPES.has(String(block.type)));
|
|
27238
|
+
}
|
|
27239
|
+
function providerLatestTurn(messages) {
|
|
27240
|
+
let last = messages.length - 1;
|
|
27241
|
+
while (last >= 0 && !isSentAssistantMessage(messages[last]))
|
|
27242
|
+
last -= 1;
|
|
27243
|
+
if (last < 0)
|
|
27244
|
+
return;
|
|
27245
|
+
let start = last;
|
|
27246
|
+
while (start > 0 && !isUserMessageOnWire(messages[start - 1]))
|
|
27247
|
+
start -= 1;
|
|
27248
|
+
let first = start;
|
|
27249
|
+
while (first < last && !isSentAssistantMessage(messages[first]))
|
|
27250
|
+
first += 1;
|
|
27251
|
+
let end = last + 1;
|
|
27252
|
+
while (end < messages.length && !isUserMessageOnWire(messages[end]))
|
|
27253
|
+
end += 1;
|
|
27254
|
+
return { start, first, last, end };
|
|
27255
|
+
}
|
|
27185
27256
|
function isAnthropicThinkingPart(part, familyRoute) {
|
|
27186
27257
|
return isRecord(part) && THINKING_TYPES.has(String(part.type ?? part.kind)) && (familyRoute || isRecord(part.metadata) && isRecord(part.metadata.anthropic));
|
|
27187
27258
|
}
|
|
@@ -27237,18 +27308,110 @@ function protectNewTagMutations(messages, targets, protectedParts, prefixBound)
|
|
|
27237
27308
|
|
|
27238
27309
|
// ../plugin/src/hooks/magic-context/latest-thinking-recovery.ts
|
|
27239
27310
|
var LATEST_THINKING_RESTORE = "latest_thinking_original";
|
|
27311
|
+
var TURN_STATE = `${LATEST_THINKING_RESTORE}_turn:`;
|
|
27240
27312
|
var knownRejectedSessions = new Set;
|
|
27241
|
-
var
|
|
27242
|
-
var
|
|
27243
|
-
|
|
27244
|
-
|
|
27245
|
-
|
|
27246
|
-
|
|
27313
|
+
var REFUSE_AT_REJECTION = 3;
|
|
27314
|
+
var STAGES = new Set(["armed", "restoring", "remove", "removed", "refused"]);
|
|
27315
|
+
function readState(target) {
|
|
27316
|
+
if (!target.startsWith(TURN_STATE))
|
|
27317
|
+
return;
|
|
27318
|
+
try {
|
|
27319
|
+
const value = JSON.parse(target.slice(TURN_STATE.length));
|
|
27320
|
+
if (!isRecord(value) || !STAGES.has(String(value.stage)) || typeof value.first !== "string" || typeof value.last !== "string" || typeof value.rejections !== "number")
|
|
27321
|
+
return;
|
|
27322
|
+
return {
|
|
27323
|
+
stage: value.stage,
|
|
27324
|
+
first: value.first,
|
|
27325
|
+
last: value.last,
|
|
27326
|
+
rejections: value.rejections,
|
|
27327
|
+
...typeof value.pass === "string" ? { pass: value.pass } : {},
|
|
27328
|
+
...typeof value.model === "string" ? { model: value.model } : {},
|
|
27329
|
+
...typeof value.provider === "string" ? { provider: value.provider } : {},
|
|
27330
|
+
...value.accepted === true ? { accepted: true } : {}
|
|
27331
|
+
};
|
|
27332
|
+
} catch {
|
|
27333
|
+
return;
|
|
27334
|
+
}
|
|
27335
|
+
}
|
|
27336
|
+
function encodeState(state) {
|
|
27337
|
+
return TURN_STATE + JSON.stringify({
|
|
27338
|
+
stage: state.stage,
|
|
27339
|
+
first: state.first,
|
|
27340
|
+
last: state.last,
|
|
27341
|
+
rejections: state.rejections,
|
|
27342
|
+
...state.pass ? { pass: state.pass } : {},
|
|
27343
|
+
...state.model ? { model: state.model } : {},
|
|
27344
|
+
...state.provider ? { provider: state.provider } : {},
|
|
27345
|
+
...state.accepted ? { accepted: true } : {}
|
|
27346
|
+
});
|
|
27347
|
+
}
|
|
27348
|
+
function identifyTurn(messages, id) {
|
|
27349
|
+
const turn = providerLatestTurn(messages);
|
|
27350
|
+
if (!turn)
|
|
27351
|
+
return;
|
|
27352
|
+
const first = id(messages[turn.first], turn.first);
|
|
27353
|
+
const last = id(messages[turn.last], turn.last);
|
|
27354
|
+
return first && last ? { turn, bound: { first, last } } : undefined;
|
|
27355
|
+
}
|
|
27356
|
+
var lastPassTurn = new Map;
|
|
27357
|
+
var PROCESS_TOKEN = Math.random().toString(36).slice(2, 10);
|
|
27358
|
+
var passCounter = 0;
|
|
27359
|
+
var LATEST_THINKING_UNSAFE = "ANTHROPIC_LATEST_TURN_EDIT_UNSAFE: The provider keeps rejecting the thinking of this conversation's latest assistant turn, even after Magic Context restored or removed it. Sending a new message does not help, because the provider checks that same turn again. Switch the model once, or run /clear, to continue.";
|
|
27360
|
+
var LATEST_THINKING_NOT_SAVED = "Magic Context could not save the change this request needs after the provider rejected the thinking of the latest assistant turn (its database was busy or changed at the same moment). Nothing was sent. Send your message again.";
|
|
27361
|
+
function escalate(state, rejections) {
|
|
27362
|
+
switch (state.stage) {
|
|
27363
|
+
case "armed":
|
|
27364
|
+
return "armed";
|
|
27365
|
+
case "restoring":
|
|
27366
|
+
case "remove":
|
|
27367
|
+
return "remove";
|
|
27368
|
+
case "removed":
|
|
27369
|
+
if (state.accepted)
|
|
27370
|
+
return "remove";
|
|
27371
|
+
return rejections >= REFUSE_AT_REJECTION ? "refused" : "removed";
|
|
27372
|
+
case "refused":
|
|
27373
|
+
return "refused";
|
|
27374
|
+
}
|
|
27375
|
+
}
|
|
27376
|
+
function armLatestThinkingRecovery(db, sessionId, modelID) {
|
|
27247
27377
|
knownRejectedSessions.add(sessionId);
|
|
27248
27378
|
ensureSessionMetaRow(db, sessionId);
|
|
27249
27379
|
const current = getThinkingBindingRecoveryTarget(db, sessionId);
|
|
27250
|
-
const
|
|
27251
|
-
const
|
|
27380
|
+
const state = current ? readState(current) : undefined;
|
|
27381
|
+
const pass = lastPassTurn.get(sessionId);
|
|
27382
|
+
let next;
|
|
27383
|
+
if (state) {
|
|
27384
|
+
if (pass !== undefined && state.pass === pass.pass)
|
|
27385
|
+
return;
|
|
27386
|
+
const rejections = state.accepted ? 1 : state.rejections + 1;
|
|
27387
|
+
const stage = escalate(state, rejections);
|
|
27388
|
+
const last = pass?.first === state.first ? pass.last : state.last;
|
|
27389
|
+
next = encodeState({
|
|
27390
|
+
...state,
|
|
27391
|
+
stage,
|
|
27392
|
+
last,
|
|
27393
|
+
rejections,
|
|
27394
|
+
pass: pass?.pass,
|
|
27395
|
+
accepted: false
|
|
27396
|
+
});
|
|
27397
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: provider rejected the bound turn again (rejection ${rejections}, first=${state.first} last=${last}); ${state.stage} -> ${stage}`);
|
|
27398
|
+
} else if (pass) {
|
|
27399
|
+
const model = pass.model ?? modelID;
|
|
27400
|
+
const provider = pass.model ? pass.provider : undefined;
|
|
27401
|
+
next = encodeState({
|
|
27402
|
+
stage: "armed",
|
|
27403
|
+
first: pass.first,
|
|
27404
|
+
last: pass.last,
|
|
27405
|
+
rejections: 1,
|
|
27406
|
+
pass: pass.pass,
|
|
27407
|
+
...model ? { model } : {},
|
|
27408
|
+
...provider ? { provider } : {}
|
|
27409
|
+
});
|
|
27410
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: armed for the provider's latest turn (first=${pass.first} last=${pass.last} model=${provider ? `${provider}/` : ""}${model ?? "unknown"})`);
|
|
27411
|
+
} else {
|
|
27412
|
+
next = LATEST_THINKING_RESTORE;
|
|
27413
|
+
sessionLog2(sessionId, "latest-turn thinking recovery: rejection not bound, no pass in this process built the rejected request");
|
|
27414
|
+
}
|
|
27252
27415
|
db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ?").run(next, sessionId);
|
|
27253
27416
|
}
|
|
27254
27417
|
function clone(value) {
|
|
@@ -27271,72 +27434,253 @@ function replayableOriginal(part) {
|
|
|
27271
27434
|
const signature = part.signature ?? part.thinkingSignature ?? metadata.signature ?? part.data ?? metadata.redactedData;
|
|
27272
27435
|
return typeof signature === "string" && signature.length > 0 && part.text !== "[cleared]" && part.thinking !== "[cleared]";
|
|
27273
27436
|
}
|
|
27437
|
+
var NO_RECOVERY = { restore: false, ended: false };
|
|
27438
|
+
var LATEST_TURN_THINKING_REMOVED_REASON = "latest_turn_thinking_removed";
|
|
27439
|
+
function replaceTarget(db, sessionId, expected, next) {
|
|
27440
|
+
return db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(next, sessionId, expected).changes > 0;
|
|
27441
|
+
}
|
|
27442
|
+
function decisionMessageId(decision) {
|
|
27443
|
+
if (decision === "binding_mismatch_order:end" || decision === TOOL_SWEEP_SCOPED_MARKER)
|
|
27444
|
+
return;
|
|
27445
|
+
return decodeMergedReasoningParts(decision)?.[0] ?? (decision.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX) ? decision.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length) : decision);
|
|
27446
|
+
}
|
|
27447
|
+
function sentAssistantIds(args, turn) {
|
|
27448
|
+
const ids = [];
|
|
27449
|
+
for (let index = turn.start;index < turn.end; index += 1) {
|
|
27450
|
+
const message = args.messages[index];
|
|
27451
|
+
if (!isSentAssistantMessage(message))
|
|
27452
|
+
continue;
|
|
27453
|
+
const id = args.id(message, index);
|
|
27454
|
+
if (id)
|
|
27455
|
+
ids.push(id);
|
|
27456
|
+
}
|
|
27457
|
+
return ids;
|
|
27458
|
+
}
|
|
27459
|
+
function magicContextEditedTurn(args, turn, modelID) {
|
|
27460
|
+
const ids = new Set(sentAssistantIds(args, turn));
|
|
27461
|
+
for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
27462
|
+
const id = decisionMessageId(decision);
|
|
27463
|
+
if (id !== undefined && ids.has(id))
|
|
27464
|
+
return true;
|
|
27465
|
+
}
|
|
27466
|
+
try {
|
|
27467
|
+
for (const id of getReasoningRemovalState(args.db, args.sessionId).messageIds) {
|
|
27468
|
+
if (ids.has(id))
|
|
27469
|
+
return true;
|
|
27470
|
+
}
|
|
27471
|
+
} catch {}
|
|
27472
|
+
return !isPrefixBoundThinkingModel(undefined, modelID) && clearedByWatermark(args, turn);
|
|
27473
|
+
}
|
|
27474
|
+
function clearedByWatermark(args, turn) {
|
|
27475
|
+
try {
|
|
27476
|
+
const row = args.db.prepare("SELECT cleared_reasoning_through_tag AS watermark FROM session_meta WHERE session_id = ?").get(args.sessionId);
|
|
27477
|
+
const watermark = row?.watermark ?? 0;
|
|
27478
|
+
if (!(watermark > 0))
|
|
27479
|
+
return false;
|
|
27480
|
+
const textTags = args.db.prepare("SELECT MAX(tag_number) AS n FROM tags WHERE session_id = ? AND message_id >= ? AND message_id < ?");
|
|
27481
|
+
const toolTags = args.db.prepare("SELECT MAX(tag_number) AS n FROM tags WHERE session_id = ? AND type = 'tool' AND tool_owner_message_id = ?");
|
|
27482
|
+
for (let index = turn.start;index < turn.end; index += 1) {
|
|
27483
|
+
const message = args.messages[index];
|
|
27484
|
+
if (!isSentAssistantMessage(message))
|
|
27485
|
+
continue;
|
|
27486
|
+
if (!args.parts(message).some(isThinkingPart))
|
|
27487
|
+
continue;
|
|
27488
|
+
const id = args.id(message, index);
|
|
27489
|
+
if (!id)
|
|
27490
|
+
continue;
|
|
27491
|
+
const text = textTags.get(args.sessionId, `${id}:`, `${id};`);
|
|
27492
|
+
const tool = toolTags.get(args.sessionId, id);
|
|
27493
|
+
const newest = Math.max(text?.n ?? 0, tool?.n ?? 0);
|
|
27494
|
+
if (newest > 0 && newest <= watermark)
|
|
27495
|
+
return true;
|
|
27496
|
+
}
|
|
27497
|
+
} catch {}
|
|
27498
|
+
return false;
|
|
27499
|
+
}
|
|
27500
|
+
function restoreBlocker(args, turn) {
|
|
27501
|
+
if (turn.start === 0)
|
|
27502
|
+
return "no-turn-start";
|
|
27503
|
+
const turnMessages = args.messages.slice(turn.start, turn.end);
|
|
27504
|
+
if (!turnMessages.some((message) => args.parts(message).some(replayableOriginal)))
|
|
27505
|
+
return "missing-thinking-original";
|
|
27506
|
+
const ids = new Map(args.messages.map((message, index) => [args.id(message, index), index]));
|
|
27507
|
+
for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
27508
|
+
const id = decisionMessageId(decision);
|
|
27509
|
+
if (id === undefined)
|
|
27510
|
+
continue;
|
|
27511
|
+
const index = ids.get(id);
|
|
27512
|
+
if (index === undefined || index >= turn.start && !args.parts(args.messages[index]).some(replayableOriginal))
|
|
27513
|
+
return `missing-original:${id}`;
|
|
27514
|
+
}
|
|
27515
|
+
return;
|
|
27516
|
+
}
|
|
27517
|
+
function refuse(sessionId, why) {
|
|
27518
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: refused locally (${why})`);
|
|
27519
|
+
throw contextRefusalError(LATEST_THINKING_UNSAFE);
|
|
27520
|
+
}
|
|
27521
|
+
function refuseUnsaved(sessionId, why) {
|
|
27522
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: refused locally (${why})`);
|
|
27523
|
+
throw contextRefusalError(LATEST_THINKING_NOT_SAVED);
|
|
27524
|
+
}
|
|
27525
|
+
function frozenBindingIds(args) {
|
|
27526
|
+
const frozen = new Set;
|
|
27527
|
+
for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
27528
|
+
if (decision.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX))
|
|
27529
|
+
frozen.add(decision.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length));
|
|
27530
|
+
}
|
|
27531
|
+
return frozen;
|
|
27532
|
+
}
|
|
27533
|
+
function frozenTurnIds(args, turn) {
|
|
27534
|
+
const frozen = frozenBindingIds(args);
|
|
27535
|
+
return sentAssistantIds(args, turn).filter((id) => frozen.has(id));
|
|
27536
|
+
}
|
|
27537
|
+
function persistBindingRemoval(db, sessionId, ids) {
|
|
27538
|
+
return addMergedReasoningStrippedIds(db, sessionId, ids.map(thinkingBindingRecoveryFrozenId));
|
|
27539
|
+
}
|
|
27540
|
+
function removeTurnThinking(args, target, state, turn, current) {
|
|
27541
|
+
const frozen = frozenBindingIds(args);
|
|
27542
|
+
const ids = [];
|
|
27543
|
+
let parts = 0;
|
|
27544
|
+
for (let index = turn.start;index < turn.end; index += 1) {
|
|
27545
|
+
const message = args.messages[index];
|
|
27546
|
+
if (!isSentAssistantMessage(message))
|
|
27547
|
+
continue;
|
|
27548
|
+
const thinking = args.parts(message).filter(isThinkingPart).length;
|
|
27549
|
+
if (thinking === 0)
|
|
27550
|
+
continue;
|
|
27551
|
+
const id = args.id(message, index);
|
|
27552
|
+
if (!id)
|
|
27553
|
+
refuse(args.sessionId, "a thinking message of the turn has no stable id");
|
|
27554
|
+
if (frozen.has(id))
|
|
27555
|
+
continue;
|
|
27556
|
+
ids.push(id);
|
|
27557
|
+
parts += thinking;
|
|
27558
|
+
}
|
|
27559
|
+
if (ids.length === 0) {
|
|
27560
|
+
replaceTarget(args.db, args.sessionId, target, encodeState({ ...state, stage: "refused", last: current.last }));
|
|
27561
|
+
refuse(args.sessionId, "the rejected turn has no thinking left to remove");
|
|
27562
|
+
}
|
|
27563
|
+
const persist = args.persistRemoval ?? ((next) => persistBindingRemoval(args.db, args.sessionId, next));
|
|
27564
|
+
let persisted = false;
|
|
27565
|
+
try {
|
|
27566
|
+
args.db.transaction(() => {
|
|
27567
|
+
if (!persist(ids))
|
|
27568
|
+
throw new Error("thinking removal was not persisted");
|
|
27569
|
+
const next = encodeState({ ...state, stage: "removed", last: current.last });
|
|
27570
|
+
if (!replaceTarget(args.db, args.sessionId, target, next))
|
|
27571
|
+
throw new Error("recovery state changed concurrently");
|
|
27572
|
+
}).immediate();
|
|
27573
|
+
persisted = true;
|
|
27574
|
+
} catch (error) {
|
|
27575
|
+
sessionLog2(args.sessionId, "latest-turn thinking recovery: removal write failed:", error);
|
|
27576
|
+
}
|
|
27577
|
+
if (!persisted)
|
|
27578
|
+
refuseUnsaved(args.sessionId, "the thinking removal could not be saved");
|
|
27579
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: removed thinking from the bound turn (parts=${parts} messages=${ids.length} first=${state.first} last=${current.last})`);
|
|
27580
|
+
return {
|
|
27581
|
+
restore: false,
|
|
27582
|
+
ended: false,
|
|
27583
|
+
removedThisPass: true,
|
|
27584
|
+
removedIds: frozenTurnIds(args, turn)
|
|
27585
|
+
};
|
|
27586
|
+
}
|
|
27274
27587
|
function prepareLatestThinkingRecovery(args) {
|
|
27275
|
-
const
|
|
27276
|
-
|
|
27277
|
-
|
|
27278
|
-
|
|
27588
|
+
const identified = identifyTurn(args.messages, args.id);
|
|
27589
|
+
if (identified)
|
|
27590
|
+
lastPassTurn.set(args.sessionId, {
|
|
27591
|
+
...identified.bound,
|
|
27592
|
+
pass: `${PROCESS_TOKEN}:${++passCounter}`,
|
|
27593
|
+
...args.modelID ? { model: args.modelID } : {},
|
|
27594
|
+
...args.modelID && args.providerID ? { provider: args.providerID } : {}
|
|
27595
|
+
});
|
|
27279
27596
|
else
|
|
27280
|
-
|
|
27597
|
+
lastPassTurn.delete(args.sessionId);
|
|
27281
27598
|
let target;
|
|
27282
27599
|
try {
|
|
27283
27600
|
target = getThinkingBindingRecoveryTarget(args.db, args.sessionId);
|
|
27284
27601
|
} catch (error) {
|
|
27285
27602
|
if (knownRejectedSessions.has(args.sessionId))
|
|
27286
|
-
|
|
27287
|
-
return
|
|
27603
|
+
refuseUnsaved(args.sessionId, "the recovery state could not be read");
|
|
27604
|
+
return NO_RECOVERY;
|
|
27288
27605
|
}
|
|
27289
27606
|
if (!target || !target.startsWith(LATEST_THINKING_RESTORE)) {
|
|
27290
27607
|
knownRejectedSessions.delete(args.sessionId);
|
|
27291
|
-
return
|
|
27608
|
+
return NO_RECOVERY;
|
|
27292
27609
|
}
|
|
27293
|
-
const
|
|
27294
|
-
if (
|
|
27295
|
-
args.db
|
|
27610
|
+
const state = readState(target);
|
|
27611
|
+
if (!state) {
|
|
27612
|
+
replaceTarget(args.db, args.sessionId, target, "");
|
|
27296
27613
|
knownRejectedSessions.delete(args.sessionId);
|
|
27297
|
-
|
|
27614
|
+
sessionLog2(args.sessionId, "latest-turn thinking recovery: cleared a rejection that names no turn");
|
|
27615
|
+
return NO_RECOVERY;
|
|
27298
27616
|
}
|
|
27299
|
-
|
|
27300
|
-
|
|
27301
|
-
if (savedAnchor !== undefined && savedAnchor !== anchor) {
|
|
27302
|
-
args.db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(args.sessionId, target);
|
|
27617
|
+
const unbind = (why) => {
|
|
27618
|
+
replaceTarget(args.db, args.sessionId, target, "");
|
|
27303
27619
|
knownRejectedSessions.delete(args.sessionId);
|
|
27304
|
-
|
|
27305
|
-
|
|
27306
|
-
|
|
27307
|
-
|
|
27308
|
-
|
|
27309
|
-
|
|
27310
|
-
|
|
27311
|
-
const
|
|
27312
|
-
if (!
|
|
27313
|
-
|
|
27314
|
-
const
|
|
27315
|
-
|
|
27316
|
-
if (
|
|
27317
|
-
|
|
27318
|
-
|
|
27319
|
-
|
|
27320
|
-
|
|
27321
|
-
throw contextRefusalError(LATEST_THINKING_UNSAFE + ` [missing-original:${id}]`);
|
|
27620
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: unbound because ${why} (stage=${state.stage} first=${state.first} last=${state.last})`);
|
|
27621
|
+
return { restore: false, ended: state.stage === "restoring" };
|
|
27622
|
+
};
|
|
27623
|
+
if (args.modelID && state.model && args.modelID.toLowerCase() !== state.model.toLowerCase())
|
|
27624
|
+
return unbind(`the request now goes to ${args.modelID}`);
|
|
27625
|
+
if (args.providerID && state.provider && args.providerID.toLowerCase() !== state.provider.toLowerCase())
|
|
27626
|
+
return unbind(`the request now goes through ${args.providerID}`);
|
|
27627
|
+
const current = identified?.bound;
|
|
27628
|
+
if (!identified || !current || current.first !== state.first)
|
|
27629
|
+
return unbind(`a newer turn was accepted (now first=${current?.first ?? "none"} last=${current?.last ?? "none"})`);
|
|
27630
|
+
const turn = identified.turn;
|
|
27631
|
+
if (current.last !== state.last && state.stage !== "restoring") {
|
|
27632
|
+
if (state.stage !== "removed")
|
|
27633
|
+
return unbind(`a newer message of the turn was accepted (now last=${current.last})`);
|
|
27634
|
+
replaceTarget(args.db, args.sessionId, target, encodeState({ ...state, last: current.last, accepted: true }));
|
|
27635
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: a request without the turn's removed thinking was accepted (first=${state.first} last=${current.last})`);
|
|
27636
|
+
return { ...NO_RECOVERY, removedIds: frozenTurnIds(args, identified.turn) };
|
|
27322
27637
|
}
|
|
27323
|
-
|
|
27324
|
-
|
|
27325
|
-
|
|
27638
|
+
knownRejectedSessions.add(args.sessionId);
|
|
27639
|
+
switch (state.stage) {
|
|
27640
|
+
case "refused":
|
|
27641
|
+
return refuse(args.sessionId, `the provider rejected the turn first=${state.first} ${state.rejections} times`);
|
|
27642
|
+
case "removed":
|
|
27643
|
+
return { ...NO_RECOVERY, removedIds: frozenTurnIds(args, turn) };
|
|
27644
|
+
case "restoring": {
|
|
27645
|
+
const blocker = restoreBlocker(args, turn);
|
|
27646
|
+
if (blocker === undefined)
|
|
27647
|
+
return { restore: true, ended: false };
|
|
27648
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: restore no longer possible (${blocker}); removing the turn's thinking instead`);
|
|
27649
|
+
return removeTurnThinking(args, target, state, turn, current);
|
|
27650
|
+
}
|
|
27651
|
+
case "armed": {
|
|
27652
|
+
if (magicContextEditedTurn(args, turn, args.modelID)) {
|
|
27653
|
+
const blocker = restoreBlocker(args, turn);
|
|
27654
|
+
if (blocker === undefined) {
|
|
27655
|
+
replaceTarget(args.db, args.sessionId, target, encodeState({ ...state, stage: "restoring", last: current.last }));
|
|
27656
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: restore applied to the bound turn (first=${state.first} last=${current.last})`);
|
|
27657
|
+
return { restore: true, ended: false };
|
|
27658
|
+
}
|
|
27659
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: restore unavailable (${blocker}); removing the turn's thinking instead`);
|
|
27660
|
+
}
|
|
27661
|
+
return removeTurnThinking(args, target, state, turn, current);
|
|
27662
|
+
}
|
|
27663
|
+
case "remove":
|
|
27664
|
+
return removeTurnThinking(args, target, state, turn, current);
|
|
27665
|
+
}
|
|
27666
|
+
}
|
|
27667
|
+
function latestThinkingRestoringTurnMessages(args) {
|
|
27326
27668
|
let target;
|
|
27327
27669
|
try {
|
|
27328
27670
|
target = getThinkingBindingRecoveryTarget(args.db, args.sessionId);
|
|
27329
27671
|
} catch {
|
|
27330
|
-
return
|
|
27672
|
+
return;
|
|
27331
27673
|
}
|
|
27332
|
-
const
|
|
27333
|
-
if (
|
|
27334
|
-
return
|
|
27335
|
-
const
|
|
27336
|
-
|
|
27674
|
+
const state = target ? readState(target) : undefined;
|
|
27675
|
+
if (state?.stage !== "restoring")
|
|
27676
|
+
return;
|
|
27677
|
+
const identified = identifyTurn(args.messages, args.id);
|
|
27678
|
+
if (identified?.bound.first !== state.first)
|
|
27679
|
+
return;
|
|
27680
|
+
return new Set(args.messages.slice(identified.turn.start));
|
|
27337
27681
|
}
|
|
27338
27682
|
function captureOriginalTurn(messages, parts, setParts) {
|
|
27339
|
-
const start = Math.max(0, latestAssistantTurnStart(messages) - 1);
|
|
27683
|
+
const start = Math.max(0, (providerLatestTurn(messages)?.start ?? latestAssistantTurnStart(messages)) - 1);
|
|
27340
27684
|
const originals = messages.slice(start).map((message) => ({ message, parts: clone(parts(message)) }));
|
|
27341
27685
|
const before = messages.slice(0, start);
|
|
27342
27686
|
return (target = messages) => {
|
|
@@ -27350,10 +27694,17 @@ function captureOriginalTurn(messages, parts, setParts) {
|
|
|
27350
27694
|
};
|
|
27351
27695
|
}
|
|
27352
27696
|
function armBindingRecoverySafely(db, sessionId) {
|
|
27353
|
-
|
|
27354
|
-
|
|
27355
|
-
|
|
27356
|
-
|
|
27697
|
+
const target = getThinkingBindingRecoveryTarget(db, sessionId);
|
|
27698
|
+
if (target?.startsWith(LATEST_THINKING_RESTORE)) {
|
|
27699
|
+
const stage = readState(target)?.stage;
|
|
27700
|
+
if (stage !== "removed" && stage !== "refused") {
|
|
27701
|
+
armLatestThinkingRecovery(db, sessionId);
|
|
27702
|
+
return;
|
|
27703
|
+
}
|
|
27704
|
+
knownRejectedSessions.delete(sessionId);
|
|
27705
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: binding rejection handed to the binding recovery (stage=${stage})`);
|
|
27706
|
+
}
|
|
27707
|
+
armThinkingBindingRecovery(db, sessionId);
|
|
27357
27708
|
}
|
|
27358
27709
|
|
|
27359
27710
|
// ../plugin/src/hooks/magic-context/reasoning-budget-status.ts
|
|
@@ -27621,8 +27972,13 @@ function decideSignedThinkingHold(args) {
|
|
|
27621
27972
|
heavyStepTokens,
|
|
27622
27973
|
capPercentage
|
|
27623
27974
|
};
|
|
27624
|
-
|
|
27625
|
-
|
|
27975
|
+
const ended = readingEndsHold({
|
|
27976
|
+
usagePercentage: args.usagePercentage,
|
|
27977
|
+
capPercentage,
|
|
27978
|
+
forceBandPressure: args.forceBandPressure
|
|
27979
|
+
});
|
|
27980
|
+
if (ended !== null)
|
|
27981
|
+
return { held: false, reason: ended, heavyStepsBack, heavyStepTokens, capPercentage };
|
|
27626
27982
|
return {
|
|
27627
27983
|
held: true,
|
|
27628
27984
|
reason: "heavy_reasoning",
|
|
@@ -27631,6 +27987,11 @@ function decideSignedThinkingHold(args) {
|
|
|
27631
27987
|
capPercentage
|
|
27632
27988
|
};
|
|
27633
27989
|
}
|
|
27990
|
+
function readingEndsHold(args) {
|
|
27991
|
+
if (!(args.usagePercentage < args.capPercentage))
|
|
27992
|
+
return "above_cap";
|
|
27993
|
+
return args.forceBandPressure ? "force_band" : null;
|
|
27994
|
+
}
|
|
27634
27995
|
|
|
27635
27996
|
// ../plugin/src/hooks/magic-context/strict-thinking-prefix.ts
|
|
27636
27997
|
function servedPrefixMatches(args) {
|
|
@@ -29953,11 +30314,11 @@ async function embedAndStoreCompartmentChunks(db, sessionId, projectPath, compar
|
|
|
29953
30314
|
if (currentModelId !== "off" && chunkEmbeddingWindowsAreCurrent2(db, compartment.id, currentModelId, windows, projectPath)) {
|
|
29954
30315
|
continue;
|
|
29955
30316
|
}
|
|
29956
|
-
const result = await
|
|
30317
|
+
const result = await embedItemsWindowBounded2(projectPath, windows.map((window) => ({
|
|
29957
30318
|
id: `chunk:${compartment.id}:${window.windowIndex}`,
|
|
29958
30319
|
text: window.text,
|
|
29959
30320
|
contentSha256: contentSha2562(window.text)
|
|
29960
|
-
})), undefined, db, sessionId);
|
|
30321
|
+
})), undefined, db, sessionId, { stopOnIncompleteSlice: true });
|
|
29961
30322
|
if (!result)
|
|
29962
30323
|
continue;
|
|
29963
30324
|
if (chunkEmbeddingWindowsAreCurrent2(db, compartment.id, currentModelId, windows, projectPath)) {
|
|
@@ -30020,6 +30381,11 @@ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
|
|
|
30020
30381
|
const start = chunk.startIndex;
|
|
30021
30382
|
if (chunk.text || chunk.messageCount !== 0 || eligibleEnd <= start || rows.length !== eligibleEnd - start || rows.some((row, index) => row.ordinal !== start + index || !row.messageId))
|
|
30022
30383
|
return false;
|
|
30384
|
+
const endId = rows[rows.length - 1].messageId;
|
|
30385
|
+
if (!hasRawSessionMessageById2(sessionId, endId)) {
|
|
30386
|
+
sessionLog2(sessionId, `historian skipped a filtered-noise marker for ordinals ${start}-${eligibleEnd - 1}: its end row ${endId} is no longer in the host store`);
|
|
30387
|
+
return false;
|
|
30388
|
+
}
|
|
30023
30389
|
const saved = db.transaction(() => {
|
|
30024
30390
|
const prior = getCompartments(db, sessionId);
|
|
30025
30391
|
const last = prior.at(-1);
|
|
@@ -30051,7 +30417,7 @@ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
|
|
|
30051
30417
|
|
|
30052
30418
|
// src/pi-history-retirement.ts
|
|
30053
30419
|
var KEY2 = "piHistorianRetirement";
|
|
30054
|
-
function
|
|
30420
|
+
function readState2(db, sessionId) {
|
|
30055
30421
|
const row = db.prepare("SELECT deferred_execute_state AS state FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
30056
30422
|
const state = row?.state ? JSON.parse(row.state) : {};
|
|
30057
30423
|
if (!state || typeof state !== "object" || Array.isArray(state))
|
|
@@ -30059,17 +30425,17 @@ function readState(db, sessionId) {
|
|
|
30059
30425
|
return state;
|
|
30060
30426
|
}
|
|
30061
30427
|
function readPiHistoryRetirement(db, sessionId) {
|
|
30062
|
-
const target =
|
|
30428
|
+
const target = readState2(db, sessionId)[KEY2];
|
|
30063
30429
|
return typeof target === "string" && target.length > 0 ? target : null;
|
|
30064
30430
|
}
|
|
30065
30431
|
function queuePiHistoryRetirement(db, sessionId, throughMessageId) {
|
|
30066
30432
|
ensureSessionMetaRow(db, sessionId);
|
|
30067
|
-
const state =
|
|
30433
|
+
const state = readState2(db, sessionId);
|
|
30068
30434
|
state[KEY2] = throughMessageId;
|
|
30069
30435
|
db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(state), sessionId);
|
|
30070
30436
|
}
|
|
30071
30437
|
function acknowledgePiHistoryRetirement(db, sessionId, publishedEnd, ordinalOf) {
|
|
30072
|
-
const state =
|
|
30438
|
+
const state = readState2(db, sessionId);
|
|
30073
30439
|
const target = state[KEY2];
|
|
30074
30440
|
if (typeof target !== "string")
|
|
30075
30441
|
return;
|
|
@@ -34316,6 +34682,7 @@ function piImageFromDataUrl(dataUrl) {
|
|
|
34316
34682
|
return null;
|
|
34317
34683
|
return { type: "image", mimeType: match[1], data: match[2] };
|
|
34318
34684
|
}
|
|
34685
|
+
var PI_IMAGE_DATA_URL_PREFIX = /^data:image\/[a-zA-Z0-9.+-]+;base64,[\s\S]/;
|
|
34319
34686
|
function resolveMuralForM0Pi(state, db, modelKey, budgetTokens, mode = "persist") {
|
|
34320
34687
|
if (state.memoryEnabled === false)
|
|
34321
34688
|
return;
|
|
@@ -34684,6 +35051,7 @@ function materializeM0Pi(state, db, passSnapshot) {
|
|
|
34684
35051
|
const upgradeIdentity = withCachedM0MemoryIds(encodeCachedM0UpgradeIdentity(snapshotMarkers.upgradeState, snapshotMarkers.compartmentRenderEpoch, snapshotMarkers.muralEnabled, snapshotMarkers.renderBudgetIdentity, snapshotMarkers.memoryRenderEpoch, snapshotMarkers.renderedBudgets ?? null), renderedMemoryIds);
|
|
34685
35052
|
steps.mark("pre_metadata");
|
|
34686
35053
|
state.beforeCacheCommitForTest?.();
|
|
35054
|
+
const commitFold = state.onFoldPrepare?.();
|
|
34687
35055
|
try {
|
|
34688
35056
|
db.exec("BEGIN IMMEDIATE");
|
|
34689
35057
|
} catch (error) {
|
|
@@ -34733,6 +35101,15 @@ function materializeM0Pi(state, db, passSnapshot) {
|
|
|
34733
35101
|
steps.mark("persistCachedM0");
|
|
34734
35102
|
db.prepare("UPDATE session_meta SET memory_block_count = ?, memory_block_ids = ?, cached_m0_last_baseline_end_message_id = ? WHERE session_id = ?").run(visibleMemoryIds.length, visibleIdsJson, snapshotMarkers.lastBaselineEndMessageId, state.sessionId);
|
|
34735
35103
|
steps.mark("sessionMeta");
|
|
35104
|
+
if (commitFold) {
|
|
35105
|
+
const muralWire = m0.includes("<memory-mural>") && frozenMuralDataUrl ? frozenMuralDataUrl : null;
|
|
35106
|
+
commitFold(db, {
|
|
35107
|
+
m0Text: muralWire ? m0 : stripMemoryMuralBlock(m0),
|
|
35108
|
+
m1Text: m1Render.text,
|
|
35109
|
+
muralDataUrl: muralWire && PI_IMAGE_DATA_URL_PREFIX.test(muralWire) ? muralWire : null
|
|
35110
|
+
});
|
|
35111
|
+
steps.mark("onFoldCommit");
|
|
35112
|
+
}
|
|
34736
35113
|
db.exec("COMMIT");
|
|
34737
35114
|
steps.mark("commit");
|
|
34738
35115
|
logSlowWriteTransaction("pi_materialize_cache", transactionStartedAt, undefined, performance.now(), steps.durations);
|
|
@@ -35517,6 +35894,12 @@ var RESPONSES_APIS = new Set([
|
|
|
35517
35894
|
function isPiDropPlaceholder(text) {
|
|
35518
35895
|
return DROP_PLACEHOLDER.test(text);
|
|
35519
35896
|
}
|
|
35897
|
+
function nativeTextMatchesBlock(nativeText, blockText) {
|
|
35898
|
+
return nativeText === blockText.replace(TAG_LABEL, "");
|
|
35899
|
+
}
|
|
35900
|
+
function hookCleanedTextMatchesBlock(nativeText, blockText) {
|
|
35901
|
+
return nativeTextMatchesBlock(stripPersistedAssistantText(nativeText), blockText);
|
|
35902
|
+
}
|
|
35520
35903
|
function getNativeEnvelope(message) {
|
|
35521
35904
|
if (!isRecord(message) || isPiSystemEntry(message))
|
|
35522
35905
|
return;
|
|
@@ -35643,12 +36026,11 @@ function hookRewrittenSlot(previous, partIndex, items) {
|
|
|
35643
36026
|
return;
|
|
35644
36027
|
continue;
|
|
35645
36028
|
}
|
|
35646
|
-
|
|
35647
|
-
if (stripped !== block.text.replace(TAG_LABEL, ""))
|
|
36029
|
+
if (!hookCleanedTextMatchesBlock(slot.text, block.text))
|
|
35648
36030
|
return;
|
|
35649
36031
|
if (index !== partIndex)
|
|
35650
36032
|
continue;
|
|
35651
|
-
if (
|
|
36033
|
+
if (item.content.length !== 1)
|
|
35652
36034
|
return;
|
|
35653
36035
|
target = slot;
|
|
35654
36036
|
}
|
|
@@ -35738,7 +36120,7 @@ function rewriteNativeAssistantTexts(message, previous, sessionId, options = {})
|
|
|
35738
36120
|
return;
|
|
35739
36121
|
const content = envelope.message.content;
|
|
35740
36122
|
const arrivedItems = envelope.items;
|
|
35741
|
-
const
|
|
36123
|
+
const unsignedEdits = options.unsignedEdits === true && RESPONSES_APIS.has(String(envelope.message.api)) && envelope.payload.dt === true;
|
|
35742
36124
|
for (let index = 0;index < content.length; index++) {
|
|
35743
36125
|
const part = content[index];
|
|
35744
36126
|
const before = previous.content[index];
|
|
@@ -35747,14 +36129,14 @@ function rewriteNativeAssistantTexts(message, previous, sessionId, options = {})
|
|
|
35747
36129
|
if (part.text.replace(/^§\d+§ /u, "") === before.text.replace(/^§\d+§ /u, ""))
|
|
35748
36130
|
continue;
|
|
35749
36131
|
const identity = textIdentity(part);
|
|
35750
|
-
if (identity === undefined &&
|
|
36132
|
+
if (identity === undefined && unsignedEdits && !("textSignature" in part)) {
|
|
35751
36133
|
const slot = hookRewrittenSlot(previous.content, index, arrivedItems);
|
|
35752
36134
|
if (slot) {
|
|
35753
36135
|
const item = envelope.items[slot.itemIndex];
|
|
35754
36136
|
const outputs = item.content.slice();
|
|
35755
36137
|
outputs[slot.outputIndex] = {
|
|
35756
36138
|
...outputs[slot.outputIndex],
|
|
35757
|
-
text: part.text
|
|
36139
|
+
text: part.text.replace(TAG_LABEL, "")
|
|
35758
36140
|
};
|
|
35759
36141
|
const items = envelope.items.slice();
|
|
35760
36142
|
items[slot.itemIndex] = { ...item, content: outputs };
|
|
@@ -36130,15 +36512,9 @@ function authorizePiToolRemoval(args) {
|
|
|
36130
36512
|
|
|
36131
36513
|
// src/native-replay-tag-provenance-pi.ts
|
|
36132
36514
|
import { createHash as createHash13 } from "node:crypto";
|
|
36133
|
-
var PI_NATIVE_TAG_STRIP_PROVENANCE = "magicContextNativeTagStrips";
|
|
36134
36515
|
function nativeResponseTagStripKey(id, phase, text) {
|
|
36135
36516
|
return createHash13("sha256").update(JSON.stringify([id, phase, text])).digest("hex");
|
|
36136
36517
|
}
|
|
36137
|
-
function ownsNativeResponseTagStrip(decisions, id, phase, text) {
|
|
36138
|
-
if (!isRecord(decisions) || phase !== undefined && phase !== "commentary" && phase !== "final_answer")
|
|
36139
|
-
return false;
|
|
36140
|
-
return Object.entries(decisions).some(([key, original]) => typeof original === "string" && /^§\d+§ /u.test(original) && original.replace(/^§\d+§ /u, "") === text && nativeResponseTagStripKey(id, phase, original) === key);
|
|
36141
|
-
}
|
|
36142
36518
|
|
|
36143
36519
|
// src/native-replay-tags-pi.ts
|
|
36144
36520
|
var FIELD = "piResponsesTagStrips";
|
|
@@ -36186,7 +36562,6 @@ function applyNativeResponseTagReplayPi(args) {
|
|
|
36186
36562
|
const frozen = saved;
|
|
36187
36563
|
const content = message.content;
|
|
36188
36564
|
const nativeItems = payload.items;
|
|
36189
|
-
const decisions = {};
|
|
36190
36565
|
let changed = false;
|
|
36191
36566
|
const items = nativeItems.map((item) => {
|
|
36192
36567
|
if (!isRecord(item) || item.type !== "message" || item.role !== "assistant" || item.phase !== undefined && item.phase !== "commentary" && item.phase !== "final_answer" || !Array.isArray(item.content) || item.content.length !== 1)
|
|
@@ -36209,7 +36584,6 @@ function applyNativeResponseTagReplayPi(args) {
|
|
|
36209
36584
|
return item;
|
|
36210
36585
|
added.add(key);
|
|
36211
36586
|
}
|
|
36212
|
-
decisions[key] = output.text;
|
|
36213
36587
|
changed = true;
|
|
36214
36588
|
return {
|
|
36215
36589
|
...item,
|
|
@@ -36219,7 +36593,6 @@ function applyNativeResponseTagReplayPi(args) {
|
|
|
36219
36593
|
if (changed)
|
|
36220
36594
|
pending.set(index, {
|
|
36221
36595
|
...message,
|
|
36222
|
-
[PI_NATIVE_TAG_STRIP_PROVENANCE]: decisions,
|
|
36223
36596
|
providerPayload: { ...payload, items }
|
|
36224
36597
|
});
|
|
36225
36598
|
}
|
|
@@ -37409,7 +37782,7 @@ function coldReplayable(items) {
|
|
|
37409
37782
|
}
|
|
37410
37783
|
return reasoning;
|
|
37411
37784
|
}
|
|
37412
|
-
function piResponsesAssistantTexts(value, model, host, alternatives
|
|
37785
|
+
function piResponsesAssistantTexts(value, model, host, alternatives) {
|
|
37413
37786
|
const message = object8(value);
|
|
37414
37787
|
if (!message || !Array.isArray(message.content))
|
|
37415
37788
|
return;
|
|
@@ -37472,8 +37845,6 @@ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagSt
|
|
|
37472
37845
|
"openai-codex-responses"
|
|
37473
37846
|
].includes(model?.api ?? "");
|
|
37474
37847
|
let unsigned = false;
|
|
37475
|
-
let rewrittenText = false;
|
|
37476
|
-
let allUnsignedFrozen = true;
|
|
37477
37848
|
for (const value of payload.items) {
|
|
37478
37849
|
const item = object8(value);
|
|
37479
37850
|
if (item?.type === "reasoning")
|
|
@@ -37499,15 +37870,12 @@ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagSt
|
|
|
37499
37870
|
} catch {
|
|
37500
37871
|
return texts;
|
|
37501
37872
|
}
|
|
37502
|
-
const signed = signature?.v === 1 && typeof signature.id === "string" && item.id === signature.id && item.phase === signature.phase && part.text
|
|
37873
|
+
const signed = signature?.v === 1 && typeof signature.id === "string" && item.id === signature.id && item.phase === signature.phase && nativeTextMatchesBlock(part.text, block.text);
|
|
37503
37874
|
if (!signed) {
|
|
37504
|
-
const stripped = stripPersistedAssistantText(part.text);
|
|
37505
37875
|
const droppedPlaceholder = isPiDropPlaceholder(block.text) && part.text === block.text;
|
|
37506
|
-
if (!allowUnsigned || "textSignature" in block || !droppedPlaceholder &&
|
|
37876
|
+
if (!allowUnsigned || "textSignature" in block || !droppedPlaceholder && !hookCleanedTextMatchesBlock(part.text, block.text))
|
|
37507
37877
|
return texts;
|
|
37508
37878
|
unsigned = true;
|
|
37509
|
-
allUnsignedFrozen &&= droppedPlaceholder || part.text === block.text && ownsNativeResponseTagStrip(frozenTagStrips, item.id, item.phase, part.text);
|
|
37510
|
-
rewrittenText ||= !droppedPlaceholder && part.text !== stripped;
|
|
37511
37879
|
}
|
|
37512
37880
|
bound++;
|
|
37513
37881
|
itemTexts.push(part.text);
|
|
@@ -37518,7 +37886,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagSt
|
|
|
37518
37886
|
for (const text of itemTexts)
|
|
37519
37887
|
replay.push(textIdentity2(wellFormed2(text), item.phase));
|
|
37520
37888
|
}
|
|
37521
|
-
if (!output || bound !== blocks.length
|
|
37889
|
+
if (!output || bound !== blocks.length)
|
|
37522
37890
|
return texts;
|
|
37523
37891
|
if (unsigned && alternatives) {
|
|
37524
37892
|
alternatives.fallback = texts;
|
|
@@ -38250,7 +38618,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
|
|
|
38250
38618
|
continue;
|
|
38251
38619
|
}
|
|
38252
38620
|
const alternatives = {};
|
|
38253
|
-
const texts = piResponsesAssistantTexts(projectedMessages[index], model, host, alternatives
|
|
38621
|
+
const texts = piResponsesAssistantTexts(projectedMessages[index], model, host, alternatives);
|
|
38254
38622
|
if (!texts) {
|
|
38255
38623
|
responsesMessages = undefined;
|
|
38256
38624
|
break;
|
|
@@ -42364,6 +42732,26 @@ function releasePiOperationPayloads(operation) {
|
|
|
42364
42732
|
function operationKey(ctx) {
|
|
42365
42733
|
return ctx.sessionManager?.getSessionId?.() ?? ctx.sessionManager ?? "no-session";
|
|
42366
42734
|
}
|
|
42735
|
+
function servedSessionOf(ctx) {
|
|
42736
|
+
try {
|
|
42737
|
+
const id = ctx.sessionManager?.getSessionId?.();
|
|
42738
|
+
return typeof id === "string" && id.length > 0 ? id : undefined;
|
|
42739
|
+
} catch {
|
|
42740
|
+
return;
|
|
42741
|
+
}
|
|
42742
|
+
}
|
|
42743
|
+
function finishPiServedRequest(sessionId, ctx, messages, compactionOff) {
|
|
42744
|
+
try {
|
|
42745
|
+
commitServedRequest({
|
|
42746
|
+
sessionId,
|
|
42747
|
+
host: "pi",
|
|
42748
|
+
messages,
|
|
42749
|
+
providerID: ctx.model?.provider,
|
|
42750
|
+
modelID: ctx.model?.id,
|
|
42751
|
+
compactionOff: compactionOff()
|
|
42752
|
+
});
|
|
42753
|
+
} catch {}
|
|
42754
|
+
}
|
|
42367
42755
|
function messageKey(message) {
|
|
42368
42756
|
if (!message || typeof message !== "object")
|
|
42369
42757
|
return;
|
|
@@ -42434,7 +42822,14 @@ function inputBranch(ctx, inputs) {
|
|
|
42434
42822
|
return;
|
|
42435
42823
|
}
|
|
42436
42824
|
}
|
|
42437
|
-
function
|
|
42825
|
+
function endsWithFailedAttempt(input, messages, ended) {
|
|
42826
|
+
if (ended.length !== input.length + 1 || exactReusablePrefix(input, ended) !== input.length)
|
|
42827
|
+
return false;
|
|
42828
|
+
const last = messages.at(-1);
|
|
42829
|
+
const lastKey = ended.at(-1)?.id;
|
|
42830
|
+
return last?.role === "assistant" && (last.stopReason === "error" || last.stopReason === "aborted") && !!lastKey && !input.some((message) => message.id === lastKey);
|
|
42831
|
+
}
|
|
42832
|
+
function dispatchedEndBelongsToEarlierRun(operation, event, ctx, startOutstanding) {
|
|
42438
42833
|
if (!operation.dispatched || !operation.started || !operation.ready || !operation.pass?.completed || operation.refused || operation.pass.abandoned || !operation.inputBranch)
|
|
42439
42834
|
return false;
|
|
42440
42835
|
try {
|
|
@@ -42444,9 +42839,16 @@ function dispatchedEndBelongsToEarlierRun(operation, event, ctx) {
|
|
|
42444
42839
|
const prepared = operation.inputBranch;
|
|
42445
42840
|
if (!current || current.entryIds[prepared.anchorIndex] !== prepared.anchorId || current.messages.length !== prepared.messages.length || exactReusablePrefix(current.messages, prepared.messages) !== prepared.messages.length)
|
|
42446
42841
|
return false;
|
|
42447
|
-
const
|
|
42842
|
+
const end = event;
|
|
42843
|
+
const messages = end?.messages;
|
|
42448
42844
|
const ended = Array.isArray(messages) ? messageSnapshots(messages) : undefined;
|
|
42449
|
-
|
|
42845
|
+
if (!ended || !Array.isArray(messages))
|
|
42846
|
+
return false;
|
|
42847
|
+
if (end.willContinue === true && endsWithFailedAttempt(prepared.messages, messages, ended))
|
|
42848
|
+
return true;
|
|
42849
|
+
if (!startOutstanding)
|
|
42850
|
+
return false;
|
|
42851
|
+
return ended.length <= prepared.anchorIndex && ended.length < prepared.messages.length && exactReusablePrefix(prepared.messages, ended) === ended.length;
|
|
42450
42852
|
} catch {
|
|
42451
42853
|
return false;
|
|
42452
42854
|
}
|
|
@@ -42550,7 +42952,7 @@ function registerPiGuardedContext(pi, handler, options = {}) {
|
|
|
42550
42952
|
log2(`[magic-context][pi] OMP context counts session=${String(key)} side_contexts=${counts.sides} context_passes=${counts.contexts} dispatch_fence=${counts.sides ? "latched off" : "on"}`);
|
|
42551
42953
|
const operation = operations.get(key);
|
|
42552
42954
|
if (operation) {
|
|
42553
|
-
if (endBelongsToEarlierRun(operation, event) || lifecycleSeen.starts > lifecycleSeen.ends
|
|
42955
|
+
if (endBelongsToEarlierRun(operation, event) || dispatchedEndBelongsToEarlierRun(operation, event, ctx, lifecycleSeen.starts > lifecycleSeen.ends)) {
|
|
42554
42956
|
if (operation.dispatched)
|
|
42555
42957
|
operation.retainedAfterEnd = true;
|
|
42556
42958
|
if (lifecycleSeen.starts <= lifecycleSeen.ends)
|
|
@@ -42760,6 +43162,9 @@ function registerPiGuardedContext(pi, handler, options = {}) {
|
|
|
42760
43162
|
active.ready = false;
|
|
42761
43163
|
active.refused = false;
|
|
42762
43164
|
active.refusalMessage = undefined;
|
|
43165
|
+
const servedSessionId = budget.sideTurn ? undefined : servedSessionOf(ctx);
|
|
43166
|
+
if (servedSessionId)
|
|
43167
|
+
beginServedRequest(servedSessionId);
|
|
42763
43168
|
const { isOwned, isCurrent, assertOwner } = createPiContextOwnershipGuards(operations, key, active, budget, owner);
|
|
42764
43169
|
budget.assertOwner = assertOwner;
|
|
42765
43170
|
try {
|
|
@@ -42795,8 +43200,12 @@ function registerPiGuardedContext(pi, handler, options = {}) {
|
|
|
42795
43200
|
if (inputs)
|
|
42796
43201
|
active.inputBranch = inputBranch(ctx, inputs);
|
|
42797
43202
|
}
|
|
43203
|
+
if (servedSessionId)
|
|
43204
|
+
finishPiServedRequest(servedSessionId, ctx, result?.messages ?? event.messages, () => options.compactionOff?.(ctx) === true);
|
|
42798
43205
|
return result;
|
|
42799
43206
|
} catch (error) {
|
|
43207
|
+
if (servedSessionId)
|
|
43208
|
+
countServedRefusal(servedSessionId);
|
|
42800
43209
|
if (budget.isCancelled(error)) {
|
|
42801
43210
|
budget.cancel();
|
|
42802
43211
|
if (isOwned())
|
|
@@ -44655,7 +45064,7 @@ function handlePiProviderFailure(args) {
|
|
|
44655
45064
|
const model = typeof message.model === "string" ? message.model : undefined;
|
|
44656
45065
|
const binding = detectThinkingBindingMismatch(message.errorMessage);
|
|
44657
45066
|
if (detectLatestTurnThinkingMismatch(message.errorMessage) && !args.compactionOff && isAnthropicFamilyRoute(provider, model)) {
|
|
44658
|
-
armLatestThinkingRecovery(args.db, args.sessionId);
|
|
45067
|
+
armLatestThinkingRecovery(args.db, args.sessionId, model);
|
|
44659
45068
|
clearPiLkgSessionState(args.sessionId);
|
|
44660
45069
|
dropSlot(args.sessionId, "latest-thinking-recovery-arm");
|
|
44661
45070
|
return { kind: "thinking_binding", armed: true };
|
|
@@ -44727,7 +45136,6 @@ class PiThinkingBindingRecoveryRefusal extends EmergencyFailClosedError {
|
|
|
44727
45136
|
}
|
|
44728
45137
|
}
|
|
44729
45138
|
function applyPiThinkingBindingRecovery(args) {
|
|
44730
|
-
const protectedMessages = latestAssistantTurnMessages(args.messages);
|
|
44731
45139
|
const frozenEntryIds = frozenBindingEntryIds(args.db, args.sessionId);
|
|
44732
45140
|
const flagTargetCandidate = !args.replayOnly && isPrefixBoundThinkingModel(args.provider, args.model) ? getThinkingBindingRecoveryTarget(args.db, args.sessionId) : null;
|
|
44733
45141
|
const flagTarget = flagTargetCandidate?.startsWith(LATEST_THINKING_RESTORE) ? null : flagTargetCandidate;
|
|
@@ -44756,14 +45164,14 @@ function applyPiThinkingBindingRecovery(args) {
|
|
|
44756
45164
|
} else
|
|
44757
45165
|
throw new PiThinkingBindingRecoveryRefusal;
|
|
44758
45166
|
}
|
|
44759
|
-
const
|
|
45167
|
+
const restoringTurn = latestThinkingRestoringTurnMessages({
|
|
44760
45168
|
db: args.db,
|
|
44761
45169
|
sessionId: args.sessionId,
|
|
44762
45170
|
messages: args.messages,
|
|
44763
45171
|
id: (message, index) => resolvePiStableId(message, index, args.entryIds)
|
|
44764
45172
|
});
|
|
44765
45173
|
for (let index = 0;index < args.messages.length; index += 1) {
|
|
44766
|
-
if (
|
|
45174
|
+
if (restoringTurn?.has(args.messages[index]))
|
|
44767
45175
|
continue;
|
|
44768
45176
|
const entryId = args.entryIds[index];
|
|
44769
45177
|
if (entryId && frozenEntryIds.has(entryId))
|
|
@@ -44833,6 +45241,26 @@ function frozenBindingEntryIds(db, sessionId) {
|
|
|
44833
45241
|
}
|
|
44834
45242
|
return ids;
|
|
44835
45243
|
}
|
|
45244
|
+
function persistPiLatestTurnThinkingRemoval(db, sessionId, entryIds) {
|
|
45245
|
+
const endOrder = getMergedReasoningStrippedIds(db, sessionId).has(THINKING_BINDING_STRIP_ORDER_END_MARKER) || frozenBindingEntryIds(db, sessionId).size === 0;
|
|
45246
|
+
const persisted = addMergedReasoningStrippedIds(db, sessionId, [
|
|
45247
|
+
...entryIds.map(thinkingBindingRecoveryFrozenId),
|
|
45248
|
+
...endOrder ? [THINKING_BINDING_STRIP_ORDER_END_MARKER] : []
|
|
45249
|
+
]);
|
|
45250
|
+
return { persisted, stripNow: persisted && !endOrder };
|
|
45251
|
+
}
|
|
45252
|
+
function piBindingStripsAtStart(db, sessionId) {
|
|
45253
|
+
return !getMergedReasoningStrippedIds(db, sessionId).has(THINKING_BINDING_STRIP_ORDER_END_MARKER) && frozenBindingEntryIds(db, sessionId).size > 0;
|
|
45254
|
+
}
|
|
45255
|
+
function stripPiThinkingOfIds(messages, ids, resolveId) {
|
|
45256
|
+
let stripped = 0;
|
|
45257
|
+
for (let index = 0;index < messages.length; index += 1) {
|
|
45258
|
+
const id = resolveId(messages[index], index);
|
|
45259
|
+
if (id && ids.has(id))
|
|
45260
|
+
stripped += stripThinkingParts(messages[index]);
|
|
45261
|
+
}
|
|
45262
|
+
return stripped;
|
|
45263
|
+
}
|
|
44836
45264
|
function resolvePiBindingStripOrder(args) {
|
|
44837
45265
|
const ledger = getMergedReasoningStrippedIds(args.db, args.sessionId);
|
|
44838
45266
|
if (ledger.has(THINKING_BINDING_STRIP_ORDER_END_MARKER))
|
|
@@ -45870,7 +46298,7 @@ function createPiTranscript(source, sessionId, entryIds, options = {}) {
|
|
|
45870
46298
|
committed = true;
|
|
45871
46299
|
for (const index of dirtyMessages) {
|
|
45872
46300
|
rewriteNativeAssistantTexts(working[index], source[index], sessionId, {
|
|
45873
|
-
|
|
46301
|
+
unsignedEdits: harness === "omp"
|
|
45874
46302
|
});
|
|
45875
46303
|
}
|
|
45876
46304
|
for (const [index, parts] of removals) {
|
|
@@ -48177,6 +48605,16 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
48177
48605
|
return;
|
|
48178
48606
|
}
|
|
48179
48607
|
};
|
|
48608
|
+
const afterCapture = (sessionId, statement, run) => {
|
|
48609
|
+
try {
|
|
48610
|
+
return run();
|
|
48611
|
+
} catch (error) {
|
|
48612
|
+
if (budget.isCancelled(error) || error instanceof PiContextDeadlineError || error instanceof PiContextSupersededError)
|
|
48613
|
+
throw error;
|
|
48614
|
+
sessionLog2(sessionId, `${statement} failed after the request was decided; serving the pass:`, error);
|
|
48615
|
+
return;
|
|
48616
|
+
}
|
|
48617
|
+
};
|
|
48180
48618
|
try {
|
|
48181
48619
|
const tFindSession = performance.now();
|
|
48182
48620
|
const sessionId = resolveSessionId2(ctx);
|
|
@@ -48769,7 +49207,12 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
48769
49207
|
messages: event.messages,
|
|
48770
49208
|
prefixBound: isPrefixBoundThinkingModel(ctx.model?.provider, ctx.model?.id),
|
|
48771
49209
|
usagePercentage,
|
|
48772
|
-
executeThresholdPercentage: effectiveExecuteThresholdPercentage
|
|
49210
|
+
executeThresholdPercentage: effectiveExecuteThresholdPercentage,
|
|
49211
|
+
forceBandPressure: !options.compactionOff && piForceBandPressure({
|
|
49212
|
+
forceMaterialization: forceMaterialization || isEmergency,
|
|
49213
|
+
percentage: usagePercentage,
|
|
49214
|
+
forceMaterializationPercentage
|
|
49215
|
+
})
|
|
48773
49216
|
}),
|
|
48774
49217
|
requestToolsChange,
|
|
48775
49218
|
contextUsage: {
|
|
@@ -48907,13 +49350,13 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
48907
49350
|
assertCurrentPass();
|
|
48908
49351
|
recordSuccessfulTaggedMessageIds(sessionId, taggedInputEntryIds ?? strictEntryIds, branchEntries);
|
|
48909
49352
|
}
|
|
48910
|
-
const piDecisionSnapshotNewestAssistant = result.bustedThisPass || hasPendingPiSystemPromptHashChange(sessionId) ? findNewestPiAssistantEntryId(branchEntries) : undefined;
|
|
49353
|
+
const piDecisionSnapshotNewestAssistant = result.bustedThisPass || result.latestTurnThinkingRemoved === true || hasPendingPiSystemPromptHashChange(sessionId) ? findNewestPiAssistantEntryId(branchEntries) : undefined;
|
|
48911
49354
|
const publishTransformDecision = !budget.sideTurn && piDecisionSnapshotNewestAssistant !== undefined ? () => {
|
|
48912
49355
|
recordPendingPiTransformDecision(sessionId, {
|
|
48913
49356
|
tsMs: Date.now(),
|
|
48914
49357
|
decision: schedulerDecision,
|
|
48915
49358
|
materialized: result.materialized,
|
|
48916
|
-
materializeReason: normalizeMaterializeReason("pi", result.materializeReason, result.materialized),
|
|
49359
|
+
materializeReason: normalizeMaterializeReason("pi", result.materializeReason ?? (result.latestTurnThinkingRemoved ? LATEST_TURN_THINKING_REMOVED_REASON : null), result.materialized),
|
|
48917
49360
|
systemHashPrev: result.materialized ? result.injectionResult?.systemHashPrev ?? null : null,
|
|
48918
49361
|
systemHashNew: result.materialized ? result.injectionResult?.systemHashNew ?? null : null,
|
|
48919
49362
|
m0ModelKeyPrev: result.materialized ? result.injectionResult?.m0ModelKeyPrev ?? null : null,
|
|
@@ -49423,6 +49866,8 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
49423
49866
|
}
|
|
49424
49867
|
}
|
|
49425
49868
|
publishFinalRequestAccounting();
|
|
49869
|
+
if (!budget.sideTurn && (result.strictThinkingKept && !result.signedPrefixRewritten || result.heldHeadReleasedForSystemChange === true) && !result.materialized)
|
|
49870
|
+
recordPiHeldSystemHead(sessionId, (ownsHistory) => deferPiDeliveredSystemRefresh(sessionId, ownsHistory));
|
|
49426
49871
|
let serializedOutput;
|
|
49427
49872
|
let numbersCommitted = false;
|
|
49428
49873
|
budget.stage = "LKG/served publication";
|
|
@@ -49497,7 +49942,7 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
49497
49942
|
if (!budget.sideTurn && result.identityRebuilt && (numbersCommitted || lkgCompactionOff))
|
|
49498
49943
|
acknowledgePiIdentityRebuilds(options.db, sessionId);
|
|
49499
49944
|
if (!budget.sideTurn)
|
|
49500
|
-
captureOpencodeReasoningBudgetStatus(sessionId, piReasoningStatusMessages(outputMessages), resolveKeepReasoningTokens(options.heuristics?.keepReasoningTokens, resolvePiContextModelKey(ctx)), isPrefixBoundThinkingModel(ctx.model?.provider, ctx.model?.id), sessionDecisionCalibration(options.db, sessionId).proseRatio);
|
|
49945
|
+
afterCapture(sessionId, "reasoning budget status", () => captureOpencodeReasoningBudgetStatus(sessionId, piReasoningStatusMessages(outputMessages), resolveKeepReasoningTokens(options.heuristics?.keepReasoningTokens, resolvePiContextModelKey(ctx)), isPrefixBoundThinkingModel(ctx.model?.provider, ctx.model?.id), sessionDecisionCalibration(options.db, sessionId).proseRatio));
|
|
49501
49946
|
if (thinkingBindingRecoveryApplied) {
|
|
49502
49947
|
try {
|
|
49503
49948
|
clearThinkingBindingRecoveryIf(options.db, sessionId, thinkingBindingRecoveryApplied.flagTarget);
|
|
@@ -49506,14 +49951,14 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
49506
49951
|
}
|
|
49507
49952
|
}
|
|
49508
49953
|
budget.assertOutcome();
|
|
49509
|
-
publishTransformDecision?.();
|
|
49510
|
-
|
|
49511
|
-
|
|
49512
|
-
|
|
49513
|
-
|
|
49514
|
-
|
|
49515
|
-
|
|
49516
|
-
recordServedSystemHash
|
|
49954
|
+
afterCapture(sessionId, "transform decision record", () => publishTransformDecision?.());
|
|
49955
|
+
afterCapture(sessionId, "request tools release record", () => {
|
|
49956
|
+
if (requestToolsChange === null || recordPiBindingStripEndOrder(options.db, sessionId))
|
|
49957
|
+
requestToolsRelease?.commit();
|
|
49958
|
+
else
|
|
49959
|
+
sessionLog2(sessionId, "request tools release not recorded: the end strip order could not be written");
|
|
49960
|
+
});
|
|
49961
|
+
afterCapture(sessionId, "served system hash record", recordServedSystemHash);
|
|
49517
49962
|
return { messages: outputMessages };
|
|
49518
49963
|
} catch (err) {
|
|
49519
49964
|
if (budget.isCancelled(err))
|
|
@@ -49547,6 +49992,7 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
49547
49992
|
budget.assertOutcome();
|
|
49548
49993
|
budget.recovery = err.recovery;
|
|
49549
49994
|
recordServedSystemHash();
|
|
49995
|
+
noteServedReplay(sessionIdForError);
|
|
49550
49996
|
return { messages: err.messages };
|
|
49551
49997
|
}
|
|
49552
49998
|
if ((isFailClosedBlockingError(err) || err instanceof EmergencyFailClosedError) && !baseOptions.compactionOff)
|
|
@@ -49615,6 +50061,7 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
49615
50061
|
budget.assertOutcome();
|
|
49616
50062
|
budget.recovery = "fitting LKG replay";
|
|
49617
50063
|
recordServedSystemHash();
|
|
50064
|
+
noteServedReplay(sessionIdForError);
|
|
49618
50065
|
return { messages: replay.messages };
|
|
49619
50066
|
}
|
|
49620
50067
|
logPiLkgRecovery(sessionIdForError, `${failureLabel} ${piStorageErrorReason(err)}: LKG unavailable (${replay.reason}); refusing unreduced ${rawMessageCount}-message input`);
|
|
@@ -50238,9 +50685,31 @@ function captureReasoningMutationRollback(messages) {
|
|
|
50238
50685
|
}
|
|
50239
50686
|
};
|
|
50240
50687
|
}
|
|
50688
|
+
function piServedHeadMatches(served, index, head) {
|
|
50689
|
+
const contentOf = (message) => isRecord(message) && message.role === "user" && Array.isArray(message.content) ? message.content : null;
|
|
50690
|
+
const isText = (part, text) => isRecord(part) && part.type === "text" && part.text === text;
|
|
50691
|
+
const m0 = contentOf(served?.[index]);
|
|
50692
|
+
const m1 = contentOf(served?.[index + 1]);
|
|
50693
|
+
if (!m0 || !m1 || m1.length !== 1 || !isText(m1[0], head.m1Text))
|
|
50694
|
+
return false;
|
|
50695
|
+
if (m0.length !== (head.muralDataUrl ? 2 : 1) || !isText(m0[0], head.m0Text))
|
|
50696
|
+
return false;
|
|
50697
|
+
if (!head.muralDataUrl)
|
|
50698
|
+
return true;
|
|
50699
|
+
const image = m0[1];
|
|
50700
|
+
if (!isRecord(image) || image.type !== "image" || typeof image.mimeType !== "string" || typeof image.data !== "string")
|
|
50701
|
+
return false;
|
|
50702
|
+
const prefix = `data:${image.mimeType};base64,`;
|
|
50703
|
+
return head.muralDataUrl.length === prefix.length + image.data.length && head.muralDataUrl.startsWith(prefix) && head.muralDataUrl.endsWith(image.data);
|
|
50704
|
+
}
|
|
50241
50705
|
async function runCompactionOffPipeline(args) {
|
|
50242
50706
|
let injectionResult = null;
|
|
50243
50707
|
const transcript = [...args.messages];
|
|
50708
|
+
let stripEntryIdsMemo;
|
|
50709
|
+
const stripEntryIds = () => {
|
|
50710
|
+
stripEntryIdsMemo ??= transcript.map((message, index) => resolvePiRealStableId(message, index, args.entryIds, args.entryIdByRef ?? undefined));
|
|
50711
|
+
return stripEntryIdsMemo;
|
|
50712
|
+
};
|
|
50244
50713
|
let headChangedUnderSignedThinking = false;
|
|
50245
50714
|
if (args.injection) {
|
|
50246
50715
|
const state = {
|
|
@@ -50259,13 +50728,44 @@ async function runCompactionOffPipeline(args) {
|
|
|
50259
50728
|
if (signedTurnHoldsHead)
|
|
50260
50729
|
state.preparedPrefix = prepareCachedM0M1PiReplay(state, args.db, args.injectionPassSnapshot?.cachedRow);
|
|
50261
50730
|
const servedBeforeFirstRender = signedTurnHoldsHead && !state.preparedPrefix ? args.readLastServedMessages?.() ?? null : undefined;
|
|
50731
|
+
let lastServed;
|
|
50732
|
+
const readLastServed = () => {
|
|
50733
|
+
if (lastServed === undefined)
|
|
50734
|
+
lastServed = args.readLastServedMessages?.() ?? null;
|
|
50735
|
+
return lastServed;
|
|
50736
|
+
};
|
|
50737
|
+
if (!signedTurnHoldsHead && args.reasoningClearing?.prefixBound === true) {
|
|
50738
|
+
state.onFoldPrepare = () => {
|
|
50739
|
+
const served = readLastServed();
|
|
50740
|
+
const headIndex = placePiInitialSystemAtHead([
|
|
50741
|
+
...args.messages
|
|
50742
|
+
]);
|
|
50743
|
+
return (db, head) => {
|
|
50744
|
+
if (piServedHeadMatches(served, headIndex, head))
|
|
50745
|
+
return;
|
|
50746
|
+
applyPiProactiveThinkingStrip({
|
|
50747
|
+
db,
|
|
50748
|
+
sessionId: args.sessionId,
|
|
50749
|
+
messages: transcript,
|
|
50750
|
+
entryIds: stripEntryIds(),
|
|
50751
|
+
provider: args.resolvedProviderID,
|
|
50752
|
+
model: args.resolvedModelID,
|
|
50753
|
+
cacheBustingPass: true,
|
|
50754
|
+
stripActiveTurn: true,
|
|
50755
|
+
persistOnly: true,
|
|
50756
|
+
requirePersistence: true,
|
|
50757
|
+
report: (line) => sessionLog2(args.sessionId, line)
|
|
50758
|
+
});
|
|
50759
|
+
};
|
|
50760
|
+
};
|
|
50761
|
+
}
|
|
50262
50762
|
injectionResult = injectM0M1Pi(state, args.db, args.messages, args.entryIds, false, args.injectionPassSnapshot);
|
|
50263
50763
|
if (servedBeforeFirstRender !== undefined) {
|
|
50264
50764
|
const headCount = injectionResult?.syntheticLeadingCount ?? 0;
|
|
50265
50765
|
const head = JSON.stringify(args.messages.slice(0, headCount));
|
|
50266
50766
|
headChangedUnderSignedThinking = servedBeforeFirstRender === null || JSON.stringify(servedBeforeFirstRender.slice(0, headCount)) !== head;
|
|
50267
50767
|
} else if (!signedTurnHoldsHead && args.reasoningClearing?.prefixBound === true && (injectionResult?.m0Materialized === true || injectionResult?.m1RenderedCoverage != null)) {
|
|
50268
|
-
const served =
|
|
50768
|
+
const served = readLastServed();
|
|
50269
50769
|
const headCount = injectionResult?.syntheticLeadingCount ?? 0;
|
|
50270
50770
|
headChangedUnderSignedThinking = served === null || JSON.stringify(served.slice(0, headCount)) !== JSON.stringify(args.messages.slice(0, headCount));
|
|
50271
50771
|
if (headChangedUnderSignedThinking)
|
|
@@ -50277,7 +50777,7 @@ async function runCompactionOffPipeline(args) {
|
|
|
50277
50777
|
db: args.db,
|
|
50278
50778
|
sessionId: args.sessionId,
|
|
50279
50779
|
messages: transcript,
|
|
50280
|
-
entryIds:
|
|
50780
|
+
entryIds: stripEntryIds(),
|
|
50281
50781
|
provider: args.resolvedProviderID,
|
|
50282
50782
|
model: args.resolvedModelID,
|
|
50283
50783
|
cacheBustingPass: true,
|
|
@@ -50320,6 +50820,9 @@ async function runCompactionOffPipeline(args) {
|
|
|
50320
50820
|
};
|
|
50321
50821
|
}
|
|
50322
50822
|
var signedThinkingHoldLogKeys = new Map;
|
|
50823
|
+
function piForceBandPressure(args) {
|
|
50824
|
+
return args.forceMaterialization === true || args.percentage >= args.forceMaterializationPercentage;
|
|
50825
|
+
}
|
|
50323
50826
|
function resolvePiSignedThinkingHold(args) {
|
|
50324
50827
|
if (!args.prefixBound)
|
|
50325
50828
|
return false;
|
|
@@ -50328,6 +50831,7 @@ function resolvePiSignedThinkingHold(args) {
|
|
|
50328
50831
|
messages: args.messages,
|
|
50329
50832
|
usagePercentage: args.usagePercentage,
|
|
50330
50833
|
executeThresholdPercentage: args.executeThresholdPercentage,
|
|
50834
|
+
forceBandPressure: args.forceBandPressure,
|
|
50331
50835
|
estimateTextTokens: (text) => {
|
|
50332
50836
|
proseRatio ??= sessionDecisionCalibration(args.db, args.sessionId).proseRatio;
|
|
50333
50837
|
return estimateTokens(text) * proseRatio;
|
|
@@ -50348,13 +50852,26 @@ async function runPipeline(args) {
|
|
|
50348
50852
|
const dropBranchIds = dropBranchEntries ? piDropBranchIds(dropBranchEntries) : null;
|
|
50349
50853
|
trackPiDropLeaf(args.db, args.sessionId, dropBranchIds ? [...dropBranchIds].at(-1) ?? null : null);
|
|
50350
50854
|
cancelPiAbandonedPendingDrops(args.db, args.sessionId, dropBranchIds);
|
|
50855
|
+
const piStableId = (message, index) => resolvePiStableId(message, index, args.entryIds, args.entryIdByRef ?? undefined);
|
|
50856
|
+
let stripRemovedTurnNow = false;
|
|
50351
50857
|
const thinkingRecovery = prepareLatestThinkingRecovery({
|
|
50352
50858
|
db: args.db,
|
|
50353
50859
|
sessionId: args.sessionId,
|
|
50354
50860
|
messages: args.messages,
|
|
50355
|
-
id:
|
|
50356
|
-
parts: (message) => Array.isArray(message?.content) ? message.content : []
|
|
50357
|
-
|
|
50861
|
+
id: piStableId,
|
|
50862
|
+
parts: (message) => Array.isArray(message?.content) ? message.content : [],
|
|
50863
|
+
modelID: args.resolvedModelID,
|
|
50864
|
+
providerID: args.resolvedProviderID,
|
|
50865
|
+
persistRemoval: (ids) => {
|
|
50866
|
+
const outcome = persistPiLatestTurnThinkingRemoval(args.db, args.sessionId, ids);
|
|
50867
|
+
stripRemovedTurnNow = outcome.stripNow;
|
|
50868
|
+
return outcome.persisted;
|
|
50869
|
+
}
|
|
50870
|
+
});
|
|
50871
|
+
const removedTurnIds = new Set(thinkingRecovery.removedIds ?? []);
|
|
50872
|
+
const removedTurnAtStart = removedTurnIds.size > 0 && (stripRemovedTurnNow || piBindingStripsAtStart(args.db, args.sessionId));
|
|
50873
|
+
if (removedTurnAtStart)
|
|
50874
|
+
stripPiThinkingOfIds(args.messages, removedTurnIds, piStableId);
|
|
50358
50875
|
if (thinkingRecovery.ended)
|
|
50359
50876
|
signalPiPendingMaterialization(args.sessionId, "thinking_hold");
|
|
50360
50877
|
let restoreOriginals;
|
|
@@ -50485,7 +51002,11 @@ async function runPipeline(args) {
|
|
|
50485
51002
|
lastResponseTime: hardMeta.lastResponseTime
|
|
50486
51003
|
};
|
|
50487
51004
|
})() : undefined;
|
|
50488
|
-
const emergencyDropEligible =
|
|
51005
|
+
const emergencyDropEligible = piForceBandPressure({
|
|
51006
|
+
forceMaterialization: args.forceMaterialization,
|
|
51007
|
+
percentage: args.contextUsage.percentage,
|
|
51008
|
+
forceMaterializationPercentage
|
|
51009
|
+
});
|
|
50489
51010
|
const piM0State = args.injection && piHardSignals ? {
|
|
50490
51011
|
sessionId: args.sessionId,
|
|
50491
51012
|
projectIdentity: args.projectIdentity,
|
|
@@ -50671,6 +51192,16 @@ async function runPipeline(args) {
|
|
|
50671
51192
|
let prefixMutationAllowed = prefixMutationPermitted(ridePermissionGate);
|
|
50672
51193
|
isCacheBustingPass = reclaimRidePermitted(rideSignals, ridePermissionGate);
|
|
50673
51194
|
let publishedWorkDrainAllowed = isCacheBustingPass;
|
|
51195
|
+
const noteServedPermission = () => noteServedPassPermission(args.sessionId, {
|
|
51196
|
+
permitted: isCacheBustingPass,
|
|
51197
|
+
rides: reclaimRideLabel(rideSignals),
|
|
51198
|
+
signedThinkingHold: protectedSignedPrefix,
|
|
51199
|
+
firstRender: firstRenderBust,
|
|
51200
|
+
hostCheckpointHead: false,
|
|
51201
|
+
emergency: emergencyDropEligible,
|
|
51202
|
+
schedulerDecision: args.schedulerDecision
|
|
51203
|
+
});
|
|
51204
|
+
noteServedPermission();
|
|
50674
51205
|
stripUnheldSignedTurnOnBust();
|
|
50675
51206
|
const usesTokenProtection = args.protectedTokenTierOverrides !== undefined || args.protectedTokens !== undefined;
|
|
50676
51207
|
const resolveProtectionFloor = () => resolveEpochFloorForPass(args.db, args.sessionId, {
|
|
@@ -50746,6 +51277,7 @@ async function runPipeline(args) {
|
|
|
50746
51277
|
deferredMaterializeEligible = canConsumeDeferredLate && deferredMaterializationSessions.has(args.sessionId);
|
|
50747
51278
|
isCacheBustingPass = prefixMutationAllowed;
|
|
50748
51279
|
publishedWorkDrainAllowed = isCacheBustingPass;
|
|
51280
|
+
noteServedPermission();
|
|
50749
51281
|
stripUnheldSignedTurnOnBust();
|
|
50750
51282
|
shouldRunHeuristics = args.heuristics !== undefined;
|
|
50751
51283
|
if (piM0State && prefixMutationAllowed) {
|
|
@@ -50848,22 +51380,10 @@ async function runPipeline(args) {
|
|
|
50848
51380
|
}
|
|
50849
51381
|
}
|
|
50850
51382
|
}
|
|
50851
|
-
|
|
51383
|
+
const newTargets = new Map(protectNewTagMutations(mutationView.map((message) => ({
|
|
50852
51384
|
info: message.info,
|
|
50853
51385
|
parts: message.parts
|
|
50854
51386
|
})), targets, protectedThinkingProxies, args.reasoningClearing?.prefixBound === true));
|
|
50855
|
-
if (protectedSignedPrefix && args.contextUsage.percentage >= 95 && !args.upperEstimateOnly) {
|
|
50856
|
-
const candidates = getActiveTagsBySession2(args.db, args.sessionId).filter((tag) => tag.type === "tool" && targets.get(tag.tagNumber)?.canDrop?.());
|
|
50857
|
-
if (candidates.length > 0 && candidates.every((tag) => newTargets.get(tag.tagNumber)?.thinkingRewriteProtected === true)) {
|
|
50858
|
-
stripForPrefixRewrite();
|
|
50859
|
-
newTargets = targets;
|
|
50860
|
-
prefixMutationAllowed = true;
|
|
50861
|
-
isCacheBustingPass = true;
|
|
50862
|
-
publishedWorkDrainAllowed = true;
|
|
50863
|
-
shouldRunHeuristics = args.heuristics !== undefined;
|
|
50864
|
-
hasPendingMaterializeSignal = hasPendingMaterialization(args.sessionId);
|
|
50865
|
-
}
|
|
50866
|
-
}
|
|
50867
51387
|
for (const number of identityAdoption.protectedTagNumbers) {
|
|
50868
51388
|
if (rewritingSignedPrefix)
|
|
50869
51389
|
break;
|
|
@@ -51037,6 +51557,7 @@ async function runPipeline(args) {
|
|
|
51037
51557
|
if (rideSignals.executeReclaim) {
|
|
51038
51558
|
isCacheBustingPass = reclaimRidePermitted(rideSignals, ridePermissionGate);
|
|
51039
51559
|
publishedWorkDrainAllowed = isCacheBustingPass;
|
|
51560
|
+
noteServedPermission();
|
|
51040
51561
|
shouldRunHeuristics ||= isCacheBustingPass && args.heuristics !== undefined;
|
|
51041
51562
|
stripUnheldSignedTurnOnBust();
|
|
51042
51563
|
applyTemporalOnRide();
|
|
@@ -51837,6 +52358,8 @@ async function runPipeline(args) {
|
|
|
51837
52358
|
}
|
|
51838
52359
|
if (bustedThisPass)
|
|
51839
52360
|
clearExecuteReclaimState(args.db, args.sessionId);
|
|
52361
|
+
if (removedTurnIds.size > 0 && !removedTurnAtStart)
|
|
52362
|
+
stripPiThinkingOfIds(outputMessages, removedTurnIds, (message) => message && typeof message === "object" ? postCommitStableIdByRef.get(message) : undefined);
|
|
51840
52363
|
return {
|
|
51841
52364
|
messages: outputMessages,
|
|
51842
52365
|
recoveryNormalized,
|
|
@@ -51857,6 +52380,7 @@ async function runPipeline(args) {
|
|
|
51857
52380
|
injectionResult,
|
|
51858
52381
|
materialized,
|
|
51859
52382
|
materializeReason,
|
|
52383
|
+
latestTurnThinkingRemoved: thinkingRecovery.removedThisPass === true,
|
|
51860
52384
|
droppedTokens,
|
|
51861
52385
|
droppedCount,
|
|
51862
52386
|
emergency,
|
|
@@ -52095,6 +52619,7 @@ function clearPiCompactionOffInMemoryState(sessionId) {
|
|
|
52095
52619
|
clearPiChannel1State(sessionId);
|
|
52096
52620
|
}
|
|
52097
52621
|
function clearContextHandlerSession(sessionId) {
|
|
52622
|
+
dropServedRecord(sessionId, "session_cleared");
|
|
52098
52623
|
cancelPiTagSnapshotSession(sessionId);
|
|
52099
52624
|
lastServedSystemHashBySession.delete(sessionId);
|
|
52100
52625
|
clearPiHistoryBoundaryRepairSession(sessionId);
|
|
@@ -55519,7 +56044,7 @@ function strippedAssistantContent(content, provider = "anthropic") {
|
|
|
55519
56044
|
if (part === null || typeof part !== "object" || part.type !== "text") {
|
|
55520
56045
|
continue;
|
|
55521
56046
|
}
|
|
55522
|
-
if (typeof part.text !== "string")
|
|
56047
|
+
if (typeof part.text !== "string" || !part.text.includes("§"))
|
|
55523
56048
|
continue;
|
|
55524
56049
|
const stripped = stripPersistedAssistantText(part.text, provider === "anthropic");
|
|
55525
56050
|
if (stripped === part.text)
|