@cortexkit/pi-magic-context 0.49.52 → 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.
- package/dist/auto-search-worker.js +3 -3
- package/dist/chunk-embedding-write-worker.js +3 -4
- package/dist/{embedding-backfill-fbhpk2yy.js → embedding-backfill-qde2zywg.js} +4 -4
- package/dist/embedding-worker.js +2 -2
- package/dist/{index-0hewsw7v.js → index-2pptpxq8.js} +1 -1
- package/dist/index-5n3e2gq5.js +6469 -0
- package/dist/{index-rjz01pvv.js → index-625kbnqd.js} +5 -7
- package/dist/{index-73c292h9.js → index-6ahmfva8.js} +3 -3
- package/dist/{index-1cvyaw9a.js → index-8d2z6503.js} +1 -1
- package/dist/{index-ktez4jwz.js → index-9kaj9ty1.js} +7 -6
- package/dist/{index-46wk0td0.js → index-awpx91y5.js} +1 -1
- package/dist/{index-mb34ngfr.js → index-c3mms4dp.js} +27 -16
- package/dist/{index-zc6fdyx7.js → index-d40ecdbn.js} +1 -1
- package/dist/{index-r6dj8rm9.js → index-erkb5dee.js} +11 -7
- package/dist/{index-38pf5bqw.js → index-hec3bwev.js} +1 -1
- package/dist/{index-ty2m0s0s.js → index-jnh7a6a3.js} +3 -3
- package/dist/{index-akmmkmhf.js → index-k2z7r444.js} +523 -30
- package/dist/{index-pkg07s54.js → index-nhpvvdhw.js} +2 -2
- package/dist/index-rekymyxd.js +2287 -0
- package/dist/{index-cc73przv.js → index-tn38he5d.js} +44 -31
- package/dist/{index-jxm4bvm4.js → index-v858d5d1.js} +168 -1
- package/dist/{index-aec63gtj.js → index-vcegxfwg.js} +16 -6
- package/dist/index.js +970 -352
- package/dist/{message-index-bounded-d50b5f2z.js → message-index-bounded-ac4qg6aw.js} +5 -6
- package/dist/migration-worker.js +3 -4
- package/dist/{project-embedding-registry-hpca84nz.js → project-embedding-registry-qx2zjbgs.js} +5 -3
- package/dist/raw-ordinal-warmup-worker.js +4 -4
- package/dist/{read-session-chunk-9yr9mava.js → read-session-chunk-jyfcykg4.js} +4 -5
- package/dist/{render-3s7kbr61.js → render-bqqx15n8.js} +9 -10
- package/dist/{search-archive-dd1z7xn0.js → search-archive-31054zxj.js} +7 -8
- package/dist/{search-2vgt4717.js → search-w12nc025.js} +12 -13
- package/dist/{storage-tags-ahhwtfdq.js → storage-tags-g0328gwp.js} +4 -2
- package/dist/subagent-entry.js +39 -18
- package/dist/tag-snapshot-worker-pi.js +6 -6
- package/dist/{v2-archive-reader-6jbyaafn.js → v2-archive-reader-hg4c36em.js} +1 -1
- package/package.json +3 -1
- package/dist/index-674f6qs2.js +0 -16
- package/dist/index-c6wbq66z.js +0 -168
- package/dist/index-fec4ezww.js +0 -5271
- 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-
|
|
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-
|
|
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
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
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,158 +401,8 @@ import {
|
|
|
295
401
|
getSessionsWithPendingPiMarker,
|
|
296
402
|
setSessionWorkMetrics,
|
|
297
403
|
getSessionWorkMetrics,
|
|
298
|
-
resolveEpochFloorForPass
|
|
299
|
-
|
|
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
|
-
modelAcceptsEmptyContent,
|
|
323
|
-
isAnthropicFamilyRoute,
|
|
324
|
-
variantChangeBustsProviderCache,
|
|
325
|
-
isInActiveAnthropicTurn,
|
|
326
|
-
activeAnthropicTurnStart,
|
|
327
|
-
hasAnthropicReasoning,
|
|
328
|
-
isMarkerOnlyText,
|
|
329
|
-
findLatestAssistantReasoningMutationExemptMessage,
|
|
330
|
-
DEFAULT_KEEP_REASONING_TOKENS,
|
|
331
|
-
resolveKeepReasoningTokens,
|
|
332
|
-
reasoningStepCost,
|
|
333
|
-
reasoningBudgetCutoff,
|
|
334
|
-
reasoningTextAndOpaque,
|
|
335
|
-
opaqueThinkingCost,
|
|
336
|
-
estimatePartImageTokens,
|
|
337
|
-
SKELETON_REAL_INPUT_MAX_BYTES,
|
|
338
|
-
toolInputStringBytes,
|
|
339
|
-
hasRawMessageProvider2,
|
|
340
|
-
setRawMessageProvider2,
|
|
341
|
-
withRawMessageProvider2,
|
|
342
|
-
cleanUserText2,
|
|
343
|
-
withRawSessionMessageCache2,
|
|
344
|
-
readRawSessionMessages2,
|
|
345
|
-
getRawSessionMessageOrdinalCount2,
|
|
346
|
-
visitRawSessionMessages2,
|
|
347
|
-
visitRawSessionMessagesAsync2,
|
|
348
|
-
readRawSessionMessageRange2,
|
|
349
|
-
prepareRawSessionOrdinals2,
|
|
350
|
-
primeTailRawMessageCache2,
|
|
351
|
-
getCachedAbsoluteMessageCount2,
|
|
352
|
-
primeInMemoryTailRawMessageCache2,
|
|
353
|
-
readRawSessionMessageIdOrdinalsForRange2,
|
|
354
|
-
hasRawSessionMessageById2,
|
|
355
|
-
compareRawSessionMessageOrder2,
|
|
356
|
-
getRawSessionMessageCount2,
|
|
357
|
-
getRawSessionTagKeysThrough2,
|
|
358
|
-
getLegacyProtectedTailStartOrdinal2,
|
|
359
|
-
readSessionChunk2
|
|
360
|
-
} from "./index-fec4ezww.js";
|
|
361
|
-
import {
|
|
362
|
-
UNKNOWN_FIT_RATIO,
|
|
363
|
-
hasMeasuredDecisionCalibration,
|
|
364
|
-
providerMass,
|
|
365
|
-
localBudget,
|
|
366
|
-
calibrationForModelKey,
|
|
367
|
-
historyLocalBudget,
|
|
368
|
-
adoptedProtectedToolsPolicy,
|
|
369
|
-
protectedToolTagNumbers,
|
|
370
|
-
protectedToolTokenCount,
|
|
371
|
-
stripWellFormedLeadingTagPrefix,
|
|
372
|
-
stripPersistedAssistantText,
|
|
373
|
-
byteSize,
|
|
374
|
-
stripTagPrefix,
|
|
375
|
-
peelLeadingMcTagNotation,
|
|
376
|
-
prependTag,
|
|
377
|
-
rememberCurrentToolOutputCount,
|
|
378
|
-
currentReclaimableToolOutputCount,
|
|
379
|
-
isRecord,
|
|
380
|
-
TEXT_TAG_IDENTITY_MARKER,
|
|
381
|
-
PI_FALLBACK_PREFIXES_JSON,
|
|
382
|
-
contentTagOwnerMessageId,
|
|
383
|
-
TailHygieneJsonMemo,
|
|
384
|
-
piJsonHash,
|
|
385
|
-
estimateImageTokensFromDataUrl,
|
|
386
|
-
TODO_STATUSES,
|
|
387
|
-
TODO_PRIORITIES,
|
|
388
|
-
normalizeTodoStateJson,
|
|
389
|
-
buildSyntheticTodoPart,
|
|
390
|
-
stripChannel1ReminderSpans,
|
|
391
|
-
compareMeasuredTailPrefix,
|
|
392
|
-
formatTailHygienePrefixMismatch,
|
|
393
|
-
freezeTailHygieneMeasurement,
|
|
394
|
-
effectiveTailHygiene,
|
|
395
|
-
CHANNEL1_SENTINEL,
|
|
396
|
-
CHANNEL1_FLOOR_TOKENS,
|
|
397
|
-
decideChannel1,
|
|
398
|
-
evaluateChannel2,
|
|
399
|
-
buildChannel2Reminder,
|
|
400
|
-
buildChannel1Reminder,
|
|
401
|
-
planEmergencyDrop,
|
|
402
|
-
measureEmergencyTag,
|
|
403
|
-
queuePendingDropForUnchangedTag,
|
|
404
|
-
getPendingOps,
|
|
405
|
-
getPendingOpsCount,
|
|
406
|
-
clearPendingOps,
|
|
407
|
-
removePendingOp,
|
|
408
|
-
updateTagByteSize2,
|
|
409
|
-
getRecentTagOwnerMessageIds2,
|
|
410
|
-
AGE_RECLAIM_MIN_TOKENS2,
|
|
411
|
-
getOldestActiveUnprotectedToolTags2,
|
|
412
|
-
getActiveToolTagsForAgeReclaim2,
|
|
413
|
-
getTriggerTagTokenUpperBound2,
|
|
414
|
-
updateTagInputByteSize2,
|
|
415
|
-
updateTagTokenCount2,
|
|
416
|
-
getPersistedToolTagAccounting2,
|
|
417
|
-
getAllStatusTagTokenTotalsFlat2,
|
|
418
|
-
tryGetReasoningTokenEstimatesByMessage2,
|
|
419
|
-
updateTagInputTokenCount2,
|
|
420
|
-
tagTokenCountIsNull2,
|
|
421
|
-
backfillTagTokenCounts2,
|
|
422
|
-
insertTag2,
|
|
423
|
-
updateTagStatus2,
|
|
424
|
-
markTagDropped2,
|
|
425
|
-
updateTagDropMode2,
|
|
426
|
-
updateCavemanDepth2,
|
|
427
|
-
hasPiFallbackMessageTags2,
|
|
428
|
-
findAdoptableFallbackTags2,
|
|
429
|
-
hasPiFallbackToolOwnerTags2,
|
|
430
|
-
findPiFallbackToolOwnerTags2,
|
|
431
|
-
PiTagIdentityConflictError2,
|
|
432
|
-
getPiMessageTagCandidates2,
|
|
433
|
-
findPiTagIdentityConflict2,
|
|
434
|
-
adoptPiFallbackToolOwnerTag2,
|
|
435
|
-
adoptPiFallbackMessageTag2,
|
|
436
|
-
getMaxTagNumberBySession2,
|
|
437
|
-
getAssignableTagNumberByMessageId2,
|
|
438
|
-
deriveTagLoadFloor2,
|
|
439
|
-
getTagsBySession2,
|
|
440
|
-
getActiveTagsBySession2,
|
|
441
|
-
getTagsForPendingOperations2,
|
|
442
|
-
getTagsByNumbers2,
|
|
443
|
-
getNewestToolTagNumbers2,
|
|
444
|
-
getDroppedTagsByNumbers2,
|
|
445
|
-
getMaxDroppedTagNumber2,
|
|
446
|
-
getToolTagNumberByOwner2,
|
|
447
|
-
getNullOwnerToolTag2,
|
|
448
|
-
adoptNullOwnerToolTag2
|
|
449
|
-
} from "./index-qcsjj9m0.js";
|
|
404
|
+
resolveEpochFloorForPass
|
|
405
|
+
} from "./index-5n3e2gq5.js";
|
|
450
406
|
import {
|
|
451
407
|
textMentionsRecentCommit,
|
|
452
408
|
hasMeaningfulUserText2,
|
|
@@ -459,6 +415,14 @@ import {
|
|
|
459
415
|
estimateFixedPromptTokens,
|
|
460
416
|
normalizeText
|
|
461
417
|
} from "./index-7y60kyea.js";
|
|
418
|
+
import {
|
|
419
|
+
stableStringify,
|
|
420
|
+
BoundedSessionMap,
|
|
421
|
+
getTableColumnNames,
|
|
422
|
+
observeTemporalDecisions,
|
|
423
|
+
freezeTemporalDecisions,
|
|
424
|
+
tagIdentityRevisionKey
|
|
425
|
+
} from "./index-v858d5d1.js";
|
|
462
426
|
import {
|
|
463
427
|
inRootAsyncContext2,
|
|
464
428
|
Database2,
|
|
@@ -472,13 +436,6 @@ import {
|
|
|
472
436
|
isTransientSqliteError2,
|
|
473
437
|
withAsyncPrivilegedWriter2
|
|
474
438
|
} from "./index-2qtx0q6h.js";
|
|
475
|
-
import {
|
|
476
|
-
stableStringify,
|
|
477
|
-
getTableColumnNames,
|
|
478
|
-
observeTemporalDecisions,
|
|
479
|
-
freezeTemporalDecisions,
|
|
480
|
-
tagIdentityRevisionKey
|
|
481
|
-
} from "./index-jxm4bvm4.js";
|
|
482
439
|
import {
|
|
483
440
|
piHarnessKindFromExecutable,
|
|
484
441
|
getErrorMessage,
|
|
@@ -496,7 +453,7 @@ import {
|
|
|
496
453
|
openCurrentDatabase,
|
|
497
454
|
openDatabaseAsync,
|
|
498
455
|
closeDatabase
|
|
499
|
-
} from "./index-
|
|
456
|
+
} from "./index-625kbnqd.js";
|
|
500
457
|
import {
|
|
501
458
|
LkgRecoveryFenceError,
|
|
502
459
|
clearLkgFenceProcessState,
|
|
@@ -562,6 +519,12 @@ import {
|
|
|
562
519
|
drainStaleLkgSlots,
|
|
563
520
|
createDbLkgPersistence,
|
|
564
521
|
replayLkg,
|
|
522
|
+
beginServedRequest,
|
|
523
|
+
noteServedPassPermission,
|
|
524
|
+
noteServedReplay,
|
|
525
|
+
countServedRefusal,
|
|
526
|
+
dropServedRecord,
|
|
527
|
+
commitServedRequest,
|
|
565
528
|
registerLkgPersistence,
|
|
566
529
|
LKG_SNAPSHOT_ARRAY,
|
|
567
530
|
LKG_SNAPSHOT_OBJECT,
|
|
@@ -613,7 +576,7 @@ import {
|
|
|
613
576
|
getSourceContents,
|
|
614
577
|
recordSubagentInvocation,
|
|
615
578
|
getLatestHistorianInvocationId
|
|
616
|
-
} from "./index-
|
|
579
|
+
} from "./index-k2z7r444.js";
|
|
617
580
|
import {
|
|
618
581
|
resolveOpenCodeDbPath,
|
|
619
582
|
assertOpenCodeStoreGeneration,
|
|
@@ -632,6 +595,54 @@ import {
|
|
|
632
595
|
import {
|
|
633
596
|
RAW_SUMMARY_TEXT_MAX_CHARS2
|
|
634
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";
|
|
635
646
|
import"./index-nvh6d3bz.js";
|
|
636
647
|
import {
|
|
637
648
|
formatSynapseLaneDescriptor
|
|
@@ -671,13 +682,10 @@ import {
|
|
|
671
682
|
clearCompressionDepthRange,
|
|
672
683
|
cleanSearchText,
|
|
673
684
|
matchedSearchSnippet
|
|
674
|
-
} from "./index-
|
|
685
|
+
} from "./index-2pptpxq8.js";
|
|
675
686
|
import {
|
|
676
687
|
rememberV1HiddenRun
|
|
677
688
|
} from "./index-6x556c2q.js";
|
|
678
|
-
import {
|
|
679
|
-
BoundedSessionMap
|
|
680
|
-
} from "./index-c6wbq66z.js";
|
|
681
689
|
import {
|
|
682
690
|
V2_MEMORY_CATEGORIES
|
|
683
691
|
} from "./index-135e8hvg.js";
|
|
@@ -689,7 +697,7 @@ import {
|
|
|
689
697
|
expandWorkspaceIdentitySetWithAliases,
|
|
690
698
|
sourceNameForMemory,
|
|
691
699
|
computeWorkspaceEpochFingerprint
|
|
692
|
-
} from "./index-
|
|
700
|
+
} from "./index-d40ecdbn.js";
|
|
693
701
|
import {
|
|
694
702
|
configureContextDatabasePragmas2
|
|
695
703
|
} from "./index-fapenpch.js";
|
|
@@ -714,7 +722,7 @@ import {
|
|
|
714
722
|
createPrimer,
|
|
715
723
|
updatePrimerSupport,
|
|
716
724
|
updatePrimerAnswer
|
|
717
|
-
} from "./index-
|
|
725
|
+
} from "./index-awpx91y5.js";
|
|
718
726
|
import {
|
|
719
727
|
setEmbeddingSessionBusy2,
|
|
720
728
|
isEmbeddingHostBusy2
|
|
@@ -748,7 +756,7 @@ import {
|
|
|
748
756
|
} from "./index-q1yc6bs0.js";
|
|
749
757
|
import {
|
|
750
758
|
getCachedLocalEmbeddingPooling
|
|
751
|
-
} from "./index-
|
|
759
|
+
} from "./index-hec3bwev.js";
|
|
752
760
|
import {
|
|
753
761
|
describeShadowBackfillWriteRefusal2,
|
|
754
762
|
contentSha2562,
|
|
@@ -760,16 +768,16 @@ import {
|
|
|
760
768
|
getProjectEmbeddingMaxInputTokens2,
|
|
761
769
|
embedTextForProject2,
|
|
762
770
|
embedBatchForProject2,
|
|
763
|
-
|
|
771
|
+
embedItemsWindowBounded2,
|
|
764
772
|
embedUnembeddedMemoriesForProject2,
|
|
765
773
|
drainCommitBacklogForProject2,
|
|
766
774
|
embedSessionCompartmentChunks2,
|
|
767
775
|
getEmbeddingCoverageStatus2,
|
|
768
776
|
getAutoEmbeddingSessionCoverage2
|
|
769
|
-
} from "./index-
|
|
777
|
+
} from "./index-erkb5dee.js";
|
|
770
778
|
import {
|
|
771
779
|
cosineSimilarity
|
|
772
|
-
} from "./index-
|
|
780
|
+
} from "./index-jnh7a6a3.js";
|
|
773
781
|
import {
|
|
774
782
|
USER_FACING_FAILURES,
|
|
775
783
|
renderUserFacingFailure,
|
|
@@ -803,7 +811,7 @@ import {
|
|
|
803
811
|
scheduleClearAndReindex,
|
|
804
812
|
clearSessionTracking,
|
|
805
813
|
createAutoSearchDiagnostics
|
|
806
|
-
} from "./index-
|
|
814
|
+
} from "./index-c3mms4dp.js";
|
|
807
815
|
import"./index-xssjy4z9.js";
|
|
808
816
|
import {
|
|
809
817
|
DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
|
|
@@ -831,11 +839,11 @@ import {
|
|
|
831
839
|
drainPiTagSnapshotSession,
|
|
832
840
|
assertPiTagSnapshotReady,
|
|
833
841
|
ensurePiTagSnapshotReady
|
|
834
|
-
} from "./index-
|
|
842
|
+
} from "./index-nhpvvdhw.js";
|
|
835
843
|
import"./index-yjgkjkjs.js";
|
|
836
|
-
import"./index-
|
|
837
|
-
import"./index-
|
|
838
|
-
import"./index-
|
|
844
|
+
import"./index-8d2z6503.js";
|
|
845
|
+
import"./index-6ahmfva8.js";
|
|
846
|
+
import"./index-9kaj9ty1.js";
|
|
839
847
|
import {
|
|
840
848
|
__toESM
|
|
841
849
|
} from "./index-22jkk6wg.js";
|
|
@@ -845,9 +853,6 @@ import {
|
|
|
845
853
|
import {
|
|
846
854
|
computeNormalizedHash
|
|
847
855
|
} from "./index-9x1f96r8.js";
|
|
848
|
-
import {
|
|
849
|
-
normalizeProtectedToolName
|
|
850
|
-
} from "./index-674f6qs2.js";
|
|
851
856
|
import {
|
|
852
857
|
sameProjectDirectory
|
|
853
858
|
} from "./index-wrr9rp9a.js";
|
|
@@ -3590,7 +3595,7 @@ function startHostStallProfilerSwitch() {
|
|
|
3590
3595
|
// package.json
|
|
3591
3596
|
var package_default = {
|
|
3592
3597
|
name: "@cortexkit/pi-magic-context",
|
|
3593
|
-
version: "0.49.
|
|
3598
|
+
version: "0.49.54",
|
|
3594
3599
|
type: "module",
|
|
3595
3600
|
description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
|
|
3596
3601
|
main: "dist/index.js",
|
|
@@ -3658,6 +3663,7 @@ var package_default = {
|
|
|
3658
3663
|
"omp-coding-agent-18126": "npm:@oh-my-pi/pi-coding-agent@18.12.6",
|
|
3659
3664
|
"omp-coding-agent-18132": "npm:@oh-my-pi/pi-coding-agent@18.13.2",
|
|
3660
3665
|
"omp-coding-agent-18186": "npm:@oh-my-pi/pi-coding-agent@18.18.6",
|
|
3666
|
+
"omp-coding-agent-18190": "npm:@oh-my-pi/pi-coding-agent@18.19.0",
|
|
3661
3667
|
"omp-pi-ai-171": "npm:@oh-my-pi/pi-ai@17.1.7",
|
|
3662
3668
|
"omp-pi-ai-1889": "npm:@oh-my-pi/pi-ai@18.8.9",
|
|
3663
3669
|
"omp-pi-ai-1811": "npm:@oh-my-pi/pi-ai@18.11.3",
|
|
@@ -3668,6 +3674,7 @@ var package_default = {
|
|
|
3668
3674
|
"omp-pi-ai-18180": "npm:@oh-my-pi/pi-ai@18.18.0",
|
|
3669
3675
|
"omp-pi-ai-18181": "npm:@oh-my-pi/pi-ai@18.18.1",
|
|
3670
3676
|
"omp-pi-ai-18186": "npm:@oh-my-pi/pi-ai@18.18.6",
|
|
3677
|
+
"omp-pi-ai-18190": "npm:@oh-my-pi/pi-ai@18.19.0",
|
|
3671
3678
|
"pi-agent-core-087": "npm:@earendil-works/pi-agent-core@0.87.1",
|
|
3672
3679
|
"pi-ai-086": "npm:@earendil-works/pi-ai@0.86.0",
|
|
3673
3680
|
"pi-ai-087": "npm:@earendil-works/pi-ai@0.87.1",
|
|
@@ -21292,9 +21299,19 @@ class PiSubagentRunner {
|
|
|
21292
21299
|
let mappingMessages = [];
|
|
21293
21300
|
const isMemoryMapper = options.agent.replace(/^magic-context-/, "") === "dreamer-memory-mapper";
|
|
21294
21301
|
let settled = false;
|
|
21302
|
+
let startupFailure;
|
|
21295
21303
|
const settle = (result) => {
|
|
21296
21304
|
if (settled)
|
|
21297
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
|
+
}
|
|
21298
21315
|
settled = true;
|
|
21299
21316
|
if (zenChild) {
|
|
21300
21317
|
const classified = classifyZenFreeTierFailure(result, options.model, options.agent, this.invocation.targetHarness);
|
|
@@ -21441,6 +21458,13 @@ class PiSubagentRunner {
|
|
|
21441
21458
|
}, (message) => sessionLog2(options.accountingSessionId ?? "pi-subagent", message));
|
|
21442
21459
|
};
|
|
21443
21460
|
let stderr = "";
|
|
21461
|
+
const observeStartupFailure = (event) => {
|
|
21462
|
+
const error = readSubagentStartupError(event);
|
|
21463
|
+
if (!error)
|
|
21464
|
+
return;
|
|
21465
|
+
startupFailure ??= error;
|
|
21466
|
+
terminateChild(child);
|
|
21467
|
+
};
|
|
21444
21468
|
let stderrLine = "";
|
|
21445
21469
|
const stderrDecoder = new StringDecoder("utf8");
|
|
21446
21470
|
child.stderr?.on("data", (chunk) => {
|
|
@@ -21452,10 +21476,11 @@ class PiSubagentRunner {
|
|
|
21452
21476
|
`);
|
|
21453
21477
|
stderrLine = (lines.pop() ?? "").slice(-4096);
|
|
21454
21478
|
for (const line of lines) {
|
|
21455
|
-
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"')))
|
|
21456
21480
|
continue;
|
|
21457
21481
|
const parsed = parsePiEventLine(line);
|
|
21458
21482
|
if (parsed.ok) {
|
|
21483
|
+
observeStartupFailure(parsed.event);
|
|
21459
21484
|
telemetry.observe(parsed.event);
|
|
21460
21485
|
observeTemperatureDecision(parsed.event);
|
|
21461
21486
|
}
|
|
@@ -21525,6 +21550,7 @@ class PiSubagentRunner {
|
|
|
21525
21550
|
return;
|
|
21526
21551
|
}
|
|
21527
21552
|
const event = parsed.event;
|
|
21553
|
+
observeStartupFailure(event);
|
|
21528
21554
|
observeTemperatureDecision(event);
|
|
21529
21555
|
if (typeof event !== "object" || event === null)
|
|
21530
21556
|
return;
|
|
@@ -24667,7 +24693,8 @@ var canonicalReasons = new Set([
|
|
|
24667
24693
|
"coverage_fold",
|
|
24668
24694
|
"profile_transition",
|
|
24669
24695
|
"host_compaction",
|
|
24670
|
-
"tag_identity_repair"
|
|
24696
|
+
"tag_identity_repair",
|
|
24697
|
+
"latest_turn_thinking_removed"
|
|
24671
24698
|
]);
|
|
24672
24699
|
var piReasonAliases = {
|
|
24673
24700
|
project_memory_change: "project_memory_epoch",
|
|
@@ -27183,6 +27210,66 @@ function latestAssistantTurnStart(messages) {
|
|
|
27183
27210
|
function latestAssistantTurnMessages(messages) {
|
|
27184
27211
|
return new Set(messages.slice(latestAssistantTurnStart(messages)));
|
|
27185
27212
|
}
|
|
27213
|
+
function isSentAssistantMessage(message) {
|
|
27214
|
+
if (!isRecord(message) || role(message) !== "assistant")
|
|
27215
|
+
return false;
|
|
27216
|
+
const parts = content(message);
|
|
27217
|
+
if (!Array.isArray(parts) || parts.length === 0)
|
|
27218
|
+
return false;
|
|
27219
|
+
if (message.stopReason === "error" || message.stopReason === "aborted")
|
|
27220
|
+
return false;
|
|
27221
|
+
const error = isRecord(message.info) ? message.info.error : undefined;
|
|
27222
|
+
if (error === undefined || error === null)
|
|
27223
|
+
return true;
|
|
27224
|
+
return isRecord(error) && error.name === "MessageAbortedError" && parts.some((part) => isRecord(part) && part.type !== "step-start" && part.type !== "reasoning");
|
|
27225
|
+
}
|
|
27226
|
+
var PI_USER_ON_WIRE_ROLES = new Set([
|
|
27227
|
+
"user",
|
|
27228
|
+
"developer",
|
|
27229
|
+
"custom",
|
|
27230
|
+
"hookMessage",
|
|
27231
|
+
"bashExecution",
|
|
27232
|
+
"pythonExecution",
|
|
27233
|
+
"fileMention",
|
|
27234
|
+
"branchSummary",
|
|
27235
|
+
"compactionSummary"
|
|
27236
|
+
]);
|
|
27237
|
+
var TOOL_RESULT_TYPES = new Set(["tool_result", "toolResult", "tool-result"]);
|
|
27238
|
+
function isUserMessageOnWire(message) {
|
|
27239
|
+
if (!isRecord(message))
|
|
27240
|
+
return false;
|
|
27241
|
+
if (isRecord(message.info)) {
|
|
27242
|
+
if (message.info.role !== "user" || !Array.isArray(message.parts))
|
|
27243
|
+
return false;
|
|
27244
|
+
return message.parts.some((part) => isRecord(part) && part.ignored !== true && !TOOL_RESULT_TYPES.has(String(part.type)) && !(part.type === "text" && part.text === ""));
|
|
27245
|
+
}
|
|
27246
|
+
if (!PI_USER_ON_WIRE_ROLES.has(String(message.role)))
|
|
27247
|
+
return false;
|
|
27248
|
+
if (message.excludeFromContext === true)
|
|
27249
|
+
return false;
|
|
27250
|
+
if (message.role !== "user")
|
|
27251
|
+
return true;
|
|
27252
|
+
if (typeof message.content === "string")
|
|
27253
|
+
return message.content.length > 0;
|
|
27254
|
+
return Array.isArray(message.content) && message.content.some((block) => !isRecord(block) || !TOOL_RESULT_TYPES.has(String(block.type)));
|
|
27255
|
+
}
|
|
27256
|
+
function providerLatestTurn(messages) {
|
|
27257
|
+
let last = messages.length - 1;
|
|
27258
|
+
while (last >= 0 && !isSentAssistantMessage(messages[last]))
|
|
27259
|
+
last -= 1;
|
|
27260
|
+
if (last < 0)
|
|
27261
|
+
return;
|
|
27262
|
+
let start = last;
|
|
27263
|
+
while (start > 0 && !isUserMessageOnWire(messages[start - 1]))
|
|
27264
|
+
start -= 1;
|
|
27265
|
+
let first = start;
|
|
27266
|
+
while (first < last && !isSentAssistantMessage(messages[first]))
|
|
27267
|
+
first += 1;
|
|
27268
|
+
let end = last + 1;
|
|
27269
|
+
while (end < messages.length && !isUserMessageOnWire(messages[end]))
|
|
27270
|
+
end += 1;
|
|
27271
|
+
return { start, first, last, end };
|
|
27272
|
+
}
|
|
27186
27273
|
function isAnthropicThinkingPart(part, familyRoute) {
|
|
27187
27274
|
return isRecord(part) && THINKING_TYPES.has(String(part.type ?? part.kind)) && (familyRoute || isRecord(part.metadata) && isRecord(part.metadata.anthropic));
|
|
27188
27275
|
}
|
|
@@ -27238,18 +27325,110 @@ function protectNewTagMutations(messages, targets, protectedParts, prefixBound)
|
|
|
27238
27325
|
|
|
27239
27326
|
// ../plugin/src/hooks/magic-context/latest-thinking-recovery.ts
|
|
27240
27327
|
var LATEST_THINKING_RESTORE = "latest_thinking_original";
|
|
27328
|
+
var TURN_STATE = `${LATEST_THINKING_RESTORE}_turn:`;
|
|
27241
27329
|
var knownRejectedSessions = new Set;
|
|
27242
|
-
var
|
|
27243
|
-
var
|
|
27244
|
-
|
|
27245
|
-
|
|
27246
|
-
|
|
27247
|
-
|
|
27330
|
+
var REFUSE_AT_REJECTION = 3;
|
|
27331
|
+
var STAGES = new Set(["armed", "restoring", "remove", "removed", "refused"]);
|
|
27332
|
+
function readState(target) {
|
|
27333
|
+
if (!target.startsWith(TURN_STATE))
|
|
27334
|
+
return;
|
|
27335
|
+
try {
|
|
27336
|
+
const value = JSON.parse(target.slice(TURN_STATE.length));
|
|
27337
|
+
if (!isRecord(value) || !STAGES.has(String(value.stage)) || typeof value.first !== "string" || typeof value.last !== "string" || typeof value.rejections !== "number")
|
|
27338
|
+
return;
|
|
27339
|
+
return {
|
|
27340
|
+
stage: value.stage,
|
|
27341
|
+
first: value.first,
|
|
27342
|
+
last: value.last,
|
|
27343
|
+
rejections: value.rejections,
|
|
27344
|
+
...typeof value.pass === "string" ? { pass: value.pass } : {},
|
|
27345
|
+
...typeof value.model === "string" ? { model: value.model } : {},
|
|
27346
|
+
...typeof value.provider === "string" ? { provider: value.provider } : {},
|
|
27347
|
+
...value.accepted === true ? { accepted: true } : {}
|
|
27348
|
+
};
|
|
27349
|
+
} catch {
|
|
27350
|
+
return;
|
|
27351
|
+
}
|
|
27352
|
+
}
|
|
27353
|
+
function encodeState(state) {
|
|
27354
|
+
return TURN_STATE + JSON.stringify({
|
|
27355
|
+
stage: state.stage,
|
|
27356
|
+
first: state.first,
|
|
27357
|
+
last: state.last,
|
|
27358
|
+
rejections: state.rejections,
|
|
27359
|
+
...state.pass ? { pass: state.pass } : {},
|
|
27360
|
+
...state.model ? { model: state.model } : {},
|
|
27361
|
+
...state.provider ? { provider: state.provider } : {},
|
|
27362
|
+
...state.accepted ? { accepted: true } : {}
|
|
27363
|
+
});
|
|
27364
|
+
}
|
|
27365
|
+
function identifyTurn(messages, id) {
|
|
27366
|
+
const turn = providerLatestTurn(messages);
|
|
27367
|
+
if (!turn)
|
|
27368
|
+
return;
|
|
27369
|
+
const first = id(messages[turn.first], turn.first);
|
|
27370
|
+
const last = id(messages[turn.last], turn.last);
|
|
27371
|
+
return first && last ? { turn, bound: { first, last } } : undefined;
|
|
27372
|
+
}
|
|
27373
|
+
var lastPassTurn = new Map;
|
|
27374
|
+
var PROCESS_TOKEN = Math.random().toString(36).slice(2, 10);
|
|
27375
|
+
var passCounter = 0;
|
|
27376
|
+
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.";
|
|
27377
|
+
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.";
|
|
27378
|
+
function escalate(state, rejections) {
|
|
27379
|
+
switch (state.stage) {
|
|
27380
|
+
case "armed":
|
|
27381
|
+
return "armed";
|
|
27382
|
+
case "restoring":
|
|
27383
|
+
case "remove":
|
|
27384
|
+
return "remove";
|
|
27385
|
+
case "removed":
|
|
27386
|
+
if (state.accepted)
|
|
27387
|
+
return "remove";
|
|
27388
|
+
return rejections >= REFUSE_AT_REJECTION ? "refused" : "removed";
|
|
27389
|
+
case "refused":
|
|
27390
|
+
return "refused";
|
|
27391
|
+
}
|
|
27392
|
+
}
|
|
27393
|
+
function armLatestThinkingRecovery(db, sessionId, modelID) {
|
|
27248
27394
|
knownRejectedSessions.add(sessionId);
|
|
27249
27395
|
ensureSessionMetaRow(db, sessionId);
|
|
27250
27396
|
const current = getThinkingBindingRecoveryTarget(db, sessionId);
|
|
27251
|
-
const
|
|
27252
|
-
const
|
|
27397
|
+
const state = current ? readState(current) : undefined;
|
|
27398
|
+
const pass = lastPassTurn.get(sessionId);
|
|
27399
|
+
let next;
|
|
27400
|
+
if (state) {
|
|
27401
|
+
if (pass !== undefined && state.pass === pass.pass)
|
|
27402
|
+
return;
|
|
27403
|
+
const rejections = state.accepted ? 1 : state.rejections + 1;
|
|
27404
|
+
const stage = escalate(state, rejections);
|
|
27405
|
+
const last = pass?.first === state.first ? pass.last : state.last;
|
|
27406
|
+
next = encodeState({
|
|
27407
|
+
...state,
|
|
27408
|
+
stage,
|
|
27409
|
+
last,
|
|
27410
|
+
rejections,
|
|
27411
|
+
pass: pass?.pass,
|
|
27412
|
+
accepted: false
|
|
27413
|
+
});
|
|
27414
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: provider rejected the bound turn again (rejection ${rejections}, first=${state.first} last=${last}); ${state.stage} -> ${stage}`);
|
|
27415
|
+
} else if (pass) {
|
|
27416
|
+
const model = pass.model ?? modelID;
|
|
27417
|
+
const provider = pass.model ? pass.provider : undefined;
|
|
27418
|
+
next = encodeState({
|
|
27419
|
+
stage: "armed",
|
|
27420
|
+
first: pass.first,
|
|
27421
|
+
last: pass.last,
|
|
27422
|
+
rejections: 1,
|
|
27423
|
+
pass: pass.pass,
|
|
27424
|
+
...model ? { model } : {},
|
|
27425
|
+
...provider ? { provider } : {}
|
|
27426
|
+
});
|
|
27427
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: armed for the provider's latest turn (first=${pass.first} last=${pass.last} model=${provider ? `${provider}/` : ""}${model ?? "unknown"})`);
|
|
27428
|
+
} else {
|
|
27429
|
+
next = LATEST_THINKING_RESTORE;
|
|
27430
|
+
sessionLog2(sessionId, "latest-turn thinking recovery: rejection not bound, no pass in this process built the rejected request");
|
|
27431
|
+
}
|
|
27253
27432
|
db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ?").run(next, sessionId);
|
|
27254
27433
|
}
|
|
27255
27434
|
function clone(value) {
|
|
@@ -27272,72 +27451,253 @@ function replayableOriginal(part) {
|
|
|
27272
27451
|
const signature = part.signature ?? part.thinkingSignature ?? metadata.signature ?? part.data ?? metadata.redactedData;
|
|
27273
27452
|
return typeof signature === "string" && signature.length > 0 && part.text !== "[cleared]" && part.thinking !== "[cleared]";
|
|
27274
27453
|
}
|
|
27454
|
+
var NO_RECOVERY = { restore: false, ended: false };
|
|
27455
|
+
var LATEST_TURN_THINKING_REMOVED_REASON = "latest_turn_thinking_removed";
|
|
27456
|
+
function replaceTarget(db, sessionId, expected, next) {
|
|
27457
|
+
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;
|
|
27458
|
+
}
|
|
27459
|
+
function decisionMessageId(decision) {
|
|
27460
|
+
if (decision === "binding_mismatch_order:end" || decision === TOOL_SWEEP_SCOPED_MARKER)
|
|
27461
|
+
return;
|
|
27462
|
+
return decodeMergedReasoningParts(decision)?.[0] ?? (decision.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX) ? decision.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length) : decision);
|
|
27463
|
+
}
|
|
27464
|
+
function sentAssistantIds(args, turn) {
|
|
27465
|
+
const ids = [];
|
|
27466
|
+
for (let index = turn.start;index < turn.end; index += 1) {
|
|
27467
|
+
const message = args.messages[index];
|
|
27468
|
+
if (!isSentAssistantMessage(message))
|
|
27469
|
+
continue;
|
|
27470
|
+
const id = args.id(message, index);
|
|
27471
|
+
if (id)
|
|
27472
|
+
ids.push(id);
|
|
27473
|
+
}
|
|
27474
|
+
return ids;
|
|
27475
|
+
}
|
|
27476
|
+
function magicContextEditedTurn(args, turn, modelID) {
|
|
27477
|
+
const ids = new Set(sentAssistantIds(args, turn));
|
|
27478
|
+
for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
27479
|
+
const id = decisionMessageId(decision);
|
|
27480
|
+
if (id !== undefined && ids.has(id))
|
|
27481
|
+
return true;
|
|
27482
|
+
}
|
|
27483
|
+
try {
|
|
27484
|
+
for (const id of getReasoningRemovalState(args.db, args.sessionId).messageIds) {
|
|
27485
|
+
if (ids.has(id))
|
|
27486
|
+
return true;
|
|
27487
|
+
}
|
|
27488
|
+
} catch {}
|
|
27489
|
+
return !isPrefixBoundThinkingModel(undefined, modelID) && clearedByWatermark(args, turn);
|
|
27490
|
+
}
|
|
27491
|
+
function clearedByWatermark(args, turn) {
|
|
27492
|
+
try {
|
|
27493
|
+
const row = args.db.prepare("SELECT cleared_reasoning_through_tag AS watermark FROM session_meta WHERE session_id = ?").get(args.sessionId);
|
|
27494
|
+
const watermark = row?.watermark ?? 0;
|
|
27495
|
+
if (!(watermark > 0))
|
|
27496
|
+
return false;
|
|
27497
|
+
const textTags = args.db.prepare("SELECT MAX(tag_number) AS n FROM tags WHERE session_id = ? AND message_id >= ? AND message_id < ?");
|
|
27498
|
+
const toolTags = args.db.prepare("SELECT MAX(tag_number) AS n FROM tags WHERE session_id = ? AND type = 'tool' AND tool_owner_message_id = ?");
|
|
27499
|
+
for (let index = turn.start;index < turn.end; index += 1) {
|
|
27500
|
+
const message = args.messages[index];
|
|
27501
|
+
if (!isSentAssistantMessage(message))
|
|
27502
|
+
continue;
|
|
27503
|
+
if (!args.parts(message).some(isThinkingPart))
|
|
27504
|
+
continue;
|
|
27505
|
+
const id = args.id(message, index);
|
|
27506
|
+
if (!id)
|
|
27507
|
+
continue;
|
|
27508
|
+
const text = textTags.get(args.sessionId, `${id}:`, `${id};`);
|
|
27509
|
+
const tool = toolTags.get(args.sessionId, id);
|
|
27510
|
+
const newest = Math.max(text?.n ?? 0, tool?.n ?? 0);
|
|
27511
|
+
if (newest > 0 && newest <= watermark)
|
|
27512
|
+
return true;
|
|
27513
|
+
}
|
|
27514
|
+
} catch {}
|
|
27515
|
+
return false;
|
|
27516
|
+
}
|
|
27517
|
+
function restoreBlocker(args, turn) {
|
|
27518
|
+
if (turn.start === 0)
|
|
27519
|
+
return "no-turn-start";
|
|
27520
|
+
const turnMessages = args.messages.slice(turn.start, turn.end);
|
|
27521
|
+
if (!turnMessages.some((message) => args.parts(message).some(replayableOriginal)))
|
|
27522
|
+
return "missing-thinking-original";
|
|
27523
|
+
const ids = new Map(args.messages.map((message, index) => [args.id(message, index), index]));
|
|
27524
|
+
for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
27525
|
+
const id = decisionMessageId(decision);
|
|
27526
|
+
if (id === undefined)
|
|
27527
|
+
continue;
|
|
27528
|
+
const index = ids.get(id);
|
|
27529
|
+
if (index === undefined || index >= turn.start && !args.parts(args.messages[index]).some(replayableOriginal))
|
|
27530
|
+
return `missing-original:${id}`;
|
|
27531
|
+
}
|
|
27532
|
+
return;
|
|
27533
|
+
}
|
|
27534
|
+
function refuse(sessionId, why) {
|
|
27535
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: refused locally (${why})`);
|
|
27536
|
+
throw contextRefusalError(LATEST_THINKING_UNSAFE);
|
|
27537
|
+
}
|
|
27538
|
+
function refuseUnsaved(sessionId, why) {
|
|
27539
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: refused locally (${why})`);
|
|
27540
|
+
throw contextRefusalError(LATEST_THINKING_NOT_SAVED);
|
|
27541
|
+
}
|
|
27542
|
+
function frozenBindingIds(args) {
|
|
27543
|
+
const frozen = new Set;
|
|
27544
|
+
for (const decision of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
27545
|
+
if (decision.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX))
|
|
27546
|
+
frozen.add(decision.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length));
|
|
27547
|
+
}
|
|
27548
|
+
return frozen;
|
|
27549
|
+
}
|
|
27550
|
+
function frozenTurnIds(args, turn) {
|
|
27551
|
+
const frozen = frozenBindingIds(args);
|
|
27552
|
+
return sentAssistantIds(args, turn).filter((id) => frozen.has(id));
|
|
27553
|
+
}
|
|
27554
|
+
function persistBindingRemoval(db, sessionId, ids) {
|
|
27555
|
+
return addMergedReasoningStrippedIds(db, sessionId, ids.map(thinkingBindingRecoveryFrozenId));
|
|
27556
|
+
}
|
|
27557
|
+
function removeTurnThinking(args, target, state, turn, current) {
|
|
27558
|
+
const frozen = frozenBindingIds(args);
|
|
27559
|
+
const ids = [];
|
|
27560
|
+
let parts = 0;
|
|
27561
|
+
for (let index = turn.start;index < turn.end; index += 1) {
|
|
27562
|
+
const message = args.messages[index];
|
|
27563
|
+
if (!isSentAssistantMessage(message))
|
|
27564
|
+
continue;
|
|
27565
|
+
const thinking = args.parts(message).filter(isThinkingPart).length;
|
|
27566
|
+
if (thinking === 0)
|
|
27567
|
+
continue;
|
|
27568
|
+
const id = args.id(message, index);
|
|
27569
|
+
if (!id)
|
|
27570
|
+
refuse(args.sessionId, "a thinking message of the turn has no stable id");
|
|
27571
|
+
if (frozen.has(id))
|
|
27572
|
+
continue;
|
|
27573
|
+
ids.push(id);
|
|
27574
|
+
parts += thinking;
|
|
27575
|
+
}
|
|
27576
|
+
if (ids.length === 0) {
|
|
27577
|
+
replaceTarget(args.db, args.sessionId, target, encodeState({ ...state, stage: "refused", last: current.last }));
|
|
27578
|
+
refuse(args.sessionId, "the rejected turn has no thinking left to remove");
|
|
27579
|
+
}
|
|
27580
|
+
const persist = args.persistRemoval ?? ((next) => persistBindingRemoval(args.db, args.sessionId, next));
|
|
27581
|
+
let persisted = false;
|
|
27582
|
+
try {
|
|
27583
|
+
args.db.transaction(() => {
|
|
27584
|
+
if (!persist(ids))
|
|
27585
|
+
throw new Error("thinking removal was not persisted");
|
|
27586
|
+
const next = encodeState({ ...state, stage: "removed", last: current.last });
|
|
27587
|
+
if (!replaceTarget(args.db, args.sessionId, target, next))
|
|
27588
|
+
throw new Error("recovery state changed concurrently");
|
|
27589
|
+
}).immediate();
|
|
27590
|
+
persisted = true;
|
|
27591
|
+
} catch (error) {
|
|
27592
|
+
sessionLog2(args.sessionId, "latest-turn thinking recovery: removal write failed:", error);
|
|
27593
|
+
}
|
|
27594
|
+
if (!persisted)
|
|
27595
|
+
refuseUnsaved(args.sessionId, "the thinking removal could not be saved");
|
|
27596
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: removed thinking from the bound turn (parts=${parts} messages=${ids.length} first=${state.first} last=${current.last})`);
|
|
27597
|
+
return {
|
|
27598
|
+
restore: false,
|
|
27599
|
+
ended: false,
|
|
27600
|
+
removedThisPass: true,
|
|
27601
|
+
removedIds: frozenTurnIds(args, turn)
|
|
27602
|
+
};
|
|
27603
|
+
}
|
|
27275
27604
|
function prepareLatestThinkingRecovery(args) {
|
|
27276
|
-
const
|
|
27277
|
-
|
|
27278
|
-
|
|
27279
|
-
|
|
27605
|
+
const identified = identifyTurn(args.messages, args.id);
|
|
27606
|
+
if (identified)
|
|
27607
|
+
lastPassTurn.set(args.sessionId, {
|
|
27608
|
+
...identified.bound,
|
|
27609
|
+
pass: `${PROCESS_TOKEN}:${++passCounter}`,
|
|
27610
|
+
...args.modelID ? { model: args.modelID } : {},
|
|
27611
|
+
...args.modelID && args.providerID ? { provider: args.providerID } : {}
|
|
27612
|
+
});
|
|
27280
27613
|
else
|
|
27281
|
-
|
|
27614
|
+
lastPassTurn.delete(args.sessionId);
|
|
27282
27615
|
let target;
|
|
27283
27616
|
try {
|
|
27284
27617
|
target = getThinkingBindingRecoveryTarget(args.db, args.sessionId);
|
|
27285
27618
|
} catch (error) {
|
|
27286
27619
|
if (knownRejectedSessions.has(args.sessionId))
|
|
27287
|
-
|
|
27288
|
-
return
|
|
27620
|
+
refuseUnsaved(args.sessionId, "the recovery state could not be read");
|
|
27621
|
+
return NO_RECOVERY;
|
|
27289
27622
|
}
|
|
27290
27623
|
if (!target || !target.startsWith(LATEST_THINKING_RESTORE)) {
|
|
27291
27624
|
knownRejectedSessions.delete(args.sessionId);
|
|
27292
|
-
return
|
|
27625
|
+
return NO_RECOVERY;
|
|
27293
27626
|
}
|
|
27294
|
-
const
|
|
27295
|
-
if (
|
|
27296
|
-
args.db
|
|
27627
|
+
const state = readState(target);
|
|
27628
|
+
if (!state) {
|
|
27629
|
+
replaceTarget(args.db, args.sessionId, target, "");
|
|
27297
27630
|
knownRejectedSessions.delete(args.sessionId);
|
|
27298
|
-
|
|
27631
|
+
sessionLog2(args.sessionId, "latest-turn thinking recovery: cleared a rejection that names no turn");
|
|
27632
|
+
return NO_RECOVERY;
|
|
27299
27633
|
}
|
|
27300
|
-
|
|
27301
|
-
|
|
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);
|
|
27634
|
+
const unbind = (why) => {
|
|
27635
|
+
replaceTarget(args.db, args.sessionId, target, "");
|
|
27304
27636
|
knownRejectedSessions.delete(args.sessionId);
|
|
27305
|
-
|
|
27306
|
-
|
|
27307
|
-
|
|
27308
|
-
|
|
27309
|
-
|
|
27310
|
-
|
|
27311
|
-
|
|
27312
|
-
const
|
|
27313
|
-
if (!
|
|
27314
|
-
|
|
27315
|
-
const
|
|
27316
|
-
|
|
27317
|
-
if (
|
|
27318
|
-
|
|
27319
|
-
|
|
27320
|
-
|
|
27321
|
-
|
|
27322
|
-
throw contextRefusalError(LATEST_THINKING_UNSAFE + ` [missing-original:${id}]`);
|
|
27637
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: unbound because ${why} (stage=${state.stage} first=${state.first} last=${state.last})`);
|
|
27638
|
+
return { restore: false, ended: state.stage === "restoring" };
|
|
27639
|
+
};
|
|
27640
|
+
if (args.modelID && state.model && args.modelID.toLowerCase() !== state.model.toLowerCase())
|
|
27641
|
+
return unbind(`the request now goes to ${args.modelID}`);
|
|
27642
|
+
if (args.providerID && state.provider && args.providerID.toLowerCase() !== state.provider.toLowerCase())
|
|
27643
|
+
return unbind(`the request now goes through ${args.providerID}`);
|
|
27644
|
+
const current = identified?.bound;
|
|
27645
|
+
if (!identified || !current || current.first !== state.first)
|
|
27646
|
+
return unbind(`a newer turn was accepted (now first=${current?.first ?? "none"} last=${current?.last ?? "none"})`);
|
|
27647
|
+
const turn = identified.turn;
|
|
27648
|
+
if (current.last !== state.last && state.stage !== "restoring") {
|
|
27649
|
+
if (state.stage !== "removed")
|
|
27650
|
+
return unbind(`a newer message of the turn was accepted (now last=${current.last})`);
|
|
27651
|
+
replaceTarget(args.db, args.sessionId, target, encodeState({ ...state, last: current.last, accepted: true }));
|
|
27652
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: a request without the turn's removed thinking was accepted (first=${state.first} last=${current.last})`);
|
|
27653
|
+
return { ...NO_RECOVERY, removedIds: frozenTurnIds(args, identified.turn) };
|
|
27323
27654
|
}
|
|
27324
|
-
|
|
27325
|
-
|
|
27326
|
-
|
|
27655
|
+
knownRejectedSessions.add(args.sessionId);
|
|
27656
|
+
switch (state.stage) {
|
|
27657
|
+
case "refused":
|
|
27658
|
+
return refuse(args.sessionId, `the provider rejected the turn first=${state.first} ${state.rejections} times`);
|
|
27659
|
+
case "removed":
|
|
27660
|
+
return { ...NO_RECOVERY, removedIds: frozenTurnIds(args, turn) };
|
|
27661
|
+
case "restoring": {
|
|
27662
|
+
const blocker = restoreBlocker(args, turn);
|
|
27663
|
+
if (blocker === undefined)
|
|
27664
|
+
return { restore: true, ended: false };
|
|
27665
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: restore no longer possible (${blocker}); removing the turn's thinking instead`);
|
|
27666
|
+
return removeTurnThinking(args, target, state, turn, current);
|
|
27667
|
+
}
|
|
27668
|
+
case "armed": {
|
|
27669
|
+
if (magicContextEditedTurn(args, turn, args.modelID)) {
|
|
27670
|
+
const blocker = restoreBlocker(args, turn);
|
|
27671
|
+
if (blocker === undefined) {
|
|
27672
|
+
replaceTarget(args.db, args.sessionId, target, encodeState({ ...state, stage: "restoring", last: current.last }));
|
|
27673
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: restore applied to the bound turn (first=${state.first} last=${current.last})`);
|
|
27674
|
+
return { restore: true, ended: false };
|
|
27675
|
+
}
|
|
27676
|
+
sessionLog2(args.sessionId, `latest-turn thinking recovery: restore unavailable (${blocker}); removing the turn's thinking instead`);
|
|
27677
|
+
}
|
|
27678
|
+
return removeTurnThinking(args, target, state, turn, current);
|
|
27679
|
+
}
|
|
27680
|
+
case "remove":
|
|
27681
|
+
return removeTurnThinking(args, target, state, turn, current);
|
|
27682
|
+
}
|
|
27683
|
+
}
|
|
27684
|
+
function latestThinkingRestoringTurnMessages(args) {
|
|
27327
27685
|
let target;
|
|
27328
27686
|
try {
|
|
27329
27687
|
target = getThinkingBindingRecoveryTarget(args.db, args.sessionId);
|
|
27330
27688
|
} catch {
|
|
27331
|
-
return
|
|
27689
|
+
return;
|
|
27332
27690
|
}
|
|
27333
|
-
const
|
|
27334
|
-
if (
|
|
27335
|
-
return
|
|
27336
|
-
const
|
|
27337
|
-
|
|
27691
|
+
const state = target ? readState(target) : undefined;
|
|
27692
|
+
if (state?.stage !== "restoring")
|
|
27693
|
+
return;
|
|
27694
|
+
const identified = identifyTurn(args.messages, args.id);
|
|
27695
|
+
if (identified?.bound.first !== state.first)
|
|
27696
|
+
return;
|
|
27697
|
+
return new Set(args.messages.slice(identified.turn.start));
|
|
27338
27698
|
}
|
|
27339
27699
|
function captureOriginalTurn(messages, parts, setParts) {
|
|
27340
|
-
const start = Math.max(0, latestAssistantTurnStart(messages) - 1);
|
|
27700
|
+
const start = Math.max(0, (providerLatestTurn(messages)?.start ?? latestAssistantTurnStart(messages)) - 1);
|
|
27341
27701
|
const originals = messages.slice(start).map((message) => ({ message, parts: clone(parts(message)) }));
|
|
27342
27702
|
const before = messages.slice(0, start);
|
|
27343
27703
|
return (target = messages) => {
|
|
@@ -27351,10 +27711,17 @@ function captureOriginalTurn(messages, parts, setParts) {
|
|
|
27351
27711
|
};
|
|
27352
27712
|
}
|
|
27353
27713
|
function armBindingRecoverySafely(db, sessionId) {
|
|
27354
|
-
|
|
27355
|
-
|
|
27356
|
-
|
|
27357
|
-
|
|
27714
|
+
const target = getThinkingBindingRecoveryTarget(db, sessionId);
|
|
27715
|
+
if (target?.startsWith(LATEST_THINKING_RESTORE)) {
|
|
27716
|
+
const stage = readState(target)?.stage;
|
|
27717
|
+
if (stage !== "removed" && stage !== "refused") {
|
|
27718
|
+
armLatestThinkingRecovery(db, sessionId);
|
|
27719
|
+
return;
|
|
27720
|
+
}
|
|
27721
|
+
knownRejectedSessions.delete(sessionId);
|
|
27722
|
+
sessionLog2(sessionId, `latest-turn thinking recovery: binding rejection handed to the binding recovery (stage=${stage})`);
|
|
27723
|
+
}
|
|
27724
|
+
armThinkingBindingRecovery(db, sessionId);
|
|
27358
27725
|
}
|
|
27359
27726
|
|
|
27360
27727
|
// ../plugin/src/hooks/magic-context/reasoning-budget-status.ts
|
|
@@ -27622,8 +27989,13 @@ function decideSignedThinkingHold(args) {
|
|
|
27622
27989
|
heavyStepTokens,
|
|
27623
27990
|
capPercentage
|
|
27624
27991
|
};
|
|
27625
|
-
|
|
27626
|
-
|
|
27992
|
+
const ended = readingEndsHold({
|
|
27993
|
+
usagePercentage: args.usagePercentage,
|
|
27994
|
+
capPercentage,
|
|
27995
|
+
forceBandPressure: args.forceBandPressure
|
|
27996
|
+
});
|
|
27997
|
+
if (ended !== null)
|
|
27998
|
+
return { held: false, reason: ended, heavyStepsBack, heavyStepTokens, capPercentage };
|
|
27627
27999
|
return {
|
|
27628
28000
|
held: true,
|
|
27629
28001
|
reason: "heavy_reasoning",
|
|
@@ -27632,6 +28004,11 @@ function decideSignedThinkingHold(args) {
|
|
|
27632
28004
|
capPercentage
|
|
27633
28005
|
};
|
|
27634
28006
|
}
|
|
28007
|
+
function readingEndsHold(args) {
|
|
28008
|
+
if (!(args.usagePercentage < args.capPercentage))
|
|
28009
|
+
return "above_cap";
|
|
28010
|
+
return args.forceBandPressure ? "force_band" : null;
|
|
28011
|
+
}
|
|
27635
28012
|
|
|
27636
28013
|
// ../plugin/src/hooks/magic-context/strict-thinking-prefix.ts
|
|
27637
28014
|
function servedPrefixMatches(args) {
|
|
@@ -29954,11 +30331,11 @@ async function embedAndStoreCompartmentChunks(db, sessionId, projectPath, compar
|
|
|
29954
30331
|
if (currentModelId !== "off" && chunkEmbeddingWindowsAreCurrent2(db, compartment.id, currentModelId, windows, projectPath)) {
|
|
29955
30332
|
continue;
|
|
29956
30333
|
}
|
|
29957
|
-
const result = await
|
|
30334
|
+
const result = await embedItemsWindowBounded2(projectPath, windows.map((window) => ({
|
|
29958
30335
|
id: `chunk:${compartment.id}:${window.windowIndex}`,
|
|
29959
30336
|
text: window.text,
|
|
29960
30337
|
contentSha256: contentSha2562(window.text)
|
|
29961
|
-
})), undefined, db, sessionId);
|
|
30338
|
+
})), undefined, db, sessionId, { stopOnIncompleteSlice: true });
|
|
29962
30339
|
if (!result)
|
|
29963
30340
|
continue;
|
|
29964
30341
|
if (chunkEmbeddingWindowsAreCurrent2(db, compartment.id, currentModelId, windows, projectPath)) {
|
|
@@ -30057,7 +30434,7 @@ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
|
|
|
30057
30434
|
|
|
30058
30435
|
// src/pi-history-retirement.ts
|
|
30059
30436
|
var KEY2 = "piHistorianRetirement";
|
|
30060
|
-
function
|
|
30437
|
+
function readState2(db, sessionId) {
|
|
30061
30438
|
const row = db.prepare("SELECT deferred_execute_state AS state FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
30062
30439
|
const state = row?.state ? JSON.parse(row.state) : {};
|
|
30063
30440
|
if (!state || typeof state !== "object" || Array.isArray(state))
|
|
@@ -30065,17 +30442,17 @@ function readState(db, sessionId) {
|
|
|
30065
30442
|
return state;
|
|
30066
30443
|
}
|
|
30067
30444
|
function readPiHistoryRetirement(db, sessionId) {
|
|
30068
|
-
const target =
|
|
30445
|
+
const target = readState2(db, sessionId)[KEY2];
|
|
30069
30446
|
return typeof target === "string" && target.length > 0 ? target : null;
|
|
30070
30447
|
}
|
|
30071
30448
|
function queuePiHistoryRetirement(db, sessionId, throughMessageId) {
|
|
30072
30449
|
ensureSessionMetaRow(db, sessionId);
|
|
30073
|
-
const state =
|
|
30450
|
+
const state = readState2(db, sessionId);
|
|
30074
30451
|
state[KEY2] = throughMessageId;
|
|
30075
30452
|
db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(state), sessionId);
|
|
30076
30453
|
}
|
|
30077
30454
|
function acknowledgePiHistoryRetirement(db, sessionId, publishedEnd, ordinalOf) {
|
|
30078
|
-
const state =
|
|
30455
|
+
const state = readState2(db, sessionId);
|
|
30079
30456
|
const target = state[KEY2];
|
|
30080
30457
|
if (typeof target !== "string")
|
|
30081
30458
|
return;
|
|
@@ -31479,6 +31856,9 @@ function recordPiTransformTiming(sample) {
|
|
|
31479
31856
|
// src/ctx-reduce-nudge-pi.ts
|
|
31480
31857
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
31481
31858
|
|
|
31859
|
+
// src/tail-hygiene-walk-pi.ts
|
|
31860
|
+
import { createHash as createHash13 } from "node:crypto";
|
|
31861
|
+
|
|
31482
31862
|
// src/provider-visible-parts-pi.ts
|
|
31483
31863
|
function isRecord4(value) {
|
|
31484
31864
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
@@ -31535,10 +31915,15 @@ function providerVisiblePiPart(value, providerApi) {
|
|
|
31535
31915
|
// src/tail-hygiene-walk-pi.ts
|
|
31536
31916
|
var TAG_PREFIX = /^§(\d+)§\s*/;
|
|
31537
31917
|
var SYNTHETIC_TODO_PREFIX = "mc_synthetic_todo_";
|
|
31538
|
-
var MAX_CONTENT_MEMO_ENTRIES =
|
|
31918
|
+
var MAX_CONTENT_MEMO_ENTRIES = 250000;
|
|
31539
31919
|
var MAX_CONTENT_MEMO_BYTES = 64 * 1024 * 1024;
|
|
31920
|
+
var INLINE_CONTENT_KEY_CHARS = 64;
|
|
31540
31921
|
var contentMemo = new Map;
|
|
31541
31922
|
var contentMemoBytes = 0;
|
|
31923
|
+
var contentMemoHits = 0;
|
|
31924
|
+
var contentMemoMisses = 0;
|
|
31925
|
+
var contentMemoEvictions = 0;
|
|
31926
|
+
var contentMemoTokenizations = 0;
|
|
31542
31927
|
function clearPiTailHygieneContentMemo() {
|
|
31543
31928
|
contentMemo.clear();
|
|
31544
31929
|
contentMemoBytes = 0;
|
|
@@ -31572,12 +31957,15 @@ function safeStableStringify(value) {
|
|
|
31572
31957
|
}
|
|
31573
31958
|
}
|
|
31574
31959
|
function memoizedContent(kind, content) {
|
|
31575
|
-
const key =
|
|
31960
|
+
const key = contentMemoKey(kind, content);
|
|
31576
31961
|
const cached = contentMemo.get(key);
|
|
31577
|
-
if (cached)
|
|
31962
|
+
if (cached) {
|
|
31963
|
+
contentMemoHits += 1;
|
|
31578
31964
|
return cached;
|
|
31965
|
+
}
|
|
31966
|
+
contentMemoMisses += 1;
|
|
31579
31967
|
const measured = {
|
|
31580
|
-
hash: fnv1a32(
|
|
31968
|
+
hash: fnv1a32(`${kind}\x00${content}`),
|
|
31581
31969
|
tokens: kind === "excluded" ? 0 : undefined,
|
|
31582
31970
|
keyBytes: key.length * 2 + 32
|
|
31583
31971
|
};
|
|
@@ -31591,15 +31979,26 @@ function memoizedContent(kind, content) {
|
|
|
31591
31979
|
if (removed)
|
|
31592
31980
|
contentMemoBytes -= removed.keyBytes;
|
|
31593
31981
|
contentMemo.delete(oldest);
|
|
31982
|
+
contentMemoEvictions += 1;
|
|
31594
31983
|
}
|
|
31595
31984
|
return measured;
|
|
31596
31985
|
}
|
|
31597
|
-
function
|
|
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) {
|
|
31598
31993
|
const measured = memoizedContent(kind, content);
|
|
31599
31994
|
if (measured.tokens === undefined) {
|
|
31995
|
+
contentMemoTokenizations += 1;
|
|
31600
31996
|
measured.tokens = estimateTokens(content);
|
|
31601
31997
|
}
|
|
31602
|
-
return measured.tokens;
|
|
31998
|
+
return { contentHash: measured.hash, tokens: measured.tokens };
|
|
31999
|
+
}
|
|
32000
|
+
function memoizedTokens(kind, content) {
|
|
32001
|
+
return measuredContent(kind, content).tokens;
|
|
31603
32002
|
}
|
|
31604
32003
|
function partHash(kind, content) {
|
|
31605
32004
|
return memoizedContent(kind, content).hash;
|
|
@@ -32094,7 +32493,7 @@ function measurePiTailHygiene(input) {
|
|
|
32094
32493
|
key: `${messageKey}\x00text:0`,
|
|
32095
32494
|
kind: "text",
|
|
32096
32495
|
content,
|
|
32097
|
-
|
|
32496
|
+
...measuredContent("text", content),
|
|
32098
32497
|
tag
|
|
32099
32498
|
});
|
|
32100
32499
|
}
|
|
@@ -32132,7 +32531,7 @@ function measurePiTailHygiene(input) {
|
|
|
32132
32531
|
key: `${key}\x00toolOutput`,
|
|
32133
32532
|
kind: "toolOutput",
|
|
32134
32533
|
content,
|
|
32135
|
-
|
|
32534
|
+
...measuredContent("toolOutput", content),
|
|
32136
32535
|
tag: arc?.sentinel ? undefined : tag
|
|
32137
32536
|
});
|
|
32138
32537
|
}
|
|
@@ -32148,7 +32547,7 @@ function measurePiTailHygiene(input) {
|
|
|
32148
32547
|
key: `${key}\x00text`,
|
|
32149
32548
|
kind: "text",
|
|
32150
32549
|
content,
|
|
32151
|
-
|
|
32550
|
+
...measuredContent("text", content),
|
|
32152
32551
|
tag
|
|
32153
32552
|
});
|
|
32154
32553
|
}
|
|
@@ -32186,7 +32585,7 @@ function measurePiTailHygiene(input) {
|
|
|
32186
32585
|
key: `${key}\x00toolInput`,
|
|
32187
32586
|
kind: "toolInput",
|
|
32188
32587
|
content,
|
|
32189
|
-
|
|
32588
|
+
...measuredContent("toolInput", content),
|
|
32190
32589
|
tag: arc?.sentinel ? undefined : arc?.tag
|
|
32191
32590
|
});
|
|
32192
32591
|
}
|
|
@@ -32531,6 +32930,50 @@ var DEDUP_SAFE_TOOLS = new Set([
|
|
|
32531
32930
|
"mcp_lsp_goto_definition",
|
|
32532
32931
|
"mcp_lsp_prepare_rename"
|
|
32533
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
|
+
}
|
|
32534
32977
|
function buildPiToolFingerprints(messages, resolveStableId) {
|
|
32535
32978
|
const fingerprints = new Map;
|
|
32536
32979
|
for (let i = 0;i < messages.length; i++) {
|
|
@@ -32677,9 +33120,11 @@ function applyPiHeuristicCleanup(sessionId, db, targets, piMessages, config, pre
|
|
|
32677
33120
|
} : measured;
|
|
32678
33121
|
}
|
|
32679
33122
|
} : target;
|
|
32680
|
-
|
|
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;
|
|
32681
33125
|
});
|
|
32682
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;
|
|
32683
33128
|
const droppableTags = candidateTags.flatMap((tag) => {
|
|
32684
33129
|
const measured = byTag.get(tag.tagNumber);
|
|
32685
33130
|
return measured ? [measured] : [];
|
|
@@ -32693,6 +33138,7 @@ function applyPiHeuristicCleanup(sessionId, db, targets, piMessages, config, pre
|
|
|
32693
33138
|
maxTag,
|
|
32694
33139
|
protectedCutoff,
|
|
32695
33140
|
currentTotalInputTokens: emergency.currentTotalInputTokens,
|
|
33141
|
+
removedThisPassTokens,
|
|
32696
33142
|
ceilingTokens: emergency.ceilingTokens,
|
|
32697
33143
|
usagePercentage: emergency.usagePercentage,
|
|
32698
33144
|
priorInputSample,
|
|
@@ -34322,6 +34768,7 @@ function piImageFromDataUrl(dataUrl) {
|
|
|
34322
34768
|
return null;
|
|
34323
34769
|
return { type: "image", mimeType: match[1], data: match[2] };
|
|
34324
34770
|
}
|
|
34771
|
+
var PI_IMAGE_DATA_URL_PREFIX = /^data:image\/[a-zA-Z0-9.+-]+;base64,[\s\S]/;
|
|
34325
34772
|
function resolveMuralForM0Pi(state, db, modelKey, budgetTokens, mode = "persist") {
|
|
34326
34773
|
if (state.memoryEnabled === false)
|
|
34327
34774
|
return;
|
|
@@ -34690,6 +35137,7 @@ function materializeM0Pi(state, db, passSnapshot) {
|
|
|
34690
35137
|
const upgradeIdentity = withCachedM0MemoryIds(encodeCachedM0UpgradeIdentity(snapshotMarkers.upgradeState, snapshotMarkers.compartmentRenderEpoch, snapshotMarkers.muralEnabled, snapshotMarkers.renderBudgetIdentity, snapshotMarkers.memoryRenderEpoch, snapshotMarkers.renderedBudgets ?? null), renderedMemoryIds);
|
|
34691
35138
|
steps.mark("pre_metadata");
|
|
34692
35139
|
state.beforeCacheCommitForTest?.();
|
|
35140
|
+
const commitFold = state.onFoldPrepare?.();
|
|
34693
35141
|
try {
|
|
34694
35142
|
db.exec("BEGIN IMMEDIATE");
|
|
34695
35143
|
} catch (error) {
|
|
@@ -34739,6 +35187,15 @@ function materializeM0Pi(state, db, passSnapshot) {
|
|
|
34739
35187
|
steps.mark("persistCachedM0");
|
|
34740
35188
|
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
35189
|
steps.mark("sessionMeta");
|
|
35190
|
+
if (commitFold) {
|
|
35191
|
+
const muralWire = m0.includes("<memory-mural>") && frozenMuralDataUrl ? frozenMuralDataUrl : null;
|
|
35192
|
+
commitFold(db, {
|
|
35193
|
+
m0Text: muralWire ? m0 : stripMemoryMuralBlock(m0),
|
|
35194
|
+
m1Text: m1Render.text,
|
|
35195
|
+
muralDataUrl: muralWire && PI_IMAGE_DATA_URL_PREFIX.test(muralWire) ? muralWire : null
|
|
35196
|
+
});
|
|
35197
|
+
steps.mark("onFoldCommit");
|
|
35198
|
+
}
|
|
34742
35199
|
db.exec("COMMIT");
|
|
34743
35200
|
steps.mark("commit");
|
|
34744
35201
|
logSlowWriteTransaction("pi_materialize_cache", transactionStartedAt, undefined, performance.now(), steps.durations);
|
|
@@ -35523,6 +35980,12 @@ var RESPONSES_APIS = new Set([
|
|
|
35523
35980
|
function isPiDropPlaceholder(text) {
|
|
35524
35981
|
return DROP_PLACEHOLDER.test(text);
|
|
35525
35982
|
}
|
|
35983
|
+
function nativeTextMatchesBlock(nativeText, blockText) {
|
|
35984
|
+
return nativeText === blockText.replace(TAG_LABEL, "");
|
|
35985
|
+
}
|
|
35986
|
+
function hookCleanedTextMatchesBlock(nativeText, blockText) {
|
|
35987
|
+
return nativeTextMatchesBlock(stripPersistedAssistantText(nativeText), blockText);
|
|
35988
|
+
}
|
|
35526
35989
|
function getNativeEnvelope(message) {
|
|
35527
35990
|
if (!isRecord(message) || isPiSystemEntry(message))
|
|
35528
35991
|
return;
|
|
@@ -35649,12 +36112,11 @@ function hookRewrittenSlot(previous, partIndex, items) {
|
|
|
35649
36112
|
return;
|
|
35650
36113
|
continue;
|
|
35651
36114
|
}
|
|
35652
|
-
|
|
35653
|
-
if (stripped !== block.text.replace(TAG_LABEL, ""))
|
|
36115
|
+
if (!hookCleanedTextMatchesBlock(slot.text, block.text))
|
|
35654
36116
|
return;
|
|
35655
36117
|
if (index !== partIndex)
|
|
35656
36118
|
continue;
|
|
35657
|
-
if (
|
|
36119
|
+
if (item.content.length !== 1)
|
|
35658
36120
|
return;
|
|
35659
36121
|
target = slot;
|
|
35660
36122
|
}
|
|
@@ -35744,7 +36206,7 @@ function rewriteNativeAssistantTexts(message, previous, sessionId, options = {})
|
|
|
35744
36206
|
return;
|
|
35745
36207
|
const content = envelope.message.content;
|
|
35746
36208
|
const arrivedItems = envelope.items;
|
|
35747
|
-
const
|
|
36209
|
+
const unsignedEdits = options.unsignedEdits === true && RESPONSES_APIS.has(String(envelope.message.api)) && envelope.payload.dt === true;
|
|
35748
36210
|
for (let index = 0;index < content.length; index++) {
|
|
35749
36211
|
const part = content[index];
|
|
35750
36212
|
const before = previous.content[index];
|
|
@@ -35753,14 +36215,14 @@ function rewriteNativeAssistantTexts(message, previous, sessionId, options = {})
|
|
|
35753
36215
|
if (part.text.replace(/^§\d+§ /u, "") === before.text.replace(/^§\d+§ /u, ""))
|
|
35754
36216
|
continue;
|
|
35755
36217
|
const identity = textIdentity(part);
|
|
35756
|
-
if (identity === undefined &&
|
|
36218
|
+
if (identity === undefined && unsignedEdits && !("textSignature" in part)) {
|
|
35757
36219
|
const slot = hookRewrittenSlot(previous.content, index, arrivedItems);
|
|
35758
36220
|
if (slot) {
|
|
35759
36221
|
const item = envelope.items[slot.itemIndex];
|
|
35760
36222
|
const outputs = item.content.slice();
|
|
35761
36223
|
outputs[slot.outputIndex] = {
|
|
35762
36224
|
...outputs[slot.outputIndex],
|
|
35763
|
-
text: part.text
|
|
36225
|
+
text: part.text.replace(TAG_LABEL, "")
|
|
35764
36226
|
};
|
|
35765
36227
|
const items = envelope.items.slice();
|
|
35766
36228
|
items[slot.itemIndex] = { ...item, content: outputs };
|
|
@@ -36135,15 +36597,9 @@ function authorizePiToolRemoval(args) {
|
|
|
36135
36597
|
}
|
|
36136
36598
|
|
|
36137
36599
|
// src/native-replay-tag-provenance-pi.ts
|
|
36138
|
-
import { createHash as
|
|
36139
|
-
var PI_NATIVE_TAG_STRIP_PROVENANCE = "magicContextNativeTagStrips";
|
|
36600
|
+
import { createHash as createHash14 } from "node:crypto";
|
|
36140
36601
|
function nativeResponseTagStripKey(id, phase, text) {
|
|
36141
|
-
return
|
|
36142
|
-
}
|
|
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);
|
|
36602
|
+
return createHash14("sha256").update(JSON.stringify([id, phase, text])).digest("hex");
|
|
36147
36603
|
}
|
|
36148
36604
|
|
|
36149
36605
|
// src/native-replay-tags-pi.ts
|
|
@@ -36192,7 +36648,6 @@ function applyNativeResponseTagReplayPi(args) {
|
|
|
36192
36648
|
const frozen = saved;
|
|
36193
36649
|
const content = message.content;
|
|
36194
36650
|
const nativeItems = payload.items;
|
|
36195
|
-
const decisions = {};
|
|
36196
36651
|
let changed = false;
|
|
36197
36652
|
const items = nativeItems.map((item) => {
|
|
36198
36653
|
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 +36670,6 @@ function applyNativeResponseTagReplayPi(args) {
|
|
|
36215
36670
|
return item;
|
|
36216
36671
|
added.add(key);
|
|
36217
36672
|
}
|
|
36218
|
-
decisions[key] = output.text;
|
|
36219
36673
|
changed = true;
|
|
36220
36674
|
return {
|
|
36221
36675
|
...item,
|
|
@@ -36225,7 +36679,6 @@ function applyNativeResponseTagReplayPi(args) {
|
|
|
36225
36679
|
if (changed)
|
|
36226
36680
|
pending.set(index, {
|
|
36227
36681
|
...message,
|
|
36228
|
-
[PI_NATIVE_TAG_STRIP_PROVENANCE]: decisions,
|
|
36229
36682
|
providerPayload: { ...payload, items }
|
|
36230
36683
|
});
|
|
36231
36684
|
}
|
|
@@ -37415,7 +37868,7 @@ function coldReplayable(items) {
|
|
|
37415
37868
|
}
|
|
37416
37869
|
return reasoning;
|
|
37417
37870
|
}
|
|
37418
|
-
function piResponsesAssistantTexts(value, model, host, alternatives
|
|
37871
|
+
function piResponsesAssistantTexts(value, model, host, alternatives) {
|
|
37419
37872
|
const message = object8(value);
|
|
37420
37873
|
if (!message || !Array.isArray(message.content))
|
|
37421
37874
|
return;
|
|
@@ -37478,8 +37931,6 @@ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagSt
|
|
|
37478
37931
|
"openai-codex-responses"
|
|
37479
37932
|
].includes(model?.api ?? "");
|
|
37480
37933
|
let unsigned = false;
|
|
37481
|
-
let rewrittenText = false;
|
|
37482
|
-
let allUnsignedFrozen = true;
|
|
37483
37934
|
for (const value of payload.items) {
|
|
37484
37935
|
const item = object8(value);
|
|
37485
37936
|
if (item?.type === "reasoning")
|
|
@@ -37505,15 +37956,12 @@ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagSt
|
|
|
37505
37956
|
} catch {
|
|
37506
37957
|
return texts;
|
|
37507
37958
|
}
|
|
37508
|
-
const signed = signature?.v === 1 && typeof signature.id === "string" && item.id === signature.id && item.phase === signature.phase && part.text
|
|
37959
|
+
const signed = signature?.v === 1 && typeof signature.id === "string" && item.id === signature.id && item.phase === signature.phase && nativeTextMatchesBlock(part.text, block.text);
|
|
37509
37960
|
if (!signed) {
|
|
37510
|
-
const stripped = stripPersistedAssistantText(part.text);
|
|
37511
37961
|
const droppedPlaceholder = isPiDropPlaceholder(block.text) && part.text === block.text;
|
|
37512
|
-
if (!allowUnsigned || "textSignature" in block || !droppedPlaceholder &&
|
|
37962
|
+
if (!allowUnsigned || "textSignature" in block || !droppedPlaceholder && !hookCleanedTextMatchesBlock(part.text, block.text))
|
|
37513
37963
|
return texts;
|
|
37514
37964
|
unsigned = true;
|
|
37515
|
-
allUnsignedFrozen &&= droppedPlaceholder || part.text === block.text && ownsNativeResponseTagStrip(frozenTagStrips, item.id, item.phase, part.text);
|
|
37516
|
-
rewrittenText ||= !droppedPlaceholder && part.text !== stripped;
|
|
37517
37965
|
}
|
|
37518
37966
|
bound++;
|
|
37519
37967
|
itemTexts.push(part.text);
|
|
@@ -37524,7 +37972,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagSt
|
|
|
37524
37972
|
for (const text of itemTexts)
|
|
37525
37973
|
replay.push(textIdentity2(wellFormed2(text), item.phase));
|
|
37526
37974
|
}
|
|
37527
|
-
if (!output || bound !== blocks.length
|
|
37975
|
+
if (!output || bound !== blocks.length)
|
|
37528
37976
|
return texts;
|
|
37529
37977
|
if (unsigned && alternatives) {
|
|
37530
37978
|
alternatives.fallback = texts;
|
|
@@ -38256,7 +38704,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
|
|
|
38256
38704
|
continue;
|
|
38257
38705
|
}
|
|
38258
38706
|
const alternatives = {};
|
|
38259
|
-
const texts = piResponsesAssistantTexts(projectedMessages[index], model, host, alternatives
|
|
38707
|
+
const texts = piResponsesAssistantTexts(projectedMessages[index], model, host, alternatives);
|
|
38260
38708
|
if (!texts) {
|
|
38261
38709
|
responsesMessages = undefined;
|
|
38262
38710
|
break;
|
|
@@ -39042,7 +39490,7 @@ function piDispatchMismatchDiagnostic(payload, prepared, mismatch) {
|
|
|
39042
39490
|
}
|
|
39043
39491
|
|
|
39044
39492
|
// src/pi-foreign-session-index.ts
|
|
39045
|
-
import { createHash as
|
|
39493
|
+
import { createHash as createHash15 } from "node:crypto";
|
|
39046
39494
|
|
|
39047
39495
|
// src/pi-foreign-omp-kinds.ts
|
|
39048
39496
|
var PI_FOREIGN_RENDERED_CONTENT_KINDS = [
|
|
@@ -39875,7 +40323,7 @@ function fingerprint(text, index, wire = false) {
|
|
|
39875
40323
|
index.stats.wireHashes++;
|
|
39876
40324
|
else
|
|
39877
40325
|
index.stats.hashes++;
|
|
39878
|
-
return
|
|
40326
|
+
return createHash15("sha256").update(stableStringify([{ type: "text", text }])).digest("hex");
|
|
39879
40327
|
}
|
|
39880
40328
|
function protectSession(index, message, roleOverride, trackEntry = false) {
|
|
39881
40329
|
const rendering = texts(index, message, roleOverride, trackEntry);
|
|
@@ -40706,7 +41154,7 @@ function piExpandChainedRequest(payload, chained, anchor, prepared, pass) {
|
|
|
40706
41154
|
}
|
|
40707
41155
|
|
|
40708
41156
|
// src/pi-dispatch-cursor.ts
|
|
40709
|
-
import { createHash as
|
|
41157
|
+
import { createHash as createHash16 } from "node:crypto";
|
|
40710
41158
|
var MAX_BYTES = 32 * 1024 * 1024;
|
|
40711
41159
|
var MAX_ENTRIES = 1e5;
|
|
40712
41160
|
function object13(value) {
|
|
@@ -40833,7 +41281,7 @@ Today: ${day}; current working directory: '${cwd.replace(/\\/gu, "/")}'. Do not
|
|
|
40833
41281
|
const hash = (content) => {
|
|
40834
41282
|
const json = JSON.stringify({ role: "user", content });
|
|
40835
41283
|
if (json.length <= MAX_BYTES)
|
|
40836
|
-
roots.add(
|
|
41284
|
+
roots.add(createHash16("sha256").update(json).digest("hex"));
|
|
40837
41285
|
};
|
|
40838
41286
|
hash(parts);
|
|
40839
41287
|
if (reminder) {
|
|
@@ -41957,7 +42405,7 @@ function tokenizePiMessages(messages, options) {
|
|
|
41957
42405
|
}
|
|
41958
42406
|
}
|
|
41959
42407
|
}
|
|
41960
|
-
if (options && liveIds) {
|
|
42408
|
+
if (options && liveIds && options.prune !== false) {
|
|
41961
42409
|
const cachePruneStart = options.onTiming ? performance.now() : 0;
|
|
41962
42410
|
for (const id of options.cache.keys()) {
|
|
41963
42411
|
if (!liveIds.has(id))
|
|
@@ -42150,7 +42598,7 @@ function piFallbackRefusal(site, cause) {
|
|
|
42150
42598
|
}
|
|
42151
42599
|
return cause instanceof PiDegradedPassError ? cause : new PiDegradedPassError(site, { cause });
|
|
42152
42600
|
}
|
|
42153
|
-
function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, contextLimit) {
|
|
42601
|
+
function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, contextLimit, tokenCounts) {
|
|
42154
42602
|
if (!observed || !Number.isFinite(observed.systemTokens) || observed.systemTokens <= 0 || !Number.isFinite(observed.toolDefinitionTokens) || observed.toolDefinitionTokens < 0 || !hasTokenizerForFit())
|
|
42155
42603
|
return { tokens: 0, trusted: false };
|
|
42156
42604
|
const knownRole = (message) => {
|
|
@@ -42245,7 +42693,7 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
|
|
|
42245
42693
|
refusalGrade: false,
|
|
42246
42694
|
refusalBasis: "byte-bound"
|
|
42247
42695
|
};
|
|
42248
|
-
const raw = tokenizePiMessages([...messages]);
|
|
42696
|
+
const raw = tokenizePiMessages([...messages], tokenCounts ? { ...tokenCounts, prune: false } : undefined);
|
|
42249
42697
|
const calibration = observed.calibration ?? calibrationForModelKey(observed.modelKey);
|
|
42250
42698
|
const refusalCalibration = calibrationForModelKey(observed.modelKey);
|
|
42251
42699
|
const tokens = providerMass({
|
|
@@ -42370,6 +42818,26 @@ function releasePiOperationPayloads(operation) {
|
|
|
42370
42818
|
function operationKey(ctx) {
|
|
42371
42819
|
return ctx.sessionManager?.getSessionId?.() ?? ctx.sessionManager ?? "no-session";
|
|
42372
42820
|
}
|
|
42821
|
+
function servedSessionOf(ctx) {
|
|
42822
|
+
try {
|
|
42823
|
+
const id = ctx.sessionManager?.getSessionId?.();
|
|
42824
|
+
return typeof id === "string" && id.length > 0 ? id : undefined;
|
|
42825
|
+
} catch {
|
|
42826
|
+
return;
|
|
42827
|
+
}
|
|
42828
|
+
}
|
|
42829
|
+
function finishPiServedRequest(sessionId, ctx, messages, compactionOff) {
|
|
42830
|
+
try {
|
|
42831
|
+
commitServedRequest({
|
|
42832
|
+
sessionId,
|
|
42833
|
+
host: "pi",
|
|
42834
|
+
messages,
|
|
42835
|
+
providerID: ctx.model?.provider,
|
|
42836
|
+
modelID: ctx.model?.id,
|
|
42837
|
+
compactionOff: compactionOff()
|
|
42838
|
+
});
|
|
42839
|
+
} catch {}
|
|
42840
|
+
}
|
|
42373
42841
|
function messageKey(message) {
|
|
42374
42842
|
if (!message || typeof message !== "object")
|
|
42375
42843
|
return;
|
|
@@ -42440,7 +42908,14 @@ function inputBranch(ctx, inputs) {
|
|
|
42440
42908
|
return;
|
|
42441
42909
|
}
|
|
42442
42910
|
}
|
|
42443
|
-
function
|
|
42911
|
+
function endsWithFailedAttempt(input, messages, ended) {
|
|
42912
|
+
if (ended.length !== input.length + 1 || exactReusablePrefix(input, ended) !== input.length)
|
|
42913
|
+
return false;
|
|
42914
|
+
const last = messages.at(-1);
|
|
42915
|
+
const lastKey = ended.at(-1)?.id;
|
|
42916
|
+
return last?.role === "assistant" && (last.stopReason === "error" || last.stopReason === "aborted") && !!lastKey && !input.some((message) => message.id === lastKey);
|
|
42917
|
+
}
|
|
42918
|
+
function dispatchedEndBelongsToEarlierRun(operation, event, ctx, startOutstanding) {
|
|
42444
42919
|
if (!operation.dispatched || !operation.started || !operation.ready || !operation.pass?.completed || operation.refused || operation.pass.abandoned || !operation.inputBranch)
|
|
42445
42920
|
return false;
|
|
42446
42921
|
try {
|
|
@@ -42450,9 +42925,16 @@ function dispatchedEndBelongsToEarlierRun(operation, event, ctx) {
|
|
|
42450
42925
|
const prepared = operation.inputBranch;
|
|
42451
42926
|
if (!current || current.entryIds[prepared.anchorIndex] !== prepared.anchorId || current.messages.length !== prepared.messages.length || exactReusablePrefix(current.messages, prepared.messages) !== prepared.messages.length)
|
|
42452
42927
|
return false;
|
|
42453
|
-
const
|
|
42928
|
+
const end = event;
|
|
42929
|
+
const messages = end?.messages;
|
|
42454
42930
|
const ended = Array.isArray(messages) ? messageSnapshots(messages) : undefined;
|
|
42455
|
-
|
|
42931
|
+
if (!ended || !Array.isArray(messages))
|
|
42932
|
+
return false;
|
|
42933
|
+
if (end.willContinue === true && endsWithFailedAttempt(prepared.messages, messages, ended))
|
|
42934
|
+
return true;
|
|
42935
|
+
if (!startOutstanding)
|
|
42936
|
+
return false;
|
|
42937
|
+
return ended.length <= prepared.anchorIndex && ended.length < prepared.messages.length && exactReusablePrefix(prepared.messages, ended) === ended.length;
|
|
42456
42938
|
} catch {
|
|
42457
42939
|
return false;
|
|
42458
42940
|
}
|
|
@@ -42556,7 +43038,7 @@ function registerPiGuardedContext(pi, handler, options = {}) {
|
|
|
42556
43038
|
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
43039
|
const operation = operations.get(key);
|
|
42558
43040
|
if (operation) {
|
|
42559
|
-
if (endBelongsToEarlierRun(operation, event) || lifecycleSeen.starts > lifecycleSeen.ends
|
|
43041
|
+
if (endBelongsToEarlierRun(operation, event) || dispatchedEndBelongsToEarlierRun(operation, event, ctx, lifecycleSeen.starts > lifecycleSeen.ends)) {
|
|
42560
43042
|
if (operation.dispatched)
|
|
42561
43043
|
operation.retainedAfterEnd = true;
|
|
42562
43044
|
if (lifecycleSeen.starts <= lifecycleSeen.ends)
|
|
@@ -42766,6 +43248,9 @@ function registerPiGuardedContext(pi, handler, options = {}) {
|
|
|
42766
43248
|
active.ready = false;
|
|
42767
43249
|
active.refused = false;
|
|
42768
43250
|
active.refusalMessage = undefined;
|
|
43251
|
+
const servedSessionId = budget.sideTurn ? undefined : servedSessionOf(ctx);
|
|
43252
|
+
if (servedSessionId)
|
|
43253
|
+
beginServedRequest(servedSessionId);
|
|
42769
43254
|
const { isOwned, isCurrent, assertOwner } = createPiContextOwnershipGuards(operations, key, active, budget, owner);
|
|
42770
43255
|
budget.assertOwner = assertOwner;
|
|
42771
43256
|
try {
|
|
@@ -42801,8 +43286,12 @@ function registerPiGuardedContext(pi, handler, options = {}) {
|
|
|
42801
43286
|
if (inputs)
|
|
42802
43287
|
active.inputBranch = inputBranch(ctx, inputs);
|
|
42803
43288
|
}
|
|
43289
|
+
if (servedSessionId)
|
|
43290
|
+
finishPiServedRequest(servedSessionId, ctx, result?.messages ?? event.messages, () => options.compactionOff?.(ctx) === true);
|
|
42804
43291
|
return result;
|
|
42805
43292
|
} catch (error) {
|
|
43293
|
+
if (servedSessionId)
|
|
43294
|
+
countServedRefusal(servedSessionId);
|
|
42806
43295
|
if (budget.isCancelled(error)) {
|
|
42807
43296
|
budget.cancel();
|
|
42808
43297
|
if (isOwned())
|
|
@@ -42968,7 +43457,7 @@ function createPiFallbackIndex() {
|
|
|
42968
43457
|
}
|
|
42969
43458
|
|
|
42970
43459
|
// src/pi-fit-reclaim.ts
|
|
42971
|
-
import { createHash as
|
|
43460
|
+
import { createHash as createHash17, randomUUID as randomUUID4 } from "node:crypto";
|
|
42972
43461
|
var pendingInput = new Set;
|
|
42973
43462
|
var KEY3 = "piUpperEstimateReclaim";
|
|
42974
43463
|
function piFitOverflowPossible(args) {
|
|
@@ -43004,7 +43493,7 @@ function piUpperReclaimCursor(args) {
|
|
|
43004
43493
|
sessionId: args.sessionId,
|
|
43005
43494
|
modelKey: args.modelKey,
|
|
43006
43495
|
contextWindow: args.contextWindow ?? null,
|
|
43007
|
-
head: head ?
|
|
43496
|
+
head: head ? createHash17("sha256").update(JSON.stringify([
|
|
43008
43497
|
Buffer.from(head.cachedM0Bytes ?? []).toString("base64"),
|
|
43009
43498
|
Buffer.from(head.cachedM1Bytes ?? []).toString("base64"),
|
|
43010
43499
|
head.cachedM0MuralDataUrl ?? null
|
|
@@ -43091,7 +43580,7 @@ async function waitForPiHistorianInTurn(sessionId, remainingMs, wait) {
|
|
|
43091
43580
|
}
|
|
43092
43581
|
|
|
43093
43582
|
// src/pi-lkg-fit-envelope.ts
|
|
43094
|
-
import { createHash as
|
|
43583
|
+
import { createHash as createHash18 } from "node:crypto";
|
|
43095
43584
|
function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
|
|
43096
43585
|
try {
|
|
43097
43586
|
if (!modelKey || typeof pi.getAllTools !== "function")
|
|
@@ -43153,7 +43642,7 @@ function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
|
|
|
43153
43642
|
refusalToolDefinitionTokens,
|
|
43154
43643
|
toolDefinitionsMeasured: refusalToolDefinitionTokens !== undefined,
|
|
43155
43644
|
envelopeBytes: Buffer.byteLength(envelopeJson),
|
|
43156
|
-
envelopeSignature: activeNames ?
|
|
43645
|
+
envelopeSignature: activeNames ? createHash18("sha256").update(envelopeJson).update(JSON.stringify(activeNames)).digest("hex") : undefined,
|
|
43157
43646
|
calibration
|
|
43158
43647
|
};
|
|
43159
43648
|
} catch {
|
|
@@ -43162,13 +43651,13 @@ function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
|
|
|
43162
43651
|
}
|
|
43163
43652
|
|
|
43164
43653
|
// src/pi-message-identity.ts
|
|
43165
|
-
import { createHash as
|
|
43654
|
+
import { createHash as createHash21 } from "node:crypto";
|
|
43166
43655
|
|
|
43167
43656
|
// src/pi-tool-identity.ts
|
|
43168
|
-
import { createHash as
|
|
43657
|
+
import { createHash as createHash20 } from "node:crypto";
|
|
43169
43658
|
|
|
43170
43659
|
// src/served-array-ledger.ts
|
|
43171
|
-
import { createHash as
|
|
43660
|
+
import { createHash as createHash19 } from "node:crypto";
|
|
43172
43661
|
import {
|
|
43173
43662
|
closeSync as closeSync2,
|
|
43174
43663
|
fstatSync,
|
|
@@ -43446,7 +43935,7 @@ function getPiLastServedArray(sessionId) {
|
|
|
43446
43935
|
return previous ? `[${previous.serializedMessages.join(",")}]` : undefined;
|
|
43447
43936
|
}
|
|
43448
43937
|
function sha256(value) {
|
|
43449
|
-
return
|
|
43938
|
+
return createHash19("sha256").update(value).digest("hex");
|
|
43450
43939
|
}
|
|
43451
43940
|
function safeSessionFileStem(sessionId) {
|
|
43452
43941
|
const readable = sessionId.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 96);
|
|
@@ -43731,7 +44220,7 @@ function readPiServedCachedArray(sessionId) {
|
|
|
43731
44220
|
const memory = getPiLastServedArray(sessionId);
|
|
43732
44221
|
const slot = memory === undefined ? getSlot(sessionId) : undefined;
|
|
43733
44222
|
const jsonPrefix = memory ?? slot?.jsonPrefix;
|
|
43734
|
-
if (jsonPrefix === undefined ||
|
|
44223
|
+
if (jsonPrefix === undefined || createHash20("sha256").update(jsonPrefix).digest("hex") !== getPiLastServedDigest(sessionId))
|
|
43735
44224
|
return;
|
|
43736
44225
|
let parsed;
|
|
43737
44226
|
try {
|
|
@@ -43755,7 +44244,7 @@ function piMessageEntryFingerprint(message) {
|
|
|
43755
44244
|
const m = message;
|
|
43756
44245
|
if (typeof m.role !== "string")
|
|
43757
44246
|
return null;
|
|
43758
|
-
const contentHash =
|
|
44247
|
+
const contentHash = createHash21("sha256").update(stableStringify(m.content)).digest("hex");
|
|
43759
44248
|
return JSON.stringify([
|
|
43760
44249
|
typeof m.responseId === "string" ? m.responseId : null,
|
|
43761
44250
|
typeof m.timestamp === "number" || typeof m.timestamp === "string" ? m.timestamp : null,
|
|
@@ -44661,7 +45150,7 @@ function handlePiProviderFailure(args) {
|
|
|
44661
45150
|
const model = typeof message.model === "string" ? message.model : undefined;
|
|
44662
45151
|
const binding = detectThinkingBindingMismatch(message.errorMessage);
|
|
44663
45152
|
if (detectLatestTurnThinkingMismatch(message.errorMessage) && !args.compactionOff && isAnthropicFamilyRoute(provider, model)) {
|
|
44664
|
-
armLatestThinkingRecovery(args.db, args.sessionId);
|
|
45153
|
+
armLatestThinkingRecovery(args.db, args.sessionId, model);
|
|
44665
45154
|
clearPiLkgSessionState(args.sessionId);
|
|
44666
45155
|
dropSlot(args.sessionId, "latest-thinking-recovery-arm");
|
|
44667
45156
|
return { kind: "thinking_binding", armed: true };
|
|
@@ -44733,7 +45222,6 @@ class PiThinkingBindingRecoveryRefusal extends EmergencyFailClosedError {
|
|
|
44733
45222
|
}
|
|
44734
45223
|
}
|
|
44735
45224
|
function applyPiThinkingBindingRecovery(args) {
|
|
44736
|
-
const protectedMessages = latestAssistantTurnMessages(args.messages);
|
|
44737
45225
|
const frozenEntryIds = frozenBindingEntryIds(args.db, args.sessionId);
|
|
44738
45226
|
const flagTargetCandidate = !args.replayOnly && isPrefixBoundThinkingModel(args.provider, args.model) ? getThinkingBindingRecoveryTarget(args.db, args.sessionId) : null;
|
|
44739
45227
|
const flagTarget = flagTargetCandidate?.startsWith(LATEST_THINKING_RESTORE) ? null : flagTargetCandidate;
|
|
@@ -44762,14 +45250,14 @@ function applyPiThinkingBindingRecovery(args) {
|
|
|
44762
45250
|
} else
|
|
44763
45251
|
throw new PiThinkingBindingRecoveryRefusal;
|
|
44764
45252
|
}
|
|
44765
|
-
const
|
|
45253
|
+
const restoringTurn = latestThinkingRestoringTurnMessages({
|
|
44766
45254
|
db: args.db,
|
|
44767
45255
|
sessionId: args.sessionId,
|
|
44768
45256
|
messages: args.messages,
|
|
44769
45257
|
id: (message, index) => resolvePiStableId(message, index, args.entryIds)
|
|
44770
45258
|
});
|
|
44771
45259
|
for (let index = 0;index < args.messages.length; index += 1) {
|
|
44772
|
-
if (
|
|
45260
|
+
if (restoringTurn?.has(args.messages[index]))
|
|
44773
45261
|
continue;
|
|
44774
45262
|
const entryId = args.entryIds[index];
|
|
44775
45263
|
if (entryId && frozenEntryIds.has(entryId))
|
|
@@ -44839,6 +45327,26 @@ function frozenBindingEntryIds(db, sessionId) {
|
|
|
44839
45327
|
}
|
|
44840
45328
|
return ids;
|
|
44841
45329
|
}
|
|
45330
|
+
function persistPiLatestTurnThinkingRemoval(db, sessionId, entryIds) {
|
|
45331
|
+
const endOrder = getMergedReasoningStrippedIds(db, sessionId).has(THINKING_BINDING_STRIP_ORDER_END_MARKER) || frozenBindingEntryIds(db, sessionId).size === 0;
|
|
45332
|
+
const persisted = addMergedReasoningStrippedIds(db, sessionId, [
|
|
45333
|
+
...entryIds.map(thinkingBindingRecoveryFrozenId),
|
|
45334
|
+
...endOrder ? [THINKING_BINDING_STRIP_ORDER_END_MARKER] : []
|
|
45335
|
+
]);
|
|
45336
|
+
return { persisted, stripNow: persisted && !endOrder };
|
|
45337
|
+
}
|
|
45338
|
+
function piBindingStripsAtStart(db, sessionId) {
|
|
45339
|
+
return !getMergedReasoningStrippedIds(db, sessionId).has(THINKING_BINDING_STRIP_ORDER_END_MARKER) && frozenBindingEntryIds(db, sessionId).size > 0;
|
|
45340
|
+
}
|
|
45341
|
+
function stripPiThinkingOfIds(messages, ids, resolveId) {
|
|
45342
|
+
let stripped = 0;
|
|
45343
|
+
for (let index = 0;index < messages.length; index += 1) {
|
|
45344
|
+
const id = resolveId(messages[index], index);
|
|
45345
|
+
if (id && ids.has(id))
|
|
45346
|
+
stripped += stripThinkingParts(messages[index]);
|
|
45347
|
+
}
|
|
45348
|
+
return stripped;
|
|
45349
|
+
}
|
|
44842
45350
|
function resolvePiBindingStripOrder(args) {
|
|
44843
45351
|
const ledger = getMergedReasoningStrippedIds(args.db, args.sessionId);
|
|
44844
45352
|
if (ledger.has(THINKING_BINDING_STRIP_ORDER_END_MARKER))
|
|
@@ -45876,7 +46384,7 @@ function createPiTranscript(source, sessionId, entryIds, options = {}) {
|
|
|
45876
46384
|
committed = true;
|
|
45877
46385
|
for (const index of dirtyMessages) {
|
|
45878
46386
|
rewriteNativeAssistantTexts(working[index], source[index], sessionId, {
|
|
45879
|
-
|
|
46387
|
+
unsignedEdits: harness === "omp"
|
|
45880
46388
|
});
|
|
45881
46389
|
}
|
|
45882
46390
|
for (const [index, parts] of removals) {
|
|
@@ -48183,6 +48691,16 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
48183
48691
|
return;
|
|
48184
48692
|
}
|
|
48185
48693
|
};
|
|
48694
|
+
const afterCapture = (sessionId, statement, run) => {
|
|
48695
|
+
try {
|
|
48696
|
+
return run();
|
|
48697
|
+
} catch (error) {
|
|
48698
|
+
if (budget.isCancelled(error) || error instanceof PiContextDeadlineError || error instanceof PiContextSupersededError)
|
|
48699
|
+
throw error;
|
|
48700
|
+
sessionLog2(sessionId, `${statement} failed after the request was decided; serving the pass:`, error);
|
|
48701
|
+
return;
|
|
48702
|
+
}
|
|
48703
|
+
};
|
|
48186
48704
|
try {
|
|
48187
48705
|
const tFindSession = performance.now();
|
|
48188
48706
|
const sessionId = resolveSessionId2(ctx);
|
|
@@ -48775,7 +49293,12 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
48775
49293
|
messages: event.messages,
|
|
48776
49294
|
prefixBound: isPrefixBoundThinkingModel(ctx.model?.provider, ctx.model?.id),
|
|
48777
49295
|
usagePercentage,
|
|
48778
|
-
executeThresholdPercentage: effectiveExecuteThresholdPercentage
|
|
49296
|
+
executeThresholdPercentage: effectiveExecuteThresholdPercentage,
|
|
49297
|
+
forceBandPressure: !options.compactionOff && piForceBandPressure({
|
|
49298
|
+
forceMaterialization: forceMaterialization || isEmergency,
|
|
49299
|
+
percentage: usagePercentage,
|
|
49300
|
+
forceMaterializationPercentage
|
|
49301
|
+
})
|
|
48779
49302
|
}),
|
|
48780
49303
|
requestToolsChange,
|
|
48781
49304
|
contextUsage: {
|
|
@@ -48913,13 +49436,13 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
48913
49436
|
assertCurrentPass();
|
|
48914
49437
|
recordSuccessfulTaggedMessageIds(sessionId, taggedInputEntryIds ?? strictEntryIds, branchEntries);
|
|
48915
49438
|
}
|
|
48916
|
-
const piDecisionSnapshotNewestAssistant = result.bustedThisPass || hasPendingPiSystemPromptHashChange(sessionId) ? findNewestPiAssistantEntryId(branchEntries) : undefined;
|
|
49439
|
+
const piDecisionSnapshotNewestAssistant = result.bustedThisPass || result.latestTurnThinkingRemoved === true || hasPendingPiSystemPromptHashChange(sessionId) ? findNewestPiAssistantEntryId(branchEntries) : undefined;
|
|
48917
49440
|
const publishTransformDecision = !budget.sideTurn && piDecisionSnapshotNewestAssistant !== undefined ? () => {
|
|
48918
49441
|
recordPendingPiTransformDecision(sessionId, {
|
|
48919
49442
|
tsMs: Date.now(),
|
|
48920
49443
|
decision: schedulerDecision,
|
|
48921
49444
|
materialized: result.materialized,
|
|
48922
|
-
materializeReason: normalizeMaterializeReason("pi", result.materializeReason, result.materialized),
|
|
49445
|
+
materializeReason: normalizeMaterializeReason("pi", result.materializeReason ?? (result.latestTurnThinkingRemoved ? LATEST_TURN_THINKING_REMOVED_REASON : null), result.materialized),
|
|
48923
49446
|
systemHashPrev: result.materialized ? result.injectionResult?.systemHashPrev ?? null : null,
|
|
48924
49447
|
systemHashNew: result.materialized ? result.injectionResult?.systemHashNew ?? null : null,
|
|
48925
49448
|
m0ModelKeyPrev: result.materialized ? result.injectionResult?.m0ModelKeyPrev ?? null : null,
|
|
@@ -49234,7 +49757,14 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
49234
49757
|
const envelope = readPiLkgFitEnvelope(ctx, pi, resolvePiContextModelKey(ctx), sessionDecisionCalibration(options.db, sessionId), toolWireSchema);
|
|
49235
49758
|
const measuredPrefix = lkgPassSnapshot ? lkgCoordinator.measureOutgoingPrefix(lkgPassSnapshot, outputMessages, (id) => ctx.sessionManager.getEntry?.(id)?.parentId) : undefined;
|
|
49236
49759
|
const outgoingFitLimit = getHarness2() === "pi" && baseWindowGeometry ? baseWindowGeometry.derivation.absoluteWall : rawFallbackLimit;
|
|
49237
|
-
|
|
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());
|
|
49238
49768
|
let fitReclaimedThisPass = false;
|
|
49239
49769
|
if (!inputForThinkingFit && result.strictThinkingKept && rawFallbackLimit && estimate.refusalGrade && (estimate.refusalTokens ?? estimate.tokens) > rawFallbackLimit) {
|
|
49240
49770
|
const restored = restorePiLkgInputForFit(lkgPassSnapshot, branchEntries);
|
|
@@ -49264,7 +49794,7 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
49264
49794
|
cacheBustingPass: result.prefixBustPermitted,
|
|
49265
49795
|
stripActiveTurn: true
|
|
49266
49796
|
});
|
|
49267
|
-
estimate = estimatePiOutgoingInputTokens(outputMessages, envelope, undefined, rawFallbackLimit);
|
|
49797
|
+
estimate = estimatePiOutgoingInputTokens(outputMessages, envelope, undefined, rawFallbackLimit, fitTokenCounts());
|
|
49268
49798
|
}
|
|
49269
49799
|
const opaqueFallbackSteps = piOpaqueThinkingFallbackSteps(outputMessages);
|
|
49270
49800
|
if (opaqueFallbackSteps > 0)
|
|
@@ -49392,7 +49922,7 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
49392
49922
|
cacheBustingPass: result.prefixBustPermitted,
|
|
49393
49923
|
stripActiveTurn: result.signedPrefixRewritten
|
|
49394
49924
|
});
|
|
49395
|
-
estimate = estimatePiOutgoingInputTokens(outputMessages, envelope, undefined, outgoingFitLimit);
|
|
49925
|
+
estimate = estimatePiOutgoingInputTokens(outputMessages, envelope, undefined, outgoingFitLimit, fitTokenCounts());
|
|
49396
49926
|
} finally {
|
|
49397
49927
|
if (!reclaimCompleted && upperCursor && reservation)
|
|
49398
49928
|
releasePiUpperEstimateReclaim(options.db, upperCursor, reservation);
|
|
@@ -49429,6 +49959,8 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
49429
49959
|
}
|
|
49430
49960
|
}
|
|
49431
49961
|
publishFinalRequestAccounting();
|
|
49962
|
+
if (!budget.sideTurn && (result.strictThinkingKept && !result.signedPrefixRewritten || result.heldHeadReleasedForSystemChange === true) && !result.materialized)
|
|
49963
|
+
recordPiHeldSystemHead(sessionId, (ownsHistory) => deferPiDeliveredSystemRefresh(sessionId, ownsHistory));
|
|
49432
49964
|
let serializedOutput;
|
|
49433
49965
|
let numbersCommitted = false;
|
|
49434
49966
|
budget.stage = "LKG/served publication";
|
|
@@ -49503,7 +50035,7 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
49503
50035
|
if (!budget.sideTurn && result.identityRebuilt && (numbersCommitted || lkgCompactionOff))
|
|
49504
50036
|
acknowledgePiIdentityRebuilds(options.db, sessionId);
|
|
49505
50037
|
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);
|
|
50038
|
+
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
50039
|
if (thinkingBindingRecoveryApplied) {
|
|
49508
50040
|
try {
|
|
49509
50041
|
clearThinkingBindingRecoveryIf(options.db, sessionId, thinkingBindingRecoveryApplied.flagTarget);
|
|
@@ -49512,14 +50044,14 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
49512
50044
|
}
|
|
49513
50045
|
}
|
|
49514
50046
|
budget.assertOutcome();
|
|
49515
|
-
publishTransformDecision?.();
|
|
49516
|
-
|
|
49517
|
-
|
|
49518
|
-
|
|
49519
|
-
|
|
49520
|
-
|
|
49521
|
-
|
|
49522
|
-
recordServedSystemHash
|
|
50047
|
+
afterCapture(sessionId, "transform decision record", () => publishTransformDecision?.());
|
|
50048
|
+
afterCapture(sessionId, "request tools release record", () => {
|
|
50049
|
+
if (requestToolsChange === null || recordPiBindingStripEndOrder(options.db, sessionId))
|
|
50050
|
+
requestToolsRelease?.commit();
|
|
50051
|
+
else
|
|
50052
|
+
sessionLog2(sessionId, "request tools release not recorded: the end strip order could not be written");
|
|
50053
|
+
});
|
|
50054
|
+
afterCapture(sessionId, "served system hash record", recordServedSystemHash);
|
|
49523
50055
|
return { messages: outputMessages };
|
|
49524
50056
|
} catch (err) {
|
|
49525
50057
|
if (budget.isCancelled(err))
|
|
@@ -49553,6 +50085,7 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
49553
50085
|
budget.assertOutcome();
|
|
49554
50086
|
budget.recovery = err.recovery;
|
|
49555
50087
|
recordServedSystemHash();
|
|
50088
|
+
noteServedReplay(sessionIdForError);
|
|
49556
50089
|
return { messages: err.messages };
|
|
49557
50090
|
}
|
|
49558
50091
|
if ((isFailClosedBlockingError(err) || err instanceof EmergencyFailClosedError) && !baseOptions.compactionOff)
|
|
@@ -49621,6 +50154,7 @@ function registerPiContextHandler(pi, baseOptions) {
|
|
|
49621
50154
|
budget.assertOutcome();
|
|
49622
50155
|
budget.recovery = "fitting LKG replay";
|
|
49623
50156
|
recordServedSystemHash();
|
|
50157
|
+
noteServedReplay(sessionIdForError);
|
|
49624
50158
|
return { messages: replay.messages };
|
|
49625
50159
|
}
|
|
49626
50160
|
logPiLkgRecovery(sessionIdForError, `${failureLabel} ${piStorageErrorReason(err)}: LKG unavailable (${replay.reason}); refusing unreduced ${rawMessageCount}-message input`);
|
|
@@ -50244,9 +50778,31 @@ function captureReasoningMutationRollback(messages) {
|
|
|
50244
50778
|
}
|
|
50245
50779
|
};
|
|
50246
50780
|
}
|
|
50781
|
+
function piServedHeadMatches(served, index, head) {
|
|
50782
|
+
const contentOf = (message) => isRecord(message) && message.role === "user" && Array.isArray(message.content) ? message.content : null;
|
|
50783
|
+
const isText = (part, text) => isRecord(part) && part.type === "text" && part.text === text;
|
|
50784
|
+
const m0 = contentOf(served?.[index]);
|
|
50785
|
+
const m1 = contentOf(served?.[index + 1]);
|
|
50786
|
+
if (!m0 || !m1 || m1.length !== 1 || !isText(m1[0], head.m1Text))
|
|
50787
|
+
return false;
|
|
50788
|
+
if (m0.length !== (head.muralDataUrl ? 2 : 1) || !isText(m0[0], head.m0Text))
|
|
50789
|
+
return false;
|
|
50790
|
+
if (!head.muralDataUrl)
|
|
50791
|
+
return true;
|
|
50792
|
+
const image = m0[1];
|
|
50793
|
+
if (!isRecord(image) || image.type !== "image" || typeof image.mimeType !== "string" || typeof image.data !== "string")
|
|
50794
|
+
return false;
|
|
50795
|
+
const prefix = `data:${image.mimeType};base64,`;
|
|
50796
|
+
return head.muralDataUrl.length === prefix.length + image.data.length && head.muralDataUrl.startsWith(prefix) && head.muralDataUrl.endsWith(image.data);
|
|
50797
|
+
}
|
|
50247
50798
|
async function runCompactionOffPipeline(args) {
|
|
50248
50799
|
let injectionResult = null;
|
|
50249
50800
|
const transcript = [...args.messages];
|
|
50801
|
+
let stripEntryIdsMemo;
|
|
50802
|
+
const stripEntryIds = () => {
|
|
50803
|
+
stripEntryIdsMemo ??= transcript.map((message, index) => resolvePiRealStableId(message, index, args.entryIds, args.entryIdByRef ?? undefined));
|
|
50804
|
+
return stripEntryIdsMemo;
|
|
50805
|
+
};
|
|
50250
50806
|
let headChangedUnderSignedThinking = false;
|
|
50251
50807
|
if (args.injection) {
|
|
50252
50808
|
const state = {
|
|
@@ -50265,13 +50821,44 @@ async function runCompactionOffPipeline(args) {
|
|
|
50265
50821
|
if (signedTurnHoldsHead)
|
|
50266
50822
|
state.preparedPrefix = prepareCachedM0M1PiReplay(state, args.db, args.injectionPassSnapshot?.cachedRow);
|
|
50267
50823
|
const servedBeforeFirstRender = signedTurnHoldsHead && !state.preparedPrefix ? args.readLastServedMessages?.() ?? null : undefined;
|
|
50824
|
+
let lastServed;
|
|
50825
|
+
const readLastServed = () => {
|
|
50826
|
+
if (lastServed === undefined)
|
|
50827
|
+
lastServed = args.readLastServedMessages?.() ?? null;
|
|
50828
|
+
return lastServed;
|
|
50829
|
+
};
|
|
50830
|
+
if (!signedTurnHoldsHead && args.reasoningClearing?.prefixBound === true) {
|
|
50831
|
+
state.onFoldPrepare = () => {
|
|
50832
|
+
const served = readLastServed();
|
|
50833
|
+
const headIndex = placePiInitialSystemAtHead([
|
|
50834
|
+
...args.messages
|
|
50835
|
+
]);
|
|
50836
|
+
return (db, head) => {
|
|
50837
|
+
if (piServedHeadMatches(served, headIndex, head))
|
|
50838
|
+
return;
|
|
50839
|
+
applyPiProactiveThinkingStrip({
|
|
50840
|
+
db,
|
|
50841
|
+
sessionId: args.sessionId,
|
|
50842
|
+
messages: transcript,
|
|
50843
|
+
entryIds: stripEntryIds(),
|
|
50844
|
+
provider: args.resolvedProviderID,
|
|
50845
|
+
model: args.resolvedModelID,
|
|
50846
|
+
cacheBustingPass: true,
|
|
50847
|
+
stripActiveTurn: true,
|
|
50848
|
+
persistOnly: true,
|
|
50849
|
+
requirePersistence: true,
|
|
50850
|
+
report: (line) => sessionLog2(args.sessionId, line)
|
|
50851
|
+
});
|
|
50852
|
+
};
|
|
50853
|
+
};
|
|
50854
|
+
}
|
|
50268
50855
|
injectionResult = injectM0M1Pi(state, args.db, args.messages, args.entryIds, false, args.injectionPassSnapshot);
|
|
50269
50856
|
if (servedBeforeFirstRender !== undefined) {
|
|
50270
50857
|
const headCount = injectionResult?.syntheticLeadingCount ?? 0;
|
|
50271
50858
|
const head = JSON.stringify(args.messages.slice(0, headCount));
|
|
50272
50859
|
headChangedUnderSignedThinking = servedBeforeFirstRender === null || JSON.stringify(servedBeforeFirstRender.slice(0, headCount)) !== head;
|
|
50273
50860
|
} else if (!signedTurnHoldsHead && args.reasoningClearing?.prefixBound === true && (injectionResult?.m0Materialized === true || injectionResult?.m1RenderedCoverage != null)) {
|
|
50274
|
-
const served =
|
|
50861
|
+
const served = readLastServed();
|
|
50275
50862
|
const headCount = injectionResult?.syntheticLeadingCount ?? 0;
|
|
50276
50863
|
headChangedUnderSignedThinking = served === null || JSON.stringify(served.slice(0, headCount)) !== JSON.stringify(args.messages.slice(0, headCount));
|
|
50277
50864
|
if (headChangedUnderSignedThinking)
|
|
@@ -50283,7 +50870,7 @@ async function runCompactionOffPipeline(args) {
|
|
|
50283
50870
|
db: args.db,
|
|
50284
50871
|
sessionId: args.sessionId,
|
|
50285
50872
|
messages: transcript,
|
|
50286
|
-
entryIds:
|
|
50873
|
+
entryIds: stripEntryIds(),
|
|
50287
50874
|
provider: args.resolvedProviderID,
|
|
50288
50875
|
model: args.resolvedModelID,
|
|
50289
50876
|
cacheBustingPass: true,
|
|
@@ -50326,6 +50913,9 @@ async function runCompactionOffPipeline(args) {
|
|
|
50326
50913
|
};
|
|
50327
50914
|
}
|
|
50328
50915
|
var signedThinkingHoldLogKeys = new Map;
|
|
50916
|
+
function piForceBandPressure(args) {
|
|
50917
|
+
return args.forceMaterialization === true || args.percentage >= args.forceMaterializationPercentage;
|
|
50918
|
+
}
|
|
50329
50919
|
function resolvePiSignedThinkingHold(args) {
|
|
50330
50920
|
if (!args.prefixBound)
|
|
50331
50921
|
return false;
|
|
@@ -50334,6 +50924,7 @@ function resolvePiSignedThinkingHold(args) {
|
|
|
50334
50924
|
messages: args.messages,
|
|
50335
50925
|
usagePercentage: args.usagePercentage,
|
|
50336
50926
|
executeThresholdPercentage: args.executeThresholdPercentage,
|
|
50927
|
+
forceBandPressure: args.forceBandPressure,
|
|
50337
50928
|
estimateTextTokens: (text) => {
|
|
50338
50929
|
proseRatio ??= sessionDecisionCalibration(args.db, args.sessionId).proseRatio;
|
|
50339
50930
|
return estimateTokens(text) * proseRatio;
|
|
@@ -50354,13 +50945,26 @@ async function runPipeline(args) {
|
|
|
50354
50945
|
const dropBranchIds = dropBranchEntries ? piDropBranchIds(dropBranchEntries) : null;
|
|
50355
50946
|
trackPiDropLeaf(args.db, args.sessionId, dropBranchIds ? [...dropBranchIds].at(-1) ?? null : null);
|
|
50356
50947
|
cancelPiAbandonedPendingDrops(args.db, args.sessionId, dropBranchIds);
|
|
50948
|
+
const piStableId = (message, index) => resolvePiStableId(message, index, args.entryIds, args.entryIdByRef ?? undefined);
|
|
50949
|
+
let stripRemovedTurnNow = false;
|
|
50357
50950
|
const thinkingRecovery = prepareLatestThinkingRecovery({
|
|
50358
50951
|
db: args.db,
|
|
50359
50952
|
sessionId: args.sessionId,
|
|
50360
50953
|
messages: args.messages,
|
|
50361
|
-
id:
|
|
50362
|
-
parts: (message) => Array.isArray(message?.content) ? message.content : []
|
|
50363
|
-
|
|
50954
|
+
id: piStableId,
|
|
50955
|
+
parts: (message) => Array.isArray(message?.content) ? message.content : [],
|
|
50956
|
+
modelID: args.resolvedModelID,
|
|
50957
|
+
providerID: args.resolvedProviderID,
|
|
50958
|
+
persistRemoval: (ids) => {
|
|
50959
|
+
const outcome = persistPiLatestTurnThinkingRemoval(args.db, args.sessionId, ids);
|
|
50960
|
+
stripRemovedTurnNow = outcome.stripNow;
|
|
50961
|
+
return outcome.persisted;
|
|
50962
|
+
}
|
|
50963
|
+
});
|
|
50964
|
+
const removedTurnIds = new Set(thinkingRecovery.removedIds ?? []);
|
|
50965
|
+
const removedTurnAtStart = removedTurnIds.size > 0 && (stripRemovedTurnNow || piBindingStripsAtStart(args.db, args.sessionId));
|
|
50966
|
+
if (removedTurnAtStart)
|
|
50967
|
+
stripPiThinkingOfIds(args.messages, removedTurnIds, piStableId);
|
|
50364
50968
|
if (thinkingRecovery.ended)
|
|
50365
50969
|
signalPiPendingMaterialization(args.sessionId, "thinking_hold");
|
|
50366
50970
|
let restoreOriginals;
|
|
@@ -50491,7 +51095,11 @@ async function runPipeline(args) {
|
|
|
50491
51095
|
lastResponseTime: hardMeta.lastResponseTime
|
|
50492
51096
|
};
|
|
50493
51097
|
})() : undefined;
|
|
50494
|
-
const emergencyDropEligible =
|
|
51098
|
+
const emergencyDropEligible = piForceBandPressure({
|
|
51099
|
+
forceMaterialization: args.forceMaterialization,
|
|
51100
|
+
percentage: args.contextUsage.percentage,
|
|
51101
|
+
forceMaterializationPercentage
|
|
51102
|
+
});
|
|
50495
51103
|
const piM0State = args.injection && piHardSignals ? {
|
|
50496
51104
|
sessionId: args.sessionId,
|
|
50497
51105
|
projectIdentity: args.projectIdentity,
|
|
@@ -50677,6 +51285,16 @@ async function runPipeline(args) {
|
|
|
50677
51285
|
let prefixMutationAllowed = prefixMutationPermitted(ridePermissionGate);
|
|
50678
51286
|
isCacheBustingPass = reclaimRidePermitted(rideSignals, ridePermissionGate);
|
|
50679
51287
|
let publishedWorkDrainAllowed = isCacheBustingPass;
|
|
51288
|
+
const noteServedPermission = () => noteServedPassPermission(args.sessionId, {
|
|
51289
|
+
permitted: isCacheBustingPass,
|
|
51290
|
+
rides: reclaimRideLabel(rideSignals),
|
|
51291
|
+
signedThinkingHold: protectedSignedPrefix,
|
|
51292
|
+
firstRender: firstRenderBust,
|
|
51293
|
+
hostCheckpointHead: false,
|
|
51294
|
+
emergency: emergencyDropEligible,
|
|
51295
|
+
schedulerDecision: args.schedulerDecision
|
|
51296
|
+
});
|
|
51297
|
+
noteServedPermission();
|
|
50680
51298
|
stripUnheldSignedTurnOnBust();
|
|
50681
51299
|
const usesTokenProtection = args.protectedTokenTierOverrides !== undefined || args.protectedTokens !== undefined;
|
|
50682
51300
|
const resolveProtectionFloor = () => resolveEpochFloorForPass(args.db, args.sessionId, {
|
|
@@ -50752,6 +51370,7 @@ async function runPipeline(args) {
|
|
|
50752
51370
|
deferredMaterializeEligible = canConsumeDeferredLate && deferredMaterializationSessions.has(args.sessionId);
|
|
50753
51371
|
isCacheBustingPass = prefixMutationAllowed;
|
|
50754
51372
|
publishedWorkDrainAllowed = isCacheBustingPass;
|
|
51373
|
+
noteServedPermission();
|
|
50755
51374
|
stripUnheldSignedTurnOnBust();
|
|
50756
51375
|
shouldRunHeuristics = args.heuristics !== undefined;
|
|
50757
51376
|
if (piM0State && prefixMutationAllowed) {
|
|
@@ -50854,22 +51473,10 @@ async function runPipeline(args) {
|
|
|
50854
51473
|
}
|
|
50855
51474
|
}
|
|
50856
51475
|
}
|
|
50857
|
-
|
|
51476
|
+
const newTargets = new Map(protectNewTagMutations(mutationView.map((message) => ({
|
|
50858
51477
|
info: message.info,
|
|
50859
51478
|
parts: message.parts
|
|
50860
51479
|
})), 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
51480
|
for (const number of identityAdoption.protectedTagNumbers) {
|
|
50874
51481
|
if (rewritingSignedPrefix)
|
|
50875
51482
|
break;
|
|
@@ -51043,6 +51650,7 @@ async function runPipeline(args) {
|
|
|
51043
51650
|
if (rideSignals.executeReclaim) {
|
|
51044
51651
|
isCacheBustingPass = reclaimRidePermitted(rideSignals, ridePermissionGate);
|
|
51045
51652
|
publishedWorkDrainAllowed = isCacheBustingPass;
|
|
51653
|
+
noteServedPermission();
|
|
51046
51654
|
shouldRunHeuristics ||= isCacheBustingPass && args.heuristics !== undefined;
|
|
51047
51655
|
stripUnheldSignedTurnOnBust();
|
|
51048
51656
|
applyTemporalOnRide();
|
|
@@ -51067,6 +51675,10 @@ async function runPipeline(args) {
|
|
|
51067
51675
|
const deferredMaterialize = canConsumeDeferredLate && deferredMaterializationWasPending;
|
|
51068
51676
|
const deferredHistoryRefresh = canConsumeDeferredLate && deferredHistoryRefreshWasPending;
|
|
51069
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;
|
|
51070
51682
|
mutationGateObserverForTests?.({
|
|
51071
51683
|
foldDue: foldDueDecision.value,
|
|
51072
51684
|
foldExecuted: foldExecutedThisPass,
|
|
@@ -51225,7 +51837,9 @@ async function runPipeline(args) {
|
|
|
51225
51837
|
usagePercentage: args.contextUsage.percentage,
|
|
51226
51838
|
passAlreadyPriced: independentMutationBeforeHeuristics,
|
|
51227
51839
|
serializedImageTokens: providerOverflow ? piRecoveryToolImageTokens(workingMessages) : undefined,
|
|
51228
|
-
fitCalibration: providerOverflow ? piRecoveryFitCalibration(recoveryCalibration) : undefined
|
|
51840
|
+
fitCalibration: providerOverflow ? piRecoveryFitCalibration(recoveryCalibration) : undefined,
|
|
51841
|
+
servedBeforePass: emergencyServedBeforeDrain,
|
|
51842
|
+
sinceReading: tagsNewerThanReading
|
|
51229
51843
|
} : undefined,
|
|
51230
51844
|
caveman: args.isSubagent ? undefined : args.heuristics?.caveman
|
|
51231
51845
|
}, activeTags, stableIdResolver));
|
|
@@ -51843,6 +52457,8 @@ async function runPipeline(args) {
|
|
|
51843
52457
|
}
|
|
51844
52458
|
if (bustedThisPass)
|
|
51845
52459
|
clearExecuteReclaimState(args.db, args.sessionId);
|
|
52460
|
+
if (removedTurnIds.size > 0 && !removedTurnAtStart)
|
|
52461
|
+
stripPiThinkingOfIds(outputMessages, removedTurnIds, (message) => message && typeof message === "object" ? postCommitStableIdByRef.get(message) : undefined);
|
|
51846
52462
|
return {
|
|
51847
52463
|
messages: outputMessages,
|
|
51848
52464
|
recoveryNormalized,
|
|
@@ -51863,6 +52479,7 @@ async function runPipeline(args) {
|
|
|
51863
52479
|
injectionResult,
|
|
51864
52480
|
materialized,
|
|
51865
52481
|
materializeReason,
|
|
52482
|
+
latestTurnThinkingRemoved: thinkingRecovery.removedThisPass === true,
|
|
51866
52483
|
droppedTokens,
|
|
51867
52484
|
droppedCount,
|
|
51868
52485
|
emergency,
|
|
@@ -52101,6 +52718,7 @@ function clearPiCompactionOffInMemoryState(sessionId) {
|
|
|
52101
52718
|
clearPiChannel1State(sessionId);
|
|
52102
52719
|
}
|
|
52103
52720
|
function clearContextHandlerSession(sessionId) {
|
|
52721
|
+
dropServedRecord(sessionId, "session_cleared");
|
|
52104
52722
|
cancelPiTagSnapshotSession(sessionId);
|
|
52105
52723
|
lastServedSystemHashBySession.delete(sessionId);
|
|
52106
52724
|
clearPiHistoryBoundaryRepairSession(sessionId);
|
|
@@ -55525,7 +56143,7 @@ function strippedAssistantContent(content, provider = "anthropic") {
|
|
|
55525
56143
|
if (part === null || typeof part !== "object" || part.type !== "text") {
|
|
55526
56144
|
continue;
|
|
55527
56145
|
}
|
|
55528
|
-
if (typeof part.text !== "string")
|
|
56146
|
+
if (typeof part.text !== "string" || !part.text.includes("§"))
|
|
55529
56147
|
continue;
|
|
55530
56148
|
const stripped = stripPersistedAssistantText(part.text, provider === "anthropic");
|
|
55531
56149
|
if (stripped === part.text)
|