@cortexkit/opencode-magic-context 0.49.52 → 0.49.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +3 -4
  3. package/dist/{context-bkkd7br4.js → context-vx5gw5h2.js} +117 -80
  4. package/dist/{embedding-backfill-3wdjzrvs.js → embedding-backfill-2dvf3rcn.js} +4 -4
  5. package/dist/embedding-worker.js +2 -2
  6. package/dist/features/magic-context/compartment-embedding.d.ts.map +1 -1
  7. package/dist/features/magic-context/message-fts-session-filter.d.ts +1 -1
  8. package/dist/features/magic-context/message-fts-session-filter.d.ts.map +1 -1
  9. package/dist/features/magic-context/project-embedding-registry.d.ts +8 -0
  10. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  11. package/dist/features/magic-context/search.d.ts.map +1 -1
  12. package/dist/features/magic-context/storage-host-instruction-retention.d.ts +10 -3
  13. package/dist/features/magic-context/storage-host-instruction-retention.d.ts.map +1 -1
  14. package/dist/features/magic-context/storage-meta-persisted.d.ts +19 -0
  15. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  16. package/dist/features/magic-context/storage-meta.d.ts +1 -1
  17. package/dist/features/magic-context/storage-meta.d.ts.map +1 -1
  18. package/dist/features/magic-context/storage.d.ts +1 -1
  19. package/dist/features/magic-context/storage.d.ts.map +1 -1
  20. package/dist/features/magic-context/transform-decision-log.d.ts +1 -1
  21. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  22. package/dist/hooks/magic-context/active-anthropic-turn.d.ts +6 -0
  23. package/dist/hooks/magic-context/active-anthropic-turn.d.ts.map +1 -1
  24. package/dist/hooks/magic-context/compaction-marker-manager.d.ts +2 -1
  25. package/dist/hooks/magic-context/compaction-marker-manager.d.ts.map +1 -1
  26. package/dist/hooks/magic-context/emergency-drop.d.ts +75 -2
  27. package/dist/hooks/magic-context/emergency-drop.d.ts.map +1 -1
  28. package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts +14 -0
  30. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
  31. package/dist/hooks/magic-context/heuristic-cleanup.d.ts +12 -0
  32. package/dist/hooks/magic-context/heuristic-cleanup.d.ts.map +1 -1
  33. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  34. package/dist/hooks/magic-context/host-served-rows.d.ts +12 -2
  35. package/dist/hooks/magic-context/host-served-rows.d.ts.map +1 -1
  36. package/dist/hooks/magic-context/inject-compartments.d.ts +10 -0
  37. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  38. package/dist/hooks/magic-context/latest-assistant-turn.d.ts +43 -0
  39. package/dist/hooks/magic-context/latest-assistant-turn.d.ts.map +1 -1
  40. package/dist/hooks/magic-context/latest-thinking-recovery.d.ts +102 -26
  41. package/dist/hooks/magic-context/latest-thinking-recovery.d.ts.map +1 -1
  42. package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts +18 -2
  43. package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts.map +1 -1
  44. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  45. package/dist/hooks/magic-context/pass-outcome.d.ts.map +1 -1
  46. package/dist/hooks/magic-context/pending-marker-rearm.d.ts +20 -0
  47. package/dist/hooks/magic-context/pending-marker-rearm.d.ts.map +1 -0
  48. package/dist/hooks/magic-context/priced-pass-sizing.d.ts +7 -0
  49. package/dist/hooks/magic-context/priced-pass-sizing.d.ts.map +1 -1
  50. package/dist/hooks/magic-context/routine-cleanup-decision.d.ts +11 -1
  51. package/dist/hooks/magic-context/routine-cleanup-decision.d.ts.map +1 -1
  52. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  53. package/dist/hooks/magic-context/served-check.d.ts +127 -0
  54. package/dist/hooks/magic-context/served-check.d.ts.map +1 -0
  55. package/dist/hooks/magic-context/signed-thinking-hold.d.ts +32 -4
  56. package/dist/hooks/magic-context/signed-thinking-hold.d.ts.map +1 -1
  57. package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
  58. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +35 -1
  59. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  60. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  61. package/dist/index-29ff546v.js +2747 -0
  62. package/dist/{index-8d7gkgjs.js → index-2vsd5064.js} +3 -3
  63. package/dist/{index-kaqs6h31.js → index-52x68mj4.js} +1 -1
  64. package/dist/{index-k2efzh9r.js → index-567xsm72.js} +7 -5
  65. package/dist/{index-q9m97m5g.js → index-5gqszjq9.js} +4 -4
  66. package/dist/{index-a4zmmhxs.js → index-5ptp2de1.js} +6 -8
  67. package/dist/{index-jjy5a5w0.js → index-6nqz8hsz.js} +16 -5
  68. package/dist/{index-a6aqpfp6.js → index-9mggb1nv.js} +403 -1
  69. package/dist/{index-kanfby7e.js → index-9n6mdfqy.js} +452 -442
  70. package/dist/{index-fxgaaptn.js → index-a3n2dczz.js} +8 -7
  71. package/dist/{index-g3j49m95.js → index-b6rdv8re.js} +1 -1
  72. package/dist/{index-qbda6a8k.js → index-by14cr73.js} +30 -19
  73. package/dist/{index-25tm250q.js → index-dhdv88e5.js} +1 -1
  74. package/dist/{index-4xpff2m1.js → index-eyr425dx.js} +820 -179
  75. package/dist/{index-x4h461yf.js → index-h62j8z2r.js} +1 -1
  76. package/dist/{index-xqhejxmd.js → index-pdh4tdcq.js} +1 -1
  77. package/dist/{index-9gs34125.js → index-sk6p6esd.js} +3777 -2544
  78. package/dist/{index-pb8ysnq2.js → index-sv5tn72j.js} +1 -1
  79. package/dist/{index-bamnjp2t.js → index-sx1sppd6.js} +11 -7
  80. package/dist/{index-x7jcqpy6.js → index-tx8nfw85.js} +539 -29
  81. package/dist/{index-42n4fhxy.js → index-xj5bap1r.js} +61 -54
  82. package/dist/{index-rbs27k1d.js → index-xstbytjn.js} +1 -1
  83. package/dist/{index-0jc25yjf.js → index-xvtjwhm6.js} +3 -3
  84. package/dist/{index-qtpkkzan.js → index-yamsmkmh.js} +4 -4
  85. package/dist/index.js +87 -68
  86. package/dist/{message-index-bounded-71b75npz.js → message-index-bounded-xav3h8qe.js} +5 -6
  87. package/dist/migration-worker.js +3 -4
  88. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  89. package/dist/plugin/messages-transform.d.ts +6 -0
  90. package/dist/plugin/messages-transform.d.ts.map +1 -1
  91. package/dist/{project-embedding-registry-5dwh5zfn.js → project-embedding-registry-f2azrq24.js} +5 -3
  92. package/dist/raw-ordinal-warmup-worker.js +4 -4
  93. package/dist/{read-session-chunk-bfv831yx.js → read-session-chunk-70aam2c1.js} +4 -5
  94. package/dist/{recomp-orchestrator-8gj1b7pz.js → recomp-orchestrator-wbm4kpq9.js} +15 -16
  95. package/dist/{render-b3zcz9x4.js → render-73vrt30h.js} +10 -11
  96. package/dist/{search-archive-dp9afcv1.js → search-archive-ew4c3bsw.js} +7 -8
  97. package/dist/{search-y3w590tn.js → search-jfwb4ms3.js} +14 -15
  98. package/dist/shared/test-open-files.d.ts +17 -0
  99. package/dist/shared/test-open-files.d.ts.map +1 -0
  100. package/dist/{storage-tags-kdb4qsyq.js → storage-tags-arnkn5t1.js} +4 -2
  101. package/dist/tools/ctx-expand/search-archive.d.ts.map +1 -1
  102. package/dist/{transform-postprocess-phase-8awze16a.js → transform-postprocess-phase-mt4dcbhd.js} +16 -17
  103. package/dist/v2/auto-search-worker.js +3 -3
  104. package/dist/v2/chunk-embedding-write-worker.js +3 -4
  105. package/dist/v2/{context-99v7x7fm.js → context-13er940g.js} +1147 -467
  106. package/dist/v2/{embedding-backfill-x1zpc04f.js → embedding-backfill-48qbnh7p.js} +4 -4
  107. package/dist/v2/embedding-worker.js +2 -2
  108. package/dist/v2/fold/instruction-supersession.d.ts.map +1 -1
  109. package/dist/v2/hooks/context.d.ts.map +1 -1
  110. package/dist/v2/{message-index-bounded-2pev910h.js → message-index-bounded-sw8hyqw1.js} +5 -6
  111. package/dist/v2/migration-worker.js +3 -4
  112. package/dist/v2/{project-embedding-registry-v2fxrs8b.js → project-embedding-registry-kwahtjgg.js} +5 -3
  113. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  114. package/dist/v2/{read-session-chunk-a454a4d2.js → read-session-chunk-nqkn0yb4.js} +4 -5
  115. package/dist/v2/{recomp-orchestrator-03fskpsa.js → recomp-orchestrator-cdkfynz4.js} +15 -16
  116. package/dist/v2/{render-cryx4xsj.js → render-a7j6fqbd.js} +10 -11
  117. package/dist/v2/{search-2qj4w7rw.js → search-8dc9ex0a.js} +13 -14
  118. package/dist/v2/{search-archive-xw2rsq81.js → search-archive-3a36887a.js} +7 -8
  119. package/dist/v2/{server-kreheyw5.js → server-0ayyh3mx.js} +5 -7
  120. package/dist/v2/{server-t8n27rbt.js → server-4x0xq8a1.js} +1 -1
  121. package/dist/v2/{server-kaqs6h31.js → server-52x68mj4.js} +1 -1
  122. package/dist/v2/{server-cpstyzvy.js → server-578pc4tf.js} +3 -3
  123. package/dist/v2/{server-sb55ddgn.js → server-5p0bjk3y.js} +1 -1
  124. package/dist/v2/{server-58h6rrnx.js → server-6k0rnwbd.js} +1 -1
  125. package/dist/v2/{server-y5cma2j1.js → server-79tbtk5w.js} +8 -7
  126. package/dist/v2/{server-b3h8vqa6.js → server-7rmf6a57.js} +538 -28
  127. package/dist/v2/{server-xjzx27w2.js → server-7waad75d.js} +29 -18
  128. package/dist/v2/{server-wq9y9a03.js → server-96g41nad.js} +61 -54
  129. package/dist/v2/{server-txdsx71h.js → server-avfc9ezb.js} +4 -4
  130. package/dist/v2/{server-ww7xbxxf.js → server-b0357as4.js} +357 -1
  131. package/dist/v2/{server-qsvm6w79.js → server-beydmd68.js} +3763 -2484
  132. package/dist/v2/server-gge95a03.js +2687 -0
  133. package/dist/v2/{server-kfw4m268.js → server-jwydbwcx.js} +1 -1
  134. package/dist/v2/{server-brsx45r6.js → server-kwtnrhv3.js} +1 -1
  135. package/dist/v2/{server-4h4acntc.js → server-rpmkz5ta.js} +11 -7
  136. package/dist/v2/{server-0ms13pc8.js → server-rz6g5xne.js} +16 -5
  137. package/dist/v2/{server-dkfs58nq.js → server-v817sf79.js} +1 -1
  138. package/dist/v2/{server-vjadwb3j.js → server-ycvqg2s3.js} +3 -3
  139. package/dist/v2/server.js +4 -4
  140. package/dist/v2/{storage-tags-rzv7y0n3.js → storage-tags-19da4c0m.js} +4 -2
  141. package/dist/v2/{v2-archive-reader-3575hw8s.js → v2-archive-reader-jm3d7ccj.js} +1 -1
  142. package/dist/v2/{wrapup-orchestrator-shzv6t4v.js → wrapup-orchestrator-xnqq81c4.js} +18 -18
  143. package/dist/{v2-archive-reader-75fdm0te.js → v2-archive-reader-9bbfh131.js} +1 -1
  144. package/dist/{wrapup-orchestrator-e0z7nvnx.js → wrapup-orchestrator-svhee0fn.js} +16 -17
  145. package/package.json +1 -1
  146. package/src/shared/escalation-bands.test.ts +16 -1
  147. package/src/shared/sqlite-placeholders.test.ts +103 -0
  148. package/src/shared/storage-file-mutex-review.test.ts +5 -7
  149. package/src/shared/test-open-files.test.ts +194 -0
  150. package/src/shared/test-open-files.ts +71 -0
  151. package/dist/index-bkg4hdyh.js +0 -3865
  152. package/dist/index-d9vfe7xq.js +0 -16
  153. package/dist/index-hsv31e69.js +0 -405
  154. package/dist/v2/server-d9vfe7xq.js +0 -16
  155. package/dist/v2/server-kgq2e2hh.js +0 -361
  156. package/dist/v2/server-rcchadw0.js +0 -3865
@@ -1,3865 +0,0 @@
1
- import {
2
- hasMeasuredDecisionCalibration,
3
- providerMass
4
- } from "./index-1zx87sdm.js";
5
- import {
6
- estimateTokens
7
- } from "./index-0tz2fzpq.js";
8
- import {
9
- getHarness2
10
- } from "./index-pavzsdc6.js";
11
- import {
12
- sessionLog2
13
- } from "./index-82dfe8en.js";
14
- import {
15
- getTagIdentityWriteGeneration2,
16
- getSqliteDatabasePath2
17
- } from "./index-gzy5w8ya.js";
18
- import {
19
- tagIdentityRevisionKey,
20
- tagOrderConstraintIndex,
21
- stableStringify,
22
- stableStringifyHash
23
- } from "./index-a6aqpfp6.js";
24
- import {
25
- DEFAULT_PROTECTED_TOOLS,
26
- normalizeProtectedToolName,
27
- mergeProtectedTools
28
- } from "./index-d9vfe7xq.js";
29
-
30
- // src/shared/record-type-guard.ts
31
- function isRecord(value) {
32
- return typeof value === "object" && value !== null && !Array.isArray(value);
33
- }
34
-
35
- // src/features/magic-context/storage-tags.ts
36
- import { isMainThread } from "node:worker_threads";
37
-
38
- // src/features/magic-context/reclaim-protection.ts
39
- var CTX_REDUCE_KEEP = DEFAULT_PROTECTED_TOOLS.ctx_reduce;
40
- function adoptedProtectedToolsPolicy(current, previous, rebuilding, hasBaseline) {
41
- if (rebuilding || !hasBaseline)
42
- return mergeProtectedTools(current);
43
- return { ...previous ?? { todowrite: 0, ctx_reduce: 3 } };
44
- }
45
- function protectedToolTagNumbers(tags, protectedTools) {
46
- const counts = mergeProtectedTools(protectedTools);
47
- const protectedTags = new Set;
48
- for (const tag of [...tags].sort((left, right) => right.tagNumber - left.tagNumber)) {
49
- if (tag.status !== undefined && tag.status !== "active")
50
- continue;
51
- if (tag.type !== undefined && tag.type !== "tool")
52
- continue;
53
- const name = normalizeProtectedToolName(tag.toolName);
54
- if (!Object.hasOwn(counts, name) || counts[name] <= 0)
55
- continue;
56
- protectedTags.add(tag.tagNumber);
57
- counts[name] -= 1;
58
- }
59
- return protectedTags;
60
- }
61
- function protectedToolTokenCount(tags, counts, calibration) {
62
- const protectedTags = protectedToolTagNumbers(tags, counts);
63
- const tokens = tags.reduce((sum, tag) => sum + (protectedTags.has(tag.tagNumber) ? tag.tokenCount ?? 0 : 0), 0);
64
- return calibration && hasMeasuredDecisionCalibration(calibration) ? providerMass({ tools: tokens }, calibration) : 0;
65
- }
66
-
67
- // src/hooks/magic-context/tag-content-primitives.ts
68
- var encoder = new TextEncoder;
69
- var TAG_PREFIX_REGEX = /^(?:§\d+§\s*)+/;
70
- var MALFORMED_TAG_PREFIX_REGEX = /^(?:§\d+">§(?:\d+§)?\s*)+/;
71
- var DANGLING_TAG_GLOBAL_REGEX = /\u00a7\d+(?!\d)(?!\.\d)[^\s\u00a7\w.]?/g;
72
- var DANGLING_TAG_PREFIX_REGEX = /^(?:\u00a7\d+(?!\d)(?!\.\d)[^\s\u00a7\w.]?\s*)+/;
73
- var COMPLETE_TAG_PAIR_GLOBAL_REGEX = /\u00a7\d+\u00a7/g;
74
- var MALFORMED_TAG_GLOBAL_REGEX = /\u00a7\d+">(?:\u00a7(?:\d+\u00a7)?)?/g;
75
- var STRAY_SECTION_CHAR_REGEX = /\u00a7/g;
76
- function stripWellFormedLeadingTagPrefix(value) {
77
- return value.replace(/^(\u00a7\d+\u00a7\s*)+/, "");
78
- }
79
- function stripCompleteTagPairsGlobally(value) {
80
- return value.replace(COMPLETE_TAG_PAIR_GLOBAL_REGEX, "");
81
- }
82
- function stripMalformedTagNotationGlobally(value) {
83
- return value.replace(MALFORMED_TAG_GLOBAL_REGEX, "");
84
- }
85
- function stripDanglingTagNotationGlobally(value) {
86
- return value.replace(DANGLING_TAG_GLOBAL_REGEX, "");
87
- }
88
- function stripTagSectionCharacters(value) {
89
- return value.replace(STRAY_SECTION_CHAR_REGEX, "");
90
- }
91
- function stripPersistedAssistantText(value, acceptsEmpty = true) {
92
- if (!acceptsEmpty && !value.includes("§") && !value.trim())
93
- return value;
94
- let text = stripWellFormedLeadingTagPrefix(value);
95
- text = stripCompleteTagPairsGlobally(text);
96
- text = stripMalformedTagNotationGlobally(text);
97
- text = stripDanglingTagNotationGlobally(text);
98
- text = stripTagSectionCharacters(text);
99
- const stripped = text.trim();
100
- return !acceptsEmpty && value.trim().length > 0 && stripped.length === 0 ? value : stripped;
101
- }
102
- function byteSize(value) {
103
- return encoder.encode(value).length;
104
- }
105
- function stripTagPrefix(value) {
106
- let stripped = value;
107
- for (let pass = 0;pass < 8; pass++) {
108
- const prev = stripped;
109
- stripped = stripped.replace(MALFORMED_TAG_PREFIX_REGEX, "");
110
- stripped = stripped.replace(TAG_PREFIX_REGEX, "");
111
- stripped = stripped.replace(DANGLING_TAG_PREFIX_REGEX, "");
112
- if (stripped === prev)
113
- break;
114
- }
115
- return stripped;
116
- }
117
- function peelLeadingMcTagNotation(value) {
118
- const body = stripTagPrefix(value);
119
- if (body === value)
120
- return { tagPrefix: "", body };
121
- return { tagPrefix: value.slice(0, value.length - body.length), body };
122
- }
123
- function prependTag(tagId, value) {
124
- const stripped = stripTagPrefix(value);
125
- return `§${tagId}§ ${stripped}`;
126
- }
127
- function isThinkingPart(part) {
128
- if (part === null || typeof part !== "object")
129
- return false;
130
- const candidate = part;
131
- return candidate.type === "thinking" || candidate.type === "reasoning";
132
- }
133
-
134
- // src/hooks/magic-context/tail-hygiene-output-count.ts
135
- var CURRENT_OUTPUT_COUNT = Symbol.for("magic-context.current-reclaimable-tool-output-count");
136
- function countReclaimableToolOutputs(parts) {
137
- return parts.filter((part) => part.kind === "toolOutput" && part.uTokens > 0).length;
138
- }
139
- function rememberCurrentToolOutputCount(baseline, measurement) {
140
- return Object.assign(baseline, {
141
- [CURRENT_OUTPUT_COUNT]: countReclaimableToolOutputs(measurement.parts)
142
- });
143
- }
144
- function currentReclaimableToolOutputCount(baseline) {
145
- if (!baseline || !Object.hasOwn(baseline, CURRENT_OUTPUT_COUNT))
146
- return 0;
147
- return baseline[CURRENT_OUTPUT_COUNT];
148
- }
149
-
150
- // src/shared/tag-owner-id.ts
151
- var TEXT_TAG_IDENTITY_MARKER = ":mc-text-v1:";
152
- var PI_FALLBACK_PREFIXES_JSON = JSON.stringify([..."pi-msg-"].reduce((prefixes, char) => prefixes.flatMap((prefix) => /[a-z]/.test(char) ? [prefix + char, prefix + char.toUpperCase()] : [prefix + char]), [""]));
153
- var POSITIONAL_CONTENT_SUFFIX = /:(?:p|file)\d+$/;
154
- var CONTENT_DERIVED_TEXT_SUFFIX = /:mc-text-v1:[0-9a-f]+:[0-9a-f]+:o\d+$/;
155
- function contentTagOwnerMessageId(contentId) {
156
- const positional = POSITIONAL_CONTENT_SUFFIX.exec(contentId);
157
- if (positional)
158
- return contentId.slice(0, positional.index);
159
- const derived = CONTENT_DERIVED_TEXT_SUFFIX.exec(contentId);
160
- if (derived)
161
- return contentId.slice(0, derived.index);
162
- return contentId;
163
- }
164
-
165
- // src/shared/tail-hygiene-json.ts
166
- var MAX_MEMO_BYTES = 64 * 1024 * 1024;
167
- var MAX_MEMO_ENTRIES = 1e4;
168
-
169
- class TailHygieneJsonMemo {
170
- entries = new Map;
171
- bytes = 0;
172
- passText = new WeakMap;
173
- passHash = new WeakMap;
174
- beginPass() {
175
- this.passText = new WeakMap;
176
- this.passHash = new WeakMap;
177
- }
178
- get(key, value, compute, fingerprint = false) {
179
- const pass = fingerprint ? this.passHash : this.passText;
180
- const object = value !== null && typeof value === "object" ? value : undefined;
181
- const local = object ? pass.get(object) : undefined;
182
- if (local !== undefined)
183
- return local;
184
- const previous = this.entries.get(key);
185
- if (previous && sameJson(previous.snapshot, value)) {
186
- if (object)
187
- pass.set(object, previous.result);
188
- return previous.result;
189
- }
190
- const result = compute();
191
- if (previous) {
192
- this.bytes -= previous.bytes;
193
- this.entries.delete(key);
194
- }
195
- try {
196
- const copy = copyJson(value);
197
- const bytes = copy.bytes + (key.length + result.length) * 2;
198
- if (bytes <= MAX_MEMO_BYTES) {
199
- this.entries.set(key, { snapshot: copy.value, result, bytes });
200
- this.bytes += bytes;
201
- if (object)
202
- pass.set(object, result);
203
- }
204
- } catch {}
205
- while (this.bytes > MAX_MEMO_BYTES || this.entries.size > MAX_MEMO_ENTRIES) {
206
- const oldest = this.entries.entries().next().value;
207
- if (!oldest)
208
- break;
209
- this.bytes -= oldest[1].bytes;
210
- this.entries.delete(oldest[0]);
211
- }
212
- return result;
213
- }
214
- }
215
- function copyJson(value) {
216
- const seen = new Map;
217
- let bytes = 0;
218
- const copy = (current) => {
219
- bytes += 16;
220
- if (typeof current === "string")
221
- bytes += current.length * 2;
222
- if (bytes > MAX_MEMO_BYTES)
223
- throw new Error("memo capacity");
224
- if (current === null || typeof current !== "object") {
225
- if (["function", "symbol", "bigint"].includes(typeof current))
226
- throw new Error("exotic");
227
- return current;
228
- }
229
- if (seen.has(current))
230
- return seen.get(current);
231
- const prototype = Object.getPrototypeOf(current);
232
- if (!Array.isArray(current) && prototype !== Object.prototype && prototype !== null)
233
- throw new Error("exotic");
234
- const result = Array.isArray(current) ? new Array(current.length) : Object.create(prototype);
235
- seen.set(current, result);
236
- for (const key of Object.keys(current)) {
237
- const descriptor = Object.getOwnPropertyDescriptor(current, key);
238
- if (!descriptor || !("value" in descriptor))
239
- throw new Error("accessor");
240
- bytes += key.length * 2 + 16;
241
- if (key === "__proto__") {
242
- Object.defineProperty(result, key, {
243
- value: copy(descriptor.value),
244
- enumerable: true,
245
- writable: true,
246
- configurable: true
247
- });
248
- } else
249
- result[key] = copy(descriptor.value);
250
- }
251
- return result;
252
- };
253
- return { value: copy(value), bytes };
254
- }
255
- function sameJson(before, after) {
256
- const forward = new Map;
257
- const reverse = new Set;
258
- const same = (left, right) => {
259
- if (left === null || right === null || typeof left !== "object" || typeof right !== "object")
260
- return Object.is(left, right);
261
- if (forward.has(left))
262
- return forward.get(left) === right;
263
- if (reverse.has(right) || Object.getPrototypeOf(left) !== Object.getPrototypeOf(right))
264
- return false;
265
- forward.set(left, right);
266
- reverse.add(right);
267
- if (Array.isArray(left) && (!Array.isArray(right) || left.length !== right.length))
268
- return false;
269
- const keys = Object.keys(left);
270
- const otherKeys = Object.keys(right);
271
- if (keys.length !== otherKeys.length)
272
- return false;
273
- for (let index = 0;index < keys.length; index++) {
274
- const key = keys[index];
275
- if (key !== otherKeys[index])
276
- return false;
277
- const descriptor = Object.getOwnPropertyDescriptor(right, key);
278
- if (!descriptor || !("value" in descriptor) || !same(left[key], descriptor.value))
279
- return false;
280
- }
281
- return true;
282
- };
283
- return same(before, after);
284
- }
285
-
286
- // src/hooks/magic-context/image-token-estimate.ts
287
- var IMAGE_TOKEN_DIVISOR = 750;
288
- var IMAGE_FALLBACK_TOKENS = 1200;
289
- var IMAGE_TOKEN_CAP = 4500;
290
- function estimateImageTokensFromDataUrl(url) {
291
- const comma = url.indexOf(",");
292
- if (comma < 0)
293
- return IMAGE_FALLBACK_TOKENS;
294
- const header = url.slice(0, comma);
295
- const payload = url.slice(comma + 1);
296
- const sliceLen = Math.min(512, payload.length);
297
- const preview = payload.slice(0, sliceLen);
298
- let bytes;
299
- try {
300
- bytes = base64Decode(preview);
301
- } catch {
302
- return IMAGE_FALLBACK_TOKENS;
303
- }
304
- if (header.includes("image/png")) {
305
- const dims = parsePngDimensions(bytes);
306
- if (dims)
307
- return clampImageTokens(Math.ceil(dims.w * dims.h / IMAGE_TOKEN_DIVISOR));
308
- } else if (header.includes("image/jpeg") || header.includes("image/jpg")) {
309
- const dims = parseJpegDimensions(createBase64ByteReader(payload, bytes));
310
- if (dims)
311
- return clampImageTokens(Math.ceil(dims.w * dims.h / IMAGE_TOKEN_DIVISOR));
312
- } else if (header.includes("image/webp")) {
313
- const dims = parseWebpDimensions(bytes);
314
- if (dims)
315
- return clampImageTokens(Math.ceil(dims.w * dims.h / IMAGE_TOKEN_DIVISOR));
316
- } else if (header.includes("image/gif")) {
317
- const dims = parseGifDimensions(bytes);
318
- if (dims)
319
- return clampImageTokens(Math.ceil(dims.w * dims.h / IMAGE_TOKEN_DIVISOR));
320
- }
321
- return IMAGE_FALLBACK_TOKENS;
322
- }
323
- function estimateToolAttachmentImageTokens(state) {
324
- if (!state || typeof state !== "object")
325
- return 0;
326
- const attachments = state.attachments;
327
- if (!Array.isArray(attachments))
328
- return 0;
329
- let tokens = 0;
330
- for (const attachment of attachments) {
331
- if (!attachment || typeof attachment !== "object")
332
- continue;
333
- const { mime, url } = attachment;
334
- if (typeof mime !== "string" || !mime.startsWith("image/"))
335
- continue;
336
- tokens += typeof url === "string" && url.startsWith("data:") ? estimateImageTokensFromDataUrl(url) : IMAGE_FALLBACK_TOKENS;
337
- }
338
- return tokens;
339
- }
340
- function clampImageTokens(n) {
341
- if (n < 1)
342
- return 1;
343
- if (n > IMAGE_TOKEN_CAP)
344
- return IMAGE_TOKEN_CAP;
345
- return n;
346
- }
347
- function base64Decode(b64) {
348
- const pad = b64.length % 4;
349
- const padded = pad === 0 ? b64 : b64 + "=".repeat(4 - pad);
350
- const binary = atob(padded);
351
- const out = new Uint8Array(binary.length);
352
- for (let i = 0;i < binary.length; i++)
353
- out[i] = binary.charCodeAt(i);
354
- return out;
355
- }
356
- function parsePngDimensions(b) {
357
- if (b.length < 24)
358
- return null;
359
- if (b[0] !== 137 || b[1] !== 80 || b[2] !== 78 || b[3] !== 71 || b[4] !== 13 || b[5] !== 10 || b[6] !== 26 || b[7] !== 10)
360
- return null;
361
- const w = readUint32BE(b, 16);
362
- const h = readUint32BE(b, 20);
363
- if (!w || !h)
364
- return null;
365
- return { w, h };
366
- }
367
- var READER_PREVIEW_CHARS = 512;
368
- var READER_PREVIEW_BYTES = 384;
369
- var READER_WINDOW_CHARS = 4096;
370
- var READER_WINDOW_BYTES = 3072;
371
- function createBase64ByteReader(payload, preview) {
372
- const windows = new Map;
373
- return (offset) => {
374
- if (offset < READER_PREVIEW_BYTES)
375
- return preview[offset];
376
- const index = Math.floor((offset - READER_PREVIEW_BYTES) / READER_WINDOW_BYTES);
377
- let window = windows.get(index);
378
- if (window === undefined) {
379
- const start = READER_PREVIEW_CHARS + index * READER_WINDOW_CHARS;
380
- const chars = payload.slice(start, start + READER_WINDOW_CHARS);
381
- try {
382
- window = chars.length > 0 ? base64Decode(chars) : null;
383
- } catch {
384
- window = null;
385
- }
386
- windows.set(index, window);
387
- }
388
- return window?.[offset - READER_PREVIEW_BYTES - index * READER_WINDOW_BYTES];
389
- };
390
- }
391
- var JPEG_SCAN_LIMIT_BYTES = 256 * 1024;
392
- function parseJpegDimensions(byteAt) {
393
- if (byteAt(0) !== 255 || byteAt(1) !== 216 || byteAt(3) === undefined)
394
- return null;
395
- let i = 2;
396
- while (i < JPEG_SCAN_LIMIT_BYTES && byteAt(i + 8) !== undefined) {
397
- if (byteAt(i) !== 255) {
398
- i++;
399
- continue;
400
- }
401
- const marker = byteAt(i + 1);
402
- if (marker === undefined)
403
- break;
404
- if (isSofMarker(marker)) {
405
- const h = byteAt(i + 5) << 8 | byteAt(i + 6);
406
- const w = byteAt(i + 7) << 8 | byteAt(i + 8);
407
- if (w && h)
408
- return { w, h };
409
- return null;
410
- }
411
- if (marker === 216 || marker === 217 || marker === 1) {
412
- i += 2;
413
- continue;
414
- }
415
- const segLen = byteAt(i + 2) << 8 | byteAt(i + 3);
416
- if (segLen < 2)
417
- return null;
418
- i += 2 + segLen;
419
- }
420
- return null;
421
- }
422
- function isSofMarker(m) {
423
- if (m >= 192 && m <= 195)
424
- return true;
425
- if (m >= 197 && m <= 199)
426
- return true;
427
- if (m >= 201 && m <= 203)
428
- return true;
429
- if (m >= 205 && m <= 207)
430
- return true;
431
- return false;
432
- }
433
- function parseWebpDimensions(b) {
434
- if (b.length < 30)
435
- return null;
436
- if (b[0] !== 82 || b[1] !== 73 || b[2] !== 70 || b[3] !== 70)
437
- return null;
438
- if (b[8] !== 87 || b[9] !== 69 || b[10] !== 66 || b[11] !== 80)
439
- return null;
440
- const variant = String.fromCharCode(b[12], b[13], b[14], b[15]);
441
- if (variant === "VP8 ") {
442
- const w = (b[26] | b[27] << 8) & 16383;
443
- const h = (b[28] | b[29] << 8) & 16383;
444
- if (w && h)
445
- return { w, h };
446
- } else if (variant === "VP8L") {
447
- const b0 = b[21];
448
- const b1 = b[22];
449
- const b2 = b[23];
450
- const b3 = b[24];
451
- const w = 1 + ((b0 | b1 << 8) & 16383);
452
- const h = 1 + ((b1 >> 6 | b2 << 2 | b3 << 10) & 16383);
453
- if (w && h)
454
- return { w, h };
455
- } else if (variant === "VP8X") {
456
- const w = 1 + (b[24] | b[25] << 8 | b[26] << 16);
457
- const h = 1 + (b[27] | b[28] << 8 | b[29] << 16);
458
- if (w && h)
459
- return { w, h };
460
- }
461
- return null;
462
- }
463
- function parseGifDimensions(b) {
464
- if (b.length < 10)
465
- return null;
466
- if (b[0] !== 71 || b[1] !== 73 || b[2] !== 70)
467
- return null;
468
- const w = b[6] | b[7] << 8;
469
- const h = b[8] | b[9] << 8;
470
- if (!w || !h)
471
- return null;
472
- return { w, h };
473
- }
474
- function readUint32BE(b, offset) {
475
- return (b[offset] << 24 | b[offset + 1] << 16 | b[offset + 2] << 8 | b[offset + 3]) >>> 0;
476
- }
477
-
478
- // src/hooks/magic-context/provider-visible-parts.ts
479
- function isRecord2(value) {
480
- return value !== null && typeof value === "object" && !Array.isArray(value);
481
- }
482
- var KEPT_TOOL_STATE_FIELDS = new Set([
483
- "status",
484
- "input",
485
- "output",
486
- "error",
487
- "attachments",
488
- "content"
489
- ]);
490
- var KEPT_TOOL_STATE_TIME_FIELD = "compacted";
491
- function tailProviderVisibleToolState(state, openCode1) {
492
- const view = {};
493
- for (const key of Object.keys(state)) {
494
- if (tailToolStateFieldIsKept(key, openCode1)) {
495
- view[key] = state[key];
496
- } else if (key === "time" && openCode1) {
497
- const value = state.time;
498
- if (isRecord2(value)) {
499
- view.time = value[KEPT_TOOL_STATE_TIME_FIELD] === undefined ? {} : { [KEPT_TOOL_STATE_TIME_FIELD]: value[KEPT_TOOL_STATE_TIME_FIELD] };
500
- }
501
- } else if (key === "metadata" && openCode1 && state.status === "error") {
502
- const metadata = state.metadata;
503
- if (isRecord2(metadata) && metadata.interrupted === true) {
504
- const output = metadata.output;
505
- if (typeof output === "string")
506
- view.metadata = { interrupted: true, output };
507
- }
508
- }
509
- }
510
- return view;
511
- }
512
- function tailToolStateFieldIsKept(key, openCode1) {
513
- return KEPT_TOOL_STATE_FIELDS.has(key) && (key !== "content" || !openCode1);
514
- }
515
- function tailToolStateIsReduced(state, openCode1) {
516
- for (const key of Object.keys(state)) {
517
- if (tailToolStateFieldIsKept(key, openCode1))
518
- continue;
519
- return false;
520
- }
521
- return true;
522
- }
523
- function providerVisiblePart(part) {
524
- if (!isRecord2(part) || part.type !== "tool" || !isRecord2(part.state))
525
- return part;
526
- if (toolStateIsReduced(part.state))
527
- return part;
528
- return { ...part, state: providerVisibleToolState(part.state) };
529
- }
530
- function providerVisiblePartForTailHygiene(part) {
531
- return providerVisiblePartForHost(part, true);
532
- }
533
- function providerVisiblePartForOpenCode2(part) {
534
- return providerVisiblePartForHost(part, false);
535
- }
536
- function providerVisiblePartForHost(part, openCode1) {
537
- if (!isRecord2(part))
538
- return part;
539
- if (part.type !== "tool") {
540
- if (!Object.hasOwn(part, "state"))
541
- return part;
542
- const view = {};
543
- for (const key of Object.keys(part)) {
544
- if (key !== "state")
545
- view[key] = part[key];
546
- }
547
- return view;
548
- }
549
- if (!isRecord2(part.state))
550
- return part;
551
- if (tailToolStateIsReduced(part.state, openCode1))
552
- return part;
553
- return { ...part, state: tailProviderVisibleToolState(part.state, openCode1) };
554
- }
555
- var KEPT_ERROR_METADATA_FIELDS = ["interrupted", "output"];
556
- function providerVisibleToolState(state) {
557
- const view = {};
558
- for (const key of Object.keys(state)) {
559
- const value = state[key];
560
- if (KEPT_TOOL_STATE_FIELDS.has(key)) {
561
- view[key] = value;
562
- } else if (key === "time" && isRecord2(value)) {
563
- view.time = value[KEPT_TOOL_STATE_TIME_FIELD] === undefined ? {} : { [KEPT_TOOL_STATE_TIME_FIELD]: value[KEPT_TOOL_STATE_TIME_FIELD] };
564
- } else if (key === "metadata" && state.status === "error" && isRecord2(value)) {
565
- const kept = {};
566
- for (const field of KEPT_ERROR_METADATA_FIELDS) {
567
- if (Object.hasOwn(value, field))
568
- kept[field] = value[field];
569
- }
570
- view.metadata = kept;
571
- }
572
- }
573
- return view;
574
- }
575
- function toolStateIsReduced(state) {
576
- for (const key of Object.keys(state)) {
577
- if (KEPT_TOOL_STATE_FIELDS.has(key))
578
- continue;
579
- const value = state[key];
580
- if (key === "time" && isRecord2(value)) {
581
- const keys = Object.keys(value);
582
- if (keys.length === 0)
583
- continue;
584
- if (keys.length === 1 && keys[0] === KEPT_TOOL_STATE_TIME_FIELD)
585
- continue;
586
- return false;
587
- }
588
- if (key === "metadata" && state.status === "error" && isRecord2(value)) {
589
- const extra = Object.keys(value).some((field) => !KEPT_ERROR_METADATA_FIELDS.includes(field));
590
- if (!extra)
591
- continue;
592
- }
593
- return false;
594
- }
595
- return true;
596
- }
597
- function providerVisibleMessage(message) {
598
- return projectMessage(message, providerVisiblePart);
599
- }
600
- function providerVisibleMessageForTailHygiene(message) {
601
- return projectMessage(message, providerVisiblePartForTailHygiene);
602
- }
603
- function providerVisibleMessageForOpenCode2(message) {
604
- return projectMessage(message, providerVisiblePartForOpenCode2);
605
- }
606
- function projectMessage(message, projectPart) {
607
- if (!isRecord2(message) || !Array.isArray(message.parts))
608
- return message;
609
- let parts;
610
- for (let index = 0;index < message.parts.length; index += 1) {
611
- const part = message.parts[index];
612
- const view = projectPart(part);
613
- if (view !== part) {
614
- parts ??= message.parts.slice(0, index);
615
- parts.push(view);
616
- } else if (parts) {
617
- parts.push(part);
618
- }
619
- }
620
- return parts ? { ...message, parts } : message;
621
- }
622
-
623
- // src/hooks/magic-context/todo-view.ts
624
- import { createHash } from "node:crypto";
625
- var TODO_STATUS_COMPLETED = "completed";
626
- var TODO_STATUS_CANCELLED = "cancelled";
627
- var TODO_PRIORITY_MEDIUM = "medium";
628
- var TERMINAL_STATUSES = new Set([
629
- TODO_STATUS_COMPLETED,
630
- TODO_STATUS_CANCELLED
631
- ]);
632
- var TITLE_DONE_STATUSES = new Set([TODO_STATUS_COMPLETED]);
633
- var SYNTHETIC_CALL_ID_PREFIX = "mc_synthetic_todo_";
634
- var CLEARED_TODO_STATE_JSON = "[]";
635
- function normalizeTodoStateJson(todos) {
636
- if (!Array.isArray(todos))
637
- return null;
638
- const normalized = [];
639
- for (const todo of todos) {
640
- if (!isTodoItem(todo))
641
- return null;
642
- normalized.push({
643
- content: todo.content,
644
- status: todo.status,
645
- priority: todo.priority ?? TODO_PRIORITY_MEDIUM
646
- });
647
- }
648
- return JSON.stringify(normalized);
649
- }
650
- function buildSyntheticTodoPart(stateJson) {
651
- const todos = parseTodoState(stateJson);
652
- if (todos === null || todos.length === 0)
653
- return null;
654
- if (todos.every((t) => TERMINAL_STATUSES.has(t.status)))
655
- return null;
656
- const callID = computeSyntheticCallId(stateJson);
657
- const activeCount = todos.filter((t) => !TITLE_DONE_STATUSES.has(t.status)).length;
658
- const output = JSON.stringify(todos, null, 2);
659
- const ts = 0;
660
- return {
661
- type: "tool",
662
- callID,
663
- tool: "todowrite",
664
- state: {
665
- status: "completed",
666
- input: { todos },
667
- output,
668
- title: `${activeCount} todos`,
669
- metadata: { todos, truncated: false },
670
- time: { start: ts, end: ts }
671
- },
672
- syntheticTodoMarker: true
673
- };
674
- }
675
- function computeSyntheticCallId(stateJson) {
676
- const hash = createHash("sha256").update(stateJson).digest("hex").slice(0, 16);
677
- return `${SYNTHETIC_CALL_ID_PREFIX}${hash}`;
678
- }
679
- function isSyntheticTodoPart(part) {
680
- if (part === null || typeof part !== "object")
681
- return false;
682
- const p = part;
683
- if (p.syntheticTodoMarker === true)
684
- return true;
685
- return p.type === "tool" && p.tool === "todowrite" && typeof p.callID === "string" && p.callID.startsWith(SYNTHETIC_CALL_ID_PREFIX);
686
- }
687
- function parseTodoState(stateJson) {
688
- if (stateJson.length === 0)
689
- return null;
690
- try {
691
- const parsed = JSON.parse(stateJson);
692
- if (!Array.isArray(parsed))
693
- return null;
694
- const result = [];
695
- for (const item of parsed) {
696
- if (!isTodoItem(item))
697
- return null;
698
- result.push({
699
- content: item.content,
700
- status: item.status,
701
- priority: item.priority ?? TODO_PRIORITY_MEDIUM
702
- });
703
- }
704
- return result;
705
- } catch {
706
- return null;
707
- }
708
- }
709
- function isTodoItem(value) {
710
- if (value === null || typeof value !== "object")
711
- return false;
712
- const todo = value;
713
- return typeof todo.content === "string" && typeof todo.status === "string" && todo.status.length > 0 && (todo.priority === undefined || typeof todo.priority === "string");
714
- }
715
-
716
- // src/hooks/magic-context/tail-hygiene-walk.ts
717
- var MAX_CONTENT_MEMO_ENTRIES = 1e5;
718
- var MAX_CONTENT_MEMO_BYTES = 256 * 1024 * 1024;
719
- var contentMemo = new Map;
720
- var contentMemoOrder = new Set;
721
- var contentMemoBytes = 0;
722
- var FNV1A_32_OFFSET = 2166136261;
723
- var FNV1A_32_PRIME = 16777619;
724
- var TAG_PREFIX = /^§\d+§\s*/;
725
- var DROP_PREFIXES = ["[dropped", "[truncated"];
726
- var CHANNEL1_REMINDER_OPEN = `
727
-
728
- <system-reminder>
729
- `;
730
- var CHANNEL1_REMINDER_CLOSE = `
731
- </system-reminder>`;
732
- var TODO_HEAD_ANCHOR_ID = "__magic_context_todo_head__";
733
- function fnv1a32(value) {
734
- let hash = FNV1A_32_OFFSET;
735
- for (let index = 0;index < value.length; index += 1) {
736
- hash ^= value.charCodeAt(index);
737
- hash = Math.imul(hash, FNV1A_32_PRIME) >>> 0;
738
- }
739
- return hash.toString(16).padStart(8, "0");
740
- }
741
- function memoizedContent(kind, content) {
742
- let byContent = contentMemo.get(kind);
743
- if (!byContent) {
744
- byContent = new Map;
745
- contentMemo.set(kind, byContent);
746
- }
747
- const cached = byContent.get(content);
748
- if (cached)
749
- return cached;
750
- let hash = FNV1A_32_OFFSET;
751
- for (const segment of [kind, "\x00", content]) {
752
- for (let index = 0;index < segment.length; index += 1) {
753
- hash ^= segment.charCodeAt(index);
754
- hash = Math.imul(hash, FNV1A_32_PRIME) >>> 0;
755
- }
756
- }
757
- const measured = {
758
- hash: hash.toString(16).padStart(8, "0"),
759
- tokens: kind === "excluded" ? 0 : undefined,
760
- keyBytes: (kind.length + 1 + content.length) * 2 + 32,
761
- kind,
762
- content
763
- };
764
- byContent.set(content, measured);
765
- contentMemoOrder.add(measured);
766
- contentMemoBytes += measured.keyBytes;
767
- while (contentMemoOrder.size > MAX_CONTENT_MEMO_ENTRIES || contentMemoBytes > MAX_CONTENT_MEMO_BYTES) {
768
- const oldest = contentMemoOrder.values().next().value;
769
- if (!oldest)
770
- break;
771
- contentMemoBytes -= oldest.keyBytes;
772
- contentMemo.get(oldest.kind)?.delete(oldest.content);
773
- contentMemoOrder.delete(oldest);
774
- }
775
- return measured;
776
- }
777
- function memoizedTokens(kind, content) {
778
- const measured = memoizedContent(kind, content);
779
- if (measured.tokens === undefined) {
780
- measured.tokens = estimateTokens(content);
781
- }
782
- return measured.tokens;
783
- }
784
- function safeStableStringify(value) {
785
- if (value === undefined || value === null)
786
- return "";
787
- if (typeof value === "string")
788
- return value;
789
- try {
790
- return stableStringify(value);
791
- } catch {
792
- return String(value);
793
- }
794
- }
795
- function firstString(record, fields) {
796
- for (const field of fields) {
797
- const value = record[field];
798
- if (typeof value === "string")
799
- return value;
800
- }
801
- return "";
802
- }
803
- function callIdFromPart(part) {
804
- const direct = firstString(part, ["callID", "callId", "toolCallId", "tool_call_id", "id"]);
805
- if (direct)
806
- return direct;
807
- const state = isRecord(part.state) ? part.state : null;
808
- return state ? firstString(state, ["callID", "callId", "toolCallId", "tool_call_id", "id"]) : "";
809
- }
810
- function toolResultCallId(part) {
811
- return firstString(part, ["tool_use_id", "toolUseId", "callID", "callId"]);
812
- }
813
- function messageIdentity(message, messageIndex) {
814
- return typeof message.info.id === "string" ? message.info.id : `ordinal:${messageIndex}:${message.info.role ?? "unknown"}`;
815
- }
816
- function collectToolPartIdentities(messages) {
817
- const identities = new Map;
818
- const pendingOwners = new Map;
819
- for (let messageIndex = 0;messageIndex < messages.length; messageIndex += 1) {
820
- const message = messages[messageIndex];
821
- const currentOwner = messageIdentity(message, messageIndex);
822
- for (const part of message.parts) {
823
- if (!isRecord(part))
824
- continue;
825
- if (part.type === "tool-invocation" || part.type === "tool_use") {
826
- const callId = callIdFromPart(part);
827
- if (!callId)
828
- continue;
829
- const owners = pendingOwners.get(callId) ?? [];
830
- owners.push(currentOwner);
831
- pendingOwners.set(callId, owners);
832
- identities.set(part, {
833
- callId,
834
- ownerMessageId: currentOwner,
835
- messageIndex,
836
- kind: "invocation"
837
- });
838
- continue;
839
- }
840
- if (part.type === "tool_result") {
841
- const callId = toolResultCallId(part);
842
- if (!callId)
843
- continue;
844
- const owners = pendingOwners.get(callId);
845
- const ownerMessageId = owners?.shift() ?? currentOwner;
846
- identities.set(part, {
847
- callId,
848
- ownerMessageId,
849
- messageIndex,
850
- kind: "result"
851
- });
852
- continue;
853
- }
854
- if (part.type === "tool") {
855
- const callId = callIdFromPart(part);
856
- if (!callId)
857
- continue;
858
- identities.set(part, {
859
- callId,
860
- ownerMessageId: currentOwner,
861
- messageIndex,
862
- kind: "native"
863
- });
864
- }
865
- }
866
- }
867
- return identities;
868
- }
869
- function isMachineGeneratedUserPart(part) {
870
- if (!isRecord(part))
871
- return false;
872
- const metadata = isRecord(part.metadata) ? part.metadata : null;
873
- const marker = metadata && isRecord(metadata.marker) ? metadata.marker : null;
874
- return part.synthetic === true || part.ignored === true || marker?.kind != null || isSyntheticTodoPart(part);
875
- }
876
- function isSyntheticMessage(message) {
877
- const syntheticUserRow = message.info.role === "user" && message.parts.length > 0 && message.parts.every(isMachineGeneratedUserPart);
878
- return syntheticUserRow || message.info.summary === true || message.info.id === TODO_HEAD_ANCHOR_ID;
879
- }
880
- function countRealUserMessages(messages) {
881
- let count = 0;
882
- for (const message of messages) {
883
- if (message.info.role === "user" && !isSyntheticMessage(message))
884
- count += 1;
885
- }
886
- return count;
887
- }
888
- function isSyntheticPart(part) {
889
- return isMachineGeneratedUserPart(part);
890
- }
891
- function stripChannel1ReminderSpans(output) {
892
- let stripped = output;
893
- while (stripped.endsWith(CHANNEL1_REMINDER_CLOSE)) {
894
- const opener = stripped.lastIndexOf(CHANNEL1_REMINDER_OPEN);
895
- if (opener < 0)
896
- break;
897
- stripped = stripped.slice(0, opener);
898
- }
899
- return stripped;
900
- }
901
- function isDropSentinel(content) {
902
- let stripped = content.trimStart();
903
- const tag = TAG_PREFIX.exec(stripped);
904
- if (tag)
905
- stripped = stripped.slice(tag[0].length).trimStart();
906
- return DROP_PREFIXES.some((prefix) => stripped.slice(0, prefix.length).toLowerCase() === prefix);
907
- }
908
- function toolOutputText(part, key) {
909
- const serialize = (value) => partJsonMemo.get(key, value, () => safeStableStringify(value));
910
- if (part.type === "tool") {
911
- const state = isRecord(part.state) ? part.state : null;
912
- if (!state)
913
- return null;
914
- if (state.output !== undefined)
915
- return serialize(state.output);
916
- if (state.error !== undefined)
917
- return serialize(state.error);
918
- if (state.result !== undefined)
919
- return serialize(state.result);
920
- return null;
921
- }
922
- if (part.type === "tool_result") {
923
- const value = part.content ?? part.output ?? part.result;
924
- return value === undefined ? null : serialize(value);
925
- }
926
- return null;
927
- }
928
- function toolInputText(part, key) {
929
- const serialize = (value) => partJsonMemo.get(key, value, () => safeStableStringify(value));
930
- if (part.type === "tool") {
931
- const state = isRecord(part.state) ? part.state : null;
932
- if (!state || state.input === undefined)
933
- return null;
934
- return serialize(state.input);
935
- }
936
- if (part.type === "tool-invocation") {
937
- const value = part.args ?? part.input;
938
- return value === undefined ? null : serialize(value);
939
- }
940
- if (part.type === "tool_use") {
941
- return part.input === undefined ? null : serialize(part.input);
942
- }
943
- return null;
944
- }
945
- function messageIdForTag(tag) {
946
- if (tag.type === "tool")
947
- return tag.toolOwnerMessageId;
948
- return contentTagOwnerMessageId(tag.messageId);
949
- }
950
- function resolveProtectedTagNumbers(tags, protectedTagNumbersInput, protectedToolTags) {
951
- const protectedNumbers = new Set(protectedTagNumbersInput);
952
- const protectedCtxReduceTags = protectedToolTags ?? protectedToolTagNumbers(tags);
953
- for (const tagNumber of protectedCtxReduceTags)
954
- protectedNumbers.add(tagNumber);
955
- return protectedNumbers;
956
- }
957
- function neighborhoodConsistent(args) {
958
- let previousMax = null;
959
- for (let index = 0;index <= args.messageIndex; index += 1) {
960
- const bound = args.boundsByMessageIndex.get(index);
961
- if (bound)
962
- previousMax = previousMax === null ? bound.max : Math.max(previousMax, bound.max);
963
- }
964
- let nextMin = null;
965
- for (let index = args.messageIndex + 1;index < args.messageCount; index += 1) {
966
- const bound = args.boundsByMessageIndex.get(index);
967
- if (bound)
968
- nextMin = nextMin === null ? bound.min : Math.min(nextMin, bound.min);
969
- }
970
- if (previousMax === null || nextMin === null)
971
- return false;
972
- return args.orphanTagNumber >= previousMax && args.orphanTagNumber <= nextMin;
973
- }
974
- function buildTagAttribution(args) {
975
- const protectedNumbers = resolveProtectedTagNumbers(args.tags, args.protectedTagNumbers, args.protectedToolTags);
976
- const messageTags = new Map;
977
- const exactToolTags = new Map;
978
- const orphanTagsByCall = new Map;
979
- const messageIndexById = new Map;
980
- for (let index = 0;index < args.messages.length; index += 1) {
981
- const id = args.messages[index].info.id;
982
- if (typeof id === "string")
983
- messageIndexById.set(id, index);
984
- }
985
- const boundsByMessageIndex = new Map;
986
- for (const tag of args.tags) {
987
- if (tag.type === "tool") {
988
- if (tag.toolOwnerMessageId === null) {
989
- const rows = orphanTagsByCall.get(tag.messageId) ?? [];
990
- rows.push(tag);
991
- orphanTagsByCall.set(tag.messageId, rows);
992
- } else {
993
- exactToolTags.set(`${tag.toolOwnerMessageId}\x00${tag.messageId}`, tag);
994
- }
995
- } else {
996
- messageTags.set(tag.messageId, tag);
997
- }
998
- const ownerId = messageIdForTag(tag);
999
- const index = ownerId === null ? undefined : messageIndexById.get(ownerId);
1000
- if (index === undefined)
1001
- continue;
1002
- const existing = boundsByMessageIndex.get(index);
1003
- boundsByMessageIndex.set(index, {
1004
- min: existing ? Math.min(existing.min, tag.tagNumber) : tag.tagNumber,
1005
- max: existing ? Math.max(existing.max, tag.tagNumber) : tag.tagNumber
1006
- });
1007
- }
1008
- const toolTagsByPart = new Map;
1009
- const orphanCandidateOwners = new Map;
1010
- for (const [part, identity] of args.toolIdentities) {
1011
- const exact = exactToolTags.get(`${identity.ownerMessageId}\x00${identity.callId}`);
1012
- if (exact) {
1013
- toolTagsByPart.set(part, exact);
1014
- continue;
1015
- }
1016
- const orphans = orphanTagsByCall.get(identity.callId);
1017
- if (orphans?.length !== 1)
1018
- continue;
1019
- if (!neighborhoodConsistent({
1020
- orphanTagNumber: orphans[0].tagNumber,
1021
- messageIndex: identity.messageIndex,
1022
- boundsByMessageIndex,
1023
- messageCount: args.messages.length
1024
- })) {
1025
- continue;
1026
- }
1027
- const byOwner = orphanCandidateOwners.get(identity.callId) ?? new Map;
1028
- const ownerParts = byOwner.get(identity.ownerMessageId) ?? [];
1029
- ownerParts.push(identity);
1030
- byOwner.set(identity.ownerMessageId, ownerParts);
1031
- orphanCandidateOwners.set(identity.callId, byOwner);
1032
- }
1033
- for (const [callId, byOwner] of orphanCandidateOwners) {
1034
- if (byOwner.size !== 1)
1035
- continue;
1036
- const orphan = orphanTagsByCall.get(callId)?.[0];
1037
- if (!orphan)
1038
- continue;
1039
- const ownerId = byOwner.keys().next().value;
1040
- if (typeof ownerId !== "string")
1041
- continue;
1042
- for (const [part, identity] of args.toolIdentities) {
1043
- if (identity.callId === callId && identity.ownerMessageId === ownerId) {
1044
- toolTagsByPart.set(part, orphan);
1045
- }
1046
- }
1047
- }
1048
- return { protectedNumbers, messageTags, toolTagsByPart };
1049
- }
1050
- function snapshot(args) {
1051
- const memo = memoizedContent(args.kind, args.content);
1052
- const tag = args.tag;
1053
- const isProtected = tag ? args.protectedNumbers.has(tag.tagNumber) : false;
1054
- const queuedForDrop = tag ? args.pendingDropTagNumbers.has(tag.tagNumber) : false;
1055
- const uTokens = tag?.status === "active" && !isProtected && !queuedForDrop && args.kind !== "excluded" ? args.tokens : 0;
1056
- return {
1057
- key: args.key,
1058
- contentHash: memo.hash,
1059
- kind: args.kind,
1060
- tokens: args.tokens,
1061
- uTokens,
1062
- tagNumber: tag?.tagNumber ?? null,
1063
- tagStatus: tag?.status ?? null,
1064
- protected: isProtected,
1065
- queuedForDrop
1066
- };
1067
- }
1068
- var partJsonMemo = new TailHygieneJsonMemo;
1069
- function excludedSnapshot(key, part) {
1070
- const contentHash = partJsonMemo.get(key, part, () => {
1071
- if (part === null || part === undefined || typeof part === "string")
1072
- return memoizedContent("excluded", safeStableStringify(part)).hash;
1073
- try {
1074
- return stableStringifyHash(part, "excluded\x00");
1075
- } catch {
1076
- return memoizedContent("excluded", String(part)).hash;
1077
- }
1078
- }, true);
1079
- return {
1080
- key,
1081
- contentHash,
1082
- kind: "excluded",
1083
- tokens: 0,
1084
- uTokens: 0,
1085
- tagNumber: null,
1086
- tagStatus: null,
1087
- protected: false,
1088
- queuedForDrop: false
1089
- };
1090
- }
1091
- function fileContentAndTokens(part) {
1092
- const mime = typeof part.mime === "string" ? part.mime : "";
1093
- const type = typeof part.type === "string" ? part.type.toLowerCase() : "";
1094
- const url = typeof part.url === "string" ? part.url : "";
1095
- if (mime.startsWith("image/") || type.includes("image")) {
1096
- return {
1097
- content: url,
1098
- tokens: url.startsWith("data:") ? estimateImageTokensFromDataUrl(url) : 1200
1099
- };
1100
- }
1101
- const content = firstString(part, ["content", "text", "source", "url"]);
1102
- const tokens = memoizedTokens("file", content);
1103
- return { content, tokens };
1104
- }
1105
- function contentSignature(parts) {
1106
- return fnv1a32(parts.map((part) => `${part.key}:${part.contentHash}`).join("\x00"));
1107
- }
1108
- function structuralSize(value) {
1109
- if (typeof value === "string")
1110
- return value.length;
1111
- if (Array.isArray(value)) {
1112
- let size = value.length;
1113
- for (let index = 0;index < value.length; index += 1) {
1114
- size += structuralSize(value[index]);
1115
- }
1116
- return size;
1117
- }
1118
- if (value !== null && typeof value === "object") {
1119
- let size = 0;
1120
- for (const key in value) {
1121
- if (Object.hasOwn(value, key)) {
1122
- size += 1 + structuralSize(value[key]);
1123
- }
1124
- }
1125
- return size;
1126
- }
1127
- return 0;
1128
- }
1129
- function tailHygieneStructuralSignature(messages, opencode2 = false) {
1130
- const partCounts = [];
1131
- let totalBytes = 0;
1132
- for (const message of messages) {
1133
- partCounts.push(message.parts.length);
1134
- totalBytes += structuralSize(opencode2 ? providerVisibleMessageForOpenCode2(message) : providerVisibleMessageForTailHygiene(message));
1135
- }
1136
- return { messageCount: messages.length, partCounts, totalBytes };
1137
- }
1138
- function sameTailHygieneStructuralSignature(expected, actual) {
1139
- if (expected.messageCount !== actual.messageCount || expected.totalBytes !== actual.totalBytes || expected.partCounts.length !== actual.partCounts.length) {
1140
- return false;
1141
- }
1142
- return expected.partCounts.every((count, index) => count === actual.partCounts[index]);
1143
- }
1144
- function measureTailHygiene(input) {
1145
- return measureWithReplay(input);
1146
- }
1147
- function measureWithReplay(input, replay) {
1148
- partJsonMemo.beginPass();
1149
- const projectPart = input.opencode2 ? providerVisiblePartForOpenCode2 : providerVisiblePartForTailHygiene;
1150
- const views = new WeakMap;
1151
- const excluded = (key, part) => {
1152
- let view = part !== null && typeof part === "object" ? views.get(part) : undefined;
1153
- if (view === undefined) {
1154
- view = projectPart(part);
1155
- if (part !== null && typeof part === "object")
1156
- views.set(part, view);
1157
- }
1158
- return excludedSnapshot(key, view);
1159
- };
1160
- const pendingDropTagNumbers = input.pendingDropTagNumbers ?? new Set;
1161
- const unchanged = input.messages.map((message, index) => {
1162
- const previous = replay?.messages[index];
1163
- return previous !== undefined && sameReplayMessage(previous, message, projectPart);
1164
- });
1165
- const toolIdentities = collectToolPartIdentities(input.messages);
1166
- const attribution = buildTagAttribution({
1167
- messages: input.messages,
1168
- tags: input.tags,
1169
- toolIdentities,
1170
- protectedTagNumbers: input.protectedTagNumbers,
1171
- protectedToolTags: input.protectedToolTags
1172
- });
1173
- const toolOutputs = input.messages.map((message, index) => message.parts.map((part, partIndex) => unchanged[index] ? replay?.measured.toolOutputs[index][partIndex] ?? null : isRecord(part) ? toolOutputText(part, `${messageIdentity(message, index)}\x00${partIndex}\x00output`) : null));
1174
- const outputByPart = new Map;
1175
- input.messages.forEach((message, index) => {
1176
- message.parts.forEach((part, partIndex) => {
1177
- outputByPart.set(part, toolOutputs[index][partIndex]);
1178
- });
1179
- });
1180
- const droppedToolOwners = new Set;
1181
- for (const [part, identity] of toolIdentities) {
1182
- if (!isRecord(part))
1183
- continue;
1184
- const output = outputByPart.get(part) ?? null;
1185
- if (output !== null && isDropSentinel(output)) {
1186
- droppedToolOwners.add(`${identity.ownerMessageId}\x00${identity.callId}`);
1187
- }
1188
- }
1189
- const parts = [];
1190
- let t = 0;
1191
- let u = 0;
1192
- let newestMessagePartStart = 0;
1193
- const messagePartStarts = [];
1194
- for (let messageIndex = 0;messageIndex < input.messages.length; messageIndex += 1) {
1195
- const message = input.messages[messageIndex];
1196
- messagePartStarts.push(parts.length);
1197
- if (messageIndex === input.messages.length - 1)
1198
- newestMessagePartStart = parts.length;
1199
- const messageKey = messageIdentity(message, messageIndex);
1200
- const priorMessage = replay?.messages[messageIndex];
1201
- const reusable = unchanged[messageIndex] && priorMessage && message.parts.every((part, index) => {
1202
- const current = toolIdentities.get(part);
1203
- const prior = replay?.measured.toolOwners.get(priorMessage.parts[index]);
1204
- if (!current || !prior)
1205
- return current === prior;
1206
- const currentKey = `${current.ownerMessageId}\x00${current.callId}`;
1207
- const priorKey = `${prior.ownerMessageId}\x00${prior.callId}`;
1208
- return currentKey === priorKey && droppedToolOwners.has(currentKey) === replay?.measured.droppedToolOwners.has(priorKey);
1209
- });
1210
- if (reusable && replay) {
1211
- const start = replay.measured.messagePartStarts[messageIndex];
1212
- const end = replay.measured.messagePartStarts[messageIndex + 1] ?? replay.measured.parts.length;
1213
- for (let index = start;index < end; index += 1) {
1214
- const prior = replay.measured.parts[index];
1215
- const partIndex = Number(prior.key.slice(messageKey.length + 1).split("\x00")[0]);
1216
- const tag = prior.kind === "text" ? attribution.messageTags.get(`${message.info.id}:p${partIndex}`) : prior.kind === "file" ? attribution.messageTags.get(`${message.info.id}:file${partIndex}`) : prior.kind === "toolInput" || prior.kind === "toolOutput" ? attribution.toolTagsByPart.get(message.parts[partIndex]) : undefined;
1217
- const protectedPart = tag ? attribution.protectedNumbers.has(tag.tagNumber) : false;
1218
- const queuedForDrop = tag ? pendingDropTagNumbers.has(tag.tagNumber) : false;
1219
- const uTokens = tag?.status === "active" && !protectedPart && !queuedForDrop && prior.kind !== "excluded" ? prior.tokens : 0;
1220
- const measured = prior.tagNumber === (tag?.tagNumber ?? null) && prior.tagStatus === (tag?.status ?? null) && prior.protected === protectedPart && prior.queuedForDrop === queuedForDrop && prior.uTokens === uTokens ? prior : {
1221
- ...prior,
1222
- tagNumber: tag?.tagNumber ?? null,
1223
- tagStatus: tag?.status ?? null,
1224
- protected: protectedPart,
1225
- queuedForDrop,
1226
- uTokens
1227
- };
1228
- parts.push(measured);
1229
- t += measured.tokens;
1230
- u += measured.uTokens;
1231
- }
1232
- continue;
1233
- }
1234
- const messageSynthetic = isSyntheticMessage(message);
1235
- for (let partIndex = 0;partIndex < message.parts.length; partIndex += 1) {
1236
- const part = message.parts[partIndex];
1237
- const key = `${messageKey}\x00${partIndex}`;
1238
- if (messageSynthetic || isSyntheticPart(part) || !isRecord(part)) {
1239
- parts.push(excluded(`${key}\x00excluded`, part));
1240
- continue;
1241
- }
1242
- const type = typeof part.type === "string" ? part.type : "";
1243
- if (type === "reasoning" || type === "thinking" || type === "redacted_thinking" || type === "signature") {
1244
- parts.push(excluded(`${key}\x00excluded`, part));
1245
- continue;
1246
- }
1247
- if (type === "text") {
1248
- const rawContent = firstString(part, ["text", "content"]);
1249
- const content = rawContent === null ? null : stripChannel1ReminderSpans(rawContent);
1250
- if (!content || isDropSentinel(content)) {
1251
- parts.push(excluded(`${key}\x00excluded`, part));
1252
- continue;
1253
- }
1254
- const tokens = memoizedTokens("text", content);
1255
- const tag = attribution.messageTags.get(`${message.info.id}:p${partIndex}`);
1256
- const measured = snapshot({
1257
- key: `${key}\x00text`,
1258
- kind: "text",
1259
- content,
1260
- tokens,
1261
- tag,
1262
- protectedNumbers: attribution.protectedNumbers,
1263
- pendingDropTagNumbers
1264
- });
1265
- parts.push(measured);
1266
- t += measured.tokens;
1267
- u += measured.uTokens;
1268
- continue;
1269
- }
1270
- if (type === "file" || type.includes("image") || type === "source") {
1271
- const file = fileContentAndTokens(part);
1272
- if (!file.content || isDropSentinel(file.content)) {
1273
- parts.push(excluded(`${key}\x00excluded`, part));
1274
- continue;
1275
- }
1276
- const tag = attribution.messageTags.get(`${message.info.id}:file${partIndex}`);
1277
- const measured = snapshot({
1278
- key: `${key}\x00file`,
1279
- kind: "file",
1280
- content: file.content,
1281
- tokens: file.tokens,
1282
- tag,
1283
- protectedNumbers: attribution.protectedNumbers,
1284
- pendingDropTagNumbers
1285
- });
1286
- parts.push(measured);
1287
- t += measured.tokens;
1288
- u += measured.uTokens;
1289
- continue;
1290
- }
1291
- const toolIdentity = toolIdentities.get(part);
1292
- if (toolIdentity) {
1293
- const ownerKey = `${toolIdentity.ownerMessageId}\x00${toolIdentity.callId}`;
1294
- if (droppedToolOwners.has(ownerKey)) {
1295
- parts.push(excluded(`${key}\x00excluded`, part));
1296
- continue;
1297
- }
1298
- const tag = attribution.toolTagsByPart.get(part);
1299
- const inputText = toolInputText(part, `${key}\x00input`);
1300
- if (inputText !== null) {
1301
- const tokens = memoizedTokens("toolInput", inputText);
1302
- const measured = snapshot({
1303
- key: `${key}\x00toolInput`,
1304
- kind: "toolInput",
1305
- content: inputText,
1306
- tokens,
1307
- tag,
1308
- protectedNumbers: attribution.protectedNumbers,
1309
- pendingDropTagNumbers
1310
- });
1311
- parts.push(measured);
1312
- t += measured.tokens;
1313
- u += measured.uTokens;
1314
- }
1315
- const rawOutput = outputByPart.get(part) ?? null;
1316
- if (rawOutput !== null) {
1317
- const output = stripChannel1ReminderSpans(rawOutput);
1318
- if (isDropSentinel(output)) {
1319
- parts.push(excluded(`${key}\x00excludedOutput`, output));
1320
- } else {
1321
- const tokens = memoizedTokens("toolOutput", output) + (part.type === "tool" ? estimateToolAttachmentImageTokens(part.state) : 0);
1322
- const measured = snapshot({
1323
- key: `${key}\x00toolOutput`,
1324
- kind: "toolOutput",
1325
- content: output,
1326
- tokens,
1327
- tag,
1328
- protectedNumbers: attribution.protectedNumbers,
1329
- pendingDropTagNumbers
1330
- });
1331
- parts.push(measured);
1332
- t += measured.tokens;
1333
- u += measured.uTokens;
1334
- }
1335
- }
1336
- if (inputText === null && rawOutput === null) {
1337
- parts.push(excluded(`${key}\x00excluded`, part));
1338
- }
1339
- continue;
1340
- }
1341
- parts.push(excluded(`${key}\x00excluded`, part));
1342
- }
1343
- }
1344
- return {
1345
- u: Math.min(Math.max(0, u), Math.max(0, t)),
1346
- t: Math.max(0, t),
1347
- contentSignature: contentSignature(parts),
1348
- parts,
1349
- newestMessagePartStart,
1350
- messagePartStarts,
1351
- toolOutputs,
1352
- toolOwners: toolIdentities,
1353
- droppedToolOwners
1354
- };
1355
- }
1356
- function messageIdFromPartKey(key) {
1357
- const separator = key.indexOf("\x00");
1358
- return separator > 0 ? key.slice(0, separator) : key;
1359
- }
1360
- function prefixMismatch(baseline, current, partIndex, field) {
1361
- return {
1362
- valid: false,
1363
- boundaryAdvanceU: 0,
1364
- queuedDropDeltaU: 0,
1365
- mismatch: {
1366
- partIndex,
1367
- messageId: messageIdFromPartKey(baseline[partIndex]?.key ?? ""),
1368
- field,
1369
- frozenParts: baseline.length,
1370
- measuredParts: current.length
1371
- }
1372
- };
1373
- }
1374
- function compareMeasuredTailPrefix(baseline, current) {
1375
- if (current.length < baseline.length) {
1376
- return prefixMismatch(baseline, current, current.length, "shorter");
1377
- }
1378
- let boundaryAdvanceU = 0;
1379
- let queuedDropDeltaU = 0;
1380
- for (let index = 0;index < baseline.length; index += 1) {
1381
- const before = baseline[index];
1382
- const after = current[index];
1383
- const changedField = comparedField(before, after);
1384
- if (changedField)
1385
- return prefixMismatch(baseline, current, index, changedField);
1386
- if (before.protected && !after.protected) {
1387
- boundaryAdvanceU += after.uTokens;
1388
- } else if (before.queuedForDrop !== after.queuedForDrop) {
1389
- queuedDropDeltaU += after.uTokens - before.uTokens;
1390
- }
1391
- }
1392
- return { valid: true, boundaryAdvanceU, queuedDropDeltaU };
1393
- }
1394
- function comparedField(before, after) {
1395
- if (before.key !== after.key)
1396
- return "key";
1397
- if (before.contentHash !== after.contentHash)
1398
- return "contentHash";
1399
- if (before.kind !== after.kind)
1400
- return "kind";
1401
- if (before.tokens !== after.tokens)
1402
- return "tokens";
1403
- if (before.tagNumber !== after.tagNumber)
1404
- return "tagNumber";
1405
- if (before.tagStatus !== after.tagStatus)
1406
- return "tagStatus";
1407
- if (!before.protected && after.protected)
1408
- return "protection-entered";
1409
- if (before.protected && !after.protected) {
1410
- return after.tagStatus === "active" ? null : "protection-exit-inactive";
1411
- }
1412
- if (before.queuedForDrop !== after.queuedForDrop) {
1413
- return before.tagStatus === "active" && after.tagStatus === "active" ? null : "queued-drop-inactive";
1414
- }
1415
- return before.uTokens === after.uTokens ? null : "uTokens";
1416
- }
1417
- function formatTailHygienePrefixMismatch(mismatch, baselineGeneration) {
1418
- return [
1419
- "tail hygiene prefix invalidated:",
1420
- `part_index=${mismatch.partIndex}`,
1421
- `message=${mismatch.messageId || "unknown"}`,
1422
- `field=${mismatch.field}`,
1423
- `frozen_parts=${mismatch.frozenParts}`,
1424
- `measured_parts=${mismatch.measuredParts}`,
1425
- "action=re-measured",
1426
- `generation=${baselineGeneration}`
1427
- ].join(" ");
1428
- }
1429
- function sameReplayValue(before, after) {
1430
- if (before === after)
1431
- return true;
1432
- if (!before || !after || typeof before !== "object" || typeof after !== "object") {
1433
- return false;
1434
- }
1435
- if (Array.isArray(before)) {
1436
- if (!Array.isArray(after) || before.length !== after.length)
1437
- return false;
1438
- for (let index = 0;index < before.length; index += 1) {
1439
- if (!sameReplayValue(before[index], after[index]))
1440
- return false;
1441
- }
1442
- return true;
1443
- }
1444
- if (Array.isArray(after))
1445
- return false;
1446
- const prototype = Object.getPrototypeOf(before);
1447
- if (prototype !== Object.prototype && prototype !== null || Object.getPrototypeOf(after) !== prototype)
1448
- return false;
1449
- const left = before;
1450
- const right = after;
1451
- const keys = Object.keys(left);
1452
- if (keys.length !== Object.keys(right).length)
1453
- return false;
1454
- for (const key of keys) {
1455
- if (!Object.hasOwn(right, key) || !sameReplayValue(left[key], right[key]))
1456
- return false;
1457
- }
1458
- return true;
1459
- }
1460
- function copyReplayValue(value) {
1461
- if (Array.isArray(value))
1462
- return value.map(copyReplayValue);
1463
- if (value !== null && typeof value === "object") {
1464
- const prototype = Object.getPrototypeOf(value);
1465
- if (prototype !== Object.prototype && prototype !== null)
1466
- return structuredClone(value);
1467
- const copy = Object.create(prototype);
1468
- for (const key of Object.keys(value))
1469
- copy[key] = copyReplayValue(value[key]);
1470
- return copy;
1471
- }
1472
- return value;
1473
- }
1474
- function sameNumbers(before, after) {
1475
- if (before.size !== after.size)
1476
- return false;
1477
- for (const number of before)
1478
- if (!after.has(number))
1479
- return false;
1480
- return true;
1481
- }
1482
- function sameReplayMessage(left, right, projectPart = providerVisiblePartForTailHygiene) {
1483
- return left.info.id === right.info.id && left.info.role === right.info.role && left.info.summary === right.info.summary && sameReplayValue(left.parts, right.parts.map(projectPart));
1484
- }
1485
- function replaySnapshotParts(parts, projectPart = providerVisiblePartForTailHygiene) {
1486
- return copyReplayValue(parts.map(projectPart));
1487
- }
1488
- function sameReplayMessages(before, after, projectPart = providerVisiblePartForTailHygiene) {
1489
- if (before.length !== after.length)
1490
- return false;
1491
- for (let index = 0;index < before.length; index += 1) {
1492
- const left = before[index];
1493
- const right = after[index];
1494
- if (!sameReplayMessage(left, right, projectPart))
1495
- return false;
1496
- }
1497
- return true;
1498
- }
1499
- var baselineMeasurementMemo = new Map;
1500
- var MAX_BASELINE_MEMO_SIZE = 128 * 1024 * 1024;
1501
- var baselineMemoSize = 0;
1502
- function retainBaselineMeasurement(key, memo) {
1503
- const previous = baselineMeasurementMemo.get(key);
1504
- if (previous)
1505
- baselineMemoSize -= previous.size;
1506
- baselineMeasurementMemo.delete(key);
1507
- if (memo.size > MAX_BASELINE_MEMO_SIZE)
1508
- return;
1509
- baselineMeasurementMemo.set(key, memo);
1510
- baselineMemoSize += memo.size;
1511
- while (baselineMemoSize > MAX_BASELINE_MEMO_SIZE || baselineMeasurementMemo.size > 8) {
1512
- const oldest = baselineMeasurementMemo.keys().next().value;
1513
- if (!oldest)
1514
- break;
1515
- baselineMemoSize -= baselineMeasurementMemo.get(oldest)?.size ?? 0;
1516
- baselineMeasurementMemo.delete(oldest);
1517
- }
1518
- }
1519
- function freezeTailHygieneMeasurement(measured) {
1520
- const cut = Math.min(Math.max(0, measured.newestMessagePartStart), measured.parts.length);
1521
- let baselineT = 0;
1522
- let baselineU = 0;
1523
- for (let index = 0;index < cut; index += 1) {
1524
- baselineT += measured.parts[index].tokens;
1525
- baselineU += measured.parts[index].uTokens;
1526
- }
1527
- let turnDeltaT = 0;
1528
- let turnDeltaU = 0;
1529
- for (let index = cut;index < measured.parts.length; index += 1) {
1530
- const part = measured.parts[index];
1531
- turnDeltaT += part.tokens;
1532
- if (part.kind !== "toolOutput" || !part.protected)
1533
- turnDeltaU += part.uTokens;
1534
- }
1535
- baselineT = Math.max(0, baselineT);
1536
- return {
1537
- baselineU: Math.min(Math.max(0, baselineU), baselineT),
1538
- baselineT,
1539
- turnDeltaU,
1540
- turnDeltaT,
1541
- baselineParts: cut === measured.parts.length ? measured.parts : measured.parts.slice(0, cut)
1542
- };
1543
- }
1544
- function refreshTailHygieneBaseline(input) {
1545
- const protectedToolsPolicy = adoptedProtectedToolsPolicy(input.protectedTools, input.previous?.protectedToolsPolicy, input.cacheBusting, !!input.previous);
1546
- const protectedToolTags = protectedToolTagNumbers(input.tags, protectedToolsPolicy);
1547
- input = {
1548
- ...input,
1549
- protectedToolTags,
1550
- protectedTagNumbers: new Set([...input.protectedTagNumbers, ...protectedToolTags])
1551
- };
1552
- const pendingDropTagNumbers = input.pendingDropTagNumbers ?? new Set;
1553
- const priorMemo = input.previous ? baselineMeasurementMemo.get(input.previous.baselineParts) : undefined;
1554
- const cached = priorMemo?.opencode2 === !!input.opencode2 ? priorMemo : undefined;
1555
- const projectPart = input.opencode2 ? providerVisiblePartForOpenCode2 : providerVisiblePartForTailHygiene;
1556
- const hit = !input.cacheBusting && cached && sameReplayMessages(cached.messages, input.messages, projectPart) && sameReplayValue(cached.tags, input.tags) && sameNumbers(cached.protectedTagNumbers, input.protectedTagNumbers) && sameNumbers(cached.pendingDropTagNumbers, pendingDropTagNumbers);
1557
- const rawMeasured = hit ? cached.measured : measureWithReplay(input, cached);
1558
- const frozenCalibration = !input.cacheBusting && input.previous ? {
1559
- toolsRatio: input.previous.toolsRatio,
1560
- proseRatio: input.previous.proseRatio,
1561
- hygieneUnitsVersion: input.previous.hygieneUnitsVersion
1562
- } : {
1563
- toolsRatio: input.calibration?.toolsRatio ?? 1,
1564
- proseRatio: input.calibration?.proseRatio ?? 1,
1565
- hygieneUnitsVersion: input.hygieneUnitsVersion ?? 1
1566
- };
1567
- const ratioFor = (kind) => kind === "toolInput" || kind === "toolOutput" ? frozenCalibration.toolsRatio : kind === "text" || kind === "file" ? frozenCalibration.proseRatio : 1;
1568
- const measured = {
1569
- ...rawMeasured,
1570
- parts: rawMeasured.parts.map((part) => {
1571
- const ratio = ratioFor(part.kind);
1572
- return { ...part, tokens: part.tokens * ratio, uTokens: part.uTokens * ratio };
1573
- })
1574
- };
1575
- const memo = hit ? cached : {
1576
- opencode2: !!input.opencode2,
1577
- messages: input.messages.map((message, index) => cached?.messages[index] && sameReplayMessage(cached.messages[index], message, projectPart) ? cached.messages[index] : {
1578
- info: {
1579
- id: message.info.id,
1580
- role: message.info.role,
1581
- summary: message.info.summary
1582
- },
1583
- parts: replaySnapshotParts(message.parts, projectPart)
1584
- }),
1585
- tags: structuredClone(input.tags),
1586
- protectedTagNumbers: new Set(input.protectedTagNumbers),
1587
- pendingDropTagNumbers: new Set(pendingDropTagNumbers),
1588
- measured: rawMeasured,
1589
- size: 2 * structuralSize(input.messages.map(input.opencode2 ? providerVisibleMessageForOpenCode2 : providerVisibleMessageForTailHygiene)) + 512 * input.tags.length
1590
- };
1591
- if (!hit) {
1592
- const owners = new Map;
1593
- input.messages.forEach((message, index) => {
1594
- message.parts.forEach((part, partIndex) => {
1595
- const identity = rawMeasured.toolOwners.get(part);
1596
- if (identity)
1597
- owners.set(memo.messages[index].parts[partIndex], identity);
1598
- });
1599
- });
1600
- rawMeasured.toolOwners = owners;
1601
- }
1602
- const now = input.now ?? Date.now();
1603
- const refrozen = (mismatch) => {
1604
- const frozen = freezeTailHygieneMeasurement(measured);
1605
- retainBaselineMeasurement(frozen.baselineParts, memo);
1606
- return rememberCurrentToolOutputCount({
1607
- ...frozen,
1608
- protectedToolsPolicy,
1609
- hygieneUnitsVersion: frozenCalibration.hygieneUnitsVersion,
1610
- toolsRatio: frozenCalibration.toolsRatio,
1611
- proseRatio: frozenCalibration.proseRatio,
1612
- baselineGeneration: (input.previous?.baselineGeneration ?? 0) + 1,
1613
- computedAt: now,
1614
- evaluable: true,
1615
- generationInvalidated: false,
1616
- contentSignature: measured.contentSignature,
1617
- channel1PostReduceGrace: input.previous?.channel1PostReduceGrace,
1618
- lastPrefixMismatch: mismatch
1619
- }, measured);
1620
- };
1621
- if (input.cacheBusting || !input.previous)
1622
- return refrozen();
1623
- const prefix = compareMeasuredTailPrefix(input.previous.baselineParts, measured.parts);
1624
- if (!prefix.valid)
1625
- return refrozen(prefix.mismatch);
1626
- retainBaselineMeasurement(input.previous.baselineParts, memo);
1627
- let turnDeltaT = 0;
1628
- let turnDeltaU = prefix.boundaryAdvanceU + prefix.queuedDropDeltaU;
1629
- for (let index = input.previous.baselineParts.length;index < measured.parts.length; index += 1) {
1630
- const part = measured.parts[index];
1631
- turnDeltaT += part.tokens;
1632
- if (part.kind !== "toolOutput" || !part.protected)
1633
- turnDeltaU += part.uTokens;
1634
- }
1635
- return rememberCurrentToolOutputCount({
1636
- ...input.previous,
1637
- protectedToolsPolicy,
1638
- turnDeltaU,
1639
- turnDeltaT,
1640
- evaluable: true,
1641
- generationInvalidated: false,
1642
- contentSignature: measured.contentSignature,
1643
- lastPrefixMismatch: undefined
1644
- }, measured);
1645
- }
1646
- function effectiveTailHygiene(baseline) {
1647
- const t = Math.ceil(Math.max(0, baseline.baselineT + baseline.turnDeltaT));
1648
- const u = Math.min(t, Math.ceil(Math.max(0, baseline.baselineU + baseline.turnDeltaU)));
1649
- return { u, t };
1650
- }
1651
- function assertTailHygieneContentUnchanged(input) {
1652
- const actual = measureTailHygiene(input).contentSignature;
1653
- if (actual !== input.expectedSignature) {
1654
- throw new Error(`tail hygiene walk was not the last byte-affecting operation: expected ${input.expectedSignature}, got ${actual}`);
1655
- }
1656
- }
1657
- function assertTailHygieneContentUnchangedIfEnabled(input) {
1658
- if (process.env.MAGIC_CONTEXT_DEBUG_ASSERTIONS === "1") {
1659
- assertTailHygieneContentUnchanged(input);
1660
- }
1661
- }
1662
-
1663
- // src/hooks/magic-context/ctx-reduce-nudge.ts
1664
- var CHANNEL1_SENTINEL = "<system-reminder>";
1665
- var TOKENS_PER_BYTE = 0.25;
1666
- var CHANNEL1_MIN_TOKENS = 60000;
1667
- var CHANNEL1_FLOOR_TOKENS = 25000;
1668
- var CHANNEL1_REFIRE_FLOOR_TOKENS = 25000;
1669
- var S_GENTLE = 0.2;
1670
- var S_FIRM = 0.4;
1671
- var S_URGENT = 0.6;
1672
- var CHANNEL2_SEVERITY_THRESHOLD = 0.75;
1673
- var CHANNEL2_FLOOR_TOKENS = 50000;
1674
- var LEVEL_RANK = { gentle: 1, firm: 2, urgent: 3 };
1675
- var DROP_SENTINELS = ["[dropped", "[truncated"];
1676
- function channel1RefireTokens(tailTokens) {
1677
- const scaled = Math.round(0.08 * Math.max(0, tailTokens));
1678
- return Math.max(CHANNEL1_REFIRE_FLOOR_TOKENS, scaled);
1679
- }
1680
- function isDroppedToolOutput(output) {
1681
- const head = output.trimStart().replace(/^§\d+§\s*/, "").slice(0, 16).toLowerCase();
1682
- return DROP_SENTINELS.some((sentinel) => head.startsWith(sentinel));
1683
- }
1684
- function toolOutputTokens(output) {
1685
- return estimateTokens(stripChannel1ReminderSpans(output));
1686
- }
1687
- function channel1Band(undroppedTokens, tailTokens) {
1688
- if (tailTokens < CHANNEL1_MIN_TOKENS || undroppedTokens < CHANNEL1_FLOOR_TOKENS) {
1689
- return "quiet";
1690
- }
1691
- const severity = Math.min(1, Math.max(0, undroppedTokens / Math.max(tailTokens, 1)));
1692
- if (severity >= S_URGENT)
1693
- return "urgent";
1694
- if (severity >= S_FIRM)
1695
- return "firm";
1696
- if (severity >= S_GENTLE)
1697
- return "gentle";
1698
- return "quiet";
1699
- }
1700
- function nudgeBand(undroppedTokens, tailTokens) {
1701
- const base = channel1Band(undroppedTokens, tailTokens);
1702
- const severity = Math.min(1, Math.max(0, undroppedTokens / Math.max(tailTokens, 1)));
1703
- return base === "urgent" && undroppedTokens >= CHANNEL2_FLOOR_TOKENS && severity >= CHANNEL2_SEVERITY_THRESHOLD ? "channel2" : base;
1704
- }
1705
- function decideChannel1(input) {
1706
- const tailTokens = Math.max(0, input.baselineT + input.turnDeltaT);
1707
- const undroppedTokens = Math.min(tailTokens, Math.max(0, input.baselineU + input.turnDeltaU));
1708
- const severity = Math.min(1, Math.max(0, undroppedTokens / Math.max(tailTokens, 1)));
1709
- const previousLevel = input.lastNudgeLevel;
1710
- let lastNudge = Math.max(0, input.lastNudgeUndropped);
1711
- let nextLevel = previousLevel;
1712
- let clearPostReduceGrace = false;
1713
- const growthThreshold = channel1RefireTokens(tailTokens);
1714
- const graceBaselineU = input.postReduceGraceBaselineU === undefined ? null : Math.max(0, input.postReduceGraceBaselineU);
1715
- const graceGrowth = graceBaselineU === null ? 0 : undroppedTokens - graceBaselineU;
1716
- const cadenceGrowth = undroppedTokens - lastNudge;
1717
- const currentTurn = input.currentRealUserTurnCount;
1718
- const lastFireTurn = input.lastFireOrdinal;
1719
- const stickyTurnsRemaining = currentTurn === undefined || lastFireTurn === undefined || lastFireTurn > currentTurn ? 0 : Math.max(0, CHANNEL1_STICKY_REAL_USER_TURN_GAP - (currentTurn - lastFireTurn));
1720
- const measuredBand = channel1Band(undroppedTokens, tailTokens);
1721
- const quiet = (reason, dampeningState, level = measuredBand === "quiet" ? "gentle" : measuredBand) => ({
1722
- fire: false,
1723
- sticky: false,
1724
- level,
1725
- band: measuredBand,
1726
- undroppedTokens,
1727
- tailTokens,
1728
- severity,
1729
- graceBaselineU,
1730
- graceGrowth,
1731
- growthThreshold,
1732
- cadenceGrowth,
1733
- stickyTurnsRemaining,
1734
- dampeningState,
1735
- verdictReason: reason,
1736
- nextLastNudge: lastNudge,
1737
- nextLastNudgeLevel: nextLevel,
1738
- clearPostReduceGrace
1739
- });
1740
- if (input.evaluable === false || input.generationInvalidated === true) {
1741
- return quiet("baseline-unevaluable", "baseline-hold");
1742
- }
1743
- if (input.hasRecentReduce)
1744
- return quiet("recent-reduce-refresh", "baseline-hold");
1745
- if (input.agentDropsAppliedThisPass) {
1746
- return quiet("agent-drops-applied", "baseline-hold");
1747
- }
1748
- if (input.postReduceGracePending) {
1749
- return quiet("post-reduce-baseline-pending", "baseline-hold");
1750
- }
1751
- const level = measuredBand === "quiet" ? "" : measuredBand;
1752
- const previousRank = previousLevel === "" ? 0 : LEVEL_RANK[previousLevel];
1753
- const currentRank = level === "" ? 0 : LEVEL_RANK[level];
1754
- let graceReleaseReason = null;
1755
- if (graceBaselineU !== null) {
1756
- const preReduceLevel = input.postReduceGracePreLevel ?? previousLevel;
1757
- const preReduceRank = preReduceLevel === "" ? 0 : LEVEL_RANK[preReduceLevel];
1758
- const regrowthReached = graceGrowth >= growthThreshold;
1759
- const escalatedAbovePreReduceBand = currentRank > preReduceRank;
1760
- if (!regrowthReached && !escalatedAbovePreReduceBand) {
1761
- return quiet("post-reduce-compliance-grace", "post-reduce-grace");
1762
- }
1763
- clearPostReduceGrace = true;
1764
- graceReleaseReason = regrowthReached ? "post-reduce-regrowth-reached" : "post-reduce-band-escalation";
1765
- }
1766
- if (level === "") {
1767
- nextLevel = "";
1768
- lastNudge = 0;
1769
- if (tailTokens < CHANNEL1_MIN_TOKENS) {
1770
- return quiet("tail-below-minimum", "none");
1771
- }
1772
- if (undroppedTokens < CHANNEL1_FLOOR_TOKENS) {
1773
- return quiet("reclaimable-below-floor", "none");
1774
- }
1775
- return quiet("ratio-below-gentle", "none");
1776
- }
1777
- if (currentRank < previousRank) {
1778
- nextLevel = level;
1779
- lastNudge = undroppedTokens;
1780
- return quiet("band-deescalation", "band-hysteresis", level);
1781
- }
1782
- const crossedFromBelow = currentRank > previousRank;
1783
- const cadenceReached = currentRank === previousRank && cadenceGrowth >= growthThreshold;
1784
- const stickyTurnGapReached = stickyTurnsRemaining === 0;
1785
- if (!crossedFromBelow && !cadenceReached) {
1786
- return quiet("cadence-growth", "cadence", level);
1787
- }
1788
- if (!crossedFromBelow && !stickyTurnGapReached) {
1789
- return quiet("sticky-turn-floor", "sticky-floor", level);
1790
- }
1791
- return {
1792
- fire: true,
1793
- sticky: !crossedFromBelow,
1794
- level,
1795
- band: measuredBand,
1796
- undroppedTokens,
1797
- tailTokens,
1798
- severity,
1799
- graceBaselineU,
1800
- graceGrowth,
1801
- growthThreshold,
1802
- cadenceGrowth,
1803
- stickyTurnsRemaining,
1804
- dampeningState: "none",
1805
- verdictReason: graceReleaseReason ?? (crossedFromBelow ? "band-crossing" : "cadence-refire"),
1806
- nextLastNudge: undroppedTokens,
1807
- nextLastNudgeLevel: level,
1808
- clearPostReduceGrace
1809
- };
1810
- }
1811
- function evaluateChannel2(input) {
1812
- const unavailable = (reason) => ({
1813
- evaluable: false,
1814
- shouldTrigger: false,
1815
- reclaimableTokens: 0,
1816
- tailTokens: 0,
1817
- severity: 0,
1818
- band: "quiet",
1819
- verdictReason: reason
1820
- });
1821
- if (!input)
1822
- return unavailable("baseline-unavailable");
1823
- if (input.evaluable !== true)
1824
- return unavailable("baseline-unevaluable");
1825
- if (input.generationInvalidated === true)
1826
- return unavailable("generation-invalidated");
1827
- const values = [input.baselineU, input.baselineT, input.turnDeltaU, input.turnDeltaT];
1828
- if (values.some((value) => !Number.isFinite(value)))
1829
- return unavailable("non-finite-input");
1830
- const tailTokens = Math.max(0, input.baselineT + input.turnDeltaT);
1831
- const reclaimableTokens = Math.min(tailTokens, Math.max(0, input.baselineU + input.turnDeltaU));
1832
- const severity = Math.min(1, Math.max(0, reclaimableTokens / Math.max(tailTokens, 1)));
1833
- const band = nudgeBand(reclaimableTokens, tailTokens);
1834
- let verdictReason = "ceiling-threshold-met";
1835
- if (tailTokens < CHANNEL1_MIN_TOKENS)
1836
- verdictReason = "tail-below-minimum";
1837
- else if (reclaimableTokens < CHANNEL2_FLOOR_TOKENS) {
1838
- verdictReason = "reclaimable-below-floor";
1839
- } else if (severity < CHANNEL2_SEVERITY_THRESHOLD)
1840
- verdictReason = "ratio-below-ceiling";
1841
- return {
1842
- evaluable: true,
1843
- shouldTrigger: verdictReason === "ceiling-threshold-met",
1844
- reclaimableTokens,
1845
- tailTokens,
1846
- severity,
1847
- band,
1848
- verdictReason
1849
- };
1850
- }
1851
- function formatRatio(value) {
1852
- return Number.isFinite(value) ? value.toFixed(4) : "nan";
1853
- }
1854
- function formatChannel1Evaluation(decision, ctxReduceCallable = true) {
1855
- return [
1856
- "channel1 evaluation:",
1857
- `ctx_reduce=${ctxReduceCallable ? "callable" : "unavailable"}`,
1858
- `U=${decision.undroppedTokens}`,
1859
- `T=${decision.tailTokens}`,
1860
- `ratio=${formatRatio(decision.severity)}`,
1861
- `band=${decision.band}`,
1862
- `grace_baseline_u=${decision.graceBaselineU ?? "none"}`,
1863
- `grace_growth=${decision.graceGrowth}`,
1864
- `growth_threshold=${decision.growthThreshold}`,
1865
- `sticky_floor_turns_remaining=${decision.stickyTurnsRemaining}`,
1866
- `dampening=${decision.dampeningState}`,
1867
- `verdict=${decision.fire ? "fire" : "hold"}`,
1868
- `reason=${ctxReduceCallable ? decision.verdictReason : "ctx-reduce-unavailable"}`
1869
- ].join(" ");
1870
- }
1871
- function formatChannel2Evaluation(evaluation, input) {
1872
- const leaseAfter = input.leaseAfter ?? input.leaseBefore;
1873
- let verdict = "hold";
1874
- let reason = evaluation.verdictReason;
1875
- if (input.ctxReduceCallable === false) {
1876
- reason = "ctx-reduce-unavailable";
1877
- } else if (input.gateHoldReason) {
1878
- reason = input.gateHoldReason;
1879
- } else if (evaluation.shouldTrigger) {
1880
- if (input.leaseBefore === "" && input.leaseAfter === undefined) {
1881
- verdict = "arm";
1882
- } else if (leaseAfter === "pending") {
1883
- verdict = input.leaseBefore === "" ? "arm" : "pending";
1884
- reason = input.leaseBefore === "" ? evaluation.verdictReason : "lease-pending";
1885
- } else if (leaseAfter === "claimed") {
1886
- reason = "lease-claimed";
1887
- } else if (leaseAfter === "delivered") {
1888
- reason = "lease-delivered";
1889
- } else {
1890
- reason = "lease-cas-not-armed";
1891
- }
1892
- }
1893
- return [
1894
- "channel2 evaluation:",
1895
- `ctx_reduce=${input.ctxReduceCallable === false ? "unavailable" : "callable"}`,
1896
- `U=${evaluation.reclaimableTokens}`,
1897
- `T=${evaluation.tailTokens}`,
1898
- `ratio=${formatRatio(evaluation.severity)}`,
1899
- `band=${evaluation.band}`,
1900
- `lease=${input.leaseBefore || "empty"}->${leaseAfter || "empty"}`,
1901
- `verdict=${verdict}`,
1902
- `reason=${reason}`
1903
- ].join(" ");
1904
- }
1905
- function approxThousands(tokens) {
1906
- return `${Math.round(tokens / 1000)}k`;
1907
- }
1908
- function formatOldestReclaimableHint(hint) {
1909
- if (!hint || hint.length === 0)
1910
- return "";
1911
- const rendered = hint.slice(0, 4).map((tag) => `§${tag.tagNumber}§ ${tag.toolName ?? "tool"}`).join(" · ");
1912
- return rendered.length > 0 ? `
1913
- oldest reclaimable: ${rendered}.` : "";
1914
- }
1915
- function formatReclaimableOutputSummary(count, tokens) {
1916
- const outputCount = Math.max(0, Math.floor(count));
1917
- const outputs = outputCount === 0 ? "spent tool outputs" : `${outputCount} spent tool output${outputCount === 1 ? "" : "s"}`;
1918
- return `${outputs} (~${approxThousands(tokens)} tokens)`;
1919
- }
1920
- function buildChannel2Reminder(undroppedTokens, reclaimableToolOutputs, hint) {
1921
- const summary = formatReclaimableOutputSummary(reclaimableToolOutputs, undroppedTokens);
1922
- const hintText = formatOldestReclaimableHint(hint);
1923
- return `<system-reminder>
1924
- ` + `Your next step: call ctx_reduce on the outputs you've already used (${summary}). Then continue your task.${hintText}
1925
- ` + `</system-reminder>`;
1926
- }
1927
- var CHANNEL1_STICKY_REAL_USER_TURN_GAP = 5;
1928
- function buildChannel1Reminder(level, undroppedTokens, reclaimableToolOutputs, hint, sticky = false) {
1929
- const summary = formatReclaimableOutputSummary(reclaimableToolOutputs, undroppedTokens);
1930
- const hintText = formatOldestReclaimableHint(hint);
1931
- if (sticky) {
1932
- return `
1933
-
1934
- <system-reminder>
1935
- Still unstamped: ${summary}. Stamp the ones you've used with ctx_reduce now.${hintText}
1936
- </system-reminder>`;
1937
- }
1938
- let body;
1939
- switch (level) {
1940
- case "gentle":
1941
- body = `Housekeeping: ${summary} are reclaimable. Stamp each output with ctx_reduce as soon as you've taken what you need from it; don't wait for the task to finish.`;
1942
- break;
1943
- case "firm":
1944
- body = `${summary} are reclaimable. Make a ctx_reduce pass now over the outputs you've already used, then continue.`;
1945
- break;
1946
- case "urgent":
1947
- body = `${summary} are still unstamped. Call ctx_reduce now, before your next tool call, on every output you've already used.`;
1948
- break;
1949
- }
1950
- return `
1951
-
1952
- <system-reminder>
1953
- ${body}${hintText}
1954
- </system-reminder>`;
1955
- }
1956
-
1957
- // src/hooks/magic-context/emergency-drop.ts
1958
- var TARGET_FRACTION = 0.3;
1959
- var TIER_RECENCY_RESERVE = 0.2;
1960
- var EMERGENCY_REARM_MIN_TOKENS = 2000;
1961
- var EMERGENCY_MIN_ACHIEVABLE_RECLAIM_TOKENS = EMERGENCY_REARM_MIN_TOKENS;
1962
- var T1_TOOLS = new Set(["read", "todowrite", "task", "aft_outline", "aft_zoom"]);
1963
- var T2_TOOLS = new Set(["edit", "write", "apply_patch", "grep", "glob", "aft_search"]);
1964
- function normalizeToolName(toolName) {
1965
- if (!toolName)
1966
- return "";
1967
- let name = toolName.toLowerCase();
1968
- if (name.startsWith("mcp_"))
1969
- name = name.slice(4);
1970
- return name;
1971
- }
1972
- function resolveToolTier(toolName) {
1973
- const name = normalizeToolName(toolName);
1974
- if (T1_TOOLS.has(name))
1975
- return 1;
1976
- if (T2_TOOLS.has(name))
1977
- return 2;
1978
- return 3;
1979
- }
1980
- function tagReclaimBytes(tag) {
1981
- return tag.byteSize + tag.inputByteSize + tag.reasoningByteSize;
1982
- }
1983
- function estimateEmergencyDropReclaimTokens(tag) {
1984
- if (tag.reclaimableTokens !== undefined)
1985
- return Number.isFinite(tag.reclaimableTokens) ? Math.max(0, tag.reclaimableTokens) : 0;
1986
- return Math.round(tagReclaimBytes(tag) * TOKENS_PER_BYTE);
1987
- }
1988
- function planEmergencyDrop(input) {
1989
- const {
1990
- tags,
1991
- floorTags,
1992
- currentTotalInputTokens,
1993
- ceilingTokens,
1994
- priorInputSample,
1995
- hasPriorDrop
1996
- } = input;
1997
- const noop = (reason) => ({
1998
- shouldDrop: false,
1999
- tagNumbers: [],
2000
- reclaimTokens: 0,
2001
- reason
2002
- });
2003
- if (!Number.isFinite(ceilingTokens) || ceilingTokens <= 0) {
2004
- return noop("unknown-ceiling");
2005
- }
2006
- if (!Number.isFinite(currentTotalInputTokens) || currentTotalInputTokens <= 0) {
2007
- return noop("unknown-usage");
2008
- }
2009
- const absoluteEmergency = (input.usagePercentage ?? 0) >= 95;
2010
- if (hasPriorDrop && !absoluteEmergency) {
2011
- return noop(`pressure-episode-latched (prior sample ${priorInputSample}; awaiting exit or independent bust)`);
2012
- }
2013
- let tailTokens = 0;
2014
- for (const tag of floorTags) {
2015
- if (tag.status !== "active")
2016
- continue;
2017
- tailTokens += tag.servedTokens ?? estimateEmergencyDropReclaimTokens(tag);
2018
- }
2019
- const fixedFloor = Math.max(currentTotalInputTokens - tailTokens, 0);
2020
- const workingSpan = Math.max(ceilingTokens - fixedFloor, 0);
2021
- const target = fixedFloor + TARGET_FRACTION * workingSpan;
2022
- const reclaimTokens = Math.round(currentTotalInputTokens - target);
2023
- if (fixedFloor > ceilingTokens) {
2024
- return noop(`fixed floor ≈${Math.round(fixedFloor)} already exceeds ceiling ${Math.round(ceilingTokens)}: tool drops cannot reach the target`);
2025
- }
2026
- if (reclaimTokens <= EMERGENCY_REARM_MIN_TOKENS) {
2027
- return noop(`reclaim<=min (${reclaimTokens} <= ${EMERGENCY_REARM_MIN_TOKENS})`);
2028
- }
2029
- const cutoff = input.protectedCutoff;
2030
- const windowYields = absoluteEmergency;
2031
- const tierActive = { 1: [], 2: [] };
2032
- for (const tag of tags) {
2033
- if (tag.status !== "active" || tag.type !== "tool")
2034
- continue;
2035
- const tier = resolveToolTier(tag.toolName);
2036
- if (tier === 1 || tier === 2)
2037
- tierActive[tier].push(tag.tagNumber);
2038
- }
2039
- const reserved = new Set;
2040
- for (const tier of [1, 2]) {
2041
- const nums = tierActive[tier];
2042
- if (nums.length === 0)
2043
- continue;
2044
- nums.sort((a, b) => b - a);
2045
- const reserveCount = absoluteEmergency ? 0 : Math.ceil(TIER_RECENCY_RESERVE * nums.length);
2046
- for (let i = 0;i < reserveCount && i < nums.length; i++) {
2047
- reserved.add(nums[i]);
2048
- }
2049
- }
2050
- const protectedTags = input.protectedToolTags ?? protectedToolTagNumbers(floorTags, input.protectedTools);
2051
- const byTier = { 1: [], 2: [], 3: [] };
2052
- for (const tag of tags) {
2053
- if (tag.status !== "active" || tag.type !== "tool")
2054
- continue;
2055
- if (!windowYields) {
2056
- if (cutoff !== null) {
2057
- if (tag.tagNumber >= cutoff)
2058
- continue;
2059
- }
2060
- }
2061
- if (protectedTags.has(tag.tagNumber))
2062
- continue;
2063
- const tier = resolveToolTier(tag.toolName);
2064
- if ((tier === 1 || tier === 2) && reserved.has(tag.tagNumber))
2065
- continue;
2066
- byTier[tier].push(tag);
2067
- }
2068
- const selected = [];
2069
- let reclaimed = 0;
2070
- outer:
2071
- for (const tier of [3, 2, 1]) {
2072
- const group = byTier[tier];
2073
- group.sort((a, b) => a.tagNumber - b.tagNumber);
2074
- for (const tag of group) {
2075
- selected.push(tag.tagNumber);
2076
- reclaimed += estimateEmergencyDropReclaimTokens(tag);
2077
- if (reclaimed >= reclaimTokens)
2078
- break outer;
2079
- }
2080
- }
2081
- if (selected.length === 0) {
2082
- return noop("no-candidates");
2083
- }
2084
- if (!input.passAlreadyPriced && reclaimed < EMERGENCY_MIN_ACHIEVABLE_RECLAIM_TOKENS) {
2085
- return noop(`achievable reclaim below minimum (${selected.length} tags, reclaim≈${Math.round(reclaimed)} < ${EMERGENCY_MIN_ACHIEVABLE_RECLAIM_TOKENS} against gap ${reclaimTokens})`);
2086
- }
2087
- return {
2088
- shouldDrop: true,
2089
- tagNumbers: selected,
2090
- reclaimTokens,
2091
- reason: `tiered drop: ${selected.length} tags, reclaim≈${reclaimed}/${reclaimTokens} tokens (floor≈${fixedFloor}, ceiling=${Math.round(ceilingTokens)})`
2092
- };
2093
- }
2094
- function measureEmergencyTag(tag, target, calibration, skeleton) {
2095
- const observation = target?.measureReclaim?.(skeleton);
2096
- if (observation) {
2097
- const before = observation.beforeTools * calibration.toolsRatio + observation.beforeProse * calibration.proseRatio;
2098
- const after = observation.afterTools * calibration.toolsRatio + observation.afterProse * calibration.proseRatio;
2099
- return { ...tag, servedTokens: before, reclaimableTokens: Math.max(0, before - after) };
2100
- }
2101
- const content = target?.getContent?.();
2102
- const served = content ? estimateTokens(content) * (tag.type === "tool" ? calibration.toolsRatio : calibration.proseRatio) : 0;
2103
- return { ...tag, servedTokens: served, reclaimableTokens: 0 };
2104
- }
2105
-
2106
- // src/features/magic-context/storage-ops.ts
2107
- var queuePendingOpStatements = new WeakMap;
2108
- var queueUnchangedDropStatements = new WeakMap;
2109
- var getPendingOpsStatements = new WeakMap;
2110
- var getPendingOpsCountStatements = new WeakMap;
2111
- var hasPendingDropOpsStatements = new WeakMap;
2112
- var clearPendingOpsStatements = new WeakMap;
2113
- var removePendingOpStatements = new WeakMap;
2114
- function getQueuePendingOpStatement(db) {
2115
- let stmt = queuePendingOpStatements.get(db);
2116
- if (!stmt) {
2117
- stmt = db.prepare(`INSERT INTO pending_ops (session_id, tag_id, operation, queued_at, harness)
2118
- SELECT ?, ?, ?, ?, ? WHERE NOT EXISTS (
2119
- SELECT 1 FROM pending_ops WHERE session_id = ? AND tag_id = ? AND operation = ?
2120
- )`);
2121
- queuePendingOpStatements.set(db, stmt);
2122
- }
2123
- return stmt;
2124
- }
2125
- function getPendingOpsStatement(db) {
2126
- let stmt = getPendingOpsStatements.get(db);
2127
- if (!stmt) {
2128
- stmt = db.prepare("SELECT id, session_id, tag_id, operation, queued_at FROM pending_ops WHERE session_id = ? ORDER BY queued_at ASC, id ASC");
2129
- getPendingOpsStatements.set(db, stmt);
2130
- }
2131
- return stmt;
2132
- }
2133
- function getClearPendingOpsStatement(db) {
2134
- let stmt = clearPendingOpsStatements.get(db);
2135
- if (!stmt) {
2136
- stmt = db.prepare("DELETE FROM pending_ops WHERE session_id = ?");
2137
- clearPendingOpsStatements.set(db, stmt);
2138
- }
2139
- return stmt;
2140
- }
2141
- function getRemovePendingOpStatement(db) {
2142
- let stmt = removePendingOpStatements.get(db);
2143
- if (!stmt) {
2144
- stmt = db.prepare("DELETE FROM pending_ops WHERE session_id = ? AND tag_id = ?");
2145
- removePendingOpStatements.set(db, stmt);
2146
- }
2147
- return stmt;
2148
- }
2149
- function isPendingOpRow(row) {
2150
- if (row === null || typeof row !== "object")
2151
- return false;
2152
- const r = row;
2153
- return typeof r.id === "number" && typeof r.session_id === "string" && typeof r.tag_id === "number" && typeof r.operation === "string" && typeof r.queued_at === "number";
2154
- }
2155
- function toPendingOp(row) {
2156
- if (row.operation !== "drop") {
2157
- sessionLog2(row.session_id, `unknown pending operation "${row.operation}"; ignoring`);
2158
- return null;
2159
- }
2160
- return {
2161
- id: row.id,
2162
- sessionId: row.session_id,
2163
- tagId: row.tag_id,
2164
- operation: row.operation,
2165
- queuedAt: row.queued_at
2166
- };
2167
- }
2168
- function queuePendingOp(db, sessionId, tagId, operation, queuedAt = Date.now()) {
2169
- getQueuePendingOpStatement(db).run(sessionId, tagId, operation, queuedAt, getHarness2(), sessionId, tagId, operation);
2170
- }
2171
- function queuePendingDropForUnchangedTag(db, sessionId, tag) {
2172
- let statement = queueUnchangedDropStatements.get(db);
2173
- if (!statement) {
2174
- statement = db.prepare(`INSERT INTO pending_ops (session_id, tag_id, operation, queued_at, harness)
2175
- SELECT session_id, tag_number, 'drop', ?, ? FROM tags
2176
- WHERE id = ? AND session_id = ? AND tag_number = ? AND message_id = ?
2177
- AND type = ? AND tool_owner_message_id IS ? AND status = 'active'
2178
- AND NOT EXISTS (
2179
- SELECT 1 FROM pending_ops WHERE session_id = tags.session_id
2180
- AND tag_id = tags.tag_number AND operation = 'drop'
2181
- )`);
2182
- queueUnchangedDropStatements.set(db, statement);
2183
- }
2184
- return statement.run(Date.now(), getHarness2(), tag.id ?? null, sessionId, tag.tagNumber, tag.messageId, tag.type, tag.toolOwnerMessageId).changes > 0;
2185
- }
2186
- function getPendingOps(db, sessionId) {
2187
- const rows = getPendingOpsStatement(db).all(sessionId).filter(isPendingOpRow);
2188
- return rows.map(toPendingOp).filter((op) => op !== null);
2189
- }
2190
- function hasPendingDropOps(db, sessionId) {
2191
- let statement = hasPendingDropOpsStatements.get(db);
2192
- if (!statement) {
2193
- statement = db.prepare(`SELECT EXISTS (
2194
- SELECT 1 FROM pending_ops WHERE session_id = ? AND operation = 'drop'
2195
- AND typeof(id) IN ('integer', 'real')
2196
- AND typeof(session_id) = 'text'
2197
- AND typeof(tag_id) IN ('integer', 'real')
2198
- AND typeof(queued_at) IN ('integer', 'real')
2199
- ) AS present`);
2200
- hasPendingDropOpsStatements.set(db, statement);
2201
- }
2202
- return statement.get(sessionId).present === 1;
2203
- }
2204
- function getPendingOpsCount(db, sessionId) {
2205
- try {
2206
- let statement = getPendingOpsCountStatements.get(db);
2207
- if (!statement) {
2208
- statement = db.prepare("SELECT COUNT(*) AS count FROM pending_ops WHERE session_id = ?");
2209
- getPendingOpsCountStatements.set(db, statement);
2210
- }
2211
- const row = statement.get(sessionId);
2212
- return typeof row?.count === "number" && Number.isFinite(row.count) ? row.count : null;
2213
- } catch {
2214
- return null;
2215
- }
2216
- }
2217
- function clearPendingOps(db, sessionId) {
2218
- getClearPendingOpsStatement(db).run(sessionId);
2219
- }
2220
- function removePendingOp(db, sessionId, tagId) {
2221
- getRemovePendingOpStatement(db).run(sessionId, tagId);
2222
- }
2223
-
2224
- // src/features/magic-context/storage-tags.ts
2225
- var insertTagStatements = new WeakMap;
2226
- var updateTagStatusStatements = new WeakMap;
2227
- var updateTagDropModeStatements = new WeakMap;
2228
- var updateTagMessageIdStatements = new WeakMap;
2229
- var getTagNumbersByMessageIdStatements = new WeakMap;
2230
- var deleteTagsByMessageIdStatements = new WeakMap;
2231
- var getMaxTagNumberBySessionStatements = new WeakMap;
2232
- var getTagNumberByMessageIdStatements = new WeakMap;
2233
- var getAssignableTagNumberByMessageIdStatements = new WeakMap;
2234
- var hasPiFallbackMessageTagStatements = new WeakMap;
2235
- var WHITESPACE_ASSISTANT_INERT_MESSAGE_PREFIX = "__mc_whitespace_assistant_inert__:";
2236
- var WHITESPACE_ASSISTANT_INERT_FINGERPRINT_PREFIX = "mc:whitespace-assistant:";
2237
- function getInsertTagStatement(db) {
2238
- let stmt = insertTagStatements.get(db);
2239
- if (!stmt) {
2240
- stmt = db.prepare("INSERT INTO tags (session_id, message_id, type, byte_size, reasoning_byte_size, tag_number, tool_name, input_byte_size, harness, tool_owner_message_id, entry_fingerprint, token_count, input_token_count, reasoning_token_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
2241
- insertTagStatements.set(db, stmt);
2242
- }
2243
- return stmt;
2244
- }
2245
- function getUpdateTagStatusStatement(db) {
2246
- let stmt = updateTagStatusStatements.get(db);
2247
- if (!stmt) {
2248
- stmt = db.prepare("UPDATE tags SET status = ? WHERE session_id = ? AND tag_number = ?");
2249
- updateTagStatusStatements.set(db, stmt);
2250
- }
2251
- return stmt;
2252
- }
2253
- function getUpdateTagDropModeStatement(db) {
2254
- let stmt = updateTagDropModeStatements.get(db);
2255
- if (!stmt) {
2256
- stmt = db.prepare("UPDATE tags SET drop_mode = ? WHERE session_id = ? AND tag_number = ?");
2257
- updateTagDropModeStatements.set(db, stmt);
2258
- }
2259
- return stmt;
2260
- }
2261
- var updateTagByteSizeStatements = new WeakMap;
2262
- var updateTagInputByteSizeStatements = new WeakMap;
2263
- function getUpdateTagByteSizeStatement(db) {
2264
- let stmt = updateTagByteSizeStatements.get(db);
2265
- if (!stmt) {
2266
- stmt = db.prepare("UPDATE tags SET byte_size = ? WHERE session_id = ? AND tag_number = ?");
2267
- updateTagByteSizeStatements.set(db, stmt);
2268
- }
2269
- return stmt;
2270
- }
2271
- function updateTagByteSize2(db, sessionId, tagNumber, newByteSize) {
2272
- getUpdateTagByteSizeStatement(db).run(newByteSize, sessionId, tagNumber);
2273
- }
2274
- var RECENT_OWNER_SCAN_PAGE_SIZE = 128;
2275
- var recentTagOwnerStatements = new WeakMap;
2276
- function ownerMessageIdForTagRow(row) {
2277
- if (row.type === "tool") {
2278
- return row.tool_owner_message_id ?? row.message_id;
2279
- }
2280
- return contentTagOwnerMessageId(row.message_id);
2281
- }
2282
- function getRecentTagOwnerStatement(db) {
2283
- let statement = recentTagOwnerStatements.get(db);
2284
- if (!statement) {
2285
- statement = db.prepare(`SELECT type, message_id, tool_owner_message_id
2286
- FROM tags
2287
- WHERE session_id = ?
2288
- ORDER BY tag_number DESC, id DESC
2289
- LIMIT ? OFFSET ?`);
2290
- recentTagOwnerStatements.set(db, statement);
2291
- }
2292
- return statement;
2293
- }
2294
- function getRecentTagOwnerMessageIds2(db, sessionId, maxOwners) {
2295
- const recent = new Set;
2296
- if (!Number.isFinite(maxOwners) || maxOwners <= 0)
2297
- return recent;
2298
- const statement = getRecentTagOwnerStatement(db);
2299
- let offset = 0;
2300
- while (recent.size < maxOwners) {
2301
- const rows = statement.all(sessionId, RECENT_OWNER_SCAN_PAGE_SIZE, offset);
2302
- for (const row of rows) {
2303
- if (typeof row.type !== "string" || typeof row.message_id !== "string")
2304
- continue;
2305
- const ownerId = row.type === "tool" ? typeof row.tool_owner_message_id === "string" ? row.tool_owner_message_id : null : contentTagOwnerMessageId(row.message_id);
2306
- if (!ownerId || recent.has(ownerId))
2307
- continue;
2308
- recent.add(ownerId);
2309
- if (recent.size >= maxOwners)
2310
- break;
2311
- }
2312
- if (rows.length < RECENT_OWNER_SCAN_PAGE_SIZE)
2313
- break;
2314
- offset += rows.length;
2315
- }
2316
- return recent;
2317
- }
2318
- function getActiveTagTokenAggregate2(db, sessionId, protectedCutoff = null) {
2319
- const toolOutputExpr = protectedCutoff !== null ? `COALESCE(SUM(CASE WHEN type = 'tool' AND tag_number < ? THEN COALESCE(token_count, 0) ELSE 0 END), 0)` : `COALESCE(SUM(CASE WHEN type = 'tool' THEN COALESCE(token_count, 0) ELSE 0 END), 0)`;
2320
- const sql = `SELECT
2321
- COALESCE(SUM(CASE WHEN type != 'tool' THEN COALESCE(token_count, 0) ELSE 0 END), 0)
2322
- + COALESCE(SUM(COALESCE(reasoning_token_count, 0)), 0) AS conversation,
2323
- COALESCE(SUM(CASE WHEN type = 'tool' THEN COALESCE(token_count, 0) + COALESCE(input_token_count, 0) ELSE 0 END), 0) AS tool_call,
2324
- ${toolOutputExpr} AS tool_output,
2325
- COALESCE(SUM(CASE WHEN token_count IS NULL THEN 1 ELSE 0 END), 0) AS null_count
2326
- FROM tags
2327
- WHERE session_id = ? AND status = 'active'`;
2328
- const params = protectedCutoff !== null ? [protectedCutoff, sessionId] : [sessionId];
2329
- const row = db.prepare(sql).get(...params);
2330
- return {
2331
- conversation: row?.conversation ?? 0,
2332
- toolCall: row?.tool_call ?? 0,
2333
- toolOutput: row?.tool_output ?? 0,
2334
- nullCount: row?.null_count ?? 0
2335
- };
2336
- }
2337
- var RECLAIM_HINT_EXCLUDED_TOOLS = new Set([
2338
- "ask",
2339
- "bash_kill",
2340
- "bash_status",
2341
- "board",
2342
- "task",
2343
- "todoread",
2344
- "todowrite",
2345
- "work"
2346
- ]);
2347
- var AGE_RECLAIM_MIN_TOKENS2 = 250;
2348
- function isReclaimHintExcludedTool(toolName) {
2349
- if (!toolName)
2350
- return false;
2351
- const normalized = toolName.toLowerCase().replace(/^mcp_/, "");
2352
- return normalized.startsWith("ctx_") || RECLAIM_HINT_EXCLUDED_TOOLS.has(normalized);
2353
- }
2354
- function getOldestActiveUnprotectedToolTags2(db, sessionId, protectedTagNumbers = new Set, limit = 4) {
2355
- if (limit <= 0)
2356
- return [];
2357
- const boundedLimit = Math.max(1, Math.min(10, Math.floor(limit)));
2358
- const valueFloor = `AND (
2359
- (token_count IS NULL AND input_token_count IS NULL)
2360
- OR (COALESCE(token_count, 0) + COALESCE(input_token_count, 0)) >= ?
2361
- )`;
2362
- const params = [sessionId, AGE_RECLAIM_MIN_TOKENS2];
2363
- const rows = db.prepare(`SELECT tag_number, tool_name
2364
- FROM tags
2365
- WHERE session_id = ? AND status = 'active' AND type = 'tool'
2366
- AND NOT EXISTS (
2367
- SELECT 1 FROM pending_ops
2368
- WHERE pending_ops.session_id = tags.session_id
2369
- AND pending_ops.tag_id = tags.tag_number
2370
- AND pending_ops.operation = 'drop'
2371
- )
2372
- ${valueFloor}
2373
- ORDER BY tag_number ASC, id ASC`).all(...params);
2374
- return rows.filter((row) => typeof row.tag_number === "number").map((row) => ({
2375
- tagNumber: row.tag_number,
2376
- toolName: typeof row.tool_name === "string" ? row.tool_name : null
2377
- })).filter((tag) => !protectedTagNumbers.has(tag.tagNumber) && !isReclaimHintExcludedTool(tag.toolName)).sort((left, right) => resolveToolTier(right.toolName) - resolveToolTier(left.toolName) || left.tagNumber - right.tagNumber).slice(0, boundedLimit);
2378
- }
2379
- var getActiveToolTagsForAgeReclaimStatements = new WeakMap;
2380
- function getActiveToolTagsForAgeReclaim2(db, sessionId) {
2381
- let stmt = getActiveToolTagsForAgeReclaimStatements.get(db);
2382
- if (!stmt) {
2383
- stmt = db.prepare(`SELECT tag_number, tool_name, token_count, input_token_count
2384
- FROM tags
2385
- WHERE session_id = ? AND status = 'active' AND type = 'tool'
2386
- ORDER BY tag_number ASC, id ASC`);
2387
- getActiveToolTagsForAgeReclaimStatements.set(db, stmt);
2388
- }
2389
- const rows = stmt.all(sessionId);
2390
- const tags = rows.filter((row) => typeof row.tag_number === "number").map((row) => {
2391
- const outputTokens = typeof row.token_count === "number" ? row.token_count : null;
2392
- const inputTokens = typeof row.input_token_count === "number" ? row.input_token_count : null;
2393
- return {
2394
- tagNumber: row.tag_number,
2395
- toolName: typeof row.tool_name === "string" ? row.tool_name : null,
2396
- reclaimableTokens: outputTokens === null && inputTokens === null ? null : (outputTokens ?? 0) + (inputTokens ?? 0)
2397
- };
2398
- });
2399
- return tags;
2400
- }
2401
- function getTriggerTagTokenUpperBound2(db, sessionId, floor = 0) {
2402
- const sql = floor > 0 ? `SELECT
2403
- COALESCE(SUM(COALESCE(token_count, 0) + COALESCE(input_token_count, 0) + COALESCE(reasoning_token_count, 0)), 0) AS bound,
2404
- COALESCE(SUM(CASE WHEN token_count IS NULL THEN 1 ELSE 0 END), 0) AS null_count
2405
- FROM tags
2406
- WHERE session_id = ? AND status IN ('active', 'dropped') AND tag_number >= ?` : `SELECT
2407
- COALESCE(SUM(COALESCE(token_count, 0) + COALESCE(input_token_count, 0) + COALESCE(reasoning_token_count, 0)), 0) AS bound,
2408
- COALESCE(SUM(CASE WHEN token_count IS NULL THEN 1 ELSE 0 END), 0) AS null_count
2409
- FROM tags
2410
- WHERE session_id = ? AND status IN ('active', 'dropped')`;
2411
- const row = floor > 0 ? db.prepare(sql).get(sessionId, floor) : db.prepare(sql).get(sessionId);
2412
- return { bound: row?.bound ?? 0, nullCount: row?.null_count ?? 0 };
2413
- }
2414
- var scopedActiveTokenTotalStatements = new WeakMap;
2415
- function getActiveTagTokenTotalsByMessage2(db, sessionId, messageIds) {
2416
- if (messageIds?.length === 0)
2417
- return new Map;
2418
- const fields = "id, tag_number, type, message_id, tool_owner_message_id, token_count, input_token_count, reasoning_token_count".split(", ").map((field) => `tags.${field}`).join(", ");
2419
- let scoped = scopedActiveTokenTotalStatements.get(db);
2420
- if (messageIds && !scoped) {
2421
- scoped = db.prepare(`
2422
- SELECT ${fields} FROM json_each(?) AS owners
2423
- CROSS JOIN tags INDEXED BY idx_tags_session_message_id
2424
- WHERE session_id = ? AND tags.type != 'tool' AND +status = 'active'
2425
- AND message_id >= owners.value || ':' AND message_id < owners.value || ';'
2426
- UNION
2427
- SELECT ${fields} FROM tags INDEXED BY idx_tags_session_message_id
2428
- WHERE session_id = ? AND type != 'tool' AND +status = 'active'
2429
- AND message_id IN (SELECT value FROM json_each(?))
2430
- UNION
2431
- SELECT ${fields} FROM tags INDEXED BY idx_tags_pi_fallback_tool_owner
2432
- WHERE session_id = ? AND type = 'tool' AND +status = 'active'
2433
- AND tool_owner_message_id IN (SELECT value FROM json_each(?))
2434
- UNION
2435
- SELECT ${fields} FROM tags INDEXED BY idx_tags_session_message_id
2436
- WHERE session_id = ? AND type = 'tool' AND +status = 'active'
2437
- AND tool_owner_message_id IS NULL AND message_id IN (SELECT value FROM json_each(?))
2438
- ORDER BY tag_number, id`);
2439
- scopedActiveTokenTotalStatements.set(db, scoped);
2440
- }
2441
- const owners = messageIds ? new Set(messageIds) : undefined;
2442
- const encoded = owners ? JSON.stringify([...owners]) : "";
2443
- const rows = messageIds && scoped ? scoped.all(encoded, sessionId, sessionId, encoded, sessionId, encoded, sessionId, encoded) : db.prepare(`SELECT type, message_id, tool_owner_message_id, token_count, input_token_count, reasoning_token_count
2444
- FROM tags
2445
- WHERE session_id = ? AND status = 'active'`).all(sessionId);
2446
- const out = new Map;
2447
- for (const row of rows) {
2448
- const owner = ownerMessageIdForTagRow(row);
2449
- if (owners && !owners.has(owner))
2450
- continue;
2451
- let entry = out.get(owner);
2452
- if (!entry) {
2453
- entry = { conversation: 0, toolCall: 0, toolOutput: 0, hasNull: false };
2454
- out.set(owner, entry);
2455
- }
2456
- const reasoning = row.reasoning_token_count ?? 0;
2457
- if (row.type === "tool") {
2458
- const output = row.token_count ?? 0;
2459
- entry.toolCall += output + (row.input_token_count ?? 0);
2460
- entry.toolOutput += output;
2461
- } else {
2462
- entry.conversation += row.token_count ?? 0;
2463
- }
2464
- entry.conversation += reasoning;
2465
- if (row.token_count === null)
2466
- entry.hasNull = true;
2467
- }
2468
- return out;
2469
- }
2470
- var updateTagTokenCountStatements = new WeakMap;
2471
- var updateTagInputTokenCountStatements = new WeakMap;
2472
- function getUpdateTagTokenCountStatement(db) {
2473
- let stmt = updateTagTokenCountStatements.get(db);
2474
- if (!stmt) {
2475
- stmt = db.prepare("UPDATE tags SET token_count = MAX(COALESCE(token_count, 0), ?) WHERE session_id = ? AND tag_number = ?");
2476
- updateTagTokenCountStatements.set(db, stmt);
2477
- }
2478
- return stmt;
2479
- }
2480
- function updateTagTokenCount2(db, sessionId, tagNumber, newTokenCount) {
2481
- getUpdateTagTokenCountStatement(db).run(newTokenCount, sessionId, tagNumber);
2482
- }
2483
- function getPersistedToolTagAccounting2(db, sessionId, tagNumber) {
2484
- const row = db.prepare(`SELECT byte_size AS byteSize,
2485
- token_count AS tokenCount,
2486
- input_byte_size AS inputByteSize,
2487
- input_token_count AS inputTokenCount
2488
- FROM tags
2489
- WHERE session_id = ? AND tag_number = ? AND type = 'tool'`).get(sessionId, tagNumber);
2490
- if (!row || typeof row.byteSize !== "number" || row.tokenCount !== null && typeof row.tokenCount !== "number" || typeof row.inputByteSize !== "number" || row.inputTokenCount !== null && typeof row.inputTokenCount !== "number") {
2491
- return null;
2492
- }
2493
- return row;
2494
- }
2495
- function getAllStatusTagTokenTotalsFlat2(db, sessionId, floor = 0, calibration = { proseRatio: 1, toolsRatio: 1 }, ownerMessageIds) {
2496
- const columns = "type, message_id, tool_owner_message_id, token_count, input_token_count, reasoning_token_count";
2497
- const owners = ownerMessageIds ? new Set(ownerMessageIds) : undefined;
2498
- let scanOrder = "id";
2499
- if (owners) {
2500
- const planStatement = db.prepare(`EXPLAIN QUERY PLAN SELECT ${columns} FROM tags WHERE session_id = ?${floor > 0 ? " AND tag_number >= ?" : ""}`);
2501
- let plan;
2502
- try {
2503
- plan = planStatement.all(sessionId, ...floor > 0 ? [floor] : []);
2504
- } finally {
2505
- planStatement.finalize?.();
2506
- }
2507
- const index = plan.map((row) => /USING (?:COVERING )?INDEX (\S+)/.exec(row.detail)?.[1]).find(Boolean);
2508
- if (index) {
2509
- const keyStatement = db.prepare("SELECT name, coll, desc FROM pragma_index_xinfo(?) WHERE key = 1 ORDER BY seqno");
2510
- let keys;
2511
- try {
2512
- keys = keyStatement.all(index);
2513
- } finally {
2514
- keyStatement.finalize?.();
2515
- }
2516
- scanOrder = [
2517
- ...keys.map((key) => `"${(key.name ?? "id").replaceAll('"', '""')}" COLLATE "${key.coll.replaceAll('"', '""')}"${key.desc ? " DESC" : ""}`),
2518
- "id"
2519
- ].join(", ");
2520
- }
2521
- }
2522
- const rows = owners ? db.prepare(`SELECT ${columns} FROM tags WHERE id IN (
2523
- SELECT t.id FROM json_each(?) o CROSS JOIN tags t INDEXED BY idx_tags_session_message_id
2524
- ON t.session_id = ? AND t.message_id >= o.value AND t.message_id < o.value || ';'
2525
- UNION
2526
- SELECT t.id FROM json_each(?) o CROSS JOIN tags t INDEXED BY idx_tags_pi_fallback_tool_owner
2527
- ON t.session_id = ? AND t.tool_owner_message_id = o.value
2528
- WHERE t.type = 'tool'
2529
- ) AND tag_number >= ? ORDER BY ${scanOrder}`).all(JSON.stringify([...owners]), sessionId, JSON.stringify([...owners]), sessionId, floor) : floor > 0 ? db.prepare(`SELECT type, message_id, tool_owner_message_id, token_count, input_token_count, reasoning_token_count
2530
- FROM tags
2531
- WHERE session_id = ? AND tag_number >= ?`).all(sessionId, floor) : db.prepare(`SELECT type, message_id, tool_owner_message_id, token_count, input_token_count, reasoning_token_count
2532
- FROM tags
2533
- WHERE session_id = ?`).all(sessionId);
2534
- const totals = new Map;
2535
- const summaryRemovedTotals = new Map;
2536
- const nullMessageIds = new Set;
2537
- const nullSummaryRemovedMessageIds = new Set;
2538
- for (const row of rows) {
2539
- if (row.type === "tool" && row.tool_owner_message_id === null)
2540
- continue;
2541
- const owner = ownerMessageIdForTagRow(row);
2542
- if (owners && !owners.has(owner))
2543
- continue;
2544
- if (row.token_count === null) {
2545
- nullMessageIds.add(owner);
2546
- totals.delete(owner);
2547
- summaryRemovedTotals.delete(owner);
2548
- continue;
2549
- }
2550
- if (nullMessageIds.has(owner))
2551
- continue;
2552
- const ratio = row.type === "tool" ? calibration.toolsRatio : calibration.proseRatio;
2553
- const weight = ((row.token_count ?? 0) + (row.input_token_count ?? 0)) * ratio + (row.reasoning_token_count ?? 0) * calibration.proseRatio;
2554
- totals.set(owner, (totals.get(owner) ?? 0) + weight);
2555
- if (row.type === "tool" && row.input_token_count === null) {
2556
- nullSummaryRemovedMessageIds.add(owner);
2557
- summaryRemovedTotals.delete(owner);
2558
- }
2559
- if (!nullSummaryRemovedMessageIds.has(owner)) {
2560
- const removedWeight = row.type === "tool" ? (row.input_token_count ?? 0) * calibration.toolsRatio : row.type === "message" ? row.token_count * calibration.proseRatio : 0;
2561
- summaryRemovedTotals.set(owner, (summaryRemovedTotals.get(owner) ?? 0) + removedWeight);
2562
- }
2563
- }
2564
- return { totals, summaryRemovedTotals, nullMessageIds };
2565
- }
2566
- function getReasoningTokenEstimatesByMessage2(db, sessionId, proseRatio) {
2567
- const summary = readTagOwnerSummary(db, sessionId, proseRatio);
2568
- return summary.reasoningEstimatesByRatio.get(proseRatio) ?? new Map;
2569
- }
2570
- function tryGetReasoningTokenEstimatesByMessage2(db, sessionId, ratio) {
2571
- try {
2572
- return getReasoningTokenEstimatesByMessage2(db, sessionId, ratio);
2573
- } catch (error) {
2574
- if (error instanceof TagOwnerSummaryNotReady2)
2575
- return;
2576
- throw error;
2577
- }
2578
- }
2579
- function getMaxTagNumberByOwnerMessage2(db, sessionId) {
2580
- return readTagOwnerSummary(db, sessionId).maxTagByOwner;
2581
- }
2582
- var tagOwnerSummaries = new WeakMap;
2583
- var MAX_CACHED_PROSE_RATIOS = 4;
2584
- var TAG_OWNER_PAGE_LIMIT = 512;
2585
-
2586
- class TagOwnerSummaryNotReady2 extends Error {
2587
- constructor() {
2588
- super("tag owner summary needs off-thread preparation");
2589
- }
2590
- }
2591
- function scanTagOwnerSummary2(db, sessionId, ratio, ratios = []) {
2592
- db.exec("BEGIN");
2593
- try {
2594
- return readTagOwnerSummary(db, sessionId, ratio, ratios);
2595
- } finally {
2596
- db.exec("ROLLBACK");
2597
- }
2598
- }
2599
- function cachedTagOwnerRatios2(db, sessionId) {
2600
- return [...tagOwnerSummaries.get(db)?.get(sessionId)?.reasoningEstimatesByRatio.keys() ?? []];
2601
- }
2602
- function tagOwnerWarmupState2(db, sessionId) {
2603
- const cached = tagOwnerSummaries.get(db)?.get(sessionId);
2604
- if (!cached || cached.unownedToolRows.size > TAG_OWNER_PAGE_LIMIT)
2605
- return;
2606
- return {
2607
- dataVersion: cached.dataVersion,
2608
- generation: cached.generation,
2609
- schemaVersion: cached.schemaVersion,
2610
- globalLastRowId: cached.globalLastRowId,
2611
- lastRowId: cached.lastRowId,
2612
- rowCount: cached.rowCount,
2613
- identityRevision: cached.identityRevision,
2614
- unownedToolRows: new Set(cached.unownedToolRows)
2615
- };
2616
- }
2617
- function scanTagOwnerDelta2(db, sessionId, state) {
2618
- db.exec("BEGIN");
2619
- try {
2620
- const globalLastRowId = db.prepare("SELECT COALESCE(MAX(id), 0) AS id FROM tags").get().id;
2621
- if (globalLastRowId - state.globalLastRowId > TAG_OWNER_PAGE_LIMIT)
2622
- return null;
2623
- const rows = appendedSinceForeignCommit(db, sessionId, state);
2624
- if (!rows)
2625
- return null;
2626
- return { rows, adopted: adoptedSinceForeignCommit(db, state), globalLastRowId };
2627
- } finally {
2628
- db.exec("ROLLBACK");
2629
- }
2630
- }
2631
- function installTagOwnerDelta2(db, sessionId, state, delta, versions) {
2632
- const cached = tagOwnerSummaries.get(db)?.get(sessionId);
2633
- if (!cached || cached.rowCount !== state.rowCount || cached.globalLastRowId !== state.globalLastRowId || cached.identityRevision !== state.identityRevision || delta.rows.length > TAG_OWNER_PAGE_LIMIT || delta.adopted.length > TAG_OWNER_PAGE_LIMIT)
2634
- return false;
2635
- tagOwnerShapeChecks++;
2636
- tagOwnerRowsRead += delta.rows.length + delta.adopted.length;
2637
- for (const row of delta.rows)
2638
- foldTagOwnerRow(cached, row);
2639
- for (const row of delta.adopted)
2640
- foldTagOwnerRow(cached, row, false);
2641
- cached.globalLastRowId = delta.globalLastRowId;
2642
- cached.dataVersion = versions.dataVersion;
2643
- cached.schemaVersion = versions.schemaVersion;
2644
- cached.generation = versions.generation;
2645
- return true;
2646
- }
2647
- function installTagOwnerSummary2(db, sessionId, summary, versions, shapeChecked = false) {
2648
- if (shapeChecked)
2649
- tagOwnerShapeChecks++;
2650
- summary.dataVersion = versions.dataVersion;
2651
- summary.schemaVersion = versions.schemaVersion;
2652
- summary.generation = versions.generation;
2653
- const sessions = tagOwnerSummaries.get(db) ?? new Map;
2654
- sessions.set(sessionId, summary);
2655
- tagOwnerSummaries.set(db, sessions);
2656
- }
2657
- function isTagOwnerSummaryReady2(db, sessionId, ratio) {
2658
- try {
2659
- readTagOwnerSummary(db, sessionId, ratio);
2660
- return true;
2661
- } catch (error) {
2662
- if (error instanceof TagOwnerSummaryNotReady2)
2663
- return false;
2664
- throw error;
2665
- }
2666
- }
2667
- var tagOwnerRowsRead = 0;
2668
- var tagOwnerShapeChecks = 0;
2669
- function foldTagOwnerRow(summary, row, newRow = true) {
2670
- summary.lastRowId = Math.max(summary.lastRowId, row.id);
2671
- if (newRow)
2672
- summary.rowCount += 1;
2673
- if (row.type === "tool" && typeof row.tool_owner_message_id !== "string")
2674
- summary.unownedToolRows.add(row.id);
2675
- else
2676
- summary.unownedToolRows.delete(row.id);
2677
- const owner = row.type === "tool" ? typeof row.tool_owner_message_id === "string" ? row.tool_owner_message_id : null : typeof row.message_id === "string" ? contentTagOwnerMessageId(row.message_id) : null;
2678
- if (owner) {
2679
- summary.maxTagByOwner.set(owner, Math.max(summary.maxTagByOwner.get(owner) ?? 0, row.tag_number));
2680
- }
2681
- if (row.type !== "message" || row.reasoning_token_count === null)
2682
- return;
2683
- const reasoningOwner = ownerMessageIdForTagRow({
2684
- type: row.type,
2685
- message_id: row.message_id,
2686
- tool_owner_message_id: row.tool_owner_message_id
2687
- });
2688
- for (const [ratio, estimates] of summary.reasoningEstimatesByRatio) {
2689
- estimates.set(reasoningOwner, Math.max(estimates.get(reasoningOwner) ?? 0, row.reasoning_token_count * ratio));
2690
- }
2691
- }
2692
- var TAG_OWNER_COLUMNS = "id, type, message_id, tool_owner_message_id, tag_number, reasoning_token_count";
2693
- function connectionInTransaction(db) {
2694
- try {
2695
- const state = db;
2696
- return state.inTransaction !== false && state.isTransaction !== false;
2697
- } catch {
2698
- return true;
2699
- }
2700
- }
2701
- var TAG_OWNER_APPENDED_WITH_SHAPE_SQL = `SELECT ${TAG_OWNER_COLUMNS}, 0 AS shape, NULL AS tag_count, NULL AS max_id, NULL AS revision
2702
- FROM tags WHERE id > ? AND +session_id = ?
2703
- UNION ALL
2704
- SELECT NULL, NULL, NULL, NULL, NULL, NULL, 1, COUNT(*), MAX(id), (SELECT value FROM schema_migrations_meta WHERE key = ?)
2705
- FROM tags WHERE session_id = ?`;
2706
- function readTagIdentityRevision(db, sessionId) {
2707
- const row = db.prepare("SELECT value FROM schema_migrations_meta WHERE key = ?").get(tagIdentityRevisionKey(sessionId));
2708
- return typeof row?.value === "string" ? row.value : null;
2709
- }
2710
- function captureInitialTagOwnerRevision(db, sessionId, cached, appendedRows) {
2711
- if (cached.identityRevision !== null || appendedRows === 0)
2712
- return true;
2713
- const revision = readTagIdentityRevision(db, sessionId);
2714
- if (revision !== null && !/^[1-9]\d*:0$/.test(revision))
2715
- return false;
2716
- cached.identityRevision = revision;
2717
- return true;
2718
- }
2719
- function appendedSinceForeignCommit(db, sessionId, cached) {
2720
- tagOwnerShapeChecks += 1;
2721
- const rows = db.prepare(TAG_OWNER_APPENDED_WITH_SHAPE_SQL).all(cached.globalLastRowId, sessionId, tagIdentityRevisionKey(sessionId), sessionId);
2722
- const shape = rows.find((row) => row.shape === 1);
2723
- const appended = rows.filter((row) => row.shape === 0);
2724
- const highest = appended.reduce((max, row) => Math.max(max, row.id), cached.lastRowId);
2725
- if (!shape || (shape.revision ?? null) !== cached.identityRevision || shape.tag_count !== cached.rowCount + appended.length || (shape.max_id ?? 0) !== highest)
2726
- return null;
2727
- return appended;
2728
- }
2729
- function adoptedSinceForeignCommit(db, cached) {
2730
- if (cached.unownedToolRows.size === 0)
2731
- return [];
2732
- return db.prepare(`SELECT ${TAG_OWNER_COLUMNS} FROM tags
2733
- WHERE id IN (SELECT value FROM json_each(?)) AND tool_owner_message_id IS NOT NULL LIMIT ${TAG_OWNER_PAGE_LIMIT + 1}`).all(JSON.stringify([...cached.unownedToolRows]));
2734
- }
2735
- function readTagOwnerSummary(db, sessionId, proseRatio, extraRatios = []) {
2736
- const inTransaction = connectionInTransaction(db);
2737
- const versions = inTransaction ? null : db.prepare("SELECT data_version AS dataVersion, (SELECT schema_version FROM pragma_schema_version) AS schemaVersion FROM pragma_data_version").get();
2738
- const dataVersion = versions?.dataVersion ?? -1;
2739
- const schemaVersion = versions?.schemaVersion ?? -1;
2740
- const generation = getTagIdentityWriteGeneration2();
2741
- const offThreadOnly = isMainThread && Boolean(getSqliteDatabasePath2(db));
2742
- const sessions = tagOwnerSummaries.get(db) ?? new Map;
2743
- const cached = inTransaction ? undefined : sessions.get(sessionId);
2744
- if (cached && (cached.generation === generation || cached.identityRevision === readTagIdentityRevision(db, sessionId)) && cached.schemaVersion === schemaVersion && (proseRatio === undefined || cached.reasoningEstimatesByRatio.has(proseRatio))) {
2745
- let rows;
2746
- let globalLastRowId = db.prepare("SELECT COALESCE(MAX(id), 0) AS id FROM tags").get().id;
2747
- if (offThreadOnly && (globalLastRowId - cached.globalLastRowId > TAG_OWNER_PAGE_LIMIT || cached.dataVersion !== dataVersion && cached.unownedToolRows.size > TAG_OWNER_PAGE_LIMIT))
2748
- throw new TagOwnerSummaryNotReady2;
2749
- if (cached.dataVersion === dataVersion && cached.generation === generation) {
2750
- const statement = db.prepare(`SELECT ${TAG_OWNER_COLUMNS} FROM tags WHERE id > ? AND +session_id = ? ORDER BY id LIMIT ${TAG_OWNER_PAGE_LIMIT + 1}`);
2751
- rows = statement.all(cached.globalLastRowId, sessionId);
2752
- if (!offThreadOnly) {
2753
- let page = rows;
2754
- while (page.length === TAG_OWNER_PAGE_LIMIT + 1) {
2755
- page = statement.all(page[page.length - 1].id, sessionId);
2756
- rows.push(...page);
2757
- }
2758
- }
2759
- if (!captureInitialTagOwnerRevision(db, sessionId, cached, rows.length)) {
2760
- if (offThreadOnly)
2761
- throw new TagOwnerSummaryNotReady2;
2762
- rows = null;
2763
- }
2764
- } else {
2765
- if (offThreadOnly)
2766
- db.exec("BEGIN");
2767
- try {
2768
- globalLastRowId = db.prepare("SELECT COALESCE(MAX(id),0) AS id FROM tags").get().id;
2769
- if (offThreadOnly && globalLastRowId - cached.globalLastRowId > TAG_OWNER_PAGE_LIMIT)
2770
- throw new TagOwnerSummaryNotReady2;
2771
- rows = appendedSinceForeignCommit(db, sessionId, cached);
2772
- const adopted = rows ? adoptedSinceForeignCommit(db, cached) : [];
2773
- if (!rows || rows.length > TAG_OWNER_PAGE_LIMIT || adopted.length > TAG_OWNER_PAGE_LIMIT) {
2774
- if (offThreadOnly)
2775
- throw new TagOwnerSummaryNotReady2;
2776
- } else if (offThreadOnly) {
2777
- tagOwnerRowsRead += rows.length + adopted.length;
2778
- for (const row of rows)
2779
- foldTagOwnerRow(cached, row);
2780
- for (const row of adopted)
2781
- foldTagOwnerRow(cached, row, false);
2782
- cached.dataVersion = dataVersion;
2783
- cached.generation = generation;
2784
- cached.globalLastRowId = globalLastRowId;
2785
- return cached;
2786
- }
2787
- } finally {
2788
- if (offThreadOnly)
2789
- db.exec("ROLLBACK");
2790
- }
2791
- }
2792
- if (rows) {
2793
- const adopted = cached.dataVersion === dataVersion ? [] : adoptedSinceForeignCommit(db, cached);
2794
- if (isMainThread && getSqliteDatabasePath2(db) && (rows.length > TAG_OWNER_PAGE_LIMIT || adopted.length > TAG_OWNER_PAGE_LIMIT))
2795
- throw new TagOwnerSummaryNotReady2;
2796
- tagOwnerRowsRead += rows.length + adopted.length;
2797
- for (const row of rows)
2798
- foldTagOwnerRow(cached, row);
2799
- for (const row of adopted)
2800
- foldTagOwnerRow(cached, row, false);
2801
- cached.dataVersion = dataVersion;
2802
- cached.generation = generation;
2803
- cached.globalLastRowId = globalLastRowId;
2804
- return cached;
2805
- }
2806
- }
2807
- if (isMainThread && getSqliteDatabasePath2(db))
2808
- throw new TagOwnerSummaryNotReady2;
2809
- const ratios = [
2810
- ...new Set([...cached?.reasoningEstimatesByRatio.keys() ?? [], ...extraRatios])
2811
- ];
2812
- if (proseRatio !== undefined && !ratios.includes(proseRatio))
2813
- ratios.push(proseRatio);
2814
- const summary = {
2815
- dataVersion,
2816
- schemaVersion,
2817
- generation,
2818
- lastRowId: 0,
2819
- globalLastRowId: db.prepare("SELECT COALESCE(MAX(id), 0) AS id FROM tags").get().id,
2820
- rowCount: 0,
2821
- unownedToolRows: new Set,
2822
- identityRevision: readTagIdentityRevision(db, sessionId),
2823
- maxTagByOwner: new Map,
2824
- reasoningEstimatesByRatio: new Map(ratios.slice(-MAX_CACHED_PROSE_RATIOS).map((ratio) => [ratio, new Map]))
2825
- };
2826
- const rows = db.prepare(`SELECT ${TAG_OWNER_COLUMNS} FROM tags WHERE session_id = ? ORDER BY id`).all(sessionId);
2827
- tagOwnerRowsRead += rows.length;
2828
- for (const row of rows)
2829
- foldTagOwnerRow(summary, row);
2830
- if (!inTransaction) {
2831
- sessions.set(sessionId, summary);
2832
- tagOwnerSummaries.set(db, sessions);
2833
- }
2834
- return summary;
2835
- }
2836
- function tagTokenCountIsNull2(db, sessionId, tagNumber) {
2837
- const row = db.prepare("SELECT token_count FROM tags WHERE session_id = ? AND tag_number = ?").get(sessionId, tagNumber);
2838
- return row != null && row.token_count === null;
2839
- }
2840
- function backfillTagTokenCounts2(db, sessionId, tagNumber, counts) {
2841
- db.prepare(`UPDATE tags
2842
- SET token_count = CASE WHEN ? IS NOT NULL THEN MAX(COALESCE(token_count, 0), ?) ELSE token_count END,
2843
- input_token_count = ?,
2844
- reasoning_token_count = ?
2845
- WHERE session_id = ? AND tag_number = ? AND token_count IS NULL`).run(counts.tokenCount ?? null, counts.tokenCount ?? null, counts.inputTokenCount ?? null, counts.reasoningTokenCount ?? null, sessionId, tagNumber);
2846
- }
2847
- function getUpdateTagMessageIdStatement(db) {
2848
- let stmt = updateTagMessageIdStatements.get(db);
2849
- if (!stmt) {
2850
- stmt = db.prepare(`UPDATE tags SET message_id = ?
2851
- WHERE session_id = ?
2852
- AND tag_number = ?
2853
- AND message_id NOT LIKE '${WHITESPACE_ASSISTANT_INERT_MESSAGE_PREFIX}%'`);
2854
- updateTagMessageIdStatements.set(db, stmt);
2855
- }
2856
- return stmt;
2857
- }
2858
- function getTagNumbersByMessageIdStatement(db) {
2859
- let stmt = getTagNumbersByMessageIdStatements.get(db);
2860
- if (!stmt) {
2861
- stmt = db.prepare("SELECT tag_number FROM tags WHERE session_id = ? AND (message_id = ? OR message_id LIKE ? ESCAPE '\\' OR message_id LIKE ? ESCAPE '\\' OR message_id LIKE ? ESCAPE '\\') ORDER BY tag_number ASC");
2862
- getTagNumbersByMessageIdStatements.set(db, stmt);
2863
- }
2864
- return stmt;
2865
- }
2866
- function getDeleteTagsByMessageIdStatement(db) {
2867
- let stmt = deleteTagsByMessageIdStatements.get(db);
2868
- if (!stmt) {
2869
- stmt = db.prepare("DELETE FROM tags WHERE session_id = ? AND (message_id = ? OR message_id LIKE ? ESCAPE '\\' OR message_id LIKE ? ESCAPE '\\' OR message_id LIKE ? ESCAPE '\\')");
2870
- deleteTagsByMessageIdStatements.set(db, stmt);
2871
- }
2872
- return stmt;
2873
- }
2874
- function getMaxTagNumberBySessionStatement(db) {
2875
- let stmt = getMaxTagNumberBySessionStatements.get(db);
2876
- if (!stmt) {
2877
- stmt = db.prepare("SELECT COALESCE(MAX(tag_number), 0) AS max_tag_number FROM tags WHERE session_id = ?");
2878
- getMaxTagNumberBySessionStatements.set(db, stmt);
2879
- }
2880
- return stmt;
2881
- }
2882
- function getTagNumberByMessageIdStatement(db) {
2883
- let stmt = getTagNumberByMessageIdStatements.get(db);
2884
- if (!stmt) {
2885
- stmt = db.prepare("SELECT tag_number FROM tags INDEXED BY idx_tags_session_message_id WHERE session_id = ? AND message_id = ? ORDER BY tag_number ASC LIMIT 1");
2886
- getTagNumberByMessageIdStatements.set(db, stmt);
2887
- }
2888
- return stmt;
2889
- }
2890
- function getAssignableTagNumberByMessageIdStatement(db) {
2891
- let stmt = getAssignableTagNumberByMessageIdStatements.get(db);
2892
- if (!stmt) {
2893
- stmt = db.prepare(`SELECT tag_number FROM tags INDEXED BY idx_tags_session_message_id
2894
- WHERE session_id = ?
2895
- AND message_id = ?
2896
- AND NOT (
2897
- status = 'compacted'
2898
- AND COALESCE(
2899
- entry_fingerprint LIKE '${WHITESPACE_ASSISTANT_INERT_FINGERPRINT_PREFIX}%',
2900
- 0
2901
- ) = 1
2902
- )
2903
- ORDER BY tag_number ASC
2904
- LIMIT 1`);
2905
- getAssignableTagNumberByMessageIdStatements.set(db, stmt);
2906
- }
2907
- return stmt;
2908
- }
2909
- function isTagRow(row) {
2910
- if (row === null || typeof row !== "object")
2911
- return false;
2912
- const r = row;
2913
- return typeof r.id === "number" && typeof r.message_id === "string" && typeof r.type === "string" && typeof r.status === "string" && typeof r.byte_size === "number" && typeof r.session_id === "string" && typeof r.tag_number === "number";
2914
- }
2915
- function toTagEntry(row) {
2916
- const type = row.type === "tool" ? "tool" : row.type === "file" ? "file" : "message";
2917
- const status = row.status === "dropped" || row.status === "compacted" ? row.status : "active";
2918
- return {
2919
- id: row.id,
2920
- tagNumber: row.tag_number,
2921
- messageId: row.message_id,
2922
- type,
2923
- status,
2924
- dropMode: row.drop_mode === "truncated" ? "truncated" : row.drop_mode === "skeleton_real" ? "skeleton_real" : row.drop_mode === "skeleton_stripped" ? "skeleton_stripped" : row.drop_mode === "edit_marker" ? "edit_marker" : row.drop_mode === "edit_marker_stripped" ? "edit_marker_stripped" : "full",
2925
- toolName: row.tool_name ?? null,
2926
- inputByteSize: row.input_byte_size ?? 0,
2927
- byteSize: row.byte_size,
2928
- reasoningByteSize: row.reasoning_byte_size ?? 0,
2929
- sessionId: row.session_id,
2930
- cavemanDepth: typeof row.caveman_depth === "number" && Number.isFinite(row.caveman_depth) ? row.caveman_depth : 0,
2931
- toolOwnerMessageId: typeof row.tool_owner_message_id === "string" ? row.tool_owner_message_id : null,
2932
- tokenCount: typeof row.token_count === "number" ? row.token_count : null
2933
- };
2934
- }
2935
- function isTagNumberRow(row) {
2936
- if (row === null || typeof row !== "object")
2937
- return false;
2938
- const r = row;
2939
- return typeof r.tag_number === "number";
2940
- }
2941
- function isMaxTagNumberRow(row) {
2942
- if (row === null || typeof row !== "object")
2943
- return false;
2944
- const r = row;
2945
- return typeof r.max_tag_number === "number";
2946
- }
2947
- function escapeLikePattern(value) {
2948
- return value.replaceAll("\\", "\\\\").replaceAll("%", "\\%").replaceAll("_", "\\_");
2949
- }
2950
- function insertTag2(db, sessionId, messageId, type, byteSize, tagNumber, reasoningByteSize = 0, toolName = null, inputByteSize = 0, toolOwnerMessageId = null, entryFingerprint = null, tokenCounts = null) {
2951
- getInsertTagStatement(db).run(sessionId, messageId, type, byteSize, reasoningByteSize, tagNumber, toolName, inputByteSize, getHarness2(), toolOwnerMessageId, entryFingerprint, tokenCounts?.tokenCount ?? null, tokenCounts?.inputTokenCount ?? null, tokenCounts?.reasoningTokenCount ?? null);
2952
- return tagNumber;
2953
- }
2954
- function updateTagStatus2(db, sessionId, tagId, status) {
2955
- getUpdateTagStatusStatement(db).run(status, sessionId, tagId);
2956
- }
2957
- var droppedTagStatements = new WeakMap;
2958
- function markTagDropped2(db, sessionId, tagId, mode) {
2959
- if (!mode) {
2960
- updateTagStatus2(db, sessionId, tagId, "dropped");
2961
- return;
2962
- }
2963
- let statement = droppedTagStatements.get(db);
2964
- if (!statement) {
2965
- statement = db.prepare("UPDATE tags SET status = ?, drop_mode = ? WHERE session_id = ? AND tag_number = ?");
2966
- droppedTagStatements.set(db, statement);
2967
- }
2968
- statement.run("dropped", mode, sessionId, tagId);
2969
- }
2970
- function markWhitespaceAssistantTagInert2(db, sessionId, tagNumber, contentId) {
2971
- db.prepare(`UPDATE tags
2972
- SET status = 'compacted',
2973
- message_id = ?,
2974
- entry_fingerprint = ?
2975
- WHERE session_id = ? AND tag_number = ? AND type = 'message'`).run(`${WHITESPACE_ASSISTANT_INERT_MESSAGE_PREFIX}${tagNumber}`, `${WHITESPACE_ASSISTANT_INERT_FINGERPRINT_PREFIX}${contentId}`, sessionId, tagNumber);
2976
- }
2977
- var inertWhitespaceStatements = new WeakMap;
2978
- function getInertWhitespaceAssistantTags2(db, sessionId, messageIds) {
2979
- if (messageIds) {
2980
- let statement = inertWhitespaceStatements.get(db);
2981
- if (!statement) {
2982
- statement = db.prepare(`SELECT tag_number AS tagNumber, entry_fingerprint AS entryFingerprint
2983
- FROM json_each(?) AS owners CROSS JOIN tags
2984
- WHERE tags.session_id = ? AND tags.type = 'message' AND tags.status = 'compacted'
2985
- AND entry_fingerprint >= ? || owners.value || ':p'
2986
- AND entry_fingerprint < ? || owners.value || ':q'
2987
- ORDER BY CAST(owners.key AS INTEGER), entry_fingerprint, tags.id`);
2988
- inertWhitespaceStatements.set(db, statement);
2989
- }
2990
- const rows = statement.all(JSON.stringify([...new Set(messageIds)]), sessionId, WHITESPACE_ASSISTANT_INERT_FINGERPRINT_PREFIX, WHITESPACE_ASSISTANT_INERT_FINGERPRINT_PREFIX);
2991
- return rows.map((row) => ({
2992
- tagNumber: row.tagNumber,
2993
- contentId: row.entryFingerprint.slice(WHITESPACE_ASSISTANT_INERT_FINGERPRINT_PREFIX.length)
2994
- }));
2995
- }
2996
- const rows = db.prepare(`SELECT tag_number AS tagNumber, entry_fingerprint AS entryFingerprint
2997
- FROM tags
2998
- WHERE session_id = ?
2999
- AND type = 'message'
3000
- AND status = 'compacted'
3001
- AND entry_fingerprint LIKE ?`).all(sessionId, `${WHITESPACE_ASSISTANT_INERT_FINGERPRINT_PREFIX}%`);
3002
- return rows.flatMap((row) => {
3003
- const contentId = row.entryFingerprint.slice(WHITESPACE_ASSISTANT_INERT_FINGERPRINT_PREFIX.length);
3004
- return contentId.length > 0 ? [{ tagNumber: row.tagNumber, contentId }] : [];
3005
- });
3006
- }
3007
- var inertWhitespaceByNumberStatements = new WeakMap;
3008
- function getInertWhitespaceAssistantTagsByNumbers2(db, sessionId, tagNumbers) {
3009
- if (tagNumbers.length === 0)
3010
- return [];
3011
- let statement = inertWhitespaceByNumberStatements.get(db);
3012
- if (!statement) {
3013
- statement = db.prepare(`SELECT tags.tag_number AS tagNumber, tags.entry_fingerprint AS entryFingerprint
3014
- FROM json_each(?) AS wanted CROSS JOIN tags
3015
- WHERE tags.session_id = ?
3016
- AND tags.tag_number = wanted.value
3017
- AND tags.type = 'message'
3018
- AND tags.status = 'compacted'
3019
- AND tags.entry_fingerprint LIKE ?
3020
- ORDER BY tags.tag_number, tags.id`);
3021
- inertWhitespaceByNumberStatements.set(db, statement);
3022
- }
3023
- const rows = statement.all(JSON.stringify([...new Set(tagNumbers)]), sessionId, `${WHITESPACE_ASSISTANT_INERT_FINGERPRINT_PREFIX}%`);
3024
- return rows.flatMap((row) => {
3025
- const contentId = row.entryFingerprint.slice(WHITESPACE_ASSISTANT_INERT_FINGERPRINT_PREFIX.length);
3026
- return contentId.length > 0 ? [{ tagNumber: row.tagNumber, contentId }] : [];
3027
- });
3028
- }
3029
- function updateTagDropMode2(db, sessionId, tagNumber, dropMode) {
3030
- getUpdateTagDropModeStatement(db).run(dropMode, sessionId, tagNumber);
3031
- }
3032
- function updateCavemanDepth2(db, sessionId, tagNumber, depth) {
3033
- db.prepare("UPDATE tags SET caveman_depth = ? WHERE session_id = ? AND tag_number = ?").run(depth, sessionId, tagNumber);
3034
- }
3035
- function updateTagMessageId2(db, sessionId, tagId, messageId) {
3036
- getUpdateTagMessageIdStatement(db).run(messageId, sessionId, tagId);
3037
- }
3038
- function hasPiFallbackMessageTags2(db, sessionId) {
3039
- let statement = hasPiFallbackMessageTagStatements.get(db);
3040
- if (!statement) {
3041
- statement = db.prepare(`SELECT 1
3042
- FROM tags
3043
- WHERE session_id = ?
3044
- AND type = 'message'
3045
- AND message_id LIKE 'pi-msg-%'
3046
- LIMIT 1`);
3047
- hasPiFallbackMessageTagStatements.set(db, statement);
3048
- }
3049
- return statement.get(sessionId) != null;
3050
- }
3051
- function findAdoptableFallbackTags2(db, sessionId, entryFingerprint) {
3052
- const rows = db.prepare(`SELECT tag_number AS tagNumber, message_id AS messageId
3053
- FROM tags
3054
- WHERE session_id = ?
3055
- AND type = 'message'
3056
- AND entry_fingerprint = ?
3057
- AND message_id LIKE 'pi-msg-%'`).all(sessionId, entryFingerprint);
3058
- return rows;
3059
- }
3060
- function adoptFallbackTagMessageId2(db, sessionId, tagNumber, oldFallbackMessageId, newRealMessageId) {
3061
- if (oldFallbackMessageId.startsWith(WHITESPACE_ASSISTANT_INERT_MESSAGE_PREFIX))
3062
- return false;
3063
- const result = db.prepare(`UPDATE tags SET message_id = ?
3064
- WHERE session_id = ? AND tag_number = ? AND message_id = ?`).run(newRealMessageId, sessionId, tagNumber, oldFallbackMessageId);
3065
- return (result.changes ?? 0) > 0;
3066
- }
3067
- function isPiFallbackToolOwnerTag(row) {
3068
- if (row === null || typeof row !== "object")
3069
- return false;
3070
- const r = row;
3071
- return typeof r.tagNumber === "number" && typeof r.callId === "string" && typeof r.toolOwnerMessageId === "string" && typeof r.status === "string";
3072
- }
3073
- function isPiFallbackFoldTagRow(row) {
3074
- if (row === null || typeof row !== "object")
3075
- return false;
3076
- const r = row;
3077
- return typeof r.tagNumber === "number" && typeof r.messageId === "string" && (typeof r.toolOwnerMessageId === "string" || r.toolOwnerMessageId === null) && typeof r.type === "string" && typeof r.status === "string" && (typeof r.byteSize === "number" || r.byteSize === null) && (typeof r.reasoningByteSize === "number" || r.reasoningByteSize === null) && (typeof r.inputByteSize === "number" || r.inputByteSize === null) && (typeof r.tokenCount === "number" || r.tokenCount === null) && (typeof r.inputTokenCount === "number" || r.inputTokenCount === null) && (typeof r.reasoningTokenCount === "number" || r.reasoningTokenCount === null);
3078
- }
3079
- function isPendingOpIdentityRow(row) {
3080
- if (row === null || typeof row !== "object")
3081
- return false;
3082
- const r = row;
3083
- return typeof r.id === "number" && typeof r.operation === "string";
3084
- }
3085
- function maxNullableNumber(a, b) {
3086
- if (typeof a === "number" && typeof b === "number")
3087
- return Math.max(a, b);
3088
- if (typeof a === "number")
3089
- return a;
3090
- if (typeof b === "number")
3091
- return b;
3092
- return null;
3093
- }
3094
- function getPiFallbackFoldTagRowByNumber(db, sessionId, tagNumber) {
3095
- const row = db.prepare(`SELECT tag_number AS tagNumber,
3096
- message_id AS messageId,
3097
- tool_owner_message_id AS toolOwnerMessageId,
3098
- type,
3099
- status,
3100
- byte_size AS byteSize,
3101
- reasoning_byte_size AS reasoningByteSize,
3102
- input_byte_size AS inputByteSize,
3103
- token_count AS tokenCount,
3104
- input_token_count AS inputTokenCount,
3105
- reasoning_token_count AS reasoningTokenCount
3106
- FROM tags
3107
- WHERE session_id = ? AND tag_number = ?`).get(sessionId, tagNumber);
3108
- return isPiFallbackFoldTagRow(row) ? row : null;
3109
- }
3110
- function getPiFallbackToolFoldTagRowByOwner(db, sessionId, callId, ownerMsgId) {
3111
- const row = db.prepare(`SELECT tag_number AS tagNumber,
3112
- message_id AS messageId,
3113
- tool_owner_message_id AS toolOwnerMessageId,
3114
- type,
3115
- status,
3116
- byte_size AS byteSize,
3117
- reasoning_byte_size AS reasoningByteSize,
3118
- input_byte_size AS inputByteSize,
3119
- token_count AS tokenCount,
3120
- input_token_count AS inputTokenCount,
3121
- reasoning_token_count AS reasoningTokenCount
3122
- FROM tags
3123
- WHERE session_id = ?
3124
- AND message_id = ?
3125
- AND type = 'tool'
3126
- AND tool_owner_message_id = ?
3127
- LIMIT 1`).get(sessionId, callId, ownerMsgId);
3128
- return isPiFallbackFoldTagRow(row) ? row : null;
3129
- }
3130
- function getPiFallbackMessageFoldTagRowsByMessageId(db, sessionId, messageId) {
3131
- return db.prepare(`SELECT tag_number AS tagNumber,
3132
- message_id AS messageId,
3133
- tool_owner_message_id AS toolOwnerMessageId,
3134
- type,
3135
- status,
3136
- byte_size AS byteSize,
3137
- reasoning_byte_size AS reasoningByteSize,
3138
- input_byte_size AS inputByteSize,
3139
- token_count AS tokenCount,
3140
- input_token_count AS inputTokenCount,
3141
- reasoning_token_count AS reasoningTokenCount
3142
- FROM tags
3143
- WHERE session_id = ?
3144
- AND message_id = ?
3145
- AND type = 'message'
3146
- ORDER BY tag_number ASC`).all(sessionId, messageId).filter(isPiFallbackFoldTagRow);
3147
- }
3148
- var foldStatements = new WeakMap;
3149
- function foldStatement(db, sql) {
3150
- let statements = foldStatements.get(db);
3151
- if (!statements) {
3152
- statements = new Map;
3153
- foldStatements.set(db, statements);
3154
- }
3155
- let statement = statements.get(sql);
3156
- if (!statement) {
3157
- statement = db.prepare(sql);
3158
- statements.set(sql, statement);
3159
- }
3160
- return statement;
3161
- }
3162
- function mergeSizeAndTokenColumnsIntoSurvivor(db, sessionId, survivor, duplicate) {
3163
- foldStatement(db, `UPDATE tags
3164
- SET byte_size = ?,
3165
- reasoning_byte_size = ?,
3166
- input_byte_size = ?,
3167
- token_count = ?,
3168
- input_token_count = ?,
3169
- reasoning_token_count = ?
3170
- WHERE session_id = ? AND tag_number = ?`).run(maxNullableNumber(survivor.byteSize, duplicate.byteSize), maxNullableNumber(survivor.reasoningByteSize, duplicate.reasoningByteSize), maxNullableNumber(survivor.inputByteSize, duplicate.inputByteSize), maxNullableNumber(survivor.tokenCount, duplicate.tokenCount), maxNullableNumber(survivor.inputTokenCount, duplicate.inputTokenCount), maxNullableNumber(survivor.reasoningTokenCount, duplicate.reasoningTokenCount), sessionId, survivor.tagNumber);
3171
- survivor.byteSize = maxNullableNumber(survivor.byteSize, duplicate.byteSize);
3172
- survivor.reasoningByteSize = maxNullableNumber(survivor.reasoningByteSize, duplicate.reasoningByteSize);
3173
- survivor.inputByteSize = maxNullableNumber(survivor.inputByteSize, duplicate.inputByteSize);
3174
- survivor.tokenCount = maxNullableNumber(survivor.tokenCount, duplicate.tokenCount);
3175
- survivor.inputTokenCount = maxNullableNumber(survivor.inputTokenCount, duplicate.inputTokenCount);
3176
- survivor.reasoningTokenCount = maxNullableNumber(survivor.reasoningTokenCount, duplicate.reasoningTokenCount);
3177
- }
3178
- function applyDroppedStatusIfNeeded(db, sessionId, survivor, duplicate) {
3179
- if (survivor.status === "dropped")
3180
- return;
3181
- if (duplicate.status !== "dropped")
3182
- return;
3183
- foldStatement(db, "UPDATE tags SET status = 'dropped' WHERE session_id = ? AND tag_number = ?").run(sessionId, survivor.tagNumber);
3184
- survivor.status = "dropped";
3185
- }
3186
- function retargetPendingOps(db, sessionId, fromTagNumber, toTagNumber) {
3187
- const rows = foldStatement(db, `SELECT id, operation
3188
- FROM pending_ops
3189
- WHERE session_id = ? AND tag_id = ?
3190
- ORDER BY id ASC`).all(sessionId, fromTagNumber).filter(isPendingOpIdentityRow);
3191
- for (const row of rows) {
3192
- const existing = foldStatement(db, `SELECT 1
3193
- FROM pending_ops
3194
- WHERE session_id = ? AND tag_id = ? AND operation = ?
3195
- LIMIT 1`).get(sessionId, toTagNumber, row.operation);
3196
- if (existing) {
3197
- foldStatement(db, "DELETE FROM pending_ops WHERE session_id = ? AND id = ?").run(sessionId, row.id);
3198
- } else {
3199
- foldStatement(db, "UPDATE pending_ops SET tag_id = ? WHERE session_id = ? AND id = ?").run(toTagNumber, sessionId, row.id);
3200
- }
3201
- }
3202
- foldStatement(db, "DELETE FROM pending_ops WHERE session_id = ? AND tag_id = ?").run(sessionId, fromTagNumber);
3203
- }
3204
- function deleteFoldedDuplicateTag(db, sessionId, tagNumber) {
3205
- foldStatement(db, "DELETE FROM source_contents WHERE session_id = ? AND tag_id = ?").run(sessionId, tagNumber);
3206
- foldStatement(db, "DELETE FROM tags WHERE session_id = ? AND tag_number = ?").run(sessionId, tagNumber);
3207
- foldStatement(db, "DELETE FROM pending_ops WHERE session_id = ? AND tag_id = ?").run(sessionId, tagNumber);
3208
- }
3209
- function foldDuplicateIntoSurvivor(db, sessionId, survivor, duplicate, duplicateMayHaveQueuedOps = true, propagateDroppedStatus = true) {
3210
- mergeSizeAndTokenColumnsIntoSurvivor(db, sessionId, survivor, duplicate);
3211
- if (propagateDroppedStatus)
3212
- applyDroppedStatusIfNeeded(db, sessionId, survivor, duplicate);
3213
- if (duplicateMayHaveQueuedOps) {
3214
- retargetPendingOps(db, sessionId, duplicate.tagNumber, survivor.tagNumber);
3215
- }
3216
- deleteFoldedDuplicateTag(db, sessionId, duplicate.tagNumber);
3217
- }
3218
- function readPartTagRowsByMessage(db, sessionId) {
3219
- const rows = db.prepare(`SELECT tag_number AS tagNumber,
3220
- message_id AS messageId,
3221
- tool_owner_message_id AS toolOwnerMessageId,
3222
- type,
3223
- status,
3224
- byte_size AS byteSize,
3225
- reasoning_byte_size AS reasoningByteSize,
3226
- input_byte_size AS inputByteSize,
3227
- token_count AS tokenCount,
3228
- input_token_count AS inputTokenCount,
3229
- reasoning_token_count AS reasoningTokenCount
3230
- FROM tags
3231
- WHERE session_id = ?
3232
- AND type = 'message'
3233
- ORDER BY tag_number ASC`).all(sessionId).filter(isPiFallbackFoldTagRow);
3234
- const byMessage = new Map;
3235
- for (const row of rows) {
3236
- const marker = row.messageId.lastIndexOf(":p");
3237
- if (marker < 0)
3238
- continue;
3239
- const suffix = row.messageId.slice(marker + 2);
3240
- if (!/^\d+$/.test(suffix))
3241
- continue;
3242
- const messageId = row.messageId.slice(0, marker);
3243
- const group = byMessage.get(messageId);
3244
- const entry = { ...row, partIndex: Number.parseInt(suffix, 10) };
3245
- if (group)
3246
- group.push(entry);
3247
- else
3248
- byMessage.set(messageId, [entry]);
3249
- }
3250
- for (const group of byMessage.values())
3251
- group.sort((a, b) => a.partIndex - b.partIndex);
3252
- return byMessage;
3253
- }
3254
- function readQueuedTagNumbers(db, sessionId) {
3255
- const rows = db.prepare("SELECT tag_id AS tagNumber, operation FROM pending_ops WHERE session_id = ? AND tag_id IS NOT NULL").all(sessionId);
3256
- const any = new Set;
3257
- const drop = new Set;
3258
- for (const row of rows) {
3259
- if (typeof row.tagNumber !== "number")
3260
- continue;
3261
- any.add(row.tagNumber);
3262
- if (row.operation === "drop")
3263
- drop.add(row.tagNumber);
3264
- }
3265
- return { any, drop };
3266
- }
3267
- function foldShrunkPartTags2(db, sessionId, messages) {
3268
- const result = {
3269
- foldedTagNumbers: [],
3270
- rekeyedTagNumbers: [],
3271
- discardedDropTagNumbers: []
3272
- };
3273
- if (messages.length === 0)
3274
- return result;
3275
- const rowsByMessage = readPartTagRowsByMessage(db, sessionId);
3276
- const queuedTags = readQueuedTagNumbers(db, sessionId);
3277
- const discardDrop = foldStatement(db, "DELETE FROM pending_ops WHERE session_id = ? AND tag_id = ? AND operation = 'drop'");
3278
- const rekey = foldStatement(db, "UPDATE tags SET message_id = ? WHERE session_id = ? AND tag_number = ? AND type = 'message'");
3279
- for (const { messageId, partCount } of messages) {
3280
- const rows = rowsByMessage.get(messageId) ?? [];
3281
- if (rows.length === 0)
3282
- continue;
3283
- const orphans = rows.filter((row) => row.partIndex >= partCount);
3284
- if (orphans.length === 0)
3285
- continue;
3286
- const queued = [
3287
- ...new Set(rows.map((row) => row.tagNumber).filter((tag) => queuedTags.drop.has(tag)))
3288
- ].sort((a, b) => a - b);
3289
- if (queued.length > 0 && queued.length < rows.length) {
3290
- for (const tagNumber of queued) {
3291
- discardDrop.run(sessionId, tagNumber);
3292
- result.discardedDropTagNumbers.push(tagNumber);
3293
- }
3294
- }
3295
- let survivor = rows.find((row) => row.partIndex < partCount) ?? null;
3296
- if (survivor === null) {
3297
- const lowest = orphans[0];
3298
- if (!lowest)
3299
- continue;
3300
- rekey.run(`${messageId}:p0`, sessionId, lowest.tagNumber);
3301
- result.rekeyedTagNumbers.push(lowest.tagNumber);
3302
- survivor = { ...lowest, messageId: `${messageId}:p0`, partIndex: 0 };
3303
- }
3304
- for (const orphan of orphans) {
3305
- if (orphan.tagNumber === survivor.tagNumber)
3306
- continue;
3307
- foldDuplicateIntoSurvivor(db, sessionId, survivor, orphan, queuedTags.any.has(orphan.tagNumber), false);
3308
- result.foldedTagNumbers.push(orphan.tagNumber);
3309
- }
3310
- }
3311
- result.discardedDropTagNumbers.sort((a, b) => a - b);
3312
- result.foldedTagNumbers.sort((a, b) => a - b);
3313
- return result;
3314
- }
3315
- function hasPiFallbackToolOwnerTags2(db, sessionId) {
3316
- const row = db.prepare(`SELECT 1
3317
- FROM tags
3318
- WHERE session_id = ?
3319
- AND type = 'tool'
3320
- AND tool_owner_message_id LIKE 'pi-msg-%'
3321
- LIMIT 1`).get(sessionId);
3322
- return row != null;
3323
- }
3324
- function findPiFallbackToolOwnerTags2(db, sessionId) {
3325
- return db.prepare(`SELECT tag_number AS tagNumber,
3326
- message_id AS callId,
3327
- tool_owner_message_id AS toolOwnerMessageId,
3328
- status
3329
- FROM json_each(?) prefix CROSS JOIN tags
3330
- WHERE session_id = ?
3331
- AND tags.type = 'tool'
3332
- AND tool_owner_message_id >= prefix.value
3333
- AND tool_owner_message_id < substr(prefix.value, 1, 6) || '.'
3334
- AND tool_owner_message_id LIKE 'pi-msg-%'
3335
- ORDER BY tag_number ASC`).all(PI_FALLBACK_PREFIXES_JSON, sessionId).filter(isPiFallbackToolOwnerTag);
3336
- }
3337
-
3338
- class PiTagIdentityConflictError extends Error {
3339
- code = "PI_TAG_IDENTITY_CONFLICT";
3340
- constructor(detail, kind = "tool") {
3341
- super(`Magic Context ${kind}-tag identity conflict: ${detail}. This turn was refused without sending raw history; resending alone will not repair it`);
3342
- this.name = "PiTagIdentityConflictError";
3343
- }
3344
- }
3345
- function selectPiTagSurvivor(rows, servedTagNumbers, cachedSurvivor, kind, rebuildingSurvivor) {
3346
- const served = rows.filter((row) => servedTagNumbers.has(row.tagNumber));
3347
- const cached = cachedSurvivor === undefined ? undefined : rows.find((row) => row.tagNumber === cachedSurvivor);
3348
- const rebuilding = rows.find((row) => row.tagNumber === rebuildingSurvivor);
3349
- if (cachedSurvivor !== undefined && !cached || served.length !== 1 && !cached && !rebuilding) {
3350
- throw new PiTagIdentityConflictError(served.length > 1 ? `Conflicting served Pi ${kind} tag numbers; no byte-safe cached survivor is proven` : `duplicate ${kind} tag identities have no proven served-byte survivor`, kind);
3351
- }
3352
- const kept = cached ?? rebuilding ?? served[0];
3353
- if (!kept)
3354
- throw new PiTagIdentityConflictError("no served survivor is proven", kind);
3355
- return kept;
3356
- }
3357
- function foldPiIdentityDuplicate(db, sessionId, kept, duplicate) {
3358
- const owesDrop = kept.status !== "dropped" && duplicate.status === "dropped";
3359
- foldDuplicateIntoSurvivor(db, sessionId, kept, duplicate, true, false);
3360
- if (owesDrop)
3361
- queuePendingOp(db, sessionId, kept.tagNumber, "drop");
3362
- }
3363
- function adoptPiFallbackToolOwnerTag2(db, sessionId, tagNumber, callId, oldOwnerMessageId, newOwnerMessageId, servedTagNumbers = new Set, cachedSurvivor, rebuildingSurvivor) {
3364
- const survivor = getPiFallbackFoldTagRowByNumber(db, sessionId, tagNumber);
3365
- if (survivor === null || survivor.type !== "tool" || survivor.messageId !== callId || survivor.toolOwnerMessageId !== oldOwnerMessageId) {
3366
- return { action: "skipped" };
3367
- }
3368
- const existing = getPiFallbackToolFoldTagRowByOwner(db, sessionId, callId, newOwnerMessageId);
3369
- if (existing === null) {
3370
- const result = db.prepare(`UPDATE tags
3371
- SET tool_owner_message_id = ?
3372
- WHERE session_id = ?
3373
- AND tag_number = ?
3374
- AND type = 'tool'
3375
- AND message_id = ?
3376
- AND tool_owner_message_id = ?`).run(newOwnerMessageId, sessionId, tagNumber, callId, oldOwnerMessageId);
3377
- return (result.changes ?? 0) > 0 ? { action: "rekeyed", tagNumber } : { action: "skipped" };
3378
- }
3379
- if (existing.tagNumber === tagNumber) {
3380
- return { action: "skipped" };
3381
- }
3382
- const kept = selectPiTagSurvivor([survivor, existing], servedTagNumbers, cachedSurvivor, "tool", rebuildingSurvivor);
3383
- if (kept.tagNumber === survivor.tagNumber) {
3384
- foldPiIdentityDuplicate(db, sessionId, survivor, existing);
3385
- db.prepare("UPDATE tags SET tool_owner_message_id = ? WHERE session_id = ? AND tag_number = ?").run(newOwnerMessageId, sessionId, tagNumber);
3386
- return { action: "folded", tagNumber, deletedTagNumbers: [existing.tagNumber] };
3387
- }
3388
- foldPiIdentityDuplicate(db, sessionId, existing, survivor);
3389
- return {
3390
- action: "folded",
3391
- tagNumber: existing.tagNumber,
3392
- deletedTagNumbers: [tagNumber]
3393
- };
3394
- }
3395
- function adoptPiFallbackMessageTag2(db, sessionId, tagNumber, oldFallbackMessageId, newRealMessageId, servedTagNumbers = new Set, cachedSurvivor, rebuildingSurvivor) {
3396
- if (oldFallbackMessageId.startsWith(WHITESPACE_ASSISTANT_INERT_MESSAGE_PREFIX)) {
3397
- return { action: "skipped" };
3398
- }
3399
- const survivor = getPiFallbackFoldTagRowByNumber(db, sessionId, tagNumber);
3400
- if (survivor === null || survivor.type !== "message" || survivor.messageId !== oldFallbackMessageId) {
3401
- return { action: "skipped" };
3402
- }
3403
- const duplicates = getPiFallbackMessageFoldTagRowsByMessageId(db, sessionId, newRealMessageId).filter((row) => row.tagNumber !== tagNumber);
3404
- if (duplicates.length === 0) {
3405
- const result = db.prepare(`UPDATE tags
3406
- SET message_id = ?
3407
- WHERE session_id = ?
3408
- AND tag_number = ?
3409
- AND type = 'message'
3410
- AND message_id = ?`).run(newRealMessageId, sessionId, tagNumber, oldFallbackMessageId);
3411
- return (result.changes ?? 0) > 0 ? { action: "rekeyed", tagNumber } : { action: "skipped" };
3412
- }
3413
- const realSurvivor = selectPiTagSurvivor([survivor, ...duplicates], servedTagNumbers, cachedSurvivor, "message", rebuildingSurvivor);
3414
- const deletedTagNumbers = [];
3415
- for (const duplicate of [survivor, ...duplicates]) {
3416
- if (duplicate.tagNumber === realSurvivor.tagNumber)
3417
- continue;
3418
- foldPiIdentityDuplicate(db, sessionId, realSurvivor, duplicate);
3419
- deletedTagNumbers.push(duplicate.tagNumber);
3420
- }
3421
- if (realSurvivor.tagNumber === tagNumber) {
3422
- db.prepare("UPDATE tags SET message_id = ? WHERE session_id = ? AND tag_number = ?").run(newRealMessageId, sessionId, tagNumber);
3423
- }
3424
- return {
3425
- action: "folded",
3426
- tagNumber: realSurvivor.tagNumber,
3427
- deletedTagNumbers
3428
- };
3429
- }
3430
- function markTagsCompactedByMessageIds2(db, sessionId, messageIds, eligibleTagNumbers) {
3431
- const ids = new Set(messageIds);
3432
- if (ids.size === 0 || eligibleTagNumbers?.size === 0)
3433
- return 0;
3434
- const asciiLower = (value) => value.replace(/[A-Z]/g, (char) => char.toLowerCase());
3435
- const foldedIds = new Set(Array.from(ids, asciiLower));
3436
- const nulPrefixes = new Set(Array.from(ids).filter((id) => id.includes("\x00")).map((id) => asciiLower(id.split("\x00")[0])));
3437
- const matches = (messageId, owner) => {
3438
- if (messageId !== null && ids.has(messageId))
3439
- return true;
3440
- if (owner !== null && ids.has(owner))
3441
- return true;
3442
- if (messageId === null)
3443
- return false;
3444
- const nul = messageId.indexOf("\x00");
3445
- const value = nul < 0 ? messageId : messageId.slice(0, nul);
3446
- if (nulPrefixes.size > 0 && nulPrefixes.has(asciiLower(value)))
3447
- return true;
3448
- for (let colon = value.indexOf(":");colon >= 0; colon = value.indexOf(":", colon + 1)) {
3449
- const suffix = value[colon + 1];
3450
- if ((suffix === "p" || suffix === "P" || asciiLower(value.slice(colon + 1, colon + 5)) === "file") && foldedIds.has(asciiLower(value.slice(0, colon))))
3451
- return true;
3452
- }
3453
- return false;
3454
- };
3455
- const rows = db.prepare(`WITH ids AS MATERIALIZED (
3456
- SELECT value AS source_id, lower(value) AS folded_id FROM json_each(?)
3457
- )
3458
- SELECT id, tag_number, message_id, tool_owner_message_id FROM tags INDEXED BY ${tagOrderConstraintIndex(db)}
3459
- WHERE session_id = ? ${eligibleTagNumbers ? "AND tag_number IN (SELECT value FROM json_each(?))" : ""}
3460
- AND status IN ('active', 'dropped') AND (
3461
- message_id IN (SELECT source_id FROM ids)
3462
- OR tool_owner_message_id IN (SELECT source_id FROM ids)
3463
- OR (instr(lower(message_id), ':p') > 0 AND
3464
- lower(substr(message_id, 1, instr(lower(message_id), ':p') - 1)) IN (SELECT folded_id FROM ids))
3465
- OR (instr(lower(message_id), ':file') > 0 AND
3466
- lower(substr(message_id, 1, instr(lower(message_id), ':file') - 1)) IN (SELECT folded_id FROM ids))
3467
- OR (? AND instr(message_id, ':') > 0)
3468
- OR ?
3469
- )`).all(JSON.stringify(Array.from(ids)), sessionId, ...eligibleTagNumbers ? [JSON.stringify([...eligibleTagNumbers])] : [], Array.from(ids).some((id) => id.includes(":")) ? 1 : 0, nulPrefixes.size > 0 ? 1 : 0);
3470
- const candidates = rows.filter((row) => (eligibleTagNumbers === undefined || eligibleTagNumbers.has(row.tag_number)) && matches(row.message_id, row.tool_owner_message_id));
3471
- if (candidates.length === 0)
3472
- return 0;
3473
- const update = db.prepare(`UPDATE tags SET status = 'compacted'
3474
- WHERE id = ? AND session_id = ?
3475
- AND status IN ('active', 'dropped')
3476
- AND message_id IS ? AND tool_owner_message_id IS ?
3477
- RETURNING tag_number`);
3478
- let cursor = 0;
3479
- let changed = 0;
3480
- const batch = db.transaction(() => {
3481
- const start = performance.now();
3482
- let processed = 0;
3483
- do {
3484
- const row = candidates[cursor++];
3485
- const retired = update.get(row.id, sessionId, row.message_id, row.tool_owner_message_id);
3486
- if (retired) {
3487
- removePendingOp(db, sessionId, retired.tag_number);
3488
- changed++;
3489
- }
3490
- processed++;
3491
- } while (cursor < candidates.length && processed < 128 && performance.now() - start < 8);
3492
- });
3493
- while (cursor < candidates.length)
3494
- batch.immediate();
3495
- return changed;
3496
- }
3497
- function deleteTagsByMessageId2(db, sessionId, messageId) {
3498
- const deleteTransaction = db.transaction(() => {
3499
- const escapedMessageId = escapeLikePattern(messageId);
3500
- const textPartPattern = `${escapedMessageId}:p%`;
3501
- const filePartPattern = `${escapedMessageId}:file%`;
3502
- const contentDerivedTextPattern = `${escapedMessageId}${escapeLikePattern(TEXT_TAG_IDENTITY_MARKER)}%`;
3503
- const messageScopedTags = getTagNumbersByMessageIdStatement(db).all(sessionId, messageId, textPartPattern, filePartPattern, contentDerivedTextPattern).filter(isTagNumberRow).map((row) => row.tag_number);
3504
- const ownerScopedTagNumbers = getOwnerScopedToolTagNumbers(db, sessionId, messageId);
3505
- if (messageScopedTags.length === 0 && ownerScopedTagNumbers.length === 0) {
3506
- return [];
3507
- }
3508
- if (messageScopedTags.length > 0) {
3509
- getDeleteTagsByMessageIdStatement(db).run(sessionId, messageId, textPartPattern, filePartPattern, contentDerivedTextPattern);
3510
- }
3511
- if (ownerScopedTagNumbers.length > 0) {
3512
- deleteToolTagsByOwner(db, sessionId, messageId);
3513
- }
3514
- const merged = new Set([...messageScopedTags, ...ownerScopedTagNumbers]);
3515
- return Array.from(merged).sort((a, b) => a - b);
3516
- });
3517
- return deleteTransaction.immediate();
3518
- }
3519
- var getOwnerScopedToolTagNumbersStatements = new WeakMap;
3520
- function getOwnerScopedToolTagNumbers(db, sessionId, ownerMsgId) {
3521
- let stmt = getOwnerScopedToolTagNumbersStatements.get(db);
3522
- if (!stmt) {
3523
- stmt = db.prepare("SELECT tag_number FROM tags WHERE session_id = ? AND type = 'tool' AND tool_owner_message_id = ? ORDER BY tag_number ASC");
3524
- getOwnerScopedToolTagNumbersStatements.set(db, stmt);
3525
- }
3526
- return stmt.all(sessionId, ownerMsgId).filter(isTagNumberRow).map((row) => row.tag_number);
3527
- }
3528
- function getMaxTagNumberBySession2(db, sessionId) {
3529
- const row = getMaxTagNumberBySessionStatement(db).get(sessionId);
3530
- return isMaxTagNumberRow(row) ? row.max_tag_number : 0;
3531
- }
3532
- function getTagNumberByMessageId2(db, sessionId, messageId) {
3533
- const row = getTagNumberByMessageIdStatement(db).get(sessionId, messageId);
3534
- return isTagNumberRow(row) ? row.tag_number : null;
3535
- }
3536
- function getAssignableTagNumberByMessageId2(db, sessionId, messageId) {
3537
- const row = getAssignableTagNumberByMessageIdStatement(db).get(sessionId, messageId);
3538
- return isTagNumberRow(row) ? row.tag_number : null;
3539
- }
3540
- var getMinMessageTagNumberForRawIdStatements = new WeakMap;
3541
- function isMinTagNumberRow(row) {
3542
- return row !== null && typeof row === "object" && "m" in row;
3543
- }
3544
- function getMinMessageTagNumberForRawId2(db, sessionId, rawId) {
3545
- if (rawId.includes(":"))
3546
- return null;
3547
- let stmt = getMinMessageTagNumberForRawIdStatements.get(db);
3548
- if (!stmt) {
3549
- stmt = db.prepare("SELECT MIN(tag_number) AS m FROM tags WHERE session_id = ? AND message_id >= ? AND message_id < ?");
3550
- getMinMessageTagNumberForRawIdStatements.set(db, stmt);
3551
- }
3552
- const row = stmt.get(sessionId, `${rawId}:`, `${rawId};`);
3553
- return isMinTagNumberRow(row) && typeof row.m === "number" ? row.m : null;
3554
- }
3555
- var TAGGER_FLOOR_SCAN_MESSAGES = 8;
3556
- var TAGGER_FLOOR_MAX_PROBES = 64;
3557
- var TAGGER_FLOOR_SAFETY_MARGIN = 256;
3558
- var TAGGER_FLOOR_PER_SKIP_MARGIN = 64;
3559
- function deriveTagLoadFloor2(db, sessionId, rawIds) {
3560
- let min = Number.POSITIVE_INFINITY;
3561
- let probes = 0;
3562
- let hits = 0;
3563
- let skippedBeforeFirstHit = 0;
3564
- for (const rawId of rawIds) {
3565
- if (typeof rawId !== "string" || rawId.length === 0)
3566
- continue;
3567
- if (probes >= TAGGER_FLOOR_MAX_PROBES)
3568
- break;
3569
- probes++;
3570
- const m = getMinMessageTagNumberForRawId2(db, sessionId, rawId);
3571
- if (m === null) {
3572
- if (hits === 0)
3573
- skippedBeforeFirstHit++;
3574
- continue;
3575
- }
3576
- if (m < min)
3577
- min = m;
3578
- if (++hits >= TAGGER_FLOOR_SCAN_MESSAGES)
3579
- break;
3580
- }
3581
- if (!Number.isFinite(min))
3582
- return 0;
3583
- const margin = TAGGER_FLOOR_SAFETY_MARGIN + skippedBeforeFirstHit * TAGGER_FLOOR_PER_SKIP_MARGIN;
3584
- return Math.max(0, min - margin);
3585
- }
3586
- var TAG_SELECT_COLUMNS2 = "id, message_id, type, status, drop_mode, tool_name, input_byte_size, byte_size, reasoning_byte_size, session_id, tag_number, caveman_depth, tool_owner_message_id, token_count";
3587
- function getTagsBySession2(db, sessionId) {
3588
- const rows = db.prepare(`SELECT ${TAG_SELECT_COLUMNS2} FROM tags WHERE session_id = ? ORDER BY tag_number ASC, id ASC`).all(sessionId).filter(isTagRow);
3589
- return rows.map(toTagEntry);
3590
- }
3591
- var getActiveTagsBySessionStatements = new WeakMap;
3592
- var getNullOwnerToolTagsBySessionStatements = new WeakMap;
3593
- var getDroppedTagsBySessionStatements = new WeakMap;
3594
- var getMaxDroppedTagNumberStatements = new WeakMap;
3595
- function getActiveTagsBySessionStatement(db) {
3596
- let stmt = getActiveTagsBySessionStatements.get(db);
3597
- if (!stmt) {
3598
- stmt = db.prepare(`SELECT ${TAG_SELECT_COLUMNS2} FROM tags WHERE session_id = ? AND status = 'active' ORDER BY tag_number ASC, id ASC`);
3599
- getActiveTagsBySessionStatements.set(db, stmt);
3600
- }
3601
- return stmt;
3602
- }
3603
- function getDroppedTagsBySessionStatement(db) {
3604
- let stmt = getDroppedTagsBySessionStatements.get(db);
3605
- if (!stmt) {
3606
- stmt = db.prepare(`SELECT ${TAG_SELECT_COLUMNS2} FROM tags WHERE session_id = ? AND status = 'dropped' ORDER BY tag_number ASC, id ASC`);
3607
- getDroppedTagsBySessionStatements.set(db, stmt);
3608
- }
3609
- return stmt;
3610
- }
3611
- function getMaxDroppedTagNumberStatement(db) {
3612
- let stmt = getMaxDroppedTagNumberStatements.get(db);
3613
- if (!stmt) {
3614
- stmt = db.prepare("SELECT COALESCE(MAX(tag_number), 0) AS max_tag_number FROM tags WHERE session_id = ? AND status = 'dropped'");
3615
- getMaxDroppedTagNumberStatements.set(db, stmt);
3616
- }
3617
- return stmt;
3618
- }
3619
- function getActiveTagsBySession2(db, sessionId) {
3620
- const rows = getActiveTagsBySessionStatement(db).all(sessionId).filter(isTagRow);
3621
- return rows.map(toTagEntry);
3622
- }
3623
- function getTailHygieneTags2(db, sessionId) {
3624
- const active = getActiveTagsBySession2(db, sessionId);
3625
- let orphanStatement = getNullOwnerToolTagsBySessionStatements.get(db);
3626
- if (!orphanStatement) {
3627
- orphanStatement = db.prepare(`SELECT ${TAG_SELECT_COLUMNS2} FROM tags
3628
- WHERE session_id = ? AND type = 'tool' AND tool_owner_message_id IS NULL
3629
- ORDER BY tag_number ASC, id ASC`);
3630
- getNullOwnerToolTagsBySessionStatements.set(db, orphanStatement);
3631
- }
3632
- const seen = new Set(active.map((tag) => `${tag.tagNumber}\x00${tag.messageId}\x00${tag.type}`));
3633
- for (const row of orphanStatement.all(sessionId).filter(isTagRow)) {
3634
- const orphan = toTagEntry(row);
3635
- const key = `${orphan.tagNumber}\x00${orphan.messageId}\x00${orphan.type}`;
3636
- if (!seen.has(key))
3637
- active.push(orphan);
3638
- }
3639
- return active;
3640
- }
3641
- function getDroppedTagsBySession2(db, sessionId, scope) {
3642
- const rows = (scope ? db.prepare(`SELECT ${TAG_SELECT_COLUMNS2} FROM tags INDEXED BY idx_tags_pi_fallback_tool_owner
3643
- WHERE session_id = ? AND type = 'tool' AND +status = 'dropped'
3644
- AND tool_owner_message_id IN (SELECT value FROM json_each(?))
3645
- UNION ALL
3646
- SELECT ${TAG_SELECT_COLUMNS2} FROM tags INDEXED BY idx_tags_session_message_id
3647
- WHERE session_id = ? AND type != 'tool' AND +status = 'dropped'
3648
- AND message_id IN (SELECT value FROM json_each(?))
3649
- ORDER BY tag_number ASC, id ASC`).all(sessionId, JSON.stringify(scope.ownerIds), sessionId, JSON.stringify(scope.messageAddresses)) : getDroppedTagsBySessionStatement(db).all(sessionId)).filter(isTagRow);
3650
- return rows.map(toTagEntry);
3651
- }
3652
- function getTagsForPendingOperations2(db, sessionId, pendingTagNumbers, protectedCount, recentToolWindow) {
3653
- const byNumber = new Map;
3654
- for (const tag of getTagsByNumbers2(db, sessionId, pendingTagNumbers)) {
3655
- byNumber.set(tag.tagNumber, tag);
3656
- }
3657
- const addRows = (sql, limit) => {
3658
- if (limit <= 0)
3659
- return;
3660
- const rows = db.prepare(sql).all(sessionId, limit).filter(isTagRow);
3661
- for (const row of rows) {
3662
- const tag = toTagEntry(row);
3663
- byNumber.set(tag.tagNumber, tag);
3664
- }
3665
- };
3666
- addRows(`SELECT ${TAG_SELECT_COLUMNS2} FROM tags
3667
- WHERE session_id = ? AND status = 'active'
3668
- ORDER BY tag_number DESC, id DESC LIMIT ?`, protectedCount);
3669
- addRows(`SELECT ${TAG_SELECT_COLUMNS2} FROM tags
3670
- WHERE session_id = ? AND type = 'tool'
3671
- ORDER BY tag_number DESC, id DESC LIMIT ?`, recentToolWindow);
3672
- return [...byNumber.values()].sort((left, right) => left.tagNumber - right.tagNumber);
3673
- }
3674
- function getTagsByNumbers2(db, sessionId, tagNumbers) {
3675
- if (tagNumbers.length === 0)
3676
- return [];
3677
- if (tagNumbers.length > 900) {
3678
- const all = [];
3679
- for (let i = 0;i < tagNumbers.length; i += 900) {
3680
- all.push(...getTagsByNumbers2(db, sessionId, tagNumbers.slice(i, i + 900)));
3681
- }
3682
- return all;
3683
- }
3684
- const placeholders = tagNumbers.map(() => "?").join(",");
3685
- const rows = db.prepare(`SELECT ${TAG_SELECT_COLUMNS2} FROM tags WHERE session_id = ? AND tag_number IN (${placeholders}) ORDER BY tag_number ASC, id ASC`).all(sessionId, ...tagNumbers).filter(isTagRow);
3686
- return rows.map(toTagEntry);
3687
- }
3688
- var newestToolTagNumberStatements = new WeakMap;
3689
- function getNewestToolTagNumbers2(db, sessionId, limit) {
3690
- if (limit <= 0)
3691
- return [];
3692
- let statement = newestToolTagNumberStatements.get(db);
3693
- if (!statement) {
3694
- statement = db.prepare(`SELECT tag_number FROM tags
3695
- WHERE session_id = ? AND +type = 'tool'
3696
- AND typeof(message_id) = 'text'
3697
- AND typeof(status) = 'text'
3698
- AND typeof(byte_size) IN ('integer', 'real')
3699
- AND typeof(tag_number) IN ('integer', 'real')
3700
- ORDER BY tag_number DESC
3701
- LIMIT ?`);
3702
- newestToolTagNumberStatements.set(db, statement);
3703
- }
3704
- return statement.all(sessionId, limit).map((row) => row.tag_number);
3705
- }
3706
- var droppedNumberStatements = new WeakMap;
3707
- function getDroppedTagsByNumbers2(db, sessionId, tagNumbers) {
3708
- if (tagNumbers.length === 0)
3709
- return [];
3710
- if (tagNumbers.length > 900) {
3711
- const all = [];
3712
- for (let i = 0;i < tagNumbers.length; i += 900) {
3713
- all.push(...getDroppedTagsByNumbers2(db, sessionId, tagNumbers.slice(i, i + 900)));
3714
- }
3715
- return all;
3716
- }
3717
- let statement = droppedNumberStatements.get(db);
3718
- if (!statement) {
3719
- statement = db.prepare(`SELECT ${TAG_SELECT_COLUMNS2} FROM tags WHERE session_id = ? AND status = 'dropped' AND tag_number IN (SELECT value FROM json_each(?)) ORDER BY tag_number ASC, id ASC`);
3720
- droppedNumberStatements.set(db, statement);
3721
- }
3722
- const rows = statement.all(sessionId, JSON.stringify(tagNumbers)).filter(isTagRow);
3723
- return rows.map(toTagEntry);
3724
- }
3725
- function getMaxDroppedTagNumber2(db, sessionId) {
3726
- const row = getMaxDroppedTagNumberStatement(db).get(sessionId);
3727
- return isMaxTagNumberRow(row) ? row.max_tag_number : 0;
3728
- }
3729
- var tagByIdStatements = new WeakMap;
3730
- function getTagById2(db, sessionId, tagId) {
3731
- let statement = tagByIdStatements.get(db);
3732
- if (!statement) {
3733
- statement = db.prepare(`SELECT ${TAG_SELECT_COLUMNS2} FROM tags WHERE session_id = ? AND tag_number = ?`);
3734
- tagByIdStatements.set(db, statement);
3735
- }
3736
- const result = statement.get(sessionId, tagId);
3737
- if (!isTagRow(result)) {
3738
- return null;
3739
- }
3740
- return toTagEntry(result);
3741
- }
3742
- function getTopNBySize2(db, sessionId, n) {
3743
- if (n <= 0) {
3744
- return [];
3745
- }
3746
- const rows = db.prepare(`SELECT ${TAG_SELECT_COLUMNS2} FROM tags WHERE session_id = ? AND status = 'active' ORDER BY byte_size DESC, tag_number ASC LIMIT ?`).all(sessionId, n).filter(isTagRow);
3747
- return rows.map(toTagEntry);
3748
- }
3749
- var getToolTagNumberByOwnerStatements = new WeakMap;
3750
- var getNullOwnerToolTagStatements = new WeakMap;
3751
- var adoptNullOwnerToolTagStatements = new WeakMap;
3752
- var getToolOwnerByTagIdStatements = new WeakMap;
3753
- var deleteToolTagsByOwnerStatements = new WeakMap;
3754
- function getGetToolTagNumberByOwnerStatement(db) {
3755
- let stmt = getToolTagNumberByOwnerStatements.get(db);
3756
- if (!stmt) {
3757
- stmt = db.prepare(`SELECT tag_number FROM tags
3758
- WHERE session_id = ? AND message_id = ?
3759
- AND type = 'tool' AND tool_owner_message_id = ?
3760
- LIMIT 1`);
3761
- getToolTagNumberByOwnerStatements.set(db, stmt);
3762
- }
3763
- return stmt;
3764
- }
3765
- function getToolTagNumberByOwner2(db, sessionId, callId, ownerMsgId) {
3766
- const row = getGetToolTagNumberByOwnerStatement(db).get(sessionId, callId, ownerMsgId);
3767
- return isTagNumberRow(row) ? row.tag_number : null;
3768
- }
3769
- function isNullOwnerToolTagRow(row) {
3770
- if (row === null || typeof row !== "object")
3771
- return false;
3772
- const r = row;
3773
- return typeof r.id === "number" && typeof r.tag_number === "number";
3774
- }
3775
- function getGetNullOwnerToolTagStatement(db) {
3776
- let stmt = getNullOwnerToolTagStatements.get(db);
3777
- if (!stmt) {
3778
- stmt = db.prepare(`SELECT id, tag_number FROM tags
3779
- WHERE session_id = ? AND message_id = ?
3780
- AND type = 'tool' AND tool_owner_message_id IS NULL
3781
- ORDER BY tag_number ASC
3782
- LIMIT 1`);
3783
- getNullOwnerToolTagStatements.set(db, stmt);
3784
- }
3785
- return stmt;
3786
- }
3787
- function getNullOwnerToolTag2(db, sessionId, callId) {
3788
- const row = getGetNullOwnerToolTagStatement(db).get(sessionId, callId);
3789
- if (!isNullOwnerToolTagRow(row))
3790
- return null;
3791
- return { id: row.id, tagNumber: row.tag_number };
3792
- }
3793
- function getAdoptNullOwnerToolTagStatement(db) {
3794
- let stmt = adoptNullOwnerToolTagStatements.get(db);
3795
- if (!stmt) {
3796
- stmt = db.prepare(`UPDATE tags
3797
- SET tool_owner_message_id = ?
3798
- WHERE id = ? AND tool_owner_message_id IS NULL`);
3799
- adoptNullOwnerToolTagStatements.set(db, stmt);
3800
- }
3801
- return stmt;
3802
- }
3803
- function getToolOwnerByTagIdStatement(db) {
3804
- let stmt = getToolOwnerByTagIdStatements.get(db);
3805
- if (!stmt) {
3806
- stmt = db.prepare("SELECT tool_owner_message_id FROM tags WHERE id = ?");
3807
- getToolOwnerByTagIdStatements.set(db, stmt);
3808
- }
3809
- return stmt;
3810
- }
3811
- function adoptNullOwnerToolTag2(db, rowId, ownerMsgId) {
3812
- return db.transaction(() => {
3813
- const before = getToolOwnerByTagIdStatement(db).get(rowId);
3814
- if (!before || before.tool_owner_message_id !== null)
3815
- return false;
3816
- getAdoptNullOwnerToolTagStatement(db).run(ownerMsgId, rowId);
3817
- const after = getToolOwnerByTagIdStatement(db).get(rowId);
3818
- return after?.tool_owner_message_id === ownerMsgId;
3819
- }).immediate();
3820
- }
3821
- function getCandidateToolOwners2(db, sessionId, callId) {
3822
- const rows = db.prepare(`SELECT DISTINCT tool_owner_message_id
3823
- FROM tags
3824
- WHERE session_id = ?
3825
- AND message_id = ?
3826
- AND type = 'tool'
3827
- AND tool_owner_message_id IS NOT NULL`).all(sessionId, callId);
3828
- return rows.map((r) => r.tool_owner_message_id);
3829
- }
3830
- function pickNearestPriorOwner2(candidates, currentMessageId, times) {
3831
- const currentTime = times.get(currentMessageId);
3832
- if (typeof currentTime !== "number")
3833
- return null;
3834
- let best = null;
3835
- for (const id of candidates) {
3836
- const t = times.get(id);
3837
- if (typeof t !== "number")
3838
- continue;
3839
- if (t > currentTime)
3840
- continue;
3841
- if (t === currentTime && id >= currentMessageId)
3842
- continue;
3843
- if (best === null || t > best.time || t === best.time && id > best.id) {
3844
- best = { id, time: t };
3845
- }
3846
- }
3847
- return best?.id ?? null;
3848
- }
3849
- function getDeleteToolTagsByOwnerStatement(db) {
3850
- let stmt = deleteToolTagsByOwnerStatements.get(db);
3851
- if (!stmt) {
3852
- stmt = db.prepare(`DELETE FROM tags
3853
- WHERE session_id = ?
3854
- AND type = 'tool'
3855
- AND tool_owner_message_id = ?
3856
- RETURNING id`);
3857
- deleteToolTagsByOwnerStatements.set(db, stmt);
3858
- }
3859
- return stmt;
3860
- }
3861
- function deleteToolTagsByOwner(db, sessionId, ownerMsgId) {
3862
- return getDeleteToolTagsByOwnerStatement(db).all(sessionId, ownerMsgId).length;
3863
- }
3864
-
3865
- export { protectedToolTagNumbers, protectedToolTokenCount, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isThinkingPart, currentReclaimableToolOutputCount, isRecord, contentTagOwnerMessageId, estimateImageTokensFromDataUrl, estimateToolAttachmentImageTokens, providerVisiblePart, providerVisibleMessage, CLEARED_TODO_STATE_JSON, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, formatTailHygienePrefixMismatch, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchangedIfEnabled, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, isDroppedToolOutput, toolOutputTokens, decideChannel1, evaluateChannel2, formatChannel1Evaluation, formatChannel2Evaluation, buildChannel2Reminder, buildChannel1Reminder, estimateEmergencyDropReclaimTokens, planEmergencyDrop, measureEmergencyTag, queuePendingOp, queuePendingDropForUnchangedTag, getPendingOps, hasPendingDropOps, getPendingOpsCount, clearPendingOps, removePendingOp, updateTagByteSize2, getRecentTagOwnerMessageIds2, getActiveTagTokenAggregate2, AGE_RECLAIM_MIN_TOKENS2, getOldestActiveUnprotectedToolTags2, getActiveToolTagsForAgeReclaim2, getTriggerTagTokenUpperBound2, getActiveTagTokenTotalsByMessage2, updateTagTokenCount2, getPersistedToolTagAccounting2, getAllStatusTagTokenTotalsFlat2, getReasoningTokenEstimatesByMessage2, tryGetReasoningTokenEstimatesByMessage2, getMaxTagNumberByOwnerMessage2, TagOwnerSummaryNotReady2, scanTagOwnerSummary2, cachedTagOwnerRatios2, tagOwnerWarmupState2, scanTagOwnerDelta2, installTagOwnerDelta2, installTagOwnerSummary2, isTagOwnerSummaryReady2, tagTokenCountIsNull2, backfillTagTokenCounts2, insertTag2, updateTagStatus2, markTagDropped2, markWhitespaceAssistantTagInert2, getInertWhitespaceAssistantTags2, getInertWhitespaceAssistantTagsByNumbers2, updateTagDropMode2, updateCavemanDepth2, updateTagMessageId2, hasPiFallbackMessageTags2, findAdoptableFallbackTags2, adoptFallbackTagMessageId2, foldShrunkPartTags2, hasPiFallbackToolOwnerTags2, findPiFallbackToolOwnerTags2, adoptPiFallbackToolOwnerTag2, adoptPiFallbackMessageTag2, markTagsCompactedByMessageIds2, deleteTagsByMessageId2, getMaxTagNumberBySession2, getTagNumberByMessageId2, getAssignableTagNumberByMessageId2, getMinMessageTagNumberForRawId2, deriveTagLoadFloor2, TAG_SELECT_COLUMNS2, getTagsBySession2, getActiveTagsBySession2, getTailHygieneTags2, getDroppedTagsBySession2, getTagsForPendingOperations2, getTagsByNumbers2, getNewestToolTagNumbers2, getDroppedTagsByNumbers2, getMaxDroppedTagNumber2, getTagById2, getTopNBySize2, getToolTagNumberByOwner2, getNullOwnerToolTag2, adoptNullOwnerToolTag2, getCandidateToolOwners2, pickNearestPriorOwner2 };