@cortexkit/pi-magic-context 0.49.53 → 0.49.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +3 -4
  3. package/dist/{embedding-backfill-ad4k8e3f.js → embedding-backfill-qde2zywg.js} +4 -4
  4. package/dist/embedding-worker.js +2 -2
  5. package/dist/{index-snrkpmpf.js → index-2pptpxq8.js} +1 -1
  6. package/dist/{index-8cgk0pyh.js → index-5n3e2gq5.js} +5080 -3919
  7. package/dist/{index-tv9pqeek.js → index-625kbnqd.js} +5 -7
  8. package/dist/{index-4cmj48mq.js → index-6ahmfva8.js} +3 -3
  9. package/dist/{index-nevbaezn.js → index-9kaj9ty1.js} +1 -1
  10. package/dist/{index-46wk0td0.js → index-awpx91y5.js} +1 -1
  11. package/dist/{index-1tk6065b.js → index-c3mms4dp.js} +5 -5
  12. package/dist/{index-zc6fdyx7.js → index-d40ecdbn.js} +1 -1
  13. package/dist/{index-2yjpxzga.js → index-erkb5dee.js} +2 -2
  14. package/dist/{index-38pf5bqw.js → index-hec3bwev.js} +1 -1
  15. package/dist/{index-njd3qa8e.js → index-jnh7a6a3.js} +3 -3
  16. package/dist/{index-f07s5m8x.js → index-k2z7r444.js} +21 -23
  17. package/dist/{index-pkg07s54.js → index-nhpvvdhw.js} +2 -2
  18. package/dist/index-rekymyxd.js +2287 -0
  19. package/dist/{index-a70dwgff.js → index-tn38he5d.js} +44 -31
  20. package/dist/{index-jxm4bvm4.js → index-v858d5d1.js} +168 -1
  21. package/dist/{index-aec63gtj.js → index-vcegxfwg.js} +16 -6
  22. package/dist/index.js +319 -220
  23. package/dist/{message-index-bounded-hwatm90p.js → message-index-bounded-ac4qg6aw.js} +5 -6
  24. package/dist/migration-worker.js +3 -4
  25. package/dist/{project-embedding-registry-d67axw7r.js → project-embedding-registry-qx2zjbgs.js} +3 -3
  26. package/dist/raw-ordinal-warmup-worker.js +4 -4
  27. package/dist/{read-session-chunk-mj91mv8r.js → read-session-chunk-jyfcykg4.js} +4 -5
  28. package/dist/{render-js5tkc4g.js → render-bqqx15n8.js} +9 -10
  29. package/dist/{search-archive-159s0qp9.js → search-archive-31054zxj.js} +6 -7
  30. package/dist/{search-hyc5s9t0.js → search-w12nc025.js} +11 -12
  31. package/dist/{storage-tags-ahhwtfdq.js → storage-tags-g0328gwp.js} +4 -2
  32. package/dist/subagent-entry.js +38 -17
  33. package/dist/tag-snapshot-worker-pi.js +6 -6
  34. package/dist/{v2-archive-reader-5sc0rsh9.js → v2-archive-reader-hg4c36em.js} +1 -1
  35. package/package.json +1 -1
  36. package/dist/index-674f6qs2.js +0 -16
  37. package/dist/index-c6wbq66z.js +0 -168
  38. package/dist/index-qcsjj9m0.js +0 -3412
package/dist/index.js CHANGED
@@ -141,6 +141,7 @@ import {
141
141
  restoreOmpMentions,
142
142
  resolvePiHarnessDetection,
143
143
  resolvePiHarnessKind,
144
+ readSubagentStartupError,
144
145
  resolvePiOrdinalAlignment,
145
146
  piRawOrdinalOffsetSource,
146
147
  resolvePiOrdinalAlignmentForContext,
@@ -153,7 +154,7 @@ import {
153
154
  registerTodoStateLifecycle,
154
155
  syncCtxMemoryToolEnabled,
155
156
  registerMagicContextTools
156
- } from "./index-a70dwgff.js";
157
+ } from "./index-tn38he5d.js";
157
158
  import"./index-4knyh1kt.js";
158
159
  import {
159
160
  canonicalModelIdentity,
@@ -168,10 +169,11 @@ import {
168
169
  nextOccurrence,
169
170
  nextDueAtMs,
170
171
  resolveModelConfigValue,
172
+ normalizeProtectedToolName,
171
173
  DEFAULT_HISTORIAN_TIMEOUT_MS,
172
174
  DREAM_TASK_PROMOTION_DEFAULTS,
173
175
  LIVE_RELOAD_CONFIG_PATHS
174
- } from "./index-aec63gtj.js";
176
+ } from "./index-vcegxfwg.js";
175
177
  import {
176
178
  FAIL_CLOSED_DOCTOR_COMMAND,
177
179
  formatFailClosedBlockingMessage,
@@ -200,19 +202,123 @@ import {
200
202
  MAX_EXECUTE_THRESHOLD,
201
203
  escalationBands,
202
204
  decodeMergedReasoningParts,
205
+ UNKNOWN_FIT_RATIO,
206
+ hasMeasuredDecisionCalibration,
207
+ providerMass,
208
+ localBudget,
209
+ calibrationForModelKey,
210
+ historyLocalBudget,
203
211
  HYGIENE_PROVIDER_UNITS_VERSION,
204
212
  sessionDecisionCalibration,
205
213
  transitionSessionHygieneUnits,
206
- rowWindowMass,
207
- computeProtectionWindow,
208
- readEpochFloorSnapshot,
209
- getProtectionWindowForSession,
214
+ adoptedProtectedToolsPolicy,
215
+ protectedToolTagNumbers,
216
+ protectedToolTokenCount,
217
+ stripWellFormedLeadingTagPrefix,
218
+ stripPersistedAssistantText,
219
+ byteSize,
220
+ stripTagPrefix,
221
+ peelLeadingMcTagNotation,
222
+ prependTag,
223
+ rememberCurrentToolOutputCount,
224
+ currentReclaimableToolOutputCount,
225
+ isRecord,
226
+ TEXT_TAG_IDENTITY_MARKER,
227
+ PI_FALLBACK_PREFIXES_JSON,
228
+ contentTagOwnerMessageId,
229
+ TailHygieneJsonMemo,
230
+ piJsonHash,
231
+ estimateImageTokensFromDataUrl,
232
+ TODO_STATUSES,
233
+ TODO_PRIORITIES,
234
+ normalizeTodoStateJson,
235
+ buildSyntheticTodoPart,
236
+ stripChannel1ReminderSpans,
237
+ compareMeasuredTailPrefix,
238
+ formatTailHygienePrefixMismatch,
239
+ freezeTailHygieneMeasurement,
240
+ effectiveTailHygiene,
241
+ CHANNEL1_SENTINEL,
242
+ CHANNEL1_FLOOR_TOKENS,
243
+ decideChannel1,
244
+ evaluateChannel2,
245
+ buildChannel2Reminder,
246
+ buildChannel1Reminder,
210
247
  ensureSessionMetaRow,
211
248
  persistCachedM0,
212
249
  clearCachedM0M1,
213
250
  ReplayDocumentError,
214
251
  readReplayEnvelope,
215
252
  updateReplayDocument,
253
+ getReasoningRemovalState,
254
+ modelAcceptsEmptyContent,
255
+ isAnthropicFamilyRoute,
256
+ variantChangeBustsProviderCache,
257
+ isInActiveAnthropicTurn,
258
+ activeAnthropicTurnStart,
259
+ hasAnthropicReasoning,
260
+ isMarkerOnlyText,
261
+ findLatestAssistantReasoningMutationExemptMessage,
262
+ DEFAULT_KEEP_REASONING_TOKENS,
263
+ resolveKeepReasoningTokens,
264
+ reasoningStepCost,
265
+ reasoningBudgetCutoff,
266
+ reasoningTextAndOpaque,
267
+ opaqueThinkingCost,
268
+ estimatePartImageTokens,
269
+ planEmergencyDrop,
270
+ measureEmergencyTag,
271
+ tagsSinceReading,
272
+ queuePendingDropForUnchangedTag,
273
+ getPendingOps,
274
+ getPendingOpsCount,
275
+ clearPendingOps,
276
+ removePendingOp,
277
+ updateTagByteSize2,
278
+ getRecentTagOwnerMessageIds2,
279
+ AGE_RECLAIM_MIN_TOKENS2,
280
+ getOldestActiveUnprotectedToolTags2,
281
+ getActiveToolTagsForAgeReclaim2,
282
+ getTriggerTagTokenUpperBound2,
283
+ updateTagInputByteSize2,
284
+ updateTagTokenCount2,
285
+ getPersistedToolTagAccounting2,
286
+ getAllStatusTagTokenTotalsFlat2,
287
+ tryGetReasoningTokenEstimatesByMessage2,
288
+ updateTagInputTokenCount2,
289
+ tagTokenCountIsNull2,
290
+ backfillTagTokenCounts2,
291
+ insertTag2,
292
+ updateTagStatus2,
293
+ markTagDropped2,
294
+ updateTagDropMode2,
295
+ updateCavemanDepth2,
296
+ hasPiFallbackMessageTags2,
297
+ findAdoptableFallbackTags2,
298
+ hasPiFallbackToolOwnerTags2,
299
+ findPiFallbackToolOwnerTags2,
300
+ PiTagIdentityConflictError2,
301
+ getPiMessageTagCandidates2,
302
+ findPiTagIdentityConflict2,
303
+ adoptPiFallbackToolOwnerTag2,
304
+ adoptPiFallbackMessageTag2,
305
+ getMaxTagNumberBySession2,
306
+ getAssignableTagNumberByMessageId2,
307
+ deriveTagLoadFloor2,
308
+ getTagsBySession2,
309
+ getActiveTagsBySession2,
310
+ getTagsForPendingOperations2,
311
+ getTagsByNumbers2,
312
+ getNewestToolTagNumbers2,
313
+ getDroppedTagsByNumbers2,
314
+ getMaxDroppedTagNumber2,
315
+ getToolTagNumberByOwner2,
316
+ getNullOwnerToolTag2,
317
+ adoptNullOwnerToolTag2,
318
+ rowWindowMass,
319
+ computeProtectionWindow,
320
+ readEpochFloorSnapshot,
321
+ getProtectionWindowForSession,
216
322
  isProviderOverflowFailClosedProven,
217
323
  getEmergencyRecoveryArmedAt,
218
324
  describeProtectedTailDrainBudgetSkip,
@@ -295,159 +401,8 @@ import {
295
401
  getSessionsWithPendingPiMarker,
296
402
  setSessionWorkMetrics,
297
403
  getSessionWorkMetrics,
298
- resolveEpochFloorForPass,
299
- askAnswerLines,
300
- removeUnsupportedCommitHashes,
301
- completedToolArcCrossesBoundary,
302
- estimateTrueRawMessageTokens,
303
- buildToolArcs,
304
- fenceBoundaryForCompletedToolArcs,
305
- fenceBoundaryForToolArcs,
306
- buildTrueRawTokenIndex,
307
- computeRawRangeFingerprint,
308
- invalidateTrueRawTokenCache,
309
- stripSystemInjection,
310
- isFilePart,
311
- hasUserAnswerMetadata,
312
- DreamTokenBudgetExceeded,
313
- TOKEN_BUDGET_FINALIZE_MESSAGE,
314
- TOKEN_BUDGET_TOOL_REFUSAL,
315
- registerBudgetFinalizeChild,
316
- releaseBudgetFinalizeChild,
317
- createDreamTokenBudget,
318
- droppedInputMarker,
319
- createDroppedInputGuard,
320
- isEditTool,
321
- applyEditMarkerToInput,
322
- getReasoningRemovalState,
323
- modelAcceptsEmptyContent,
324
- isAnthropicFamilyRoute,
325
- variantChangeBustsProviderCache,
326
- isInActiveAnthropicTurn,
327
- activeAnthropicTurnStart,
328
- hasAnthropicReasoning,
329
- isMarkerOnlyText,
330
- findLatestAssistantReasoningMutationExemptMessage,
331
- DEFAULT_KEEP_REASONING_TOKENS,
332
- resolveKeepReasoningTokens,
333
- reasoningStepCost,
334
- reasoningBudgetCutoff,
335
- reasoningTextAndOpaque,
336
- opaqueThinkingCost,
337
- estimatePartImageTokens,
338
- SKELETON_REAL_INPUT_MAX_BYTES,
339
- toolInputStringBytes,
340
- hasRawMessageProvider2,
341
- setRawMessageProvider2,
342
- withRawMessageProvider2,
343
- cleanUserText2,
344
- withRawSessionMessageCache2,
345
- readRawSessionMessages2,
346
- getRawSessionMessageOrdinalCount2,
347
- visitRawSessionMessages2,
348
- visitRawSessionMessagesAsync2,
349
- readRawSessionMessageRange2,
350
- prepareRawSessionOrdinals2,
351
- primeTailRawMessageCache2,
352
- getCachedAbsoluteMessageCount2,
353
- primeInMemoryTailRawMessageCache2,
354
- readRawSessionMessageIdOrdinalsForRange2,
355
- hasRawSessionMessageById2,
356
- compareRawSessionMessageOrder2,
357
- getRawSessionMessageCount2,
358
- getRawSessionTagKeysThrough2,
359
- getLegacyProtectedTailStartOrdinal2,
360
- readSessionChunk2
361
- } from "./index-8cgk0pyh.js";
362
- import {
363
- UNKNOWN_FIT_RATIO,
364
- hasMeasuredDecisionCalibration,
365
- providerMass,
366
- localBudget,
367
- calibrationForModelKey,
368
- historyLocalBudget,
369
- adoptedProtectedToolsPolicy,
370
- protectedToolTagNumbers,
371
- protectedToolTokenCount,
372
- stripWellFormedLeadingTagPrefix,
373
- stripPersistedAssistantText,
374
- byteSize,
375
- stripTagPrefix,
376
- peelLeadingMcTagNotation,
377
- prependTag,
378
- rememberCurrentToolOutputCount,
379
- currentReclaimableToolOutputCount,
380
- isRecord,
381
- TEXT_TAG_IDENTITY_MARKER,
382
- PI_FALLBACK_PREFIXES_JSON,
383
- contentTagOwnerMessageId,
384
- TailHygieneJsonMemo,
385
- piJsonHash,
386
- estimateImageTokensFromDataUrl,
387
- TODO_STATUSES,
388
- TODO_PRIORITIES,
389
- normalizeTodoStateJson,
390
- buildSyntheticTodoPart,
391
- stripChannel1ReminderSpans,
392
- compareMeasuredTailPrefix,
393
- formatTailHygienePrefixMismatch,
394
- freezeTailHygieneMeasurement,
395
- effectiveTailHygiene,
396
- CHANNEL1_SENTINEL,
397
- CHANNEL1_FLOOR_TOKENS,
398
- decideChannel1,
399
- evaluateChannel2,
400
- buildChannel2Reminder,
401
- buildChannel1Reminder,
402
- planEmergencyDrop,
403
- measureEmergencyTag,
404
- queuePendingDropForUnchangedTag,
405
- getPendingOps,
406
- getPendingOpsCount,
407
- clearPendingOps,
408
- removePendingOp,
409
- updateTagByteSize2,
410
- getRecentTagOwnerMessageIds2,
411
- AGE_RECLAIM_MIN_TOKENS2,
412
- getOldestActiveUnprotectedToolTags2,
413
- getActiveToolTagsForAgeReclaim2,
414
- getTriggerTagTokenUpperBound2,
415
- updateTagInputByteSize2,
416
- updateTagTokenCount2,
417
- getPersistedToolTagAccounting2,
418
- getAllStatusTagTokenTotalsFlat2,
419
- tryGetReasoningTokenEstimatesByMessage2,
420
- updateTagInputTokenCount2,
421
- tagTokenCountIsNull2,
422
- backfillTagTokenCounts2,
423
- insertTag2,
424
- updateTagStatus2,
425
- markTagDropped2,
426
- updateTagDropMode2,
427
- updateCavemanDepth2,
428
- hasPiFallbackMessageTags2,
429
- findAdoptableFallbackTags2,
430
- hasPiFallbackToolOwnerTags2,
431
- findPiFallbackToolOwnerTags2,
432
- PiTagIdentityConflictError2,
433
- getPiMessageTagCandidates2,
434
- findPiTagIdentityConflict2,
435
- adoptPiFallbackToolOwnerTag2,
436
- adoptPiFallbackMessageTag2,
437
- getMaxTagNumberBySession2,
438
- getAssignableTagNumberByMessageId2,
439
- deriveTagLoadFloor2,
440
- getTagsBySession2,
441
- getActiveTagsBySession2,
442
- getTagsForPendingOperations2,
443
- getTagsByNumbers2,
444
- getNewestToolTagNumbers2,
445
- getDroppedTagsByNumbers2,
446
- getMaxDroppedTagNumber2,
447
- getToolTagNumberByOwner2,
448
- getNullOwnerToolTag2,
449
- adoptNullOwnerToolTag2
450
- } from "./index-qcsjj9m0.js";
404
+ resolveEpochFloorForPass
405
+ } from "./index-5n3e2gq5.js";
451
406
  import {
452
407
  textMentionsRecentCommit,
453
408
  hasMeaningfulUserText2,
@@ -460,6 +415,14 @@ import {
460
415
  estimateFixedPromptTokens,
461
416
  normalizeText
462
417
  } from "./index-7y60kyea.js";
418
+ import {
419
+ stableStringify,
420
+ BoundedSessionMap,
421
+ getTableColumnNames,
422
+ observeTemporalDecisions,
423
+ freezeTemporalDecisions,
424
+ tagIdentityRevisionKey
425
+ } from "./index-v858d5d1.js";
463
426
  import {
464
427
  inRootAsyncContext2,
465
428
  Database2,
@@ -473,13 +436,6 @@ import {
473
436
  isTransientSqliteError2,
474
437
  withAsyncPrivilegedWriter2
475
438
  } from "./index-2qtx0q6h.js";
476
- import {
477
- stableStringify,
478
- getTableColumnNames,
479
- observeTemporalDecisions,
480
- freezeTemporalDecisions,
481
- tagIdentityRevisionKey
482
- } from "./index-jxm4bvm4.js";
483
439
  import {
484
440
  piHarnessKindFromExecutable,
485
441
  getErrorMessage,
@@ -497,7 +453,7 @@ import {
497
453
  openCurrentDatabase,
498
454
  openDatabaseAsync,
499
455
  closeDatabase
500
- } from "./index-tv9pqeek.js";
456
+ } from "./index-625kbnqd.js";
501
457
  import {
502
458
  LkgRecoveryFenceError,
503
459
  clearLkgFenceProcessState,
@@ -620,7 +576,7 @@ import {
620
576
  getSourceContents,
621
577
  recordSubagentInvocation,
622
578
  getLatestHistorianInvocationId
623
- } from "./index-f07s5m8x.js";
579
+ } from "./index-k2z7r444.js";
624
580
  import {
625
581
  resolveOpenCodeDbPath,
626
582
  assertOpenCodeStoreGeneration,
@@ -639,6 +595,54 @@ import {
639
595
  import {
640
596
  RAW_SUMMARY_TEXT_MAX_CHARS2
641
597
  } from "./index-szn2tac8.js";
598
+ import {
599
+ askAnswerLines,
600
+ removeUnsupportedCommitHashes,
601
+ completedToolArcCrossesBoundary,
602
+ estimateTrueRawMessageTokens,
603
+ buildToolArcs,
604
+ fenceBoundaryForCompletedToolArcs,
605
+ fenceBoundaryForToolArcs,
606
+ buildTrueRawTokenIndex,
607
+ computeRawRangeFingerprint,
608
+ invalidateTrueRawTokenCache,
609
+ stripSystemInjection,
610
+ isFilePart,
611
+ hasUserAnswerMetadata,
612
+ DreamTokenBudgetExceeded,
613
+ TOKEN_BUDGET_FINALIZE_MESSAGE,
614
+ TOKEN_BUDGET_TOOL_REFUSAL,
615
+ registerBudgetFinalizeChild,
616
+ releaseBudgetFinalizeChild,
617
+ createDreamTokenBudget,
618
+ droppedInputMarker,
619
+ createDroppedInputGuard,
620
+ isEditTool,
621
+ applyEditMarkerToInput,
622
+ SKELETON_REAL_INPUT_MAX_BYTES,
623
+ toolInputStringBytes,
624
+ hasRawMessageProvider2,
625
+ setRawMessageProvider2,
626
+ withRawMessageProvider2,
627
+ cleanUserText2,
628
+ withRawSessionMessageCache2,
629
+ readRawSessionMessages2,
630
+ getRawSessionMessageOrdinalCount2,
631
+ visitRawSessionMessages2,
632
+ visitRawSessionMessagesAsync2,
633
+ readRawSessionMessageRange2,
634
+ prepareRawSessionOrdinals2,
635
+ primeTailRawMessageCache2,
636
+ getCachedAbsoluteMessageCount2,
637
+ primeInMemoryTailRawMessageCache2,
638
+ readRawSessionMessageIdOrdinalsForRange2,
639
+ hasRawSessionMessageById2,
640
+ compareRawSessionMessageOrder2,
641
+ getRawSessionMessageCount2,
642
+ getRawSessionTagKeysThrough2,
643
+ getLegacyProtectedTailStartOrdinal2,
644
+ readSessionChunk2
645
+ } from "./index-rekymyxd.js";
642
646
  import"./index-nvh6d3bz.js";
643
647
  import {
644
648
  formatSynapseLaneDescriptor
@@ -678,13 +682,10 @@ import {
678
682
  clearCompressionDepthRange,
679
683
  cleanSearchText,
680
684
  matchedSearchSnippet
681
- } from "./index-snrkpmpf.js";
685
+ } from "./index-2pptpxq8.js";
682
686
  import {
683
687
  rememberV1HiddenRun
684
688
  } from "./index-6x556c2q.js";
685
- import {
686
- BoundedSessionMap
687
- } from "./index-c6wbq66z.js";
688
689
  import {
689
690
  V2_MEMORY_CATEGORIES
690
691
  } from "./index-135e8hvg.js";
@@ -696,7 +697,7 @@ import {
696
697
  expandWorkspaceIdentitySetWithAliases,
697
698
  sourceNameForMemory,
698
699
  computeWorkspaceEpochFingerprint
699
- } from "./index-zc6fdyx7.js";
700
+ } from "./index-d40ecdbn.js";
700
701
  import {
701
702
  configureContextDatabasePragmas2
702
703
  } from "./index-fapenpch.js";
@@ -721,7 +722,7 @@ import {
721
722
  createPrimer,
722
723
  updatePrimerSupport,
723
724
  updatePrimerAnswer
724
- } from "./index-46wk0td0.js";
725
+ } from "./index-awpx91y5.js";
725
726
  import {
726
727
  setEmbeddingSessionBusy2,
727
728
  isEmbeddingHostBusy2
@@ -755,7 +756,7 @@ import {
755
756
  } from "./index-q1yc6bs0.js";
756
757
  import {
757
758
  getCachedLocalEmbeddingPooling
758
- } from "./index-38pf5bqw.js";
759
+ } from "./index-hec3bwev.js";
759
760
  import {
760
761
  describeShadowBackfillWriteRefusal2,
761
762
  contentSha2562,
@@ -773,10 +774,10 @@ import {
773
774
  embedSessionCompartmentChunks2,
774
775
  getEmbeddingCoverageStatus2,
775
776
  getAutoEmbeddingSessionCoverage2
776
- } from "./index-2yjpxzga.js";
777
+ } from "./index-erkb5dee.js";
777
778
  import {
778
779
  cosineSimilarity
779
- } from "./index-njd3qa8e.js";
780
+ } from "./index-jnh7a6a3.js";
780
781
  import {
781
782
  USER_FACING_FAILURES,
782
783
  renderUserFacingFailure,
@@ -810,7 +811,7 @@ import {
810
811
  scheduleClearAndReindex,
811
812
  clearSessionTracking,
812
813
  createAutoSearchDiagnostics
813
- } from "./index-1tk6065b.js";
814
+ } from "./index-c3mms4dp.js";
814
815
  import"./index-xssjy4z9.js";
815
816
  import {
816
817
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
@@ -838,11 +839,11 @@ import {
838
839
  drainPiTagSnapshotSession,
839
840
  assertPiTagSnapshotReady,
840
841
  ensurePiTagSnapshotReady
841
- } from "./index-pkg07s54.js";
842
+ } from "./index-nhpvvdhw.js";
842
843
  import"./index-yjgkjkjs.js";
843
844
  import"./index-8d2z6503.js";
844
- import"./index-4cmj48mq.js";
845
- import"./index-nevbaezn.js";
845
+ import"./index-6ahmfva8.js";
846
+ import"./index-9kaj9ty1.js";
846
847
  import {
847
848
  __toESM
848
849
  } from "./index-22jkk6wg.js";
@@ -852,9 +853,6 @@ import {
852
853
  import {
853
854
  computeNormalizedHash
854
855
  } from "./index-9x1f96r8.js";
855
- import {
856
- normalizeProtectedToolName
857
- } from "./index-674f6qs2.js";
858
856
  import {
859
857
  sameProjectDirectory
860
858
  } from "./index-wrr9rp9a.js";
@@ -3597,7 +3595,7 @@ function startHostStallProfilerSwitch() {
3597
3595
  // package.json
3598
3596
  var package_default = {
3599
3597
  name: "@cortexkit/pi-magic-context",
3600
- version: "0.49.53",
3598
+ version: "0.49.54",
3601
3599
  type: "module",
3602
3600
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3603
3601
  main: "dist/index.js",
@@ -21301,9 +21299,19 @@ class PiSubagentRunner {
21301
21299
  let mappingMessages = [];
21302
21300
  const isMemoryMapper = options.agent.replace(/^magic-context-/, "") === "dreamer-memory-mapper";
21303
21301
  let settled = false;
21302
+ let startupFailure;
21304
21303
  const settle = (result) => {
21305
21304
  if (settled)
21306
21305
  return;
21306
+ if (startupFailure) {
21307
+ result = {
21308
+ ok: false,
21309
+ reason: "spawn_failed",
21310
+ error: startupFailure,
21311
+ durationMs: result.durationMs,
21312
+ meta: result.meta
21313
+ };
21314
+ }
21307
21315
  settled = true;
21308
21316
  if (zenChild) {
21309
21317
  const classified = classifyZenFreeTierFailure(result, options.model, options.agent, this.invocation.targetHarness);
@@ -21450,6 +21458,13 @@ class PiSubagentRunner {
21450
21458
  }, (message) => sessionLog2(options.accountingSessionId ?? "pi-subagent", message));
21451
21459
  };
21452
21460
  let stderr = "";
21461
+ const observeStartupFailure = (event) => {
21462
+ const error = readSubagentStartupError(event);
21463
+ if (!error)
21464
+ return;
21465
+ startupFailure ??= error;
21466
+ terminateChild(child);
21467
+ };
21453
21468
  let stderrLine = "";
21454
21469
  const stderrDecoder = new StringDecoder("utf8");
21455
21470
  child.stderr?.on("data", (chunk) => {
@@ -21461,10 +21476,11 @@ class PiSubagentRunner {
21461
21476
  `);
21462
21477
  stderrLine = (lines.pop() ?? "").slice(-4096);
21463
21478
  for (const line of lines) {
21464
- if (settled || !(line.startsWith('{"type":"mc_system_prompt"') || line.startsWith('{"type":"mc_temperature"')))
21479
+ if (settled || !(line.startsWith('{"type":"mc_system_prompt"') || line.startsWith('{"type":"mc_temperature"') || line.startsWith('{"type":"magic_context_startup_error"')))
21465
21480
  continue;
21466
21481
  const parsed = parsePiEventLine(line);
21467
21482
  if (parsed.ok) {
21483
+ observeStartupFailure(parsed.event);
21468
21484
  telemetry.observe(parsed.event);
21469
21485
  observeTemperatureDecision(parsed.event);
21470
21486
  }
@@ -21534,6 +21550,7 @@ class PiSubagentRunner {
21534
21550
  return;
21535
21551
  }
21536
21552
  const event = parsed.event;
21553
+ observeStartupFailure(event);
21537
21554
  observeTemperatureDecision(event);
21538
21555
  if (typeof event !== "object" || event === null)
21539
21556
  return;
@@ -31839,6 +31856,9 @@ function recordPiTransformTiming(sample) {
31839
31856
  // src/ctx-reduce-nudge-pi.ts
31840
31857
  import { randomUUID as randomUUID3 } from "node:crypto";
31841
31858
 
31859
+ // src/tail-hygiene-walk-pi.ts
31860
+ import { createHash as createHash13 } from "node:crypto";
31861
+
31842
31862
  // src/provider-visible-parts-pi.ts
31843
31863
  function isRecord4(value) {
31844
31864
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -31895,10 +31915,15 @@ function providerVisiblePiPart(value, providerApi) {
31895
31915
  // src/tail-hygiene-walk-pi.ts
31896
31916
  var TAG_PREFIX = /^§(\d+)§\s*/;
31897
31917
  var SYNTHETIC_TODO_PREFIX = "mc_synthetic_todo_";
31898
- var MAX_CONTENT_MEMO_ENTRIES = 1e5;
31918
+ var MAX_CONTENT_MEMO_ENTRIES = 250000;
31899
31919
  var MAX_CONTENT_MEMO_BYTES = 64 * 1024 * 1024;
31920
+ var INLINE_CONTENT_KEY_CHARS = 64;
31900
31921
  var contentMemo = new Map;
31901
31922
  var contentMemoBytes = 0;
31923
+ var contentMemoHits = 0;
31924
+ var contentMemoMisses = 0;
31925
+ var contentMemoEvictions = 0;
31926
+ var contentMemoTokenizations = 0;
31902
31927
  function clearPiTailHygieneContentMemo() {
31903
31928
  contentMemo.clear();
31904
31929
  contentMemoBytes = 0;
@@ -31932,12 +31957,15 @@ function safeStableStringify(value) {
31932
31957
  }
31933
31958
  }
31934
31959
  function memoizedContent(kind, content) {
31935
- const key = `${kind}\x00${content}`;
31960
+ const key = contentMemoKey(kind, content);
31936
31961
  const cached = contentMemo.get(key);
31937
- if (cached)
31962
+ if (cached) {
31963
+ contentMemoHits += 1;
31938
31964
  return cached;
31965
+ }
31966
+ contentMemoMisses += 1;
31939
31967
  const measured = {
31940
- hash: fnv1a32(key),
31968
+ hash: fnv1a32(`${kind}\x00${content}`),
31941
31969
  tokens: kind === "excluded" ? 0 : undefined,
31942
31970
  keyBytes: key.length * 2 + 32
31943
31971
  };
@@ -31951,15 +31979,26 @@ function memoizedContent(kind, content) {
31951
31979
  if (removed)
31952
31980
  contentMemoBytes -= removed.keyBytes;
31953
31981
  contentMemo.delete(oldest);
31982
+ contentMemoEvictions += 1;
31954
31983
  }
31955
31984
  return measured;
31956
31985
  }
31957
- function memoizedTokens(kind, content) {
31986
+ function contentMemoKey(kind, content) {
31987
+ if (content.length <= INLINE_CONTENT_KEY_CHARS)
31988
+ return `${kind}\x00=${content}`;
31989
+ const digest = createHash13("sha256").update(content, "utf16le").digest("base64");
31990
+ return `${kind}\x00#${content.length}\x00${digest}`;
31991
+ }
31992
+ function measuredContent(kind, content) {
31958
31993
  const measured = memoizedContent(kind, content);
31959
31994
  if (measured.tokens === undefined) {
31995
+ contentMemoTokenizations += 1;
31960
31996
  measured.tokens = estimateTokens(content);
31961
31997
  }
31962
- return measured.tokens;
31998
+ return { contentHash: measured.hash, tokens: measured.tokens };
31999
+ }
32000
+ function memoizedTokens(kind, content) {
32001
+ return measuredContent(kind, content).tokens;
31963
32002
  }
31964
32003
  function partHash(kind, content) {
31965
32004
  return memoizedContent(kind, content).hash;
@@ -32454,7 +32493,7 @@ function measurePiTailHygiene(input) {
32454
32493
  key: `${messageKey}\x00text:0`,
32455
32494
  kind: "text",
32456
32495
  content,
32457
- tokens: memoizedTokens("text", content),
32496
+ ...measuredContent("text", content),
32458
32497
  tag
32459
32498
  });
32460
32499
  }
@@ -32492,7 +32531,7 @@ function measurePiTailHygiene(input) {
32492
32531
  key: `${key}\x00toolOutput`,
32493
32532
  kind: "toolOutput",
32494
32533
  content,
32495
- tokens: memoizedTokens("toolOutput", content),
32534
+ ...measuredContent("toolOutput", content),
32496
32535
  tag: arc?.sentinel ? undefined : tag
32497
32536
  });
32498
32537
  }
@@ -32508,7 +32547,7 @@ function measurePiTailHygiene(input) {
32508
32547
  key: `${key}\x00text`,
32509
32548
  kind: "text",
32510
32549
  content,
32511
- tokens: memoizedTokens("text", content),
32550
+ ...measuredContent("text", content),
32512
32551
  tag
32513
32552
  });
32514
32553
  }
@@ -32546,7 +32585,7 @@ function measurePiTailHygiene(input) {
32546
32585
  key: `${key}\x00toolInput`,
32547
32586
  kind: "toolInput",
32548
32587
  content,
32549
- tokens: memoizedTokens("toolInput", content),
32588
+ ...measuredContent("toolInput", content),
32550
32589
  tag: arc?.sentinel ? undefined : arc?.tag
32551
32590
  });
32552
32591
  }
@@ -32891,6 +32930,50 @@ var DEDUP_SAFE_TOOLS = new Set([
32891
32930
  "mcp_lsp_goto_definition",
32892
32931
  "mcp_lsp_prepare_rename"
32893
32932
  ]);
32933
+ function piServedLocalTokens(tag, target, imageTokens) {
32934
+ let tokens = 0;
32935
+ const parts = target?.mutationParts;
32936
+ if (parts && parts.length > 0) {
32937
+ for (const { part } of parts) {
32938
+ const transcriptPart = part;
32939
+ const text = transcriptPart.kind === "tool_use" && transcriptPart.getToolInput ? JSON.stringify(transcriptPart.getToolInput() ?? {}) : transcriptPart.getText?.() ?? "";
32940
+ tokens += estimateTokens(text);
32941
+ }
32942
+ } else {
32943
+ const content = target?.getContent?.();
32944
+ tokens = content ? estimateTokens(content) : 0;
32945
+ }
32946
+ if (tag.type !== "tool")
32947
+ return { tools: 0, prose: tokens };
32948
+ return { tools: tokens + (imageTokens?.get(tag.messageId) ?? 0), prose: 0 };
32949
+ }
32950
+ function snapshotPiEmergencyServedMass(tags, targets, imageTokens) {
32951
+ const snapshot = new Map;
32952
+ for (const tag of tags) {
32953
+ if (tag.status !== "active")
32954
+ continue;
32955
+ snapshot.set(tag.tagNumber, {
32956
+ tag: { type: tag.type, messageId: tag.messageId },
32957
+ ...piServedLocalTokens(tag, targets.get(tag.tagNumber), imageTokens)
32958
+ });
32959
+ }
32960
+ return snapshot;
32961
+ }
32962
+ function piServedMassRemovedSince(snapshot, activeNow, targets, calibration, imageTokens) {
32963
+ const provider = (counts) => counts.tools * calibration.toolsRatio + counts.prose * calibration.proseRatio;
32964
+ let removed = 0;
32965
+ for (const [tagNumber, counts] of snapshot) {
32966
+ const before = provider(counts);
32967
+ const now = provider(piServedLocalTokens(counts.tag, targets.get(tagNumber), imageTokens));
32968
+ if (activeNow.has(tagNumber))
32969
+ removed += Math.max(before - now, 0);
32970
+ else if (now === before)
32971
+ removed += before;
32972
+ else
32973
+ removed += Math.max(before - now, 0);
32974
+ }
32975
+ return removed;
32976
+ }
32894
32977
  function buildPiToolFingerprints(messages, resolveStableId) {
32895
32978
  const fingerprints = new Map;
32896
32979
  for (let i = 0;i < messages.length; i++) {
@@ -33037,9 +33120,11 @@ function applyPiHeuristicCleanup(sessionId, db, targets, piMessages, config, pre
33037
33120
  } : measured;
33038
33121
  }
33039
33122
  } : target;
33040
- return measureEmergencyTag(tag, measuredTarget, calibration, targets.get(tag.tagNumber)?.requiresToolArcSkeleton === true || (emergency.usagePercentage ?? 0) < 95 && recentTags.has(tag.tagNumber) && hasSmallToolInput(targets.get(tag.tagNumber)));
33123
+ const measured = measureEmergencyTag(tag, measuredTarget, calibration, targets.get(tag.tagNumber)?.requiresToolArcSkeleton === true || (emergency.usagePercentage ?? 0) < 95 && recentTags.has(tag.tagNumber) && hasSmallToolInput(targets.get(tag.tagNumber)));
33124
+ return emergency.sinceReading?.has(tag.tagNumber) ? { ...measured, sinceReading: true } : measured;
33041
33125
  });
33042
33126
  const byTag = new Map(activeTags.map((tag) => [tag.tagNumber, tag]));
33127
+ const removedThisPassTokens = emergency.servedBeforePass ? piServedMassRemovedSince(emergency.servedBeforePass, new Set(activeTags.map((tag) => tag.tagNumber)), targets, calibration, emergency.serializedImageTokens) : 0;
33043
33128
  const droppableTags = candidateTags.flatMap((tag) => {
33044
33129
  const measured = byTag.get(tag.tagNumber);
33045
33130
  return measured ? [measured] : [];
@@ -33053,6 +33138,7 @@ function applyPiHeuristicCleanup(sessionId, db, targets, piMessages, config, pre
33053
33138
  maxTag,
33054
33139
  protectedCutoff,
33055
33140
  currentTotalInputTokens: emergency.currentTotalInputTokens,
33141
+ removedThisPassTokens,
33056
33142
  ceilingTokens: emergency.ceilingTokens,
33057
33143
  usagePercentage: emergency.usagePercentage,
33058
33144
  priorInputSample,
@@ -36511,9 +36597,9 @@ function authorizePiToolRemoval(args) {
36511
36597
  }
36512
36598
 
36513
36599
  // src/native-replay-tag-provenance-pi.ts
36514
- import { createHash as createHash13 } from "node:crypto";
36600
+ import { createHash as createHash14 } from "node:crypto";
36515
36601
  function nativeResponseTagStripKey(id, phase, text) {
36516
- return createHash13("sha256").update(JSON.stringify([id, phase, text])).digest("hex");
36602
+ return createHash14("sha256").update(JSON.stringify([id, phase, text])).digest("hex");
36517
36603
  }
36518
36604
 
36519
36605
  // src/native-replay-tags-pi.ts
@@ -39404,7 +39490,7 @@ function piDispatchMismatchDiagnostic(payload, prepared, mismatch) {
39404
39490
  }
39405
39491
 
39406
39492
  // src/pi-foreign-session-index.ts
39407
- import { createHash as createHash14 } from "node:crypto";
39493
+ import { createHash as createHash15 } from "node:crypto";
39408
39494
 
39409
39495
  // src/pi-foreign-omp-kinds.ts
39410
39496
  var PI_FOREIGN_RENDERED_CONTENT_KINDS = [
@@ -40237,7 +40323,7 @@ function fingerprint(text, index, wire = false) {
40237
40323
  index.stats.wireHashes++;
40238
40324
  else
40239
40325
  index.stats.hashes++;
40240
- return createHash14("sha256").update(stableStringify([{ type: "text", text }])).digest("hex");
40326
+ return createHash15("sha256").update(stableStringify([{ type: "text", text }])).digest("hex");
40241
40327
  }
40242
40328
  function protectSession(index, message, roleOverride, trackEntry = false) {
40243
40329
  const rendering = texts(index, message, roleOverride, trackEntry);
@@ -41068,7 +41154,7 @@ function piExpandChainedRequest(payload, chained, anchor, prepared, pass) {
41068
41154
  }
41069
41155
 
41070
41156
  // src/pi-dispatch-cursor.ts
41071
- import { createHash as createHash15 } from "node:crypto";
41157
+ import { createHash as createHash16 } from "node:crypto";
41072
41158
  var MAX_BYTES = 32 * 1024 * 1024;
41073
41159
  var MAX_ENTRIES = 1e5;
41074
41160
  function object13(value) {
@@ -41195,7 +41281,7 @@ Today: ${day}; current working directory: '${cwd.replace(/\\/gu, "/")}'. Do not
41195
41281
  const hash = (content) => {
41196
41282
  const json = JSON.stringify({ role: "user", content });
41197
41283
  if (json.length <= MAX_BYTES)
41198
- roots.add(createHash15("sha256").update(json).digest("hex"));
41284
+ roots.add(createHash16("sha256").update(json).digest("hex"));
41199
41285
  };
41200
41286
  hash(parts);
41201
41287
  if (reminder) {
@@ -42319,7 +42405,7 @@ function tokenizePiMessages(messages, options) {
42319
42405
  }
42320
42406
  }
42321
42407
  }
42322
- if (options && liveIds) {
42408
+ if (options && liveIds && options.prune !== false) {
42323
42409
  const cachePruneStart = options.onTiming ? performance.now() : 0;
42324
42410
  for (const id of options.cache.keys()) {
42325
42411
  if (!liveIds.has(id))
@@ -42512,7 +42598,7 @@ function piFallbackRefusal(site, cause) {
42512
42598
  }
42513
42599
  return cause instanceof PiDegradedPassError ? cause : new PiDegradedPassError(site, { cause });
42514
42600
  }
42515
- function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, contextLimit) {
42601
+ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, contextLimit, tokenCounts) {
42516
42602
  if (!observed || !Number.isFinite(observed.systemTokens) || observed.systemTokens <= 0 || !Number.isFinite(observed.toolDefinitionTokens) || observed.toolDefinitionTokens < 0 || !hasTokenizerForFit())
42517
42603
  return { tokens: 0, trusted: false };
42518
42604
  const knownRole = (message) => {
@@ -42607,7 +42693,7 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
42607
42693
  refusalGrade: false,
42608
42694
  refusalBasis: "byte-bound"
42609
42695
  };
42610
- const raw = tokenizePiMessages([...messages]);
42696
+ const raw = tokenizePiMessages([...messages], tokenCounts ? { ...tokenCounts, prune: false } : undefined);
42611
42697
  const calibration = observed.calibration ?? calibrationForModelKey(observed.modelKey);
42612
42698
  const refusalCalibration = calibrationForModelKey(observed.modelKey);
42613
42699
  const tokens = providerMass({
@@ -43371,7 +43457,7 @@ function createPiFallbackIndex() {
43371
43457
  }
43372
43458
 
43373
43459
  // src/pi-fit-reclaim.ts
43374
- import { createHash as createHash16, randomUUID as randomUUID4 } from "node:crypto";
43460
+ import { createHash as createHash17, randomUUID as randomUUID4 } from "node:crypto";
43375
43461
  var pendingInput = new Set;
43376
43462
  var KEY3 = "piUpperEstimateReclaim";
43377
43463
  function piFitOverflowPossible(args) {
@@ -43407,7 +43493,7 @@ function piUpperReclaimCursor(args) {
43407
43493
  sessionId: args.sessionId,
43408
43494
  modelKey: args.modelKey,
43409
43495
  contextWindow: args.contextWindow ?? null,
43410
- head: head ? createHash16("sha256").update(JSON.stringify([
43496
+ head: head ? createHash17("sha256").update(JSON.stringify([
43411
43497
  Buffer.from(head.cachedM0Bytes ?? []).toString("base64"),
43412
43498
  Buffer.from(head.cachedM1Bytes ?? []).toString("base64"),
43413
43499
  head.cachedM0MuralDataUrl ?? null
@@ -43494,7 +43580,7 @@ async function waitForPiHistorianInTurn(sessionId, remainingMs, wait) {
43494
43580
  }
43495
43581
 
43496
43582
  // src/pi-lkg-fit-envelope.ts
43497
- import { createHash as createHash17 } from "node:crypto";
43583
+ import { createHash as createHash18 } from "node:crypto";
43498
43584
  function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
43499
43585
  try {
43500
43586
  if (!modelKey || typeof pi.getAllTools !== "function")
@@ -43556,7 +43642,7 @@ function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
43556
43642
  refusalToolDefinitionTokens,
43557
43643
  toolDefinitionsMeasured: refusalToolDefinitionTokens !== undefined,
43558
43644
  envelopeBytes: Buffer.byteLength(envelopeJson),
43559
- envelopeSignature: activeNames ? createHash17("sha256").update(envelopeJson).update(JSON.stringify(activeNames)).digest("hex") : undefined,
43645
+ envelopeSignature: activeNames ? createHash18("sha256").update(envelopeJson).update(JSON.stringify(activeNames)).digest("hex") : undefined,
43560
43646
  calibration
43561
43647
  };
43562
43648
  } catch {
@@ -43565,13 +43651,13 @@ function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
43565
43651
  }
43566
43652
 
43567
43653
  // src/pi-message-identity.ts
43568
- import { createHash as createHash20 } from "node:crypto";
43654
+ import { createHash as createHash21 } from "node:crypto";
43569
43655
 
43570
43656
  // src/pi-tool-identity.ts
43571
- import { createHash as createHash19 } from "node:crypto";
43657
+ import { createHash as createHash20 } from "node:crypto";
43572
43658
 
43573
43659
  // src/served-array-ledger.ts
43574
- import { createHash as createHash18 } from "node:crypto";
43660
+ import { createHash as createHash19 } from "node:crypto";
43575
43661
  import {
43576
43662
  closeSync as closeSync2,
43577
43663
  fstatSync,
@@ -43849,7 +43935,7 @@ function getPiLastServedArray(sessionId) {
43849
43935
  return previous ? `[${previous.serializedMessages.join(",")}]` : undefined;
43850
43936
  }
43851
43937
  function sha256(value) {
43852
- return createHash18("sha256").update(value).digest("hex");
43938
+ return createHash19("sha256").update(value).digest("hex");
43853
43939
  }
43854
43940
  function safeSessionFileStem(sessionId) {
43855
43941
  const readable = sessionId.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 96);
@@ -44134,7 +44220,7 @@ function readPiServedCachedArray(sessionId) {
44134
44220
  const memory = getPiLastServedArray(sessionId);
44135
44221
  const slot = memory === undefined ? getSlot(sessionId) : undefined;
44136
44222
  const jsonPrefix = memory ?? slot?.jsonPrefix;
44137
- if (jsonPrefix === undefined || createHash19("sha256").update(jsonPrefix).digest("hex") !== getPiLastServedDigest(sessionId))
44223
+ if (jsonPrefix === undefined || createHash20("sha256").update(jsonPrefix).digest("hex") !== getPiLastServedDigest(sessionId))
44138
44224
  return;
44139
44225
  let parsed;
44140
44226
  try {
@@ -44158,7 +44244,7 @@ function piMessageEntryFingerprint(message) {
44158
44244
  const m = message;
44159
44245
  if (typeof m.role !== "string")
44160
44246
  return null;
44161
- const contentHash = createHash20("sha256").update(stableStringify(m.content)).digest("hex");
44247
+ const contentHash = createHash21("sha256").update(stableStringify(m.content)).digest("hex");
44162
44248
  return JSON.stringify([
44163
44249
  typeof m.responseId === "string" ? m.responseId : null,
44164
44250
  typeof m.timestamp === "number" || typeof m.timestamp === "string" ? m.timestamp : null,
@@ -49671,7 +49757,14 @@ function registerPiContextHandler(pi, baseOptions) {
49671
49757
  const envelope = readPiLkgFitEnvelope(ctx, pi, resolvePiContextModelKey(ctx), sessionDecisionCalibration(options.db, sessionId), toolWireSchema);
49672
49758
  const measuredPrefix = lkgPassSnapshot ? lkgCoordinator.measureOutgoingPrefix(lkgPassSnapshot, outputMessages, (id) => ctx.sessionManager.getEntry?.(id)?.parentId) : undefined;
49673
49759
  const outgoingFitLimit = getHarness2() === "pi" && baseWindowGeometry ? baseWindowGeometry.derivation.absoluteWall : rawFallbackLimit;
49674
- let estimate = estimatePiOutgoingInputTokens(outputMessages, envelope, measuredPrefix, outgoingFitLimit);
49760
+ const fitTokenCounts = () => {
49761
+ const cache = piMessageTokenCacheBySession.get(sessionId);
49762
+ return cache ? {
49763
+ cache,
49764
+ stableId: (message) => result.postCommitEntryIdByRef.get(message)
49765
+ } : undefined;
49766
+ };
49767
+ let estimate = estimatePiOutgoingInputTokens(outputMessages, envelope, measuredPrefix, outgoingFitLimit, fitTokenCounts());
49675
49768
  let fitReclaimedThisPass = false;
49676
49769
  if (!inputForThinkingFit && result.strictThinkingKept && rawFallbackLimit && estimate.refusalGrade && (estimate.refusalTokens ?? estimate.tokens) > rawFallbackLimit) {
49677
49770
  const restored = restorePiLkgInputForFit(lkgPassSnapshot, branchEntries);
@@ -49701,7 +49794,7 @@ function registerPiContextHandler(pi, baseOptions) {
49701
49794
  cacheBustingPass: result.prefixBustPermitted,
49702
49795
  stripActiveTurn: true
49703
49796
  });
49704
- estimate = estimatePiOutgoingInputTokens(outputMessages, envelope, undefined, rawFallbackLimit);
49797
+ estimate = estimatePiOutgoingInputTokens(outputMessages, envelope, undefined, rawFallbackLimit, fitTokenCounts());
49705
49798
  }
49706
49799
  const opaqueFallbackSteps = piOpaqueThinkingFallbackSteps(outputMessages);
49707
49800
  if (opaqueFallbackSteps > 0)
@@ -49829,7 +49922,7 @@ function registerPiContextHandler(pi, baseOptions) {
49829
49922
  cacheBustingPass: result.prefixBustPermitted,
49830
49923
  stripActiveTurn: result.signedPrefixRewritten
49831
49924
  });
49832
- estimate = estimatePiOutgoingInputTokens(outputMessages, envelope, undefined, outgoingFitLimit);
49925
+ estimate = estimatePiOutgoingInputTokens(outputMessages, envelope, undefined, outgoingFitLimit, fitTokenCounts());
49833
49926
  } finally {
49834
49927
  if (!reclaimCompleted && upperCursor && reservation)
49835
49928
  releasePiUpperEstimateReclaim(options.db, upperCursor, reservation);
@@ -51582,6 +51675,10 @@ async function runPipeline(args) {
51582
51675
  const deferredMaterialize = canConsumeDeferredLate && deferredMaterializationWasPending;
51583
51676
  const deferredHistoryRefresh = canConsumeDeferredLate && deferredHistoryRefreshWasPending;
51584
51677
  const shouldApplyPendingOps = publishedWorkDrainAllowed;
51678
+ const emergencyPlannerMayRun = shouldRunHeuristics && args.heuristics !== undefined && args.forceMaterialization === true && args.emergencyCeilingTokens !== undefined && args.emergencyCeilingTokens > 0;
51679
+ const tagsNewerThanReading = emergencyPlannerMayRun ? tagsSinceReading(transcript.messages, newTargets) : undefined;
51680
+ const queuedDropTags = new Set(pendingOps.map((op) => op.tagId));
51681
+ const emergencyServedBeforeDrain = emergencyPlannerMayRun && shouldApplyPendingOps && queuedDropTags.size > 0 ? snapshotPiEmergencyServedMass(getPiActiveTagSnapshotView(args.db, args.sessionId).filter((tag) => queuedDropTags.has(tag.tagNumber) && !tagsNewerThanReading?.has(tag.tagNumber)), newTargets, args.providerOverflowRecovery === true ? piRecoveryToolImageTokens(workingMessages) : undefined) : undefined;
51585
51682
  mutationGateObserverForTests?.({
51586
51683
  foldDue: foldDueDecision.value,
51587
51684
  foldExecuted: foldExecutedThisPass,
@@ -51740,7 +51837,9 @@ async function runPipeline(args) {
51740
51837
  usagePercentage: args.contextUsage.percentage,
51741
51838
  passAlreadyPriced: independentMutationBeforeHeuristics,
51742
51839
  serializedImageTokens: providerOverflow ? piRecoveryToolImageTokens(workingMessages) : undefined,
51743
- fitCalibration: providerOverflow ? piRecoveryFitCalibration(recoveryCalibration) : undefined
51840
+ fitCalibration: providerOverflow ? piRecoveryFitCalibration(recoveryCalibration) : undefined,
51841
+ servedBeforePass: emergencyServedBeforeDrain,
51842
+ sinceReading: tagsNewerThanReading
51744
51843
  } : undefined,
51745
51844
  caveman: args.isSubagent ? undefined : args.heuristics?.caveman
51746
51845
  }, activeTags, stableIdResolver));