@cortexkit/pi-magic-context 0.49.52 → 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.
Files changed (27) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{embedding-backfill-fbhpk2yy.js → embedding-backfill-ad4k8e3f.js} +2 -2
  4. package/dist/{index-mb34ngfr.js → index-1tk6065b.js} +25 -14
  5. package/dist/{index-r6dj8rm9.js → index-2yjpxzga.js} +9 -5
  6. package/dist/{index-73c292h9.js → index-4cmj48mq.js} +3 -3
  7. package/dist/{index-fec4ezww.js → index-8cgk0pyh.js} +51 -14
  8. package/dist/{index-1cvyaw9a.js → index-8d2z6503.js} +1 -1
  9. package/dist/{index-cc73przv.js → index-a70dwgff.js} +7 -7
  10. package/dist/{index-akmmkmhf.js → index-f07s5m8x.js} +504 -9
  11. package/dist/{index-ktez4jwz.js → index-nevbaezn.js} +7 -6
  12. package/dist/{index-ty2m0s0s.js → index-njd3qa8e.js} +1 -1
  13. package/dist/{index-0hewsw7v.js → index-snrkpmpf.js} +1 -1
  14. package/dist/{index-rjz01pvv.js → index-tv9pqeek.js} +1 -1
  15. package/dist/index.js +663 -144
  16. package/dist/{message-index-bounded-d50b5f2z.js → message-index-bounded-hwatm90p.js} +2 -2
  17. package/dist/migration-worker.js +1 -1
  18. package/dist/{project-embedding-registry-hpca84nz.js → project-embedding-registry-d67axw7r.js} +3 -1
  19. package/dist/raw-ordinal-warmup-worker.js +3 -3
  20. package/dist/{read-session-chunk-9yr9mava.js → read-session-chunk-mj91mv8r.js} +1 -1
  21. package/dist/{render-3s7kbr61.js → render-js5tkc4g.js} +4 -4
  22. package/dist/{search-archive-dd1z7xn0.js → search-archive-159s0qp9.js} +4 -4
  23. package/dist/{search-2vgt4717.js → search-hyc5s9t0.js} +6 -6
  24. package/dist/subagent-entry.js +11 -11
  25. package/dist/tag-snapshot-worker-pi.js +1 -1
  26. package/dist/{v2-archive-reader-6jbyaafn.js → v2-archive-reader-5sc0rsh9.js} +1 -1
  27. 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-cc73przv.js";
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,
@@ -357,7 +358,7 @@ import {
357
358
  getRawSessionTagKeysThrough2,
358
359
  getLegacyProtectedTailStartOrdinal2,
359
360
  readSessionChunk2
360
- } from "./index-fec4ezww.js";
361
+ } from "./index-8cgk0pyh.js";
361
362
  import {
362
363
  UNKNOWN_FIT_RATIO,
363
364
  hasMeasuredDecisionCalibration,
@@ -496,7 +497,7 @@ import {
496
497
  openCurrentDatabase,
497
498
  openDatabaseAsync,
498
499
  closeDatabase
499
- } from "./index-rjz01pvv.js";
500
+ } from "./index-tv9pqeek.js";
500
501
  import {
501
502
  LkgRecoveryFenceError,
502
503
  clearLkgFenceProcessState,
@@ -562,6 +563,12 @@ import {
562
563
  drainStaleLkgSlots,
563
564
  createDbLkgPersistence,
564
565
  replayLkg,
566
+ beginServedRequest,
567
+ noteServedPassPermission,
568
+ noteServedReplay,
569
+ countServedRefusal,
570
+ dropServedRecord,
571
+ commitServedRequest,
565
572
  registerLkgPersistence,
566
573
  LKG_SNAPSHOT_ARRAY,
567
574
  LKG_SNAPSHOT_OBJECT,
@@ -613,7 +620,7 @@ import {
613
620
  getSourceContents,
614
621
  recordSubagentInvocation,
615
622
  getLatestHistorianInvocationId
616
- } from "./index-akmmkmhf.js";
623
+ } from "./index-f07s5m8x.js";
617
624
  import {
618
625
  resolveOpenCodeDbPath,
619
626
  assertOpenCodeStoreGeneration,
@@ -671,7 +678,7 @@ import {
671
678
  clearCompressionDepthRange,
672
679
  cleanSearchText,
673
680
  matchedSearchSnippet
674
- } from "./index-0hewsw7v.js";
681
+ } from "./index-snrkpmpf.js";
675
682
  import {
676
683
  rememberV1HiddenRun
677
684
  } from "./index-6x556c2q.js";
@@ -760,16 +767,16 @@ import {
760
767
  getProjectEmbeddingMaxInputTokens2,
761
768
  embedTextForProject2,
762
769
  embedBatchForProject2,
763
- embedItemsForProject2,
770
+ embedItemsWindowBounded2,
764
771
  embedUnembeddedMemoriesForProject2,
765
772
  drainCommitBacklogForProject2,
766
773
  embedSessionCompartmentChunks2,
767
774
  getEmbeddingCoverageStatus2,
768
775
  getAutoEmbeddingSessionCoverage2
769
- } from "./index-r6dj8rm9.js";
776
+ } from "./index-2yjpxzga.js";
770
777
  import {
771
778
  cosineSimilarity
772
- } from "./index-ty2m0s0s.js";
779
+ } from "./index-njd3qa8e.js";
773
780
  import {
774
781
  USER_FACING_FAILURES,
775
782
  renderUserFacingFailure,
@@ -803,7 +810,7 @@ import {
803
810
  scheduleClearAndReindex,
804
811
  clearSessionTracking,
805
812
  createAutoSearchDiagnostics
806
- } from "./index-mb34ngfr.js";
813
+ } from "./index-1tk6065b.js";
807
814
  import"./index-xssjy4z9.js";
808
815
  import {
809
816
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
@@ -833,9 +840,9 @@ import {
833
840
  ensurePiTagSnapshotReady
834
841
  } from "./index-pkg07s54.js";
835
842
  import"./index-yjgkjkjs.js";
836
- import"./index-1cvyaw9a.js";
837
- import"./index-73c292h9.js";
838
- import"./index-ktez4jwz.js";
843
+ import"./index-8d2z6503.js";
844
+ import"./index-4cmj48mq.js";
845
+ import"./index-nevbaezn.js";
839
846
  import {
840
847
  __toESM
841
848
  } from "./index-22jkk6wg.js";
@@ -3590,7 +3597,7 @@ function startHostStallProfilerSwitch() {
3590
3597
  // package.json
3591
3598
  var package_default = {
3592
3599
  name: "@cortexkit/pi-magic-context",
3593
- version: "0.49.52",
3600
+ version: "0.49.53",
3594
3601
  type: "module",
3595
3602
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3596
3603
  main: "dist/index.js",
@@ -3658,6 +3665,7 @@ var package_default = {
3658
3665
  "omp-coding-agent-18126": "npm:@oh-my-pi/pi-coding-agent@18.12.6",
3659
3666
  "omp-coding-agent-18132": "npm:@oh-my-pi/pi-coding-agent@18.13.2",
3660
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",
3661
3669
  "omp-pi-ai-171": "npm:@oh-my-pi/pi-ai@17.1.7",
3662
3670
  "omp-pi-ai-1889": "npm:@oh-my-pi/pi-ai@18.8.9",
3663
3671
  "omp-pi-ai-1811": "npm:@oh-my-pi/pi-ai@18.11.3",
@@ -3668,6 +3676,7 @@ var package_default = {
3668
3676
  "omp-pi-ai-18180": "npm:@oh-my-pi/pi-ai@18.18.0",
3669
3677
  "omp-pi-ai-18181": "npm:@oh-my-pi/pi-ai@18.18.1",
3670
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",
3671
3680
  "pi-agent-core-087": "npm:@earendil-works/pi-agent-core@0.87.1",
3672
3681
  "pi-ai-086": "npm:@earendil-works/pi-ai@0.86.0",
3673
3682
  "pi-ai-087": "npm:@earendil-works/pi-ai@0.87.1",
@@ -24667,7 +24676,8 @@ var canonicalReasons = new Set([
24667
24676
  "coverage_fold",
24668
24677
  "profile_transition",
24669
24678
  "host_compaction",
24670
- "tag_identity_repair"
24679
+ "tag_identity_repair",
24680
+ "latest_turn_thinking_removed"
24671
24681
  ]);
24672
24682
  var piReasonAliases = {
24673
24683
  project_memory_change: "project_memory_epoch",
@@ -27183,6 +27193,66 @@ function latestAssistantTurnStart(messages) {
27183
27193
  function latestAssistantTurnMessages(messages) {
27184
27194
  return new Set(messages.slice(latestAssistantTurnStart(messages)));
27185
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
+ }
27186
27256
  function isAnthropicThinkingPart(part, familyRoute) {
27187
27257
  return isRecord(part) && THINKING_TYPES.has(String(part.type ?? part.kind)) && (familyRoute || isRecord(part.metadata) && isRecord(part.metadata.anthropic));
27188
27258
  }
@@ -27238,18 +27308,110 @@ function protectNewTagMutations(messages, targets, protectedParts, prefixBound)
27238
27308
 
27239
27309
  // ../plugin/src/hooks/magic-context/latest-thinking-recovery.ts
27240
27310
  var LATEST_THINKING_RESTORE = "latest_thinking_original";
27311
+ var TURN_STATE = `${LATEST_THINKING_RESTORE}_turn:`;
27241
27312
  var knownRejectedSessions = new Set;
27242
- var lastPassTurnAnchor = new Map;
27243
- var ACTIVE = `${LATEST_THINKING_RESTORE}:`;
27244
- var ARMED = `${LATEST_THINKING_RESTORE}_armed:`;
27245
- var UNRECOVERABLE = `${LATEST_THINKING_RESTORE}_unavailable`;
27246
- var LATEST_THINKING_UNSAFE = "ANTHROPIC_LATEST_TURN_EDIT_UNSAFE: The provider rejected edits to this thinking turn and its original context cannot be safely replayed. Send a new user message or /clear to continue.";
27247
- function armLatestThinkingRecovery(db, sessionId) {
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) {
27248
27377
  knownRejectedSessions.add(sessionId);
27249
27378
  ensureSessionMetaRow(db, sessionId);
27250
27379
  const current = getThinkingBindingRecoveryTarget(db, sessionId);
27251
- const anchor = lastPassTurnAnchor.get(sessionId);
27252
- const next = current?.startsWith(ACTIVE) ? UNRECOVERABLE + ":" + current.slice(ACTIVE.length) : current?.startsWith(UNRECOVERABLE) || current?.startsWith(ARMED) ? current : anchor !== undefined ? ARMED + anchor : LATEST_THINKING_RESTORE;
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
+ }
27253
27415
  db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ?").run(next, sessionId);
27254
27416
  }
27255
27417
  function clone(value) {
@@ -27272,72 +27434,253 @@ function replayableOriginal(part) {
27272
27434
  const signature = part.signature ?? part.thinkingSignature ?? metadata.signature ?? part.data ?? metadata.redactedData;
27273
27435
  return typeof signature === "string" && signature.length > 0 && part.text !== "[cleared]" && part.thinking !== "[cleared]";
27274
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
+ }
27275
27587
  function prepareLatestThinkingRecovery(args) {
27276
- const start = latestAssistantTurnStart(args.messages);
27277
- const anchor = start > 0 ? args.id(args.messages[start - 1], start - 1) : undefined;
27278
- if (anchor === undefined)
27279
- lastPassTurnAnchor.delete(args.sessionId);
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
+ });
27280
27596
  else
27281
- lastPassTurnAnchor.set(args.sessionId, anchor);
27597
+ lastPassTurn.delete(args.sessionId);
27282
27598
  let target;
27283
27599
  try {
27284
27600
  target = getThinkingBindingRecoveryTarget(args.db, args.sessionId);
27285
27601
  } catch (error) {
27286
27602
  if (knownRejectedSessions.has(args.sessionId))
27287
- throw contextRefusalError(LATEST_THINKING_UNSAFE);
27288
- return { restore: false, ended: false };
27603
+ refuseUnsaved(args.sessionId, "the recovery state could not be read");
27604
+ return NO_RECOVERY;
27289
27605
  }
27290
27606
  if (!target || !target.startsWith(LATEST_THINKING_RESTORE)) {
27291
27607
  knownRejectedSessions.delete(args.sessionId);
27292
- return { restore: false, ended: false };
27608
+ return NO_RECOVERY;
27293
27609
  }
27294
- const armedAnchor = target.startsWith(ARMED) ? target.slice(ARMED.length) : undefined;
27295
- if (target === LATEST_THINKING_RESTORE || armedAnchor !== undefined && armedAnchor !== anchor) {
27296
- args.db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(args.sessionId, target);
27610
+ const state = readState(target);
27611
+ if (!state) {
27612
+ replaceTarget(args.db, args.sessionId, target, "");
27297
27613
  knownRejectedSessions.delete(args.sessionId);
27298
- return { restore: false, ended: false };
27614
+ sessionLog2(args.sessionId, "latest-turn thinking recovery: cleared a rejection that names no turn");
27615
+ return NO_RECOVERY;
27299
27616
  }
27300
- knownRejectedSessions.add(args.sessionId);
27301
- const savedAnchor = target.startsWith(ACTIVE) ? target.slice(ACTIVE.length) : target.startsWith(UNRECOVERABLE + ":") ? target.slice(UNRECOVERABLE.length + 1) : undefined;
27302
- if (savedAnchor !== undefined && savedAnchor !== anchor) {
27303
- 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, "");
27304
27619
  knownRejectedSessions.delete(args.sessionId);
27305
- return { restore: false, ended: true };
27306
- }
27307
- if (target.startsWith(UNRECOVERABLE) || !anchor)
27308
- throw contextRefusalError(LATEST_THINKING_UNSAFE);
27309
- if (armedAnchor !== undefined) {
27310
- args.db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(ACTIVE + anchor, args.sessionId, target);
27311
- }
27312
- const active = args.messages.slice(start);
27313
- if (!active.some((message) => args.parts(message).some(replayableOriginal)))
27314
- throw contextRefusalError(LATEST_THINKING_UNSAFE + " [missing-thinking-original]");
27315
- const ids = new Map(args.messages.map((message, index) => [args.id(message, index), index]));
27316
- for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
27317
- if (decision === "binding_mismatch_order:end" || decision === TOOL_SWEEP_SCOPED_MARKER)
27318
- continue;
27319
- const id = decodeMergedReasoningParts(decision)?.[0] ?? (decision.startsWith("binding_mismatch:") ? decision.slice("binding_mismatch:".length) : decision);
27320
- const index = ids.get(id);
27321
- if (index === undefined || index >= start && !args.parts(args.messages[index]).some(replayableOriginal))
27322
- 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) };
27323
27637
  }
27324
- return { restore: true, ended: false };
27325
- }
27326
- function latestThinkingRecoveryCoversActiveTurn(args) {
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) {
27327
27668
  let target;
27328
27669
  try {
27329
27670
  target = getThinkingBindingRecoveryTarget(args.db, args.sessionId);
27330
27671
  } catch {
27331
- return false;
27672
+ return;
27332
27673
  }
27333
- const bound = target?.startsWith(ARMED) ? target.slice(ARMED.length) : target?.startsWith(ACTIVE) ? target.slice(ACTIVE.length) : undefined;
27334
- if (bound === undefined)
27335
- return false;
27336
- const start = latestAssistantTurnStart(args.messages);
27337
- return start > 0 && args.id(args.messages[start - 1], start - 1) === bound;
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));
27338
27681
  }
27339
27682
  function captureOriginalTurn(messages, parts, setParts) {
27340
- const start = Math.max(0, latestAssistantTurnStart(messages) - 1);
27683
+ const start = Math.max(0, (providerLatestTurn(messages)?.start ?? latestAssistantTurnStart(messages)) - 1);
27341
27684
  const originals = messages.slice(start).map((message) => ({ message, parts: clone(parts(message)) }));
27342
27685
  const before = messages.slice(0, start);
27343
27686
  return (target = messages) => {
@@ -27351,10 +27694,17 @@ function captureOriginalTurn(messages, parts, setParts) {
27351
27694
  };
27352
27695
  }
27353
27696
  function armBindingRecoverySafely(db, sessionId) {
27354
- if (getThinkingBindingRecoveryTarget(db, sessionId)?.startsWith(LATEST_THINKING_RESTORE))
27355
- armLatestThinkingRecovery(db, sessionId);
27356
- else
27357
- armThinkingBindingRecovery(db, sessionId);
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);
27358
27708
  }
27359
27709
 
27360
27710
  // ../plugin/src/hooks/magic-context/reasoning-budget-status.ts
@@ -27622,8 +27972,13 @@ function decideSignedThinkingHold(args) {
27622
27972
  heavyStepTokens,
27623
27973
  capPercentage
27624
27974
  };
27625
- if (!(args.usagePercentage < capPercentage))
27626
- return { held: false, reason: "above_cap", heavyStepsBack, heavyStepTokens, capPercentage };
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 };
27627
27982
  return {
27628
27983
  held: true,
27629
27984
  reason: "heavy_reasoning",
@@ -27632,6 +27987,11 @@ function decideSignedThinkingHold(args) {
27632
27987
  capPercentage
27633
27988
  };
27634
27989
  }
27990
+ function readingEndsHold(args) {
27991
+ if (!(args.usagePercentage < args.capPercentage))
27992
+ return "above_cap";
27993
+ return args.forceBandPressure ? "force_band" : null;
27994
+ }
27635
27995
 
27636
27996
  // ../plugin/src/hooks/magic-context/strict-thinking-prefix.ts
27637
27997
  function servedPrefixMatches(args) {
@@ -29954,11 +30314,11 @@ async function embedAndStoreCompartmentChunks(db, sessionId, projectPath, compar
29954
30314
  if (currentModelId !== "off" && chunkEmbeddingWindowsAreCurrent2(db, compartment.id, currentModelId, windows, projectPath)) {
29955
30315
  continue;
29956
30316
  }
29957
- const result = await embedItemsForProject2(projectPath, windows.map((window) => ({
30317
+ const result = await embedItemsWindowBounded2(projectPath, windows.map((window) => ({
29958
30318
  id: `chunk:${compartment.id}:${window.windowIndex}`,
29959
30319
  text: window.text,
29960
30320
  contentSha256: contentSha2562(window.text)
29961
- })), undefined, db, sessionId);
30321
+ })), undefined, db, sessionId, { stopOnIncompleteSlice: true });
29962
30322
  if (!result)
29963
30323
  continue;
29964
30324
  if (chunkEmbeddingWindowsAreCurrent2(db, compartment.id, currentModelId, windows, projectPath)) {
@@ -30057,7 +30417,7 @@ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
30057
30417
 
30058
30418
  // src/pi-history-retirement.ts
30059
30419
  var KEY2 = "piHistorianRetirement";
30060
- function readState(db, sessionId) {
30420
+ function readState2(db, sessionId) {
30061
30421
  const row = db.prepare("SELECT deferred_execute_state AS state FROM session_meta WHERE session_id = ?").get(sessionId);
30062
30422
  const state = row?.state ? JSON.parse(row.state) : {};
30063
30423
  if (!state || typeof state !== "object" || Array.isArray(state))
@@ -30065,17 +30425,17 @@ function readState(db, sessionId) {
30065
30425
  return state;
30066
30426
  }
30067
30427
  function readPiHistoryRetirement(db, sessionId) {
30068
- const target = readState(db, sessionId)[KEY2];
30428
+ const target = readState2(db, sessionId)[KEY2];
30069
30429
  return typeof target === "string" && target.length > 0 ? target : null;
30070
30430
  }
30071
30431
  function queuePiHistoryRetirement(db, sessionId, throughMessageId) {
30072
30432
  ensureSessionMetaRow(db, sessionId);
30073
- const state = readState(db, sessionId);
30433
+ const state = readState2(db, sessionId);
30074
30434
  state[KEY2] = throughMessageId;
30075
30435
  db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(state), sessionId);
30076
30436
  }
30077
30437
  function acknowledgePiHistoryRetirement(db, sessionId, publishedEnd, ordinalOf) {
30078
- const state = readState(db, sessionId);
30438
+ const state = readState2(db, sessionId);
30079
30439
  const target = state[KEY2];
30080
30440
  if (typeof target !== "string")
30081
30441
  return;
@@ -34322,6 +34682,7 @@ function piImageFromDataUrl(dataUrl) {
34322
34682
  return null;
34323
34683
  return { type: "image", mimeType: match[1], data: match[2] };
34324
34684
  }
34685
+ var PI_IMAGE_DATA_URL_PREFIX = /^data:image\/[a-zA-Z0-9.+-]+;base64,[\s\S]/;
34325
34686
  function resolveMuralForM0Pi(state, db, modelKey, budgetTokens, mode = "persist") {
34326
34687
  if (state.memoryEnabled === false)
34327
34688
  return;
@@ -34690,6 +35051,7 @@ function materializeM0Pi(state, db, passSnapshot) {
34690
35051
  const upgradeIdentity = withCachedM0MemoryIds(encodeCachedM0UpgradeIdentity(snapshotMarkers.upgradeState, snapshotMarkers.compartmentRenderEpoch, snapshotMarkers.muralEnabled, snapshotMarkers.renderBudgetIdentity, snapshotMarkers.memoryRenderEpoch, snapshotMarkers.renderedBudgets ?? null), renderedMemoryIds);
34691
35052
  steps.mark("pre_metadata");
34692
35053
  state.beforeCacheCommitForTest?.();
35054
+ const commitFold = state.onFoldPrepare?.();
34693
35055
  try {
34694
35056
  db.exec("BEGIN IMMEDIATE");
34695
35057
  } catch (error) {
@@ -34739,6 +35101,15 @@ function materializeM0Pi(state, db, passSnapshot) {
34739
35101
  steps.mark("persistCachedM0");
34740
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);
34741
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
+ }
34742
35113
  db.exec("COMMIT");
34743
35114
  steps.mark("commit");
34744
35115
  logSlowWriteTransaction("pi_materialize_cache", transactionStartedAt, undefined, performance.now(), steps.durations);
@@ -35523,6 +35894,12 @@ var RESPONSES_APIS = new Set([
35523
35894
  function isPiDropPlaceholder(text) {
35524
35895
  return DROP_PLACEHOLDER.test(text);
35525
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
+ }
35526
35903
  function getNativeEnvelope(message) {
35527
35904
  if (!isRecord(message) || isPiSystemEntry(message))
35528
35905
  return;
@@ -35649,12 +36026,11 @@ function hookRewrittenSlot(previous, partIndex, items) {
35649
36026
  return;
35650
36027
  continue;
35651
36028
  }
35652
- const stripped = stripPersistedAssistantText(slot.text);
35653
- if (stripped !== block.text.replace(TAG_LABEL, ""))
36029
+ if (!hookCleanedTextMatchesBlock(slot.text, block.text))
35654
36030
  return;
35655
36031
  if (index !== partIndex)
35656
36032
  continue;
35657
- if (stripped === slot.text || item.content.length !== 1)
36033
+ if (item.content.length !== 1)
35658
36034
  return;
35659
36035
  target = slot;
35660
36036
  }
@@ -35744,7 +36120,7 @@ function rewriteNativeAssistantTexts(message, previous, sessionId, options = {})
35744
36120
  return;
35745
36121
  const content = envelope.message.content;
35746
36122
  const arrivedItems = envelope.items;
35747
- const unsignedDrops = options.unsignedDrops === true && RESPONSES_APIS.has(String(envelope.message.api)) && envelope.payload.dt === true;
36123
+ const unsignedEdits = options.unsignedEdits === true && RESPONSES_APIS.has(String(envelope.message.api)) && envelope.payload.dt === true;
35748
36124
  for (let index = 0;index < content.length; index++) {
35749
36125
  const part = content[index];
35750
36126
  const before = previous.content[index];
@@ -35753,14 +36129,14 @@ function rewriteNativeAssistantTexts(message, previous, sessionId, options = {})
35753
36129
  if (part.text.replace(/^§\d+§ /u, "") === before.text.replace(/^§\d+§ /u, ""))
35754
36130
  continue;
35755
36131
  const identity = textIdentity(part);
35756
- if (identity === undefined && unsignedDrops && isPiDropPlaceholder(part.text) && !("textSignature" in part)) {
36132
+ if (identity === undefined && unsignedEdits && !("textSignature" in part)) {
35757
36133
  const slot = hookRewrittenSlot(previous.content, index, arrivedItems);
35758
36134
  if (slot) {
35759
36135
  const item = envelope.items[slot.itemIndex];
35760
36136
  const outputs = item.content.slice();
35761
36137
  outputs[slot.outputIndex] = {
35762
36138
  ...outputs[slot.outputIndex],
35763
- text: part.text
36139
+ text: part.text.replace(TAG_LABEL, "")
35764
36140
  };
35765
36141
  const items = envelope.items.slice();
35766
36142
  items[slot.itemIndex] = { ...item, content: outputs };
@@ -36136,15 +36512,9 @@ function authorizePiToolRemoval(args) {
36136
36512
 
36137
36513
  // src/native-replay-tag-provenance-pi.ts
36138
36514
  import { createHash as createHash13 } from "node:crypto";
36139
- var PI_NATIVE_TAG_STRIP_PROVENANCE = "magicContextNativeTagStrips";
36140
36515
  function nativeResponseTagStripKey(id, phase, text) {
36141
36516
  return createHash13("sha256").update(JSON.stringify([id, phase, text])).digest("hex");
36142
36517
  }
36143
- function ownsNativeResponseTagStrip(decisions, id, phase, text) {
36144
- if (!isRecord(decisions) || phase !== undefined && phase !== "commentary" && phase !== "final_answer")
36145
- return false;
36146
- return Object.entries(decisions).some(([key, original]) => typeof original === "string" && /^§\d+§ /u.test(original) && original.replace(/^§\d+§ /u, "") === text && nativeResponseTagStripKey(id, phase, original) === key);
36147
- }
36148
36518
 
36149
36519
  // src/native-replay-tags-pi.ts
36150
36520
  var FIELD = "piResponsesTagStrips";
@@ -36192,7 +36562,6 @@ function applyNativeResponseTagReplayPi(args) {
36192
36562
  const frozen = saved;
36193
36563
  const content = message.content;
36194
36564
  const nativeItems = payload.items;
36195
- const decisions = {};
36196
36565
  let changed = false;
36197
36566
  const items = nativeItems.map((item) => {
36198
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)
@@ -36215,7 +36584,6 @@ function applyNativeResponseTagReplayPi(args) {
36215
36584
  return item;
36216
36585
  added.add(key);
36217
36586
  }
36218
- decisions[key] = output.text;
36219
36587
  changed = true;
36220
36588
  return {
36221
36589
  ...item,
@@ -36225,7 +36593,6 @@ function applyNativeResponseTagReplayPi(args) {
36225
36593
  if (changed)
36226
36594
  pending.set(index, {
36227
36595
  ...message,
36228
- [PI_NATIVE_TAG_STRIP_PROVENANCE]: decisions,
36229
36596
  providerPayload: { ...payload, items }
36230
36597
  });
36231
36598
  }
@@ -37415,7 +37782,7 @@ function coldReplayable(items) {
37415
37782
  }
37416
37783
  return reasoning;
37417
37784
  }
37418
- function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagStrips) {
37785
+ function piResponsesAssistantTexts(value, model, host, alternatives) {
37419
37786
  const message = object8(value);
37420
37787
  if (!message || !Array.isArray(message.content))
37421
37788
  return;
@@ -37478,8 +37845,6 @@ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagSt
37478
37845
  "openai-codex-responses"
37479
37846
  ].includes(model?.api ?? "");
37480
37847
  let unsigned = false;
37481
- let rewrittenText = false;
37482
- let allUnsignedFrozen = true;
37483
37848
  for (const value of payload.items) {
37484
37849
  const item = object8(value);
37485
37850
  if (item?.type === "reasoning")
@@ -37505,15 +37870,12 @@ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagSt
37505
37870
  } catch {
37506
37871
  return texts;
37507
37872
  }
37508
- const signed = signature?.v === 1 && typeof signature.id === "string" && item.id === signature.id && item.phase === signature.phase && part.text === block.text.replace(/^§\d+§ /u, "");
37873
+ const signed = signature?.v === 1 && typeof signature.id === "string" && item.id === signature.id && item.phase === signature.phase && nativeTextMatchesBlock(part.text, block.text);
37509
37874
  if (!signed) {
37510
- const stripped = stripPersistedAssistantText(part.text);
37511
37875
  const droppedPlaceholder = isPiDropPlaceholder(block.text) && part.text === block.text;
37512
- if (!allowUnsigned || "textSignature" in block || !droppedPlaceholder && stripped !== block.text.replace(/^§\d+§ /u, ""))
37876
+ if (!allowUnsigned || "textSignature" in block || !droppedPlaceholder && !hookCleanedTextMatchesBlock(part.text, block.text))
37513
37877
  return texts;
37514
37878
  unsigned = true;
37515
- allUnsignedFrozen &&= droppedPlaceholder || part.text === block.text && ownsNativeResponseTagStrip(frozenTagStrips, item.id, item.phase, part.text);
37516
- rewrittenText ||= !droppedPlaceholder && part.text !== stripped;
37517
37879
  }
37518
37880
  bound++;
37519
37881
  itemTexts.push(part.text);
@@ -37524,7 +37886,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagSt
37524
37886
  for (const text of itemTexts)
37525
37887
  replay.push(textIdentity2(wellFormed2(text), item.phase));
37526
37888
  }
37527
- if (!output || bound !== blocks.length || unsigned && !rewrittenText && !allUnsignedFrozen)
37889
+ if (!output || bound !== blocks.length)
37528
37890
  return texts;
37529
37891
  if (unsigned && alternatives) {
37530
37892
  alternatives.fallback = texts;
@@ -38256,7 +38618,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38256
38618
  continue;
38257
38619
  }
38258
38620
  const alternatives = {};
38259
- const texts = piResponsesAssistantTexts(projectedMessages[index], model, host, alternatives, object10(projectedMessages[index])?.[PI_NATIVE_TAG_STRIP_PROVENANCE]);
38621
+ const texts = piResponsesAssistantTexts(projectedMessages[index], model, host, alternatives);
38260
38622
  if (!texts) {
38261
38623
  responsesMessages = undefined;
38262
38624
  break;
@@ -42370,6 +42732,26 @@ function releasePiOperationPayloads(operation) {
42370
42732
  function operationKey(ctx) {
42371
42733
  return ctx.sessionManager?.getSessionId?.() ?? ctx.sessionManager ?? "no-session";
42372
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
+ }
42373
42755
  function messageKey(message) {
42374
42756
  if (!message || typeof message !== "object")
42375
42757
  return;
@@ -42440,7 +42822,14 @@ function inputBranch(ctx, inputs) {
42440
42822
  return;
42441
42823
  }
42442
42824
  }
42443
- function dispatchedEndBelongsToEarlierRun(operation, event, ctx) {
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) {
42444
42833
  if (!operation.dispatched || !operation.started || !operation.ready || !operation.pass?.completed || operation.refused || operation.pass.abandoned || !operation.inputBranch)
42445
42834
  return false;
42446
42835
  try {
@@ -42450,9 +42839,16 @@ function dispatchedEndBelongsToEarlierRun(operation, event, ctx) {
42450
42839
  const prepared = operation.inputBranch;
42451
42840
  if (!current || current.entryIds[prepared.anchorIndex] !== prepared.anchorId || current.messages.length !== prepared.messages.length || exactReusablePrefix(current.messages, prepared.messages) !== prepared.messages.length)
42452
42841
  return false;
42453
- const messages = event?.messages;
42842
+ const end = event;
42843
+ const messages = end?.messages;
42454
42844
  const ended = Array.isArray(messages) ? messageSnapshots(messages) : undefined;
42455
- return !!(ended && ended.length <= prepared.anchorIndex && ended.length < prepared.messages.length && exactReusablePrefix(prepared.messages, ended) === ended.length);
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;
42456
42852
  } catch {
42457
42853
  return false;
42458
42854
  }
@@ -42556,7 +42952,7 @@ function registerPiGuardedContext(pi, handler, options = {}) {
42556
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"}`);
42557
42953
  const operation = operations.get(key);
42558
42954
  if (operation) {
42559
- if (endBelongsToEarlierRun(operation, event) || lifecycleSeen.starts > lifecycleSeen.ends && dispatchedEndBelongsToEarlierRun(operation, event, ctx)) {
42955
+ if (endBelongsToEarlierRun(operation, event) || dispatchedEndBelongsToEarlierRun(operation, event, ctx, lifecycleSeen.starts > lifecycleSeen.ends)) {
42560
42956
  if (operation.dispatched)
42561
42957
  operation.retainedAfterEnd = true;
42562
42958
  if (lifecycleSeen.starts <= lifecycleSeen.ends)
@@ -42766,6 +43162,9 @@ function registerPiGuardedContext(pi, handler, options = {}) {
42766
43162
  active.ready = false;
42767
43163
  active.refused = false;
42768
43164
  active.refusalMessage = undefined;
43165
+ const servedSessionId = budget.sideTurn ? undefined : servedSessionOf(ctx);
43166
+ if (servedSessionId)
43167
+ beginServedRequest(servedSessionId);
42769
43168
  const { isOwned, isCurrent, assertOwner } = createPiContextOwnershipGuards(operations, key, active, budget, owner);
42770
43169
  budget.assertOwner = assertOwner;
42771
43170
  try {
@@ -42801,8 +43200,12 @@ function registerPiGuardedContext(pi, handler, options = {}) {
42801
43200
  if (inputs)
42802
43201
  active.inputBranch = inputBranch(ctx, inputs);
42803
43202
  }
43203
+ if (servedSessionId)
43204
+ finishPiServedRequest(servedSessionId, ctx, result?.messages ?? event.messages, () => options.compactionOff?.(ctx) === true);
42804
43205
  return result;
42805
43206
  } catch (error) {
43207
+ if (servedSessionId)
43208
+ countServedRefusal(servedSessionId);
42806
43209
  if (budget.isCancelled(error)) {
42807
43210
  budget.cancel();
42808
43211
  if (isOwned())
@@ -44661,7 +45064,7 @@ function handlePiProviderFailure(args) {
44661
45064
  const model = typeof message.model === "string" ? message.model : undefined;
44662
45065
  const binding = detectThinkingBindingMismatch(message.errorMessage);
44663
45066
  if (detectLatestTurnThinkingMismatch(message.errorMessage) && !args.compactionOff && isAnthropicFamilyRoute(provider, model)) {
44664
- armLatestThinkingRecovery(args.db, args.sessionId);
45067
+ armLatestThinkingRecovery(args.db, args.sessionId, model);
44665
45068
  clearPiLkgSessionState(args.sessionId);
44666
45069
  dropSlot(args.sessionId, "latest-thinking-recovery-arm");
44667
45070
  return { kind: "thinking_binding", armed: true };
@@ -44733,7 +45136,6 @@ class PiThinkingBindingRecoveryRefusal extends EmergencyFailClosedError {
44733
45136
  }
44734
45137
  }
44735
45138
  function applyPiThinkingBindingRecovery(args) {
44736
- const protectedMessages = latestAssistantTurnMessages(args.messages);
44737
45139
  const frozenEntryIds = frozenBindingEntryIds(args.db, args.sessionId);
44738
45140
  const flagTargetCandidate = !args.replayOnly && isPrefixBoundThinkingModel(args.provider, args.model) ? getThinkingBindingRecoveryTarget(args.db, args.sessionId) : null;
44739
45141
  const flagTarget = flagTargetCandidate?.startsWith(LATEST_THINKING_RESTORE) ? null : flagTargetCandidate;
@@ -44762,14 +45164,14 @@ function applyPiThinkingBindingRecovery(args) {
44762
45164
  } else
44763
45165
  throw new PiThinkingBindingRecoveryRefusal;
44764
45166
  }
44765
- const restoringActiveTurn = latestThinkingRecoveryCoversActiveTurn({
45167
+ const restoringTurn = latestThinkingRestoringTurnMessages({
44766
45168
  db: args.db,
44767
45169
  sessionId: args.sessionId,
44768
45170
  messages: args.messages,
44769
45171
  id: (message, index) => resolvePiStableId(message, index, args.entryIds)
44770
45172
  });
44771
45173
  for (let index = 0;index < args.messages.length; index += 1) {
44772
- if (restoringActiveTurn && protectedMessages.has(args.messages[index]))
45174
+ if (restoringTurn?.has(args.messages[index]))
44773
45175
  continue;
44774
45176
  const entryId = args.entryIds[index];
44775
45177
  if (entryId && frozenEntryIds.has(entryId))
@@ -44839,6 +45241,26 @@ function frozenBindingEntryIds(db, sessionId) {
44839
45241
  }
44840
45242
  return ids;
44841
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
+ }
44842
45264
  function resolvePiBindingStripOrder(args) {
44843
45265
  const ledger = getMergedReasoningStrippedIds(args.db, args.sessionId);
44844
45266
  if (ledger.has(THINKING_BINDING_STRIP_ORDER_END_MARKER))
@@ -45876,7 +46298,7 @@ function createPiTranscript(source, sessionId, entryIds, options = {}) {
45876
46298
  committed = true;
45877
46299
  for (const index of dirtyMessages) {
45878
46300
  rewriteNativeAssistantTexts(working[index], source[index], sessionId, {
45879
- unsignedDrops: harness === "omp"
46301
+ unsignedEdits: harness === "omp"
45880
46302
  });
45881
46303
  }
45882
46304
  for (const [index, parts] of removals) {
@@ -48183,6 +48605,16 @@ function registerPiContextHandler(pi, baseOptions) {
48183
48605
  return;
48184
48606
  }
48185
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
+ };
48186
48618
  try {
48187
48619
  const tFindSession = performance.now();
48188
48620
  const sessionId = resolveSessionId2(ctx);
@@ -48775,7 +49207,12 @@ function registerPiContextHandler(pi, baseOptions) {
48775
49207
  messages: event.messages,
48776
49208
  prefixBound: isPrefixBoundThinkingModel(ctx.model?.provider, ctx.model?.id),
48777
49209
  usagePercentage,
48778
- executeThresholdPercentage: effectiveExecuteThresholdPercentage
49210
+ executeThresholdPercentage: effectiveExecuteThresholdPercentage,
49211
+ forceBandPressure: !options.compactionOff && piForceBandPressure({
49212
+ forceMaterialization: forceMaterialization || isEmergency,
49213
+ percentage: usagePercentage,
49214
+ forceMaterializationPercentage
49215
+ })
48779
49216
  }),
48780
49217
  requestToolsChange,
48781
49218
  contextUsage: {
@@ -48913,13 +49350,13 @@ function registerPiContextHandler(pi, baseOptions) {
48913
49350
  assertCurrentPass();
48914
49351
  recordSuccessfulTaggedMessageIds(sessionId, taggedInputEntryIds ?? strictEntryIds, branchEntries);
48915
49352
  }
48916
- const piDecisionSnapshotNewestAssistant = result.bustedThisPass || hasPendingPiSystemPromptHashChange(sessionId) ? findNewestPiAssistantEntryId(branchEntries) : undefined;
49353
+ const piDecisionSnapshotNewestAssistant = result.bustedThisPass || result.latestTurnThinkingRemoved === true || hasPendingPiSystemPromptHashChange(sessionId) ? findNewestPiAssistantEntryId(branchEntries) : undefined;
48917
49354
  const publishTransformDecision = !budget.sideTurn && piDecisionSnapshotNewestAssistant !== undefined ? () => {
48918
49355
  recordPendingPiTransformDecision(sessionId, {
48919
49356
  tsMs: Date.now(),
48920
49357
  decision: schedulerDecision,
48921
49358
  materialized: result.materialized,
48922
- materializeReason: normalizeMaterializeReason("pi", result.materializeReason, result.materialized),
49359
+ materializeReason: normalizeMaterializeReason("pi", result.materializeReason ?? (result.latestTurnThinkingRemoved ? LATEST_TURN_THINKING_REMOVED_REASON : null), result.materialized),
48923
49360
  systemHashPrev: result.materialized ? result.injectionResult?.systemHashPrev ?? null : null,
48924
49361
  systemHashNew: result.materialized ? result.injectionResult?.systemHashNew ?? null : null,
48925
49362
  m0ModelKeyPrev: result.materialized ? result.injectionResult?.m0ModelKeyPrev ?? null : null,
@@ -49429,6 +49866,8 @@ function registerPiContextHandler(pi, baseOptions) {
49429
49866
  }
49430
49867
  }
49431
49868
  publishFinalRequestAccounting();
49869
+ if (!budget.sideTurn && (result.strictThinkingKept && !result.signedPrefixRewritten || result.heldHeadReleasedForSystemChange === true) && !result.materialized)
49870
+ recordPiHeldSystemHead(sessionId, (ownsHistory) => deferPiDeliveredSystemRefresh(sessionId, ownsHistory));
49432
49871
  let serializedOutput;
49433
49872
  let numbersCommitted = false;
49434
49873
  budget.stage = "LKG/served publication";
@@ -49503,7 +49942,7 @@ function registerPiContextHandler(pi, baseOptions) {
49503
49942
  if (!budget.sideTurn && result.identityRebuilt && (numbersCommitted || lkgCompactionOff))
49504
49943
  acknowledgePiIdentityRebuilds(options.db, sessionId);
49505
49944
  if (!budget.sideTurn)
49506
- 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));
49507
49946
  if (thinkingBindingRecoveryApplied) {
49508
49947
  try {
49509
49948
  clearThinkingBindingRecoveryIf(options.db, sessionId, thinkingBindingRecoveryApplied.flagTarget);
@@ -49512,14 +49951,14 @@ function registerPiContextHandler(pi, baseOptions) {
49512
49951
  }
49513
49952
  }
49514
49953
  budget.assertOutcome();
49515
- publishTransformDecision?.();
49516
- if (requestToolsChange === null || recordPiBindingStripEndOrder(options.db, sessionId))
49517
- requestToolsRelease?.commit();
49518
- else
49519
- sessionLog2(sessionId, "request tools release not recorded: the end strip order could not be written");
49520
- if (!budget.sideTurn && (result.strictThinkingKept && !result.signedPrefixRewritten || result.heldHeadReleasedForSystemChange === true) && !result.materialized)
49521
- recordPiHeldSystemHead(sessionId, (ownsHistory) => deferPiDeliveredSystemRefresh(sessionId, ownsHistory));
49522
- 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);
49523
49962
  return { messages: outputMessages };
49524
49963
  } catch (err) {
49525
49964
  if (budget.isCancelled(err))
@@ -49553,6 +49992,7 @@ function registerPiContextHandler(pi, baseOptions) {
49553
49992
  budget.assertOutcome();
49554
49993
  budget.recovery = err.recovery;
49555
49994
  recordServedSystemHash();
49995
+ noteServedReplay(sessionIdForError);
49556
49996
  return { messages: err.messages };
49557
49997
  }
49558
49998
  if ((isFailClosedBlockingError(err) || err instanceof EmergencyFailClosedError) && !baseOptions.compactionOff)
@@ -49621,6 +50061,7 @@ function registerPiContextHandler(pi, baseOptions) {
49621
50061
  budget.assertOutcome();
49622
50062
  budget.recovery = "fitting LKG replay";
49623
50063
  recordServedSystemHash();
50064
+ noteServedReplay(sessionIdForError);
49624
50065
  return { messages: replay.messages };
49625
50066
  }
49626
50067
  logPiLkgRecovery(sessionIdForError, `${failureLabel} ${piStorageErrorReason(err)}: LKG unavailable (${replay.reason}); refusing unreduced ${rawMessageCount}-message input`);
@@ -50244,9 +50685,31 @@ function captureReasoningMutationRollback(messages) {
50244
50685
  }
50245
50686
  };
50246
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
+ }
50247
50705
  async function runCompactionOffPipeline(args) {
50248
50706
  let injectionResult = null;
50249
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
+ };
50250
50713
  let headChangedUnderSignedThinking = false;
50251
50714
  if (args.injection) {
50252
50715
  const state = {
@@ -50265,13 +50728,44 @@ async function runCompactionOffPipeline(args) {
50265
50728
  if (signedTurnHoldsHead)
50266
50729
  state.preparedPrefix = prepareCachedM0M1PiReplay(state, args.db, args.injectionPassSnapshot?.cachedRow);
50267
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
+ }
50268
50762
  injectionResult = injectM0M1Pi(state, args.db, args.messages, args.entryIds, false, args.injectionPassSnapshot);
50269
50763
  if (servedBeforeFirstRender !== undefined) {
50270
50764
  const headCount = injectionResult?.syntheticLeadingCount ?? 0;
50271
50765
  const head = JSON.stringify(args.messages.slice(0, headCount));
50272
50766
  headChangedUnderSignedThinking = servedBeforeFirstRender === null || JSON.stringify(servedBeforeFirstRender.slice(0, headCount)) !== head;
50273
50767
  } else if (!signedTurnHoldsHead && args.reasoningClearing?.prefixBound === true && (injectionResult?.m0Materialized === true || injectionResult?.m1RenderedCoverage != null)) {
50274
- const served = args.readLastServedMessages?.() ?? null;
50768
+ const served = readLastServed();
50275
50769
  const headCount = injectionResult?.syntheticLeadingCount ?? 0;
50276
50770
  headChangedUnderSignedThinking = served === null || JSON.stringify(served.slice(0, headCount)) !== JSON.stringify(args.messages.slice(0, headCount));
50277
50771
  if (headChangedUnderSignedThinking)
@@ -50283,7 +50777,7 @@ async function runCompactionOffPipeline(args) {
50283
50777
  db: args.db,
50284
50778
  sessionId: args.sessionId,
50285
50779
  messages: transcript,
50286
- entryIds: transcript.map((message, index) => resolvePiRealStableId(message, index, args.entryIds, args.entryIdByRef ?? undefined)),
50780
+ entryIds: stripEntryIds(),
50287
50781
  provider: args.resolvedProviderID,
50288
50782
  model: args.resolvedModelID,
50289
50783
  cacheBustingPass: true,
@@ -50326,6 +50820,9 @@ async function runCompactionOffPipeline(args) {
50326
50820
  };
50327
50821
  }
50328
50822
  var signedThinkingHoldLogKeys = new Map;
50823
+ function piForceBandPressure(args) {
50824
+ return args.forceMaterialization === true || args.percentage >= args.forceMaterializationPercentage;
50825
+ }
50329
50826
  function resolvePiSignedThinkingHold(args) {
50330
50827
  if (!args.prefixBound)
50331
50828
  return false;
@@ -50334,6 +50831,7 @@ function resolvePiSignedThinkingHold(args) {
50334
50831
  messages: args.messages,
50335
50832
  usagePercentage: args.usagePercentage,
50336
50833
  executeThresholdPercentage: args.executeThresholdPercentage,
50834
+ forceBandPressure: args.forceBandPressure,
50337
50835
  estimateTextTokens: (text) => {
50338
50836
  proseRatio ??= sessionDecisionCalibration(args.db, args.sessionId).proseRatio;
50339
50837
  return estimateTokens(text) * proseRatio;
@@ -50354,13 +50852,26 @@ async function runPipeline(args) {
50354
50852
  const dropBranchIds = dropBranchEntries ? piDropBranchIds(dropBranchEntries) : null;
50355
50853
  trackPiDropLeaf(args.db, args.sessionId, dropBranchIds ? [...dropBranchIds].at(-1) ?? null : null);
50356
50854
  cancelPiAbandonedPendingDrops(args.db, args.sessionId, dropBranchIds);
50855
+ const piStableId = (message, index) => resolvePiStableId(message, index, args.entryIds, args.entryIdByRef ?? undefined);
50856
+ let stripRemovedTurnNow = false;
50357
50857
  const thinkingRecovery = prepareLatestThinkingRecovery({
50358
50858
  db: args.db,
50359
50859
  sessionId: args.sessionId,
50360
50860
  messages: args.messages,
50361
- id: (message, index) => resolvePiStableId(message, index, args.entryIds, args.entryIdByRef ?? undefined),
50362
- parts: (message) => Array.isArray(message?.content) ? message.content : []
50363
- });
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);
50364
50875
  if (thinkingRecovery.ended)
50365
50876
  signalPiPendingMaterialization(args.sessionId, "thinking_hold");
50366
50877
  let restoreOriginals;
@@ -50491,7 +51002,11 @@ async function runPipeline(args) {
50491
51002
  lastResponseTime: hardMeta.lastResponseTime
50492
51003
  };
50493
51004
  })() : undefined;
50494
- const emergencyDropEligible = args.forceMaterialization === true || args.contextUsage.percentage >= forceMaterializationPercentage;
51005
+ const emergencyDropEligible = piForceBandPressure({
51006
+ forceMaterialization: args.forceMaterialization,
51007
+ percentage: args.contextUsage.percentage,
51008
+ forceMaterializationPercentage
51009
+ });
50495
51010
  const piM0State = args.injection && piHardSignals ? {
50496
51011
  sessionId: args.sessionId,
50497
51012
  projectIdentity: args.projectIdentity,
@@ -50677,6 +51192,16 @@ async function runPipeline(args) {
50677
51192
  let prefixMutationAllowed = prefixMutationPermitted(ridePermissionGate);
50678
51193
  isCacheBustingPass = reclaimRidePermitted(rideSignals, ridePermissionGate);
50679
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();
50680
51205
  stripUnheldSignedTurnOnBust();
50681
51206
  const usesTokenProtection = args.protectedTokenTierOverrides !== undefined || args.protectedTokens !== undefined;
50682
51207
  const resolveProtectionFloor = () => resolveEpochFloorForPass(args.db, args.sessionId, {
@@ -50752,6 +51277,7 @@ async function runPipeline(args) {
50752
51277
  deferredMaterializeEligible = canConsumeDeferredLate && deferredMaterializationSessions.has(args.sessionId);
50753
51278
  isCacheBustingPass = prefixMutationAllowed;
50754
51279
  publishedWorkDrainAllowed = isCacheBustingPass;
51280
+ noteServedPermission();
50755
51281
  stripUnheldSignedTurnOnBust();
50756
51282
  shouldRunHeuristics = args.heuristics !== undefined;
50757
51283
  if (piM0State && prefixMutationAllowed) {
@@ -50854,22 +51380,10 @@ async function runPipeline(args) {
50854
51380
  }
50855
51381
  }
50856
51382
  }
50857
- let newTargets = new Map(protectNewTagMutations(mutationView.map((message) => ({
51383
+ const newTargets = new Map(protectNewTagMutations(mutationView.map((message) => ({
50858
51384
  info: message.info,
50859
51385
  parts: message.parts
50860
51386
  })), targets, protectedThinkingProxies, args.reasoningClearing?.prefixBound === true));
50861
- if (protectedSignedPrefix && args.contextUsage.percentage >= 95 && !args.upperEstimateOnly) {
50862
- const candidates = getActiveTagsBySession2(args.db, args.sessionId).filter((tag) => tag.type === "tool" && targets.get(tag.tagNumber)?.canDrop?.());
50863
- if (candidates.length > 0 && candidates.every((tag) => newTargets.get(tag.tagNumber)?.thinkingRewriteProtected === true)) {
50864
- stripForPrefixRewrite();
50865
- newTargets = targets;
50866
- prefixMutationAllowed = true;
50867
- isCacheBustingPass = true;
50868
- publishedWorkDrainAllowed = true;
50869
- shouldRunHeuristics = args.heuristics !== undefined;
50870
- hasPendingMaterializeSignal = hasPendingMaterialization(args.sessionId);
50871
- }
50872
- }
50873
51387
  for (const number of identityAdoption.protectedTagNumbers) {
50874
51388
  if (rewritingSignedPrefix)
50875
51389
  break;
@@ -51043,6 +51557,7 @@ async function runPipeline(args) {
51043
51557
  if (rideSignals.executeReclaim) {
51044
51558
  isCacheBustingPass = reclaimRidePermitted(rideSignals, ridePermissionGate);
51045
51559
  publishedWorkDrainAllowed = isCacheBustingPass;
51560
+ noteServedPermission();
51046
51561
  shouldRunHeuristics ||= isCacheBustingPass && args.heuristics !== undefined;
51047
51562
  stripUnheldSignedTurnOnBust();
51048
51563
  applyTemporalOnRide();
@@ -51843,6 +52358,8 @@ async function runPipeline(args) {
51843
52358
  }
51844
52359
  if (bustedThisPass)
51845
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);
51846
52363
  return {
51847
52364
  messages: outputMessages,
51848
52365
  recoveryNormalized,
@@ -51863,6 +52380,7 @@ async function runPipeline(args) {
51863
52380
  injectionResult,
51864
52381
  materialized,
51865
52382
  materializeReason,
52383
+ latestTurnThinkingRemoved: thinkingRecovery.removedThisPass === true,
51866
52384
  droppedTokens,
51867
52385
  droppedCount,
51868
52386
  emergency,
@@ -52101,6 +52619,7 @@ function clearPiCompactionOffInMemoryState(sessionId) {
52101
52619
  clearPiChannel1State(sessionId);
52102
52620
  }
52103
52621
  function clearContextHandlerSession(sessionId) {
52622
+ dropServedRecord(sessionId, "session_cleared");
52104
52623
  cancelPiTagSnapshotSession(sessionId);
52105
52624
  lastServedSystemHashBySession.delete(sessionId);
52106
52625
  clearPiHistoryBoundaryRepairSession(sessionId);
@@ -55525,7 +56044,7 @@ function strippedAssistantContent(content, provider = "anthropic") {
55525
56044
  if (part === null || typeof part !== "object" || part.type !== "text") {
55526
56045
  continue;
55527
56046
  }
55528
- if (typeof part.text !== "string")
56047
+ if (typeof part.text !== "string" || !part.text.includes("§"))
55529
56048
  continue;
55530
56049
  const stripped = stripPersistedAssistantText(part.text, provider === "anthropic");
55531
56050
  if (stripped === part.text)