@cortexkit/pi-magic-context 0.49.18 → 0.49.19

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.
@@ -23,7 +23,7 @@ var [
23
23
  import("./embedding-cache-7rp4gqzr.js"),
24
24
  import("./storage-memory-yxxc5v4n.js"),
25
25
  import("./project-embedding-registry-vf1ncptn.js"),
26
- import("./search-6ztbx25v.js"),
26
+ import("./search-wh7b9zht.js"),
27
27
  import("./embedding-activity-ew6dshfd.js"),
28
28
  import("./harness-9872e0ym.js"),
29
29
  import("./sqlite-fsp0sf3r.js"),
@@ -125,4 +125,8 @@ port.on("message", (message) => {
125
125
  if (message.kind === "run" && message.input)
126
126
  run(message.input);
127
127
  });
128
- await run(input);
128
+ run(input).catch((error) => {
129
+ setTimeout(() => {
130
+ throw error;
131
+ });
132
+ });
@@ -30,8 +30,8 @@ import"./index-apgwdby5.js";
30
30
  import {
31
31
  LATEST_SUPPORTED_VERSION,
32
32
  enforceSchemaFence
33
- } from "./index-gp928w10.js";
34
- import"./index-gdjv1nnd.js";
33
+ } from "./index-sqt2haap.js";
34
+ import"./index-msqrs4nf.js";
35
35
  import"./index-jrap43gc.js";
36
36
  import"./index-135e8hvg.js";
37
37
  import"./index-8976mezv.js";
@@ -22,7 +22,7 @@ import {
22
22
  resolveStoredPathWorkspaceIdentity,
23
23
  sourceNameForMemory,
24
24
  managedAuthorityNoteRow
25
- } from "./index-gdjv1nnd.js";
25
+ } from "./index-msqrs4nf.js";
26
26
  import {
27
27
  isKnownAutocommit
28
28
  } from "./index-jrap43gc.js";
@@ -80,7 +80,7 @@ import {
80
80
  keywordRelevance,
81
81
  matchedSearchSnippet,
82
82
  getIndexedMessageCorpusSize2
83
- } from "./index-fvjthct0.js";
83
+ } from "./index-ym6nh2gk.js";
84
84
  import {
85
85
  MESSAGE_FTS_SESSION_FILTER_SQL,
86
86
  withMessageFtsSessionFilter
@@ -6,7 +6,7 @@ import {
6
6
  } from "./index-1kcfwk9c.js";
7
7
  import {
8
8
  readRawSessionMessageIdOrdinalsForRange2
9
- } from "./index-r9f4f6s1.js";
9
+ } from "./index-wveb51es.js";
10
10
 
11
11
  // ../plugin/src/tools/ctx-expand/search-archive.ts
12
12
  var archiveReadsOnThisThread = 0;
@@ -54,6 +54,7 @@ import {
54
54
  serializeStrippedPlaceholderState,
55
55
  THINKING_BINDING_RECOVERY_FROZEN_PREFIX,
56
56
  THINKING_BINDING_STRIP_ORDER_END_MARKER,
57
+ COMPACTION_OFF_THINKING_FROZEN_PREFIX,
57
58
  parseProcessedImageMarkers,
58
59
  serializeProcessedImageMarkers,
59
60
  getPendingPiCompactionMarkerState,
@@ -66,7 +67,7 @@ import {
66
67
  visitRawSessionMessages2,
67
68
  readRawSessionMessageById2,
68
69
  readSessionChunk2
69
- } from "./index-r9f4f6s1.js";
70
+ } from "./index-wveb51es.js";
70
71
  import {
71
72
  isRecord,
72
73
  providerVisibleMessage,
@@ -108,7 +109,7 @@ import {
108
109
  V2StoreReader,
109
110
  deleteSessionScopedRows,
110
111
  getLastIndexedOrdinal2
111
- } from "./index-fvjthct0.js";
112
+ } from "./index-ym6nh2gk.js";
112
113
  import {
113
114
  resolveOpenCodeDbPath,
114
115
  assertOpenCodeStoreGeneration
@@ -138,7 +139,7 @@ import {
138
139
  } from "./index-vmcgew7x.js";
139
140
  import {
140
141
  getErrorMessage
141
- } from "./index-gp928w10.js";
142
+ } from "./index-sqt2haap.js";
142
143
  import {
143
144
  V2_MEMORY_CATEGORIES,
144
145
  CATEGORY_PRIORITY,
@@ -152,7 +153,7 @@ import {
152
153
  expandWorkspaceIdentitySetWithAliases,
153
154
  resolveStoredPathWorkspaceIdentity,
154
155
  storedPathBelongsToWorkspace
155
- } from "./index-gdjv1nnd.js";
156
+ } from "./index-msqrs4nf.js";
156
157
  import {
157
158
  directoryHasGitMetadata,
158
159
  resolveProjectIdentityForSession,
@@ -174,7 +175,7 @@ import {
174
175
  resolveMemoriesByIdsForSearch2,
175
176
  unifiedSearch2,
176
177
  formatSearchResults2
177
- } from "./index-d43hmn31.js";
178
+ } from "./index-58mj0dzc.js";
178
179
  import {
179
180
  computeCueContentHash,
180
181
  getMuralCueState,
@@ -202,7 +203,7 @@ import {
202
203
  } from "./index-qpq6w67c.js";
203
204
  import {
204
205
  renderSearchArchive2
205
- } from "./index-d21pdr8v.js";
206
+ } from "./index-dtp1efvf.js";
206
207
  import {
207
208
  computeNormalizedHash
208
209
  } from "./index-9x1f96r8.js";
@@ -5221,11 +5222,15 @@ function clonePiContentDecisions(raw, filter) {
5221
5222
  ])}`);
5222
5223
  continue;
5223
5224
  }
5224
- if (entry.startsWith(THINKING_BINDING_RECOVERY_FROZEN_PREFIX)) {
5225
- const messageId = entry.slice(THINKING_BINDING_RECOVERY_FROZEN_PREFIX.length);
5225
+ const thinkingPrefix = [
5226
+ THINKING_BINDING_RECOVERY_FROZEN_PREFIX,
5227
+ COMPACTION_OFF_THINKING_FROZEN_PREFIX
5228
+ ].find((prefix) => entry.startsWith(prefix));
5229
+ if (thinkingPrefix) {
5230
+ const messageId = entry.slice(thinkingPrefix.length);
5226
5231
  if (messageId.length === 0 || !filter.includeMessageId(messageId))
5227
5232
  continue;
5228
- copied.push(`${THINKING_BINDING_RECOVERY_FROZEN_PREFIX}${mapMessageId(filter, messageId) ?? messageId}`);
5233
+ copied.push(`${thinkingPrefix}${mapMessageId(filter, messageId) ?? messageId}`);
5229
5234
  continue;
5230
5235
  }
5231
5236
  if (entry.startsWith(MERGED_REASONING_PARTS_PREFIX) || entry.startsWith("pi-content-replay-"))
@@ -2764,8 +2764,7 @@ var MIGRATIONS = [
2764
2764
  up(db) {
2765
2765
  const memoriesPresent = tableExists4(db, "memories");
2766
2766
  const notesPresent = tableExists4(db, "notes");
2767
- const native = db;
2768
- const privilegeCheck = typeof native.function === "function" || typeof native.createFunction === "function" ? "mc_privileged_writer() = 0" : "COALESCE((SELECT enabled FROM context_privilege_state WHERE id = 1), 0) = 0";
2767
+ const privilegeCheck = authorityPrivilegeCheck();
2769
2768
  if (memoriesPresent) {
2770
2769
  db.exec(`
2771
2770
  DROP TRIGGER IF EXISTS memories_authority_guard_insert;
@@ -14,7 +14,7 @@ import {
14
14
  } from "./index-rrwv9y2k.js";
15
15
  import {
16
16
  createFailClosedBlockingError
17
- } from "./index-gp928w10.js";
17
+ } from "./index-sqt2haap.js";
18
18
 
19
19
  // src/tag-snapshot-worker-client-pi.ts
20
20
  import { setImmediate as yieldImmediate } from "node:timers/promises";
@@ -50,7 +50,7 @@ import {
50
50
  hasPendingMigrations,
51
51
  getMainThreadMigrationBodyCount,
52
52
  runMigrations
53
- } from "./index-gdjv1nnd.js";
53
+ } from "./index-msqrs4nf.js";
54
54
  import {
55
55
  closeQuietly,
56
56
  ensureColumn,
@@ -1305,7 +1305,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
1305
1305
  state.running = startMessageFtsRowidMapBackfill2(db, signal).then(async () => {
1306
1306
  if (signal.aborted || !readsOpenCodeStore)
1307
1307
  return;
1308
- const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-chepqmw5.js"));
1308
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-h5bzj91r.js"));
1309
1309
  const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-ssshbdy8.js"));
1310
1310
  if (signal.aborted)
1311
1311
  return;
@@ -2407,6 +2407,7 @@ var THINKING_BINDING_STRIP_ORDER_END_MARKER = "binding_mismatch_order:end";
2407
2407
  function thinkingBindingRecoveryFrozenId(messageId) {
2408
2408
  return `${THINKING_BINDING_RECOVERY_FROZEN_PREFIX}${messageId}`;
2409
2409
  }
2410
+ var COMPACTION_OFF_THINKING_FROZEN_PREFIX = "compaction_off_thinking:";
2410
2411
  function getThinkingBindingRecoveryTarget(db, sessionId) {
2411
2412
  const row = db.prepare("SELECT thinking_binding_recovery_target FROM session_meta WHERE session_id = ?").get(sessionId);
2412
2413
  const target = row?.thinking_binding_recovery_target;
@@ -5062,4 +5063,4 @@ function readRawSessionSeedTail2(sessionId, boundaryId, onQuery) {
5062
5063
  });
5063
5064
  }
5064
5065
 
5065
- export { detectThinkingBindingMismatch, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, MAX_EXECUTE_THRESHOLD, escalationBands, MERGED_REASONING_PARTS_PREFIX, decodeMergedReasoningParts, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, computeProtectionWindow, readEpochFloorSnapshot, getProtectionWindowForSession, SESSION_META_SELECT_COLUMNS, META_COLUMNS, BOOLEAN_META_KEYS, NULL_BIND_META_KEYS, isSessionMetaRow, getDefaultSessionMeta, ensureSessionMetaRow, toSessionMeta, persistCachedM0, clearCachedM0M1, isRustMarkerAdmissionFenced, ReplayDocumentError, readReplayEnvelope, readReplayDocument, updateReplayDocument, writeReplayDocument, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, describeProtectedTailDrainBudgetSkip, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, EMERGENCY_DRAIN_FAILURE_BACKOFF_MS, getProtectedTailDrainBudgetSkip, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, queueAutoSearchHintDecisionRetirement, flushAutoSearchHintDecisionRetirement, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, setNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, parseStrippedPlaceholderState, serializeStrippedPlaceholderState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getProcessedImageStrippedIds, parseProcessedImageMarkers, serializeProcessedImageMarkers, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, logPiCompactionMarkerClear, getSessionsWithPendingPiMarker, setSessionWorkMetrics, getSessionWorkMetrics, resolveEpochFloorForPass, withReadOnlySessionDb, expandToolPart, retreatPastHostUnservedRows, isCoveredInstructionRow, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripSystemInjection, isFilePart, hasUserAnswerMetadata, DreamTokenBudgetExceeded, TOKEN_BUDGET_FINALIZE_MESSAGE, TOKEN_BUDGET_TOOL_REFUSAL, registerBudgetFinalizeChild, releaseBudgetFinalizeChild, createDreamTokenBudget, droppedInputMarker, createDroppedInputGuard, isEditTool, applyEditMarkerToInput, modelAcceptsEmptyContent, isAnthropicFamilyRoute, variantChangeBustsProviderCache, isInActiveAnthropicTurn, activeAnthropicTurnStart, hasAnthropicReasoning, findLatestAssistantReasoningMutationExemptMessage, DEFAULT_KEEP_REASONING_TOKENS, resolveKeepReasoningTokens, reasoningStepCost, reasoningBudgetCutoff, reasoningTextAndOpaque, opaqueThinkingCost, estimatePartImageTokens, SKELETON_REAL_INPUT_MAX_BYTES, toolInputStringBytes, resolveHostServedBoundaryId2, hasRawMessageProvider2, setRawMessageProvider2, setBoundedRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, RAW_MESSAGE_VISIT_PAGE_SIZE2, visitRawSessionMessages2, visitRawSessionMessagesAsync2, readRawSessionMessageRange2, prepareRawSessionOrdinals2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageOrdinalPage2, getRawSessionStoredMessageCount2, readRawSessionMessageIdOrdinalsForRange2, readRawSessionMessageIdOrdinals2, readRawSessionMessagePartsById2, readRawSessionBoundaryEndpoints2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, RAW_SESSION_TAG_KEY_PAGE_SIZE2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, getProtectedTailStartOrdinal2, readSessionChunk2, getRawSessionMessageIdsThrough2, readRawSessionSeedTail2 };
5066
+ export { detectThinkingBindingMismatch, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, MAX_EXECUTE_THRESHOLD, escalationBands, MERGED_REASONING_PARTS_PREFIX, decodeMergedReasoningParts, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, computeProtectionWindow, readEpochFloorSnapshot, getProtectionWindowForSession, SESSION_META_SELECT_COLUMNS, META_COLUMNS, BOOLEAN_META_KEYS, NULL_BIND_META_KEYS, isSessionMetaRow, getDefaultSessionMeta, ensureSessionMetaRow, toSessionMeta, persistCachedM0, clearCachedM0M1, isRustMarkerAdmissionFenced, ReplayDocumentError, readReplayEnvelope, readReplayDocument, updateReplayDocument, writeReplayDocument, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, describeProtectedTailDrainBudgetSkip, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, EMERGENCY_DRAIN_FAILURE_BACKOFF_MS, getProtectedTailDrainBudgetSkip, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, queueAutoSearchHintDecisionRetirement, flushAutoSearchHintDecisionRetirement, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, setNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, parseStrippedPlaceholderState, serializeStrippedPlaceholderState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, COMPACTION_OFF_THINKING_FROZEN_PREFIX, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getProcessedImageStrippedIds, parseProcessedImageMarkers, serializeProcessedImageMarkers, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, logPiCompactionMarkerClear, getSessionsWithPendingPiMarker, setSessionWorkMetrics, getSessionWorkMetrics, resolveEpochFloorForPass, withReadOnlySessionDb, expandToolPart, retreatPastHostUnservedRows, isCoveredInstructionRow, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripSystemInjection, isFilePart, hasUserAnswerMetadata, DreamTokenBudgetExceeded, TOKEN_BUDGET_FINALIZE_MESSAGE, TOKEN_BUDGET_TOOL_REFUSAL, registerBudgetFinalizeChild, releaseBudgetFinalizeChild, createDreamTokenBudget, droppedInputMarker, createDroppedInputGuard, isEditTool, applyEditMarkerToInput, modelAcceptsEmptyContent, isAnthropicFamilyRoute, variantChangeBustsProviderCache, isInActiveAnthropicTurn, activeAnthropicTurnStart, hasAnthropicReasoning, findLatestAssistantReasoningMutationExemptMessage, DEFAULT_KEEP_REASONING_TOKENS, resolveKeepReasoningTokens, reasoningStepCost, reasoningBudgetCutoff, reasoningTextAndOpaque, opaqueThinkingCost, estimatePartImageTokens, SKELETON_REAL_INPUT_MAX_BYTES, toolInputStringBytes, resolveHostServedBoundaryId2, hasRawMessageProvider2, setRawMessageProvider2, setBoundedRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, RAW_MESSAGE_VISIT_PAGE_SIZE2, visitRawSessionMessages2, visitRawSessionMessagesAsync2, readRawSessionMessageRange2, prepareRawSessionOrdinals2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageOrdinalPage2, getRawSessionStoredMessageCount2, readRawSessionMessageIdOrdinalsForRange2, readRawSessionMessageIdOrdinals2, readRawSessionMessagePartsById2, readRawSessionBoundaryEndpoints2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, RAW_SESSION_TAG_KEY_PAGE_SIZE2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, getProtectedTailStartOrdinal2, readSessionChunk2, getRawSessionMessageIdsThrough2, readRawSessionSeedTail2 };
@@ -46,7 +46,7 @@ import {
46
46
  } from "./index-jrap43gc.js";
47
47
  import {
48
48
  cleanUserText2
49
- } from "./index-r9f4f6s1.js";
49
+ } from "./index-wveb51es.js";
50
50
  import {
51
51
  sameProjectDirectory
52
52
  } from "./index-wrr9rp9a.js";
package/dist/index.js CHANGED
@@ -249,7 +249,7 @@ import {
249
249
  registerTodoStateLifecycle,
250
250
  syncCtxMemoryToolEnabled,
251
251
  registerMagicContextTools
252
- } from "./index-xxn1tpnv.js";
252
+ } from "./index-ek9zvs4f.js";
253
253
  import"./index-4knyh1kt.js";
254
254
  import {
255
255
  canonicalModelIdentity,
@@ -290,7 +290,7 @@ import {
290
290
  openCurrentDatabase,
291
291
  openDatabaseAsync,
292
292
  closeDatabase
293
- } from "./index-gp928w10.js";
293
+ } from "./index-sqt2haap.js";
294
294
  import {
295
295
  pruneMissingProjectIdentities,
296
296
  setHomeProjectPermission,
@@ -462,7 +462,7 @@ import {
462
462
  getRawSessionTagKeysThrough2,
463
463
  getLegacyProtectedTailStartOrdinal2,
464
464
  readSessionChunk2
465
- } from "./index-r9f4f6s1.js";
465
+ } from "./index-wveb51es.js";
466
466
  import {
467
467
  UNKNOWN_FIT_RATIO,
468
468
  hasMeasuredDecisionCalibration,
@@ -611,7 +611,7 @@ import {
611
611
  indexSingleMessage2,
612
612
  indexMessagesAfterOrdinal2,
613
613
  sweepOrphanedOpenCodeMessageIndexesCooperatively2
614
- } from "./index-fvjthct0.js";
614
+ } from "./index-ym6nh2gk.js";
615
615
  import {
616
616
  resolveOpenCodeDbPath,
617
617
  assertOpenCodeStoreGeneration,
@@ -688,7 +688,7 @@ import {
688
688
  expandWorkspaceIdentitySetWithAliases,
689
689
  sourceNameForMemory,
690
690
  computeWorkspaceEpochFingerprint
691
- } from "./index-gdjv1nnd.js";
691
+ } from "./index-msqrs4nf.js";
692
692
  import {
693
693
  configureContextDatabasePragmas2
694
694
  } from "./index-fapenpch.js";
@@ -738,7 +738,7 @@ import {
738
738
  normalizeVerificationFiles,
739
739
  indexCommitsForProject,
740
740
  embedUnembeddedCommits
741
- } from "./index-d43hmn31.js";
741
+ } from "./index-58mj0dzc.js";
742
742
  import {
743
743
  setEmbeddingSessionBusy2,
744
744
  isEmbeddingHostBusy2
@@ -795,10 +795,10 @@ import {
795
795
  drainPiTagSnapshotSession,
796
796
  assertPiTagSnapshotReady,
797
797
  ensurePiTagSnapshotReady
798
- } from "./index-4bv5bttd.js";
798
+ } from "./index-rc1dez8m.js";
799
799
  import"./index-f18ec69t.js";
800
800
  import"./index-1cvyaw9a.js";
801
- import"./index-d21pdr8v.js";
801
+ import"./index-dtp1efvf.js";
802
802
  import {
803
803
  __toESM
804
804
  } from "./index-22jkk6wg.js";
@@ -3520,7 +3520,7 @@ function startHostStallProfilerSwitch() {
3520
3520
  // package.json
3521
3521
  var package_default = {
3522
3522
  name: "@cortexkit/pi-magic-context",
3523
- version: "0.49.18",
3523
+ version: "0.49.19",
3524
3524
  type: "module",
3525
3525
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3526
3526
  main: "dist/index.js",
@@ -4844,9 +4844,33 @@ var promptFailureDetails = new WeakMap;
4844
4844
  function isHostTimeoutError(error) {
4845
4845
  return error !== null && typeof error === "object" && error.name === "TimeoutError";
4846
4846
  }
4847
+
4848
+ class ModelProducedNoOutputError extends Error {
4849
+ waitedMs;
4850
+ constructor(waitedMs) {
4851
+ super(`prompt timed out after ${waitedMs}ms with no model output`);
4852
+ this.waitedMs = waitedMs;
4853
+ this.name = "ModelProducedNoOutputError";
4854
+ }
4855
+ }
4856
+ var modelActivityBySignal = new WeakMap;
4857
+ function noteModelActivityMonitored(signal) {
4858
+ const activity = signal ? modelActivityBySignal.get(signal) : undefined;
4859
+ if (activity)
4860
+ activity.monitored = true;
4861
+ }
4862
+ function noteModelOutputReceived(signal) {
4863
+ const activity = signal ? modelActivityBySignal.get(signal) : undefined;
4864
+ if (activity) {
4865
+ activity.monitored = true;
4866
+ activity.received = true;
4867
+ }
4868
+ }
4847
4869
  function isPromptTimeoutError(error) {
4848
4870
  if (isHostTimeoutError(error))
4849
4871
  return true;
4872
+ if (error instanceof ModelProducedNoOutputError)
4873
+ return true;
4850
4874
  return error instanceof Error && /^prompt timed out after \d+ms$/.test(error.message);
4851
4875
  }
4852
4876
  function getPromptFailureDetail(error) {
@@ -4924,12 +4948,22 @@ function raceWithSignal(work, signal) {
4924
4948
  work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
4925
4949
  });
4926
4950
  }
4927
- async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
4951
+ async function promptWithTimeout(client, args, timeoutMs, signal, transport, firstOutputTimeoutMs) {
4928
4952
  if (signal?.aborted) {
4929
4953
  throw new Error(externalAbortMessage(signal));
4930
4954
  }
4931
4955
  const controller = new AbortController;
4932
4956
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
4957
+ const activity = { monitored: false, received: false };
4958
+ modelActivityBySignal.set(controller.signal, activity);
4959
+ let silent = false;
4960
+ const firstOutputTimer = firstOutputTimeoutMs !== undefined && firstOutputTimeoutMs < timeoutMs ? setTimeout(() => {
4961
+ if (!activity.monitored || activity.received)
4962
+ return;
4963
+ silent = true;
4964
+ controller.abort();
4965
+ }, firstOutputTimeoutMs) : undefined;
4966
+ const timeoutError = () => silent && firstOutputTimeoutMs !== undefined ? new ModelProducedNoOutputError(firstOutputTimeoutMs) : new Error(`prompt timed out after ${timeoutMs}ms`);
4933
4967
  const onExternalAbort = () => controller.abort();
4934
4968
  signal?.addEventListener("abort", onExternalAbort);
4935
4969
  try {
@@ -4952,7 +4986,7 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
4952
4986
  if (!transport || transport.childSessionId) {
4953
4987
  await abortChildRun(client, transport?.childSessionId ?? args.path.id);
4954
4988
  }
4955
- throw new Error(`prompt timed out after ${timeoutMs}ms`);
4989
+ throw timeoutError();
4956
4990
  }
4957
4991
  if (isHostTimeoutError(error)) {
4958
4992
  if (!transport || transport.childSessionId) {
@@ -4962,13 +4996,15 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
4962
4996
  throw error;
4963
4997
  } finally {
4964
4998
  clearTimeout(timeout);
4999
+ if (firstOutputTimer)
5000
+ clearTimeout(firstOutputTimer);
4965
5001
  signal?.removeEventListener("abort", onExternalAbort);
4966
5002
  }
4967
5003
  if (signal?.aborted || controller.signal.aborted) {
4968
5004
  if (!transport || transport.childSessionId) {
4969
5005
  await abortChildRun(client, transport?.childSessionId ?? args.path.id);
4970
5006
  }
4971
- throw new Error(signal?.aborted ? externalAbortMessage(signal) : `prompt timed out after ${timeoutMs}ms`);
5007
+ throw signal?.aborted ? new Error(externalAbortMessage(signal)) : timeoutError();
4972
5008
  }
4973
5009
  }
4974
5010
  async function abortChildRun(client, sessionId) {
@@ -4986,6 +5022,8 @@ async function abortChildRun(client, sessionId) {
4986
5022
  function isNonRetryable(error, externalSignal) {
4987
5023
  if (externalSignal?.aborted || error instanceof HiddenCompletionRefusal && error.terminal || error instanceof HiddenAgentStepLimit || error instanceof DreamTokenBudgetExceeded)
4988
5024
  return true;
5025
+ if (error instanceof ModelProducedNoOutputError)
5026
+ return false;
4989
5027
  if (error instanceof Error) {
4990
5028
  if (error.name === "AbortError")
4991
5029
  return true;
@@ -5017,7 +5055,7 @@ function classifyPromptFailure(error, phase, externalSignal) {
5017
5055
  if (externalSignal?.aborted || message === "prompt aborted by external signal") {
5018
5056
  return "child_aborted";
5019
5057
  }
5020
- if (/^prompt timed out after \d+ms$/.test(message) || isHostTimeoutError(error)) {
5058
+ if (error instanceof ModelProducedNoOutputError || /^prompt timed out after \d+ms$/.test(message) || isHostTimeoutError(error)) {
5021
5059
  return "provider_timeout";
5022
5060
  }
5023
5061
  if (phase === "validation") {
@@ -5052,11 +5090,11 @@ function throwWithPromptFailure(legacyError, failedAttempts, args, timeoutMs, tr
5052
5090
  });
5053
5091
  throw error;
5054
5092
  }
5055
- async function attemptOnce(client, args, timeoutMs, signal, callContext, label, transport, allowModelSuggestions = true) {
5093
+ async function attemptOnce(client, args, timeoutMs, signal, callContext, label, transport, allowModelSuggestions = true, firstOutputTimeoutMs) {
5056
5094
  const originalBody = { ...args.body };
5057
5095
  const attemptArgs = copyPromptArgs(args, originalBody);
5058
5096
  try {
5059
- await promptWithTimeout(client, attemptArgs, timeoutMs, signal, transport);
5097
+ await promptWithTimeout(client, attemptArgs, timeoutMs, signal, transport, firstOutputTimeoutMs);
5060
5098
  return;
5061
5099
  } catch (error) {
5062
5100
  if (isNonRetryable(error, signal) || !allowModelSuggestions)
@@ -5075,9 +5113,30 @@ async function attemptOnce(client, args, timeoutMs, signal, callContext, label,
5075
5113
  providerID: suggestion.providerID,
5076
5114
  modelID: suggestion.suggestion
5077
5115
  }
5078
- }), timeoutMs, signal, transport);
5116
+ }), timeoutMs, signal, transport, firstOutputTimeoutMs);
5079
5117
  }
5080
5118
  }
5119
+ function createChainClock(options, timeoutMs) {
5120
+ const fallbacks = options.fallbackModels ?? [];
5121
+ const hasValidFallbackFrom = (index) => fallbacks.slice(index).some((fallback) => {
5122
+ const entry = toModelEntry(fallback);
5123
+ return entry ? parseProviderModel(entry.model) !== null : false;
5124
+ });
5125
+ let silentSpentMs = 0;
5126
+ return {
5127
+ budget(nextFallbackIndex) {
5128
+ const attemptTimeoutMs = Math.max(1, timeoutMs - silentSpentMs);
5129
+ if (options.firstOutputTimeoutMs === undefined || !hasValidFallbackFrom(nextFallbackIndex))
5130
+ return { timeoutMs: attemptTimeoutMs };
5131
+ const bound = Math.min(options.firstOutputTimeoutMs, Math.floor(attemptTimeoutMs / 2));
5132
+ return bound > 0 ? { timeoutMs: attemptTimeoutMs, firstOutputTimeoutMs: bound } : { timeoutMs: attemptTimeoutMs };
5133
+ },
5134
+ settle(error, startedAt) {
5135
+ if (error instanceof ModelProducedNoOutputError)
5136
+ silentSpentMs += Date.now() - startedAt;
5137
+ }
5138
+ };
5139
+ }
5081
5140
  async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
5082
5141
  const timeoutMs = options.timeoutMs ?? 300000;
5083
5142
  const callContext = options.callContext ?? "subagent";
@@ -5086,11 +5145,15 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
5086
5145
  const baseArgs = copyPromptArgs(args, baseBody);
5087
5146
  const explicitPrimaryLabel = baseBody.model?.providerID && baseBody.model.modelID ? `${baseBody.model.providerID}/${baseBody.model.modelID}` : "primary";
5088
5147
  let lastError = null;
5148
+ const clock = createChainClock(options, timeoutMs);
5149
+ const primaryStartedAt = Date.now();
5089
5150
  try {
5090
- await attemptOnce(client, baseArgs, timeoutMs, options.signal, callContext, explicitPrimaryLabel, options.transport, options.allowModelSuggestions);
5151
+ const budget = clock.budget(0);
5152
+ await attemptOnce(client, baseArgs, budget.timeoutMs, options.signal, callContext, explicitPrimaryLabel, options.transport, options.allowModelSuggestions, budget.firstOutputTimeoutMs);
5091
5153
  return;
5092
5154
  } catch (error) {
5093
5155
  lastError = error;
5156
+ clock.settle(error, primaryStartedAt);
5094
5157
  if (isNonRetryable(error, options.signal))
5095
5158
  throw error;
5096
5159
  if (fallbacks.length === 0) {
@@ -5112,12 +5175,15 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
5112
5175
  model: parsed,
5113
5176
  ...fallback?.qualifier ? { variant: fallback.qualifier } : {}
5114
5177
  });
5178
+ const attemptStartedAt = Date.now();
5115
5179
  try {
5116
- await attemptOnce(client, attemptArgs, timeoutMs, options.signal, callContext, label, options.transport, options.allowModelSuggestions);
5180
+ const budget = clock.budget(i + 1);
5181
+ await attemptOnce(client, attemptArgs, budget.timeoutMs, options.signal, callContext, label, options.transport, options.allowModelSuggestions, budget.firstOutputTimeoutMs);
5117
5182
  log2(`[${callContext}] fallback succeeded with ${label} (attempt ${i + 2}/${fallbacks.length + 1})`);
5118
5183
  return;
5119
5184
  } catch (error) {
5120
5185
  lastError = error;
5186
+ clock.settle(error, attemptStartedAt);
5121
5187
  if (isNonRetryable(error, options.signal))
5122
5188
  throw error;
5123
5189
  const remaining = fallbacks.length - i - 1;
@@ -5129,9 +5195,9 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
5129
5195
  log2(`[${callContext}] all models exhausted; tried: ${[explicitPrimaryLabel, ...fallbacks.map((fallback) => toModelEntry(fallback)?.model ?? String(fallback))].join(", ")}; last error: ${shortErr(lastError)}`);
5130
5196
  throw lastError ?? new Error("All fallback models failed");
5131
5197
  }
5132
- async function attemptAndValidate(client, args, timeoutMs, signal, callContext, attempt, options) {
5198
+ async function attemptAndValidate(client, args, timeoutMs, signal, callContext, attempt, options, firstOutputTimeoutMs) {
5133
5199
  try {
5134
- await attemptOnce(client, args, timeoutMs, signal, callContext, attempt.label, options.transport, options.allowModelSuggestions);
5200
+ await attemptOnce(client, args, timeoutMs, signal, callContext, attempt.label, options.transport, options.allowModelSuggestions, firstOutputTimeoutMs);
5135
5201
  } catch (error) {
5136
5202
  throw {
5137
5203
  error,
@@ -5193,6 +5259,8 @@ async function promptSyncWithValidatedOutputRetry(client, args, options) {
5193
5259
  let firstError = null;
5194
5260
  let lastError = null;
5195
5261
  const cooledPrimary = primaryQuotaFailure(explicitPrimaryLabel);
5262
+ const clock = createChainClock(options, timeoutMs);
5263
+ const primaryStartedAt = Date.now();
5196
5264
  try {
5197
5265
  if (cooledPrimary)
5198
5266
  throw {
@@ -5207,16 +5275,18 @@ async function promptSyncWithValidatedOutputRetry(client, args, options) {
5207
5275
  skipped: true
5208
5276
  }
5209
5277
  };
5210
- return await attemptAndValidate(client, baseArgs, timeoutMs, options.signal, callContext, {
5278
+ const budget = clock.budget(0);
5279
+ return await attemptAndValidate(client, baseArgs, budget.timeoutMs, options.signal, callContext, {
5211
5280
  label: explicitPrimaryLabel,
5212
5281
  attemptIndex: 0,
5213
5282
  isFallback: false,
5214
5283
  totalAttempts,
5215
5284
  model: baseBody.model
5216
- }, options);
5285
+ }, options, budget.firstOutputTimeoutMs);
5217
5286
  } catch (caught) {
5218
5287
  const failure = caught;
5219
5288
  failedAttempts.push(failure);
5289
+ clock.settle(failure.error, primaryStartedAt);
5220
5290
  firstError = failure.error;
5221
5291
  lastError = failure.error;
5222
5292
  if (failure.error instanceof DreamerProviderOutputFailureError && failure.error.quotaResetAt !== undefined)
@@ -5254,13 +5324,16 @@ async function promptSyncWithValidatedOutputRetry(client, args, options) {
5254
5324
  totalAttempts,
5255
5325
  model: parsed
5256
5326
  };
5327
+ const attemptStartedAt = Date.now();
5257
5328
  try {
5258
- const result = await attemptAndValidate(client, attemptArgs, timeoutMs, options.signal, callContext, attempt, options);
5329
+ const budget = clock.budget(i + 1);
5330
+ const result = await attemptAndValidate(client, attemptArgs, budget.timeoutMs, options.signal, callContext, attempt, options, budget.firstOutputTimeoutMs);
5259
5331
  log2(`[${callContext}] fallback succeeded with ${label} (attempt ${i + 2}/${fallbacks.length + 1})`);
5260
5332
  return result;
5261
5333
  } catch (caught) {
5262
5334
  const failure = caught;
5263
5335
  failedAttempts.push(failure);
5336
+ clock.settle(failure.error, attemptStartedAt);
5264
5337
  lastError = failure.error;
5265
5338
  if (isNonRetryable(failure.error, options.signal)) {
5266
5339
  throwWithPromptFailure(failure.error, failedAttempts, args, timeoutMs, options.transport);
@@ -5476,6 +5549,24 @@ function isTerminalAssistant(message) {
5476
5549
  const info = infoOf(message);
5477
5550
  return isSettledAssistant(message) && info.finish !== "tool-calls" && info.finish !== "tool_use" && !(message && typeof message === "object" && Array.isArray(message.parts) && message.parts.some((part) => part.type === "tool"));
5478
5551
  }
5552
+ function showsModelOutput(message) {
5553
+ if (infoOf(message).role !== "assistant")
5554
+ return false;
5555
+ const tokens = sumTokensFromChildMessages([message]);
5556
+ if (tokens.input + tokens.output + tokens.cacheRead + tokens.cacheWrite > 0)
5557
+ return true;
5558
+ const parts = message?.parts;
5559
+ if (!Array.isArray(parts))
5560
+ return false;
5561
+ return parts.some((part) => {
5562
+ if (!part || typeof part !== "object")
5563
+ return false;
5564
+ const { type, text } = part;
5565
+ if (type === "tool")
5566
+ return true;
5567
+ return (type === "text" || type === "reasoning") && typeof text === "string" && text.trim().length > 0;
5568
+ });
5569
+ }
5479
5570
  function unwrapData(response) {
5480
5571
  if (response && typeof response === "object" && "data" in response) {
5481
5572
  return response.data;
@@ -5573,6 +5664,8 @@ async function promptAsyncAndWaitForIdle(client, request, options = {}) {
5573
5664
  }
5574
5665
  let sentAt = Date.now();
5575
5666
  let sawBusy = false;
5667
+ noteModelActivityMonitored(signal);
5668
+ let sawOutput = false;
5576
5669
  for (;; ) {
5577
5670
  await sleep(pollIntervalMs, signal);
5578
5671
  const hostError = activeSessionErrors.get(sessionId);
@@ -5587,6 +5680,13 @@ async function promptAsyncAndWaitForIdle(client, request, options = {}) {
5587
5680
  }
5588
5681
  const status = await readStatus(session, sessionId, dir, signal);
5589
5682
  const messages = await readMessages(session, sessionId, dir, signal);
5683
+ if (!sawOutput && messages.some((message) => {
5684
+ const id = messageId(message);
5685
+ return id !== null && !initialBaseline.has(id) && showsModelOutput(message);
5686
+ })) {
5687
+ sawOutput = true;
5688
+ noteModelOutputReceived(signal);
5689
+ }
5590
5690
  if (budget) {
5591
5691
  const latest = messages.at(-1);
5592
5692
  const latestId = messageId(latest);
@@ -10481,6 +10581,7 @@ async function applyCuesThroughModule(args, chunk, manifestText, signal) {
10481
10581
  }
10482
10582
 
10483
10583
  // ../plugin/src/features/magic-context/dreamer/hidden-single-shot.ts
10584
+ var DREAMER_FIRST_OUTPUT_TIMEOUT_MS = 90000;
10484
10585
  async function runHiddenSingleShotPrompt(args) {
10485
10586
  const system = withContentLanguageDirective(args.system, args.language);
10486
10587
  const opening = args.executor.open({
@@ -10522,6 +10623,7 @@ async function runHiddenSingleShotPrompt(args) {
10522
10623
  }, {
10523
10624
  transport: Object.assign((request) => args.executor.attempt(handle, request), { childSessionId: handle.childSessionId }),
10524
10625
  timeoutMs: args.timeoutMs,
10626
+ ...args.firstOutputTimeoutMs !== undefined ? { firstOutputTimeoutMs: args.firstOutputTimeoutMs } : {},
10525
10627
  ...args.signal ? { signal: args.signal } : {},
10526
10628
  fallbackModels: args.fallbackModels,
10527
10629
  callContext: args.callContext,
@@ -11375,6 +11477,7 @@ async function classifyOneChunk(args, chunk, anchors, sliceMs, signal) {
11375
11477
  }, {
11376
11478
  transport: Object.assign((request) => executor.attempt(opened, request), { childSessionId: opened.childSessionId }),
11377
11479
  timeoutMs: sliceMs,
11480
+ firstOutputTimeoutMs: args.firstOutputTimeoutMs ?? DREAMER_FIRST_OUTPUT_TIMEOUT_MS,
11378
11481
  signal,
11379
11482
  fallbackModels: args.fallbackModels,
11380
11483
  callContext: "dreamer:classify-memories",
@@ -14602,6 +14705,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
14602
14705
  model: args.model,
14603
14706
  fallbackModels: args.fallbackModels,
14604
14707
  timeoutMs: sliceMs,
14708
+ firstOutputTimeoutMs: args.firstOutputTimeoutMs ?? DREAMER_FIRST_OUTPUT_TIMEOUT_MS,
14605
14709
  signal,
14606
14710
  onOpened: () => {
14607
14711
  stage = "prompt";
@@ -14656,6 +14760,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
14656
14760
  onBudgetUpdate
14657
14761
  }),
14658
14762
  timeoutMs: sliceMs,
14763
+ firstOutputTimeoutMs: args.firstOutputTimeoutMs ?? DREAMER_FIRST_OUTPUT_TIMEOUT_MS,
14659
14764
  signal,
14660
14765
  fallbackModels: args.fallbackModels,
14661
14766
  callContext: "dreamer:map-memories",
@@ -16706,6 +16811,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
16706
16811
  fallbackModels: args.fallbackModels,
16707
16812
  language: args.language,
16708
16813
  timeoutMs: sliceMs,
16814
+ firstOutputTimeoutMs: args.firstOutputTimeoutMs ?? DREAMER_FIRST_OUTPUT_TIMEOUT_MS,
16709
16815
  signal: batchSignal,
16710
16816
  onFailureOutput: (completion) => {
16711
16817
  failedCompletion = completion;
@@ -16763,6 +16869,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
16763
16869
  onBudgetUpdate
16764
16870
  }),
16765
16871
  timeoutMs: sliceMs,
16872
+ firstOutputTimeoutMs: args.firstOutputTimeoutMs ?? DREAMER_FIRST_OUTPUT_TIMEOUT_MS,
16766
16873
  signal: batchSignal,
16767
16874
  fallbackModels: args.fallbackModels,
16768
16875
  callContext: "dreamer:verify",
@@ -45449,6 +45556,8 @@ function captureReasoningMutationRollback(messages) {
45449
45556
  }
45450
45557
  async function runCompactionOffPipeline(args) {
45451
45558
  let injectionResult = null;
45559
+ const transcript = [...args.messages];
45560
+ let headChangedUnderSignedTurn = false;
45452
45561
  if (args.injection) {
45453
45562
  const state = {
45454
45563
  sessionId: args.sessionId,
@@ -45462,10 +45571,30 @@ async function runCompactionOffPipeline(args) {
45462
45571
  muralEnabled: args.injection.muralEnabled === true,
45463
45572
  compactionOff: true
45464
45573
  };
45465
- if (args.reasoningClearing?.prefixBound === true && hasActiveAnthropicThinkingTurn(args.messages, args.resolvedProviderID, args.resolvedModelID))
45574
+ const signedTurnHoldsHead = args.reasoningClearing?.prefixBound === true && hasActiveAnthropicThinkingTurn(args.messages, args.resolvedProviderID, args.resolvedModelID);
45575
+ if (signedTurnHoldsHead)
45466
45576
  state.preparedPrefix = prepareCachedM0M1PiReplay(state, args.db, args.injectionPassSnapshot?.cachedRow);
45577
+ const servedBeforeFirstRender = signedTurnHoldsHead && !state.preparedPrefix ? args.readLastServedMessages?.() ?? null : undefined;
45467
45578
  injectionResult = injectM0M1Pi(state, args.db, args.messages, args.entryIds, false, args.injectionPassSnapshot);
45579
+ if (servedBeforeFirstRender !== undefined) {
45580
+ const headCount = injectionResult?.syntheticLeadingCount ?? 0;
45581
+ const head = JSON.stringify(args.messages.slice(0, headCount));
45582
+ headChangedUnderSignedTurn = servedBeforeFirstRender === null || JSON.stringify(servedBeforeFirstRender.slice(0, headCount)) !== head;
45583
+ }
45468
45584
  }
45585
+ if (headChangedUnderSignedTurn)
45586
+ applyPiProactiveThinkingStrip({
45587
+ db: args.db,
45588
+ sessionId: args.sessionId,
45589
+ messages: transcript,
45590
+ entryIds: transcript.map((message, index) => resolvePiRealStableId(message, index, args.entryIds, args.entryIdByRef ?? undefined)),
45591
+ provider: args.resolvedProviderID,
45592
+ model: args.resolvedModelID,
45593
+ cacheBustingPass: true,
45594
+ stripActiveTurn: true,
45595
+ requirePersistence: true,
45596
+ report: (line) => sessionLog2(args.sessionId, line)
45597
+ });
45469
45598
  return {
45470
45599
  messages: args.messages,
45471
45600
  prefixBustPermitted: false,
@@ -13,7 +13,7 @@ import {
13
13
  markMessageIndexDirty2,
14
14
  getIndexableContent2,
15
15
  indexSingleMessage2
16
- } from "./index-fvjthct0.js";
16
+ } from "./index-ym6nh2gk.js";
17
17
  import"./index-rhprywn6.js";
18
18
  import"./index-1kcfwk9c.js";
19
19
  import"./index-jrap43gc.js";
@@ -21,7 +21,7 @@ import"./index-bxmf4dhr.js";
21
21
  import"./index-399p688g.js";
22
22
  import"./index-vktahpdj.js";
23
23
  import"./index-8976mezv.js";
24
- import"./index-r9f4f6s1.js";
24
+ import"./index-wveb51es.js";
25
25
  import"./index-6x556c2q.js";
26
26
  import"./index-yygsh681.js";
27
27
  import"./index-d8gc0112.js";
@@ -17,9 +17,9 @@ import {
17
17
  indexMessagesAfterOrdinal2,
18
18
  indexSourcesAfterOrdinal2,
19
19
  sweepOrphanedOpenCodeMessageIndexesCooperatively2
20
- } from "./index-fvjthct0.js";
20
+ } from "./index-ym6nh2gk.js";
21
21
  import"./index-xnch62s6.js";
22
- import"./index-r9f4f6s1.js";
22
+ import"./index-wveb51es.js";
23
23
  import"./index-rhprywn6.js";
24
24
  import"./index-6x556c2q.js";
25
25
  import"./index-d8gc0112.js";
@@ -9,7 +9,7 @@ import {
9
9
  import"./index-135e8hvg.js";
10
10
  import {
11
11
  runMigrationsWithRetry
12
- } from "./index-gdjv1nnd.js";
12
+ } from "./index-msqrs4nf.js";
13
13
  import {
14
14
  closeQuietly
15
15
  } from "./index-jrap43gc.js";
@@ -20,7 +20,7 @@ import"./index-fapenpch.js";
20
20
  import {
21
21
  setSqlitePragmaConfig,
22
22
  initializeDatabase
23
- } from "./index-gp928w10.js";
23
+ } from "./index-sqt2haap.js";
24
24
  import"./index-399p688g.js";
25
25
  import"./index-vktahpdj.js";
26
26
  import"./index-yygsh681.js";
@@ -32,7 +32,7 @@ try {
32
32
  await runMessageFtsRowidMapBackfill(db);
33
33
  reply = { kind: "fts-rowid-backfill" };
34
34
  } else if (input.searchArchive) {
35
- const { renderSearchArchive } = await import("./search-archive-jg4a1kcx.js");
35
+ const { renderSearchArchive } = await import("./search-archive-4817pqev.js");
36
36
  const { readRawSessionMessageIdOrdinalsForRangeFromDb } = await import("./read-session-raw-9s3xn7fc.js");
37
37
  const archive = input.searchArchive;
38
38
  let raw;
@@ -62,7 +62,7 @@ try {
62
62
  { configureContextDatabasePragmas }
63
63
  ] = await Promise.all([
64
64
  import("./harness-9872e0ym.js"),
65
- import("./message-index-74qdqmq7.js"),
65
+ import("./message-index-rc2x41k4.js"),
66
66
  import("./sqlite-context-pragmas-gcgch6qz.js")
67
67
  ]);
68
68
  setHarness(input.harness ?? "opencode");
@@ -76,7 +76,7 @@ try {
76
76
  const { setHarness } = await import("./harness-9872e0ym.js");
77
77
  setHarness(input.harness ?? "opencode");
78
78
  const [{ indexMessageInShortChunks }, { configureContextDatabasePragmas }] = await Promise.all([
79
- import("./message-index-bounded-g9hgresf.js"),
79
+ import("./message-index-bounded-66saeq5j.js"),
80
80
  import("./sqlite-context-pragmas-gcgch6qz.js")
81
81
  ]);
82
82
  configureContextDatabasePragmas(db);
@@ -35,7 +35,7 @@ import {
35
35
  readSessionChunk2,
36
36
  getRawSessionMessageIdsThrough2,
37
37
  readRawSessionSeedTail2
38
- } from "./index-r9f4f6s1.js";
38
+ } from "./index-wveb51es.js";
39
39
  import"./index-rhprywn6.js";
40
40
  import"./index-6x556c2q.js";
41
41
  import"./index-bxmf4dhr.js";
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  renderSearchArchive2
3
- } from "./index-d21pdr8v.js";
3
+ } from "./index-dtp1efvf.js";
4
4
  import"./index-1cvyaw9a.js";
5
- import"./index-r9f4f6s1.js";
5
+ import"./index-wveb51es.js";
6
6
  import"./index-rhprywn6.js";
7
7
  import"./index-6x556c2q.js";
8
8
  import"./index-bxmf4dhr.js";
@@ -5,9 +5,9 @@ import {
5
5
  resolveMemoriesByIdsForSearch2,
6
6
  unifiedSearch2,
7
7
  formatSearchResults2
8
- } from "./index-d43hmn31.js";
8
+ } from "./index-58mj0dzc.js";
9
9
  import"./index-1cvyaw9a.js";
10
- import"./index-fvjthct0.js";
10
+ import"./index-ym6nh2gk.js";
11
11
  import"./index-z2rkv0mb.js";
12
12
  import"./index-vmcgew7x.js";
13
13
  import"./index-9p40dgkm.js";
@@ -15,13 +15,13 @@ import"./index-e1rza8gp.js";
15
15
  import"./index-yhzhdp3m.js";
16
16
  import"./index-svgkv4g2.js";
17
17
  import"./index-xnch62s6.js";
18
- import"./index-r9f4f6s1.js";
18
+ import"./index-wveb51es.js";
19
19
  import"./index-rhprywn6.js";
20
20
  import"./index-6x556c2q.js";
21
21
  import"./index-2mmy81qt.js";
22
22
  import"./index-d8gc0112.js";
23
23
  import"./index-bxmf4dhr.js";
24
- import"./index-gdjv1nnd.js";
24
+ import"./index-msqrs4nf.js";
25
25
  import"./index-apgwdby5.js";
26
26
  import"./index-g7p75667.js";
27
27
  import"./index-yygsh681.js";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  TOKEN_BUDGET_TOOL_REFUSAL
3
- } from "./index-r9f4f6s1.js";
3
+ } from "./index-wveb51es.js";
4
4
  import {
5
5
  setHarness2
6
6
  } from "./index-0h2mkab2.js";
@@ -15,11 +15,11 @@ import"./index-apgwdby5.js";
15
15
  import"./index-fapenpch.js";
16
16
  import {
17
17
  openDatabase
18
- } from "./index-gp928w10.js";
18
+ } from "./index-sqt2haap.js";
19
19
  import"./index-399p688g.js";
20
20
  import"./index-vktahpdj.js";
21
21
  import"./index-yygsh681.js";
22
- import"./index-gdjv1nnd.js";
22
+ import"./index-msqrs4nf.js";
23
23
  import"./index-jrap43gc.js";
24
24
  import"./index-135e8hvg.js";
25
25
  import"./index-8976mezv.js";
@@ -30,7 +30,7 @@ import {
30
30
  ensureProjectRegisteredFromPiDirectory,
31
31
  resolvePiHarnessKind,
32
32
  registerMagicContextTools
33
- } from "./index-xxn1tpnv.js";
33
+ } from "./index-ek9zvs4f.js";
34
34
  import"./index-bxmf4dhr.js";
35
35
  import"./index-d8gc0112.js";
36
36
  import"./index-xnch62s6.js";
@@ -40,12 +40,12 @@ import"./index-9p40dgkm.js";
40
40
  import"./index-svgkv4g2.js";
41
41
  import"./index-yhzhdp3m.js";
42
42
  import"./index-z2rkv0mb.js";
43
- import"./index-fvjthct0.js";
43
+ import"./index-ym6nh2gk.js";
44
44
  import"./index-rhprywn6.js";
45
45
  import"./index-6x556c2q.js";
46
- import"./index-d43hmn31.js";
46
+ import"./index-58mj0dzc.js";
47
47
  import"./index-1cvyaw9a.js";
48
- import"./index-d21pdr8v.js";
48
+ import"./index-dtp1efvf.js";
49
49
  import"./index-e1rza8gp.js";
50
50
  import"./index-qpq6w67c.js";
51
51
  import"./index-d4dt19md.js";
@@ -9,11 +9,11 @@ import"./index-fapenpch.js";
9
9
  import {
10
10
  LATEST_SUPPORTED_VERSION,
11
11
  getPersistedSchemaVersion
12
- } from "./index-gp928w10.js";
12
+ } from "./index-sqt2haap.js";
13
13
  import"./index-399p688g.js";
14
14
  import"./index-vktahpdj.js";
15
15
  import"./index-yygsh681.js";
16
- import"./index-gdjv1nnd.js";
16
+ import"./index-msqrs4nf.js";
17
17
  import {
18
18
  tagRevisionKey
19
19
  } from "./index-jrap43gc.js";
@@ -28,7 +28,7 @@ import {
28
28
  encodePiHydrationOperation,
29
29
  PI_FALLBACK_ROW_COLUMNS,
30
30
  PI_FALLBACK_ROW_PREDICATE
31
- } from "./index-4bv5bttd.js";
31
+ } from "./index-rc1dez8m.js";
32
32
  import"./index-d4dt19md.js";
33
33
 
34
34
  // src/tag-snapshot-worker-pi.ts
@@ -186,47 +186,50 @@ async function stream(kind) {
186
186
  }
187
187
  await send({ ...envelope(), type: "end", stream: kind, rows: rowsSent });
188
188
  }
189
- try {
190
- if (request.test?.openDelayMs)
191
- await delay(request.test.openDelayMs);
192
- db = new Database2(request.path, { readonly: true });
193
- opened = true;
194
- db.exec("PRAGMA query_only = ON; PRAGMA busy_timeout = 50; PRAGMA cache_size = -1024");
195
- generationStatement = db.prepare(`SELECT
189
+ var run = async () => {
190
+ try {
191
+ if (request.test?.openDelayMs)
192
+ await delay(request.test.openDelayMs);
193
+ db = new Database2(request.path, { readonly: true });
194
+ opened = true;
195
+ db.exec("PRAGMA query_only = ON; PRAGMA busy_timeout = 50; PRAGMA cache_size = -1024");
196
+ generationStatement = db.prepare(`SELECT
196
197
  COALESCE((SELECT value FROM schema_migrations_meta WHERE key = ?), '0') AS revision,
197
198
  COALESCE((SELECT tags_version FROM session_meta WHERE session_id = ?), 0) AS durable`);
198
- const version = getPersistedSchemaVersion(db);
199
- persistedVersion = version;
200
- if (version > LATEST_SUPPORTED_VERSION)
201
- throw new UnsupportedSchema(`shared database schema v${version} is newer than this build supports (v${LATEST_SUPPORTED_VERSION}); update and restart this host`);
202
- await stream("tags");
203
- await stream("fallback");
204
- if (request.test?.crash === "before-end")
205
- throw new Error("injected worker crash before completion");
206
- const final = sample(db);
207
- if (final.revision !== generation.revision || final.durable !== generation.durable)
208
- throw new StaleGeneration("session tags changed after final page");
209
- db.close();
210
- db = undefined;
211
- port.postMessage({
212
- ...envelope(),
213
- type: "done",
214
- maxReadTransactionMs,
215
- packetCount,
216
- packetBytes
217
- });
218
- if (request.test?.crash === "after-end")
219
- process.exitCode = 1;
220
- } catch (error) {
221
- port.postMessage({
222
- ...envelope(),
223
- type: "failed",
224
- code: error instanceof StaleGeneration ? "stale" : error instanceof UnsupportedSchema ? "schema" : opened ? "failed" : "open",
225
- persistedVersion,
226
- supportedVersion: LATEST_SUPPORTED_VERSION,
227
- reason: error instanceof Error ? error.message : String(error)
228
- });
229
- } finally {
230
- db?.close();
231
- port.close();
232
- }
199
+ const version = getPersistedSchemaVersion(db);
200
+ persistedVersion = version;
201
+ if (version > LATEST_SUPPORTED_VERSION)
202
+ throw new UnsupportedSchema(`shared database schema v${version} is newer than this build supports (v${LATEST_SUPPORTED_VERSION}); update and restart this host`);
203
+ await stream("tags");
204
+ await stream("fallback");
205
+ if (request.test?.crash === "before-end")
206
+ throw new Error("injected worker crash before completion");
207
+ const final = sample(db);
208
+ if (final.revision !== generation.revision || final.durable !== generation.durable)
209
+ throw new StaleGeneration("session tags changed after final page");
210
+ db.close();
211
+ db = undefined;
212
+ port.postMessage({
213
+ ...envelope(),
214
+ type: "done",
215
+ maxReadTransactionMs,
216
+ packetCount,
217
+ packetBytes
218
+ });
219
+ if (request.test?.crash === "after-end")
220
+ process.exitCode = 1;
221
+ } catch (error) {
222
+ port.postMessage({
223
+ ...envelope(),
224
+ type: "failed",
225
+ code: error instanceof StaleGeneration ? "stale" : error instanceof UnsupportedSchema ? "schema" : opened ? "failed" : "open",
226
+ persistedVersion,
227
+ supportedVersion: LATEST_SUPPORTED_VERSION,
228
+ reason: error instanceof Error ? error.message : String(error)
229
+ });
230
+ } finally {
231
+ db?.close();
232
+ port.close();
233
+ }
234
+ };
235
+ run();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.49.18",
3
+ "version": "0.49.19",
4
4
  "type": "module",
5
5
  "description": "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",