@cortexkit/pi-magic-context 0.49.8 → 0.49.9

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.
@@ -22,7 +22,7 @@ var [
22
22
  import("./embedding-cache-7rp4gqzr.js"),
23
23
  import("./storage-memory-axnsk5t1.js"),
24
24
  import("./project-embedding-registry-bxawck58.js"),
25
- import("./search-x7cachq0.js"),
25
+ import("./search-hsr95vex.js"),
26
26
  import("./embedding-activity-ew6dshfd.js"),
27
27
  import("./harness-9872e0ym.js"),
28
28
  import("./sqlite-adjpy399.js"),
@@ -2,7 +2,8 @@ import {
2
2
  subagentTemperature,
3
3
  promptFingerprint,
4
4
  readHostSystemPrompt
5
- } from "./index-zh1jw8qp.js";
5
+ } from "./index-xmdkde4v.js";
6
+ import"./index-6x556c2q.js";
6
7
  import"./index-0h2mkab2.js";
7
8
  import"./index-gycf3sp7.js";
8
9
 
@@ -51,13 +51,13 @@ import {
51
51
  hasPendingMigrations,
52
52
  getMainThreadMigrationBodyCount,
53
53
  runMigrations
54
- } from "./index-r8cy8hmq.js";
54
+ } from "./index-g13fb2sj.js";
55
55
  import {
56
56
  closeQuietly,
57
57
  ensureColumn,
58
58
  installV95PerfSchema,
59
59
  installTagIdentityRevisionTrigger
60
- } from "./index-zzn7qbps.js";
60
+ } from "./index-ttxsmaj5.js";
61
61
  import {
62
62
  resolveOpenCodeDbPath,
63
63
  hasV1MessageTables,
@@ -1298,7 +1298,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
1298
1298
  startMessageFtsRowidMapBackfill(db).then(async () => {
1299
1299
  if (!readsOpenCodeStore)
1300
1300
  return;
1301
- const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-1jagnq05.js"));
1301
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-4094zemt.js"));
1302
1302
  const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-q9s88zdv.js"));
1303
1303
  await startMessageTimeBackfill(db, Object.assign(readRawSessionMessages, {
1304
1304
  readPage: readRawSessionMessagePage
@@ -0,0 +1,19 @@
1
+ // ../plugin/src/shared/hidden-zen-read.ts
2
+ var blockedSessions = new Set;
3
+ var v1Runs = new Map;
4
+ function rememberV1HiddenRun(sessionID, run) {
5
+ if (run)
6
+ v1Runs.set(sessionID, run);
7
+ else {
8
+ v1Runs.delete(sessionID);
9
+ setBlockedReadSession(sessionID, false);
10
+ }
11
+ }
12
+ function setBlockedReadSession(sessionID, enabled) {
13
+ if (enabled)
14
+ blockedSessions.add(sessionID);
15
+ else
16
+ blockedSessions.delete(sessionID);
17
+ }
18
+
19
+ export { rememberV1HiddenRun };
@@ -17,11 +17,13 @@ import {
17
17
  resolveDecisionCalibration,
18
18
  calibrationForModelKey,
19
19
  isRecord,
20
+ estimateImageTokensFromDataUrl,
21
+ estimateToolAttachmentImageTokens,
20
22
  providerVisiblePart,
21
23
  TAG_SELECT_COLUMNS2,
22
24
  getCandidateToolOwners2,
23
25
  pickNearestPriorOwner2
24
- } from "./index-54r5vs9w.js";
26
+ } from "./index-x7426vy4.js";
25
27
  import {
26
28
  OMO_INTERNAL_INITIATOR_MARKER,
27
29
  isSystemDirective,
@@ -44,7 +46,7 @@ import {
44
46
  import {
45
47
  stableStringify,
46
48
  closeQuietly
47
- } from "./index-zzn7qbps.js";
49
+ } from "./index-ttxsmaj5.js";
48
50
  import {
49
51
  resolveOpenCodeDbPath,
50
52
  assertOpenCodeStoreGeneration,
@@ -4019,6 +4021,17 @@ function opaqueThinkingCost(reasoning, output) {
4019
4021
 
4020
4022
  // ../plugin/src/hooks/magic-context/final-wire-token-estimate.ts
4021
4023
  var wireTextTokens = createTokenCountMemo(1e5, 128 * 1024 * 1024);
4024
+ function estimatePartImageTokens(raw) {
4025
+ if (!raw || typeof raw !== "object")
4026
+ return 0;
4027
+ const part = raw;
4028
+ if (part.ignored)
4029
+ return 0;
4030
+ if (part.type === "file" && part.mime?.startsWith("image/")) {
4031
+ return typeof part.url === "string" && part.url.startsWith("data:") ? estimateImageTokensFromDataUrl(part.url) : 1200;
4032
+ }
4033
+ return part.type === "tool" ? estimateToolAttachmentImageTokens(part.state) : 0;
4034
+ }
4022
4035
 
4023
4036
  // ../plugin/src/hooks/magic-context/tool-input-size.ts
4024
4037
  var SKELETON_REAL_INPUT_MAX_BYTES = 1024;
@@ -5041,4 +5054,4 @@ function readRawSessionSeedTail2(sessionId, boundaryId, onQuery) {
5041
5054
  });
5042
5055
  }
5043
5056
 
5044
- 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, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripSystemInjection, 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, 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 };
5057
+ 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, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripSystemInjection, 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 };
@@ -8,7 +8,7 @@ import {
8
8
  ensureColumn,
9
9
  healAllNullColumns,
10
10
  installV95PerfSchema
11
- } from "./index-zzn7qbps.js";
11
+ } from "./index-ttxsmaj5.js";
12
12
  import {
13
13
  resolveOpenCodeDbPath,
14
14
  openCodeDbPathExists,
@@ -34,10 +34,10 @@ import {
34
34
  tagRevisionKey,
35
35
  tagIdentityRevisionKey,
36
36
  deleteTagIdentityRevisions
37
- } from "./index-zzn7qbps.js";
37
+ } from "./index-ttxsmaj5.js";
38
38
  import {
39
39
  cleanUserText2
40
- } from "./index-18qe4gs1.js";
40
+ } from "./index-9vzkrnrf.js";
41
41
  import {
42
42
  logSlowWriteTransaction
43
43
  } from "./index-43zqh10z.js";
@@ -22,10 +22,10 @@ import {
22
22
  resolveStoredPathWorkspaceIdentity,
23
23
  sourceNameForMemory,
24
24
  managedAuthorityNoteRow
25
- } from "./index-r8cy8hmq.js";
25
+ } from "./index-g13fb2sj.js";
26
26
  import {
27
27
  isKnownAutocommit
28
- } from "./index-zzn7qbps.js";
28
+ } from "./index-ttxsmaj5.js";
29
29
  import {
30
30
  SubcClient
31
31
  } from "./index-szh001qb.js";
@@ -77,7 +77,7 @@ import {
77
77
  } from "./index-hy44m6jc.js";
78
78
  import {
79
79
  getIndexedMessageCorpusSize2
80
- } from "./index-tdhppxwd.js";
80
+ } from "./index-h160xxaq.js";
81
81
  import {
82
82
  computeNormalizedHash
83
83
  } from "./index-9x1f96r8.js";
@@ -56,7 +56,7 @@ import {
56
56
  readRawSessionMessageIdOrdinalsForRange2,
57
57
  readRawSessionMessageById2,
58
58
  readSessionChunk2
59
- } from "./index-18qe4gs1.js";
59
+ } from "./index-9vzkrnrf.js";
60
60
  import {
61
61
  isRecord,
62
62
  providerVisibleMessage,
@@ -70,7 +70,7 @@ import {
70
70
  getTagNumberByMessageId2,
71
71
  getTagsBySession2,
72
72
  getTagById2
73
- } from "./index-54r5vs9w.js";
73
+ } from "./index-x7426vy4.js";
74
74
  import {
75
75
  estimateTokens
76
76
  } from "./index-4pxydwvg.js";
@@ -84,7 +84,7 @@ import {
84
84
  stableStringify,
85
85
  closeQuietly,
86
86
  getTableColumnNames
87
- } from "./index-zzn7qbps.js";
87
+ } from "./index-ttxsmaj5.js";
88
88
  import {
89
89
  resolveOpenCodeDbPath,
90
90
  assertOpenCodeStoreGeneration
@@ -103,7 +103,7 @@ import {
103
103
  clearLkgRecoveryFence,
104
104
  deleteSessionScopedRows,
105
105
  getLastIndexedOrdinal2
106
- } from "./index-tdhppxwd.js";
106
+ } from "./index-h160xxaq.js";
107
107
  import {
108
108
  SubcClient,
109
109
  connectionFileExists,
@@ -116,7 +116,7 @@ import {
116
116
  } from "./index-fdxzpnbj.js";
117
117
  import {
118
118
  getErrorMessage
119
- } from "./index-rggtvnbg.js";
119
+ } from "./index-243wh86p.js";
120
120
  import {
121
121
  V2_MEMORY_CATEGORIES,
122
122
  CATEGORY_PRIORITY,
@@ -130,7 +130,7 @@ import {
130
130
  expandWorkspaceIdentitySetWithAliases,
131
131
  resolveStoredPathWorkspaceIdentity,
132
132
  storedPathBelongsToWorkspace
133
- } from "./index-r8cy8hmq.js";
133
+ } from "./index-g13fb2sj.js";
134
134
  import {
135
135
  directoryHasGitMetadata,
136
136
  resolveProjectIdentityForSession,
@@ -165,7 +165,7 @@ import {
165
165
  resolveMemoriesByIdsForSearch2,
166
166
  unifiedSearch2,
167
167
  formatSearchResults2
168
- } from "./index-pdhbj18g.js";
168
+ } from "./index-ns319t8e.js";
169
169
  import {
170
170
  computeCueContentHash,
171
171
  getMuralCueState,
@@ -5,32 +5,32 @@ import {
5
5
  // ../plugin/src/shared/stable-json.ts
6
6
  function stableStringify(value, seen = new WeakSet) {
7
7
  const pieces = [];
8
- writeStable(value, seen, pieces);
8
+ writeStable(value, seen, (piece) => pieces.push(piece));
9
9
  return pieces.join("");
10
10
  }
11
- function writeStable(value, seen, pieces) {
11
+ function writeStable(value, seen, write) {
12
12
  if (value === undefined) {
13
- pieces.push("undefined");
13
+ write("undefined");
14
14
  return;
15
15
  }
16
16
  if (value === null || typeof value !== "object") {
17
- pieces.push(JSON.stringify(value) ?? String(value));
17
+ write(JSON.stringify(value) ?? String(value));
18
18
  return;
19
19
  }
20
20
  if (seen.has(value)) {
21
- pieces.push('"[Circular]"');
21
+ write('"[Circular]"');
22
22
  return;
23
23
  }
24
24
  seen.add(value);
25
25
  if (Array.isArray(value)) {
26
- pieces.push("[");
26
+ write("[");
27
27
  for (let index = 0;index < value.length; index += 1) {
28
28
  if (index > 0)
29
- pieces.push(",");
29
+ write(",");
30
30
  if (index in value)
31
- writeStable(value[index], seen, pieces);
31
+ writeStable(value[index], seen, write);
32
32
  }
33
- pieces.push("]");
33
+ write("]");
34
34
  return;
35
35
  }
36
36
  const entries = Object.entries(value).sort(([a], [b]) => {
@@ -40,14 +40,29 @@ function writeStable(value, seen, pieces) {
40
40
  return 1;
41
41
  return 0;
42
42
  });
43
- pieces.push("{");
43
+ if (entries.length > 0 && entries.length <= 16 && entries.every(([key, child]) => key.length <= 4096 && !/^(0|[1-9]\d*)$/.test(key) && (child === null || typeof child === "number" || typeof child === "boolean" || typeof child === "string" && child.length <= 4096))) {
44
+ write(JSON.stringify(Object.fromEntries(entries)));
45
+ return;
46
+ }
47
+ write("{");
44
48
  entries.forEach(([key, child], index) => {
45
49
  if (index > 0)
46
- pieces.push(",");
47
- pieces.push(JSON.stringify(key), ":");
48
- writeStable(child, seen, pieces);
50
+ write(",");
51
+ write(JSON.stringify(key));
52
+ write(":");
53
+ writeStable(child, seen, write);
49
54
  });
50
- pieces.push("}");
55
+ write("}");
56
+ }
57
+ function jsonHashSink(prefix = "") {
58
+ let hash = 2166136261;
59
+ const write = (piece) => {
60
+ for (let index = 0;index < piece.length; index++) {
61
+ hash = Math.imul(hash ^ piece.charCodeAt(index), 16777619);
62
+ }
63
+ };
64
+ write(prefix);
65
+ return { write, digest: () => (hash >>> 0).toString(16).padStart(8, "0") };
51
66
  }
52
67
 
53
68
  // ../plugin/src/shared/sqlite-helpers.ts
@@ -524,4 +539,4 @@ function deleteTagIdentityRevisions(db, sessionIds) {
524
539
  }
525
540
  }
526
541
 
527
- export { stableStringify, closeQuietly, isKnownAutocommit, getTableColumnNames, ensureColumn, healAllNullColumns, observeTemporalDecisions, freezeTemporalDecisions, installV95PerfSchema, tagOrderConstraintIndex, TAG_TOMBSTONE_OWNER_PREFIX, tagRevisionIncarnationSql, tagRevisionCountSql, tagTombstoneOwnerRange, tagTombstoneOwnerKey, tagRevisionKey, tagIdentityRevisionKey, TAG_INSERT_CONFLICT_ROWS, installTagIdentityRevisionTrigger, deleteTagIdentityRevisions };
542
+ export { stableStringify, jsonHashSink, closeQuietly, isKnownAutocommit, getTableColumnNames, ensureColumn, healAllNullColumns, observeTemporalDecisions, freezeTemporalDecisions, installV95PerfSchema, tagOrderConstraintIndex, TAG_TOMBSTONE_OWNER_PREFIX, tagRevisionIncarnationSql, tagRevisionCountSql, tagTombstoneOwnerRange, tagTombstoneOwnerKey, tagRevisionKey, tagIdentityRevisionKey, TAG_INSERT_CONFLICT_ROWS, installTagIdentityRevisionTrigger, deleteTagIdentityRevisions };
@@ -12,9 +12,10 @@ import {
12
12
  getSqliteDatabasePath2
13
13
  } from "./index-asrxgdt4.js";
14
14
  import {
15
+ jsonHashSink,
15
16
  tagOrderConstraintIndex,
16
17
  tagIdentityRevisionKey
17
- } from "./index-zzn7qbps.js";
18
+ } from "./index-ttxsmaj5.js";
18
19
  import {
19
20
  DEFAULT_PROTECTED_TOOLS,
20
21
  normalizeProtectedToolName,
@@ -624,6 +625,22 @@ function prependTag(tagId, value) {
624
625
  return `§${tagId}§ ${stripped}`;
625
626
  }
626
627
 
628
+ // ../plugin/src/hooks/magic-context/tail-hygiene-output-count.ts
629
+ var CURRENT_OUTPUT_COUNT = Symbol.for("magic-context.current-reclaimable-tool-output-count");
630
+ function countReclaimableToolOutputs(parts) {
631
+ return parts.filter((part) => part.kind === "toolOutput" && part.uTokens > 0).length;
632
+ }
633
+ function rememberCurrentToolOutputCount(baseline, measurement) {
634
+ return Object.assign(baseline, {
635
+ [CURRENT_OUTPUT_COUNT]: countReclaimableToolOutputs(measurement.parts)
636
+ });
637
+ }
638
+ function currentReclaimableToolOutputCount(baseline) {
639
+ if (!baseline || !Object.hasOwn(baseline, CURRENT_OUTPUT_COUNT))
640
+ return 0;
641
+ return baseline[CURRENT_OUTPUT_COUNT];
642
+ }
643
+
627
644
  // ../plugin/src/shared/record-type-guard.ts
628
645
  function isRecord(value) {
629
646
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -644,6 +661,197 @@ function contentTagOwnerMessageId(contentId) {
644
661
  return contentId;
645
662
  }
646
663
 
664
+ // ../plugin/src/shared/tail-hygiene-json.ts
665
+ var MAX_MEMO_BYTES = 64 * 1024 * 1024;
666
+ var MAX_MEMO_ENTRIES = 1e4;
667
+
668
+ class TailHygieneJsonMemo {
669
+ entries = new Map;
670
+ bytes = 0;
671
+ passText = new WeakMap;
672
+ passHash = new WeakMap;
673
+ beginPass() {
674
+ this.passText = new WeakMap;
675
+ this.passHash = new WeakMap;
676
+ }
677
+ get(key, value, compute, fingerprint = false) {
678
+ const pass = fingerprint ? this.passHash : this.passText;
679
+ const object = value !== null && typeof value === "object" ? value : undefined;
680
+ const local = object ? pass.get(object) : undefined;
681
+ if (local !== undefined)
682
+ return local;
683
+ const previous = this.entries.get(key);
684
+ if (previous && sameJson(previous.snapshot, value)) {
685
+ if (object)
686
+ pass.set(object, previous.result);
687
+ return previous.result;
688
+ }
689
+ const result = compute();
690
+ if (previous) {
691
+ this.bytes -= previous.bytes;
692
+ this.entries.delete(key);
693
+ }
694
+ try {
695
+ const copy = copyJson(value);
696
+ const bytes = copy.bytes + (key.length + result.length) * 2;
697
+ if (bytes <= MAX_MEMO_BYTES) {
698
+ this.entries.set(key, { snapshot: copy.value, result, bytes });
699
+ this.bytes += bytes;
700
+ if (object)
701
+ pass.set(object, result);
702
+ }
703
+ } catch {}
704
+ while (this.bytes > MAX_MEMO_BYTES || this.entries.size > MAX_MEMO_ENTRIES) {
705
+ const oldest = this.entries.entries().next().value;
706
+ if (!oldest)
707
+ break;
708
+ this.bytes -= oldest[1].bytes;
709
+ this.entries.delete(oldest[0]);
710
+ }
711
+ return result;
712
+ }
713
+ }
714
+ function copyJson(value) {
715
+ const seen = new Map;
716
+ let bytes = 0;
717
+ const copy = (current) => {
718
+ bytes += 16;
719
+ if (typeof current === "string")
720
+ bytes += current.length * 2;
721
+ if (bytes > MAX_MEMO_BYTES)
722
+ throw new Error("memo capacity");
723
+ if (current === null || typeof current !== "object") {
724
+ if (["function", "symbol", "bigint"].includes(typeof current))
725
+ throw new Error("exotic");
726
+ return current;
727
+ }
728
+ if (seen.has(current))
729
+ return seen.get(current);
730
+ const prototype = Object.getPrototypeOf(current);
731
+ if (!Array.isArray(current) && prototype !== Object.prototype && prototype !== null)
732
+ throw new Error("exotic");
733
+ const result = Array.isArray(current) ? new Array(current.length) : Object.create(prototype);
734
+ seen.set(current, result);
735
+ for (const key of Object.keys(current)) {
736
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
737
+ if (!descriptor || !("value" in descriptor))
738
+ throw new Error("accessor");
739
+ bytes += key.length * 2 + 16;
740
+ if (key === "__proto__") {
741
+ Object.defineProperty(result, key, {
742
+ value: copy(descriptor.value),
743
+ enumerable: true,
744
+ writable: true,
745
+ configurable: true
746
+ });
747
+ } else
748
+ result[key] = copy(descriptor.value);
749
+ }
750
+ return result;
751
+ };
752
+ return { value: copy(value), bytes };
753
+ }
754
+ function sameJson(before, after) {
755
+ const forward = new Map;
756
+ const reverse = new Set;
757
+ const same = (left, right) => {
758
+ if (left === null || right === null || typeof left !== "object" || typeof right !== "object")
759
+ return Object.is(left, right);
760
+ if (forward.has(left))
761
+ return forward.get(left) === right;
762
+ if (reverse.has(right) || Object.getPrototypeOf(left) !== Object.getPrototypeOf(right))
763
+ return false;
764
+ forward.set(left, right);
765
+ reverse.add(right);
766
+ if (Array.isArray(left) && (!Array.isArray(right) || left.length !== right.length))
767
+ return false;
768
+ const keys = Object.keys(left);
769
+ const otherKeys = Object.keys(right);
770
+ if (keys.length !== otherKeys.length)
771
+ return false;
772
+ for (let index = 0;index < keys.length; index++) {
773
+ const key = keys[index];
774
+ if (key !== otherKeys[index])
775
+ return false;
776
+ const descriptor = Object.getOwnPropertyDescriptor(right, key);
777
+ if (!descriptor || !("value" in descriptor) || !same(left[key], descriptor.value))
778
+ return false;
779
+ }
780
+ return true;
781
+ };
782
+ return same(before, after);
783
+ }
784
+ function piJsonHash(value, fallback) {
785
+ const sink = jsonHashSink("excluded\x00");
786
+ try {
787
+ const seen = new Set;
788
+ const arrays = new Set;
789
+ const write = (current) => {
790
+ if (current === null || typeof current !== "object") {
791
+ if (["function", "symbol", "bigint"].includes(typeof current))
792
+ throw new Error("exotic");
793
+ sink.write(JSON.stringify(current) ?? "");
794
+ } else if (Array.isArray(current)) {
795
+ if (Object.getPrototypeOf(current) !== Array.prototype || Object.hasOwn(current, "toJSON"))
796
+ throw new Error("exotic array");
797
+ if (arrays.has(current))
798
+ throw new Error("array cycle");
799
+ arrays.add(current);
800
+ sink.write("[");
801
+ for (let index = 0;index < current.length; index++) {
802
+ if (index)
803
+ sink.write(",");
804
+ const descriptor = Object.getOwnPropertyDescriptor(current, index);
805
+ if (descriptor && !("value" in descriptor))
806
+ throw new Error("accessor");
807
+ if (!descriptor && index in current)
808
+ throw new Error("inherited array element");
809
+ write(descriptor?.value === undefined ? null : descriptor.value);
810
+ }
811
+ sink.write("]");
812
+ arrays.delete(current);
813
+ } else if (seen.has(current)) {
814
+ sink.write('"[Circular]"');
815
+ } else {
816
+ const prototype = Object.getPrototypeOf(current);
817
+ if (prototype !== Object.prototype && prototype !== null)
818
+ throw new Error("exotic");
819
+ seen.add(current);
820
+ const entries = Object.keys(current).map((key) => {
821
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
822
+ if (!descriptor || !("value" in descriptor))
823
+ throw new Error("accessor");
824
+ return [key, descriptor.value];
825
+ });
826
+ const sorted = Object.fromEntries(entries.sort(([a], [b]) => a.localeCompare(b)));
827
+ if (entries.length <= 16 && entries.every(([key, child]) => key.length <= 4096 && (child === null || child === undefined || typeof child === "number" || typeof child === "boolean" || typeof child === "string" && child.length <= 4096))) {
828
+ sink.write(JSON.stringify(sorted));
829
+ return;
830
+ }
831
+ sink.write("{");
832
+ let first = true;
833
+ for (const [key, child] of Object.entries(sorted)) {
834
+ if (child === undefined)
835
+ continue;
836
+ if (!first)
837
+ sink.write(",");
838
+ first = false;
839
+ sink.write(JSON.stringify(key));
840
+ sink.write(":");
841
+ write(child);
842
+ }
843
+ sink.write("}");
844
+ }
845
+ };
846
+ write(value);
847
+ return sink.digest();
848
+ } catch {
849
+ const failed = jsonHashSink("excluded\x00");
850
+ failed.write(fallback());
851
+ return failed.digest();
852
+ }
853
+ }
854
+
647
855
  // ../plugin/src/hooks/magic-context/image-token-estimate.ts
648
856
  var IMAGE_TOKEN_DIVISOR = 750;
649
857
  var IMAGE_FALLBACK_TOKENS = 1200;
@@ -681,6 +889,23 @@ function estimateImageTokensFromDataUrl(url) {
681
889
  }
682
890
  return IMAGE_FALLBACK_TOKENS;
683
891
  }
892
+ function estimateToolAttachmentImageTokens(state) {
893
+ if (!state || typeof state !== "object")
894
+ return 0;
895
+ const attachments = state.attachments;
896
+ if (!Array.isArray(attachments))
897
+ return 0;
898
+ let tokens = 0;
899
+ for (const attachment of attachments) {
900
+ if (!attachment || typeof attachment !== "object")
901
+ continue;
902
+ const { mime, url } = attachment;
903
+ if (typeof mime !== "string" || !mime.startsWith("image/"))
904
+ continue;
905
+ tokens += typeof url === "string" && url.startsWith("data:") ? estimateImageTokensFromDataUrl(url) : IMAGE_FALLBACK_TOKENS;
906
+ }
907
+ return tokens;
908
+ }
684
909
  function clampImageTokens(n) {
685
910
  if (n < 1)
686
911
  return 1;
@@ -832,6 +1057,13 @@ var KEPT_TOOL_STATE_FIELDS = new Set([
832
1057
  "content"
833
1058
  ]);
834
1059
  var KEPT_TOOL_STATE_TIME_FIELD = "compacted";
1060
+ function providerVisiblePart(part) {
1061
+ if (!isRecord2(part) || part.type !== "tool" || !isRecord2(part.state))
1062
+ return part;
1063
+ if (toolStateIsReduced(part.state))
1064
+ return part;
1065
+ return { ...part, state: providerVisibleToolState(part.state) };
1066
+ }
835
1067
  var KEPT_ERROR_METADATA_FIELDS = ["interrupted", "output"];
836
1068
  function providerVisibleToolState(state) {
837
1069
  const view = {};
@@ -874,20 +1106,16 @@ function toolStateIsReduced(state) {
874
1106
  }
875
1107
  return true;
876
1108
  }
877
- function providerVisiblePart(part) {
878
- if (!isRecord2(part) || part.type !== "tool" || !isRecord2(part.state))
879
- return part;
880
- if (toolStateIsReduced(part.state))
881
- return part;
882
- return { ...part, state: providerVisibleToolState(part.state) };
883
- }
884
1109
  function providerVisibleMessage(message) {
1110
+ return projectMessage(message, providerVisiblePart);
1111
+ }
1112
+ function projectMessage(message, projectPart) {
885
1113
  if (!isRecord2(message) || !Array.isArray(message.parts))
886
1114
  return message;
887
1115
  let parts;
888
1116
  for (let index = 0;index < message.parts.length; index += 1) {
889
1117
  const part = message.parts[index];
890
- const view = providerVisiblePart(part);
1118
+ const view = projectPart(part);
891
1119
  if (view !== part) {
892
1120
  parts ??= message.parts.slice(0, index);
893
1121
  parts.push(view);
@@ -1025,6 +1253,7 @@ function stripChannel1ReminderSpans(output) {
1025
1253
  }
1026
1254
  return stripped;
1027
1255
  }
1256
+ var partJsonMemo = new TailHygieneJsonMemo;
1028
1257
  function messageIdFromPartKey(key) {
1029
1258
  const separator = key.indexOf("\x00");
1030
1259
  return separator > 0 ? key.slice(0, separator) : key;
@@ -1321,9 +1550,6 @@ function formatOldestReclaimableHint(hint) {
1321
1550
  return rendered.length > 0 ? `
1322
1551
  oldest reclaimable: ${rendered}.` : "";
1323
1552
  }
1324
- function reclaimableToolOutputCount(parts) {
1325
- return parts.filter((part) => part.kind === "toolOutput" && part.uTokens > 0).length;
1326
- }
1327
1553
  function formatReclaimableOutputSummary(count, tokens) {
1328
1554
  const outputCount = Math.max(0, Math.floor(count));
1329
1555
  const outputs = outputCount === 0 ? "spent tool outputs" : `${outputCount} spent tool output${outputCount === 1 ? "" : "s"}`;
@@ -3141,4 +3367,4 @@ function deleteToolTagsByOwner(db, sessionId, ownerMsgId) {
3141
3367
  return getDeleteToolTagsByOwnerStatement(db).all(sessionId, ownerMsgId).length;
3142
3368
  }
3143
3369
 
3144
- export { UNKNOWN_FIT_RATIO, resolveDecisionCalibration, hasMeasuredDecisionCalibration, providerMass, localBudget, calibrationForModelKey, historyLocalBudget, adoptedProtectedToolsPolicy, protectedToolTagNumbers, protectedToolTokenCount, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isRecord, TEXT_TAG_IDENTITY_MARKER, PI_FALLBACK_PREFIXES_JSON, contentTagOwnerMessageId, estimateImageTokensFromDataUrl, providerVisiblePart, providerVisibleMessage, TODO_STATUSES, TODO_PRIORITIES, TITLE_DONE_STATUSES, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, compareMeasuredTailPrefix, formatTailHygienePrefixMismatch, freezeTailHygieneMeasurement, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, measureEmergencyTag, queuePendingOp, queuePendingDropForUnchangedTag, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, updateTagByteSize2, getRecentTagOwnerMessageIds2, getActiveTagTokenAggregate2, AGE_RECLAIM_MIN_TOKENS2, getOldestActiveUnprotectedToolTags2, getActiveToolTagsForAgeReclaim2, getTriggerTagTokenUpperBound2, getActiveTagTokenTotalsByMessage2, updateTagInputByteSize2, updateTagTokenCount2, getPersistedToolTagAccounting2, getAllStatusTagTokenTotalsFlat2, getReasoningTokenEstimatesByMessage2, tryGetReasoningTokenEstimatesByMessage2, getMaxTagNumberByOwnerMessage2, scanTagOwnerSummary2, scanTagOwnerDelta2, updateTagInputTokenCount2, tagTokenCountIsNull2, backfillTagTokenCounts2, insertTag2, updateTagStatus2, getInertWhitespaceAssistantTagsByNumbers2, updateTagDropMode2, updateCavemanDepth2, updateTagMessageId2, hasPiFallbackMessageTags2, findAdoptableFallbackTags2, adoptFallbackTagMessageId2, foldShrunkPartTags2, hasPiFallbackToolOwnerTags2, findPiFallbackToolOwnerTags2, PiTagIdentityConflictError2, getPiMessageTagCandidates2, findPiTagIdentityConflict2, adoptPiFallbackToolOwnerTag2, adoptPiFallbackMessageTag2, markTagsCompactedByMessageIds2, deleteTagsByMessageId2, getMaxTagNumberBySession2, getTagNumberByMessageId2, getAssignableTagNumberByMessageId2, getMinMessageTagNumberForRawId2, deriveTagLoadFloor2, TAG_SELECT_COLUMNS2, getTagsBySession2, getActiveTagsBySession2, getTagsForPendingOperations2, getTagsByNumbers2, getNewestToolTagNumbers2, getDroppedTagsByNumbers2, getMaxDroppedTagNumber2, getTagById2, getTopNBySize2, getToolTagNumberByOwner2, getNullOwnerToolTag2, adoptNullOwnerToolTag2, getCandidateToolOwners2, pickNearestPriorOwner2 };
3370
+ export { UNKNOWN_FIT_RATIO, resolveDecisionCalibration, hasMeasuredDecisionCalibration, providerMass, localBudget, calibrationForModelKey, historyLocalBudget, adoptedProtectedToolsPolicy, protectedToolTagNumbers, protectedToolTokenCount, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, rememberCurrentToolOutputCount, currentReclaimableToolOutputCount, isRecord, TEXT_TAG_IDENTITY_MARKER, PI_FALLBACK_PREFIXES_JSON, contentTagOwnerMessageId, TailHygieneJsonMemo, piJsonHash, estimateImageTokensFromDataUrl, estimateToolAttachmentImageTokens, providerVisiblePart, providerVisibleMessage, TODO_STATUSES, TODO_PRIORITIES, TITLE_DONE_STATUSES, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, compareMeasuredTailPrefix, formatTailHygienePrefixMismatch, freezeTailHygieneMeasurement, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, measureEmergencyTag, queuePendingOp, queuePendingDropForUnchangedTag, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, updateTagByteSize2, getRecentTagOwnerMessageIds2, getActiveTagTokenAggregate2, AGE_RECLAIM_MIN_TOKENS2, getOldestActiveUnprotectedToolTags2, getActiveToolTagsForAgeReclaim2, getTriggerTagTokenUpperBound2, getActiveTagTokenTotalsByMessage2, updateTagInputByteSize2, updateTagTokenCount2, getPersistedToolTagAccounting2, getAllStatusTagTokenTotalsFlat2, getReasoningTokenEstimatesByMessage2, tryGetReasoningTokenEstimatesByMessage2, getMaxTagNumberByOwnerMessage2, scanTagOwnerSummary2, scanTagOwnerDelta2, updateTagInputTokenCount2, tagTokenCountIsNull2, backfillTagTokenCounts2, insertTag2, updateTagStatus2, getInertWhitespaceAssistantTagsByNumbers2, updateTagDropMode2, updateCavemanDepth2, updateTagMessageId2, hasPiFallbackMessageTags2, findAdoptableFallbackTags2, adoptFallbackTagMessageId2, foldShrunkPartTags2, hasPiFallbackToolOwnerTags2, findPiFallbackToolOwnerTags2, PiTagIdentityConflictError2, getPiMessageTagCandidates2, findPiTagIdentityConflict2, adoptPiFallbackToolOwnerTag2, adoptPiFallbackMessageTag2, markTagsCompactedByMessageIds2, deleteTagsByMessageId2, getMaxTagNumberBySession2, getTagNumberByMessageId2, getAssignableTagNumberByMessageId2, getMinMessageTagNumberForRawId2, deriveTagLoadFloor2, TAG_SELECT_COLUMNS2, getTagsBySession2, getActiveTagsBySession2, getTagsForPendingOperations2, getTagsByNumbers2, getNewestToolTagNumbers2, getDroppedTagsByNumbers2, getMaxDroppedTagNumber2, getTagById2, getTopNBySize2, getToolTagNumberByOwner2, getNullOwnerToolTag2, adoptNullOwnerToolTag2, getCandidateToolOwners2, pickNearestPriorOwner2 };