@cortexkit/pi-magic-context 0.49.52 → 0.49.54

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