@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
@@ -0,0 +1,2287 @@
1
+ import {
2
+ getHarness2,
3
+ harnessOwnsOpenCodeStore2
4
+ } from "./index-0h2mkab2.js";
5
+ import {
6
+ log2,
7
+ sessionLog2
8
+ } from "./index-yxeg8zaa.js";
9
+ import {
10
+ resolveOpenCodeDbPath,
11
+ assertOpenCodeStoreGeneration,
12
+ openCodeDbPathExists,
13
+ recordOpenCodeDbReadFailure,
14
+ clearOpenCodeDbReadFailure,
15
+ claimOpenCodeDbDiagnosticOnce
16
+ } from "./index-n0zjvs3h.js";
17
+ import {
18
+ Database2
19
+ } from "./index-2qtx0q6h.js";
20
+ import {
21
+ prewarmRawSessionOrdinalsForDb,
22
+ readRawSessionMessagesFromDb2,
23
+ readRawSessionMessagePageFromDb2,
24
+ readRawSessionMessageSummaryPageFromDb2,
25
+ countRawSessionMessageOrdinalsFromDb2,
26
+ readRawSessionMessageIdOrdinalsForRangeFromDb2,
27
+ readRawSessionMessageOrdinalPageFromDb2,
28
+ countStoredRawSessionMessagesFromDb2,
29
+ readRawSessionTailFromDb2,
30
+ readRawSessionMessagePartsByIdFromDb2,
31
+ readRawSessionMessageOrdinalByIdFromDb2,
32
+ readRawSessionMessageByIdFromDb2,
33
+ hasRawSessionMessageByIdFromDb2,
34
+ readRawSeedTailFromDb2,
35
+ readRawSessionBoundaryEndpointsFromDb2
36
+ } from "./index-szn2tac8.js";
37
+ import {
38
+ isRecord,
39
+ providerVisiblePart,
40
+ getCandidateToolOwners2,
41
+ pickNearestPriorOwner2
42
+ } from "./index-5n3e2gq5.js";
43
+ import {
44
+ OMO_INTERNAL_INITIATOR_MARKER,
45
+ isSystemDirective,
46
+ removeSystemReminders,
47
+ hasMeaningfulUserText2,
48
+ extractTexts2,
49
+ extractToolResultBodyTokens,
50
+ extractToolCallSummaries,
51
+ estimateTokens,
52
+ normalizeText,
53
+ compactRole,
54
+ formatBlock,
55
+ compactTextForSummary,
56
+ mergeCommitHashes
57
+ } from "./index-7y60kyea.js";
58
+ import {
59
+ stableStringify
60
+ } from "./index-v858d5d1.js";
61
+ import {
62
+ renderToolTemplate
63
+ } from "./index-vcegxfwg.js";
64
+ import {
65
+ markHostUnservedRow,
66
+ isHostUnservedRow
67
+ } from "./index-by1bzjcd.js";
68
+ import {
69
+ closeQuietly
70
+ } from "./index-nrzkqte4.js";
71
+
72
+ // ../plugin/src/hooks/magic-context/read-session-db.ts
73
+ function openCodeDbExists(generation = "v1") {
74
+ return harnessOwnsOpenCodeStore2() && openCodeDbPathExists(resolveOpenCodeDbPath(generation));
75
+ }
76
+ var cachedReadOnlyDbs = {
77
+ v1: null,
78
+ v2: null
79
+ };
80
+ function closeCachedReadOnlyDb(generation) {
81
+ const cached = cachedReadOnlyDbs[generation];
82
+ if (!cached) {
83
+ return;
84
+ }
85
+ try {
86
+ closeQuietly(cached.db);
87
+ } catch (error) {
88
+ log2("[magic-context] failed to close cached OpenCode read-only DB:", error);
89
+ } finally {
90
+ cachedReadOnlyDbs[generation] = null;
91
+ }
92
+ }
93
+ function getReadOnlySessionDb(generation = "v1") {
94
+ if (!harnessOwnsOpenCodeStore2()) {
95
+ throw new Error("OpenCode session database is not readable from a Pi-compatible process; its history lives in Pi sessions");
96
+ }
97
+ const resolution = resolveOpenCodeDbPath(generation);
98
+ const dbPath = resolution.path;
99
+ if (!openCodeDbPathExists(resolution)) {
100
+ throw new Error(`OpenCode session database is unavailable at ${dbPath} (source=${resolution.source})`);
101
+ }
102
+ const cached = cachedReadOnlyDbs[generation];
103
+ if (cached?.path === dbPath) {
104
+ return cached.db;
105
+ }
106
+ closeCachedReadOnlyDb(generation);
107
+ const db = new Database2(dbPath, { readonly: true });
108
+ try {
109
+ assertOpenCodeStoreGeneration(db, generation, dbPath);
110
+ } catch (error) {
111
+ closeQuietly(db);
112
+ throw error;
113
+ }
114
+ cachedReadOnlyDbs[generation] = { path: dbPath, db };
115
+ clearOpenCodeDbReadFailure();
116
+ return db;
117
+ }
118
+ function withReadOnlySessionDb(fn, generation = "v1") {
119
+ return fn(getReadOnlySessionDb(generation));
120
+ }
121
+ function getRawSessionMessageCountFromDb(db, sessionId) {
122
+ const row = db.prepare(`SELECT COUNT(*) as count FROM message WHERE session_id = ?
123
+ AND NOT (COALESCE(json_extract(data, '$.summary'), 0) = 1
124
+ AND COALESCE(json_extract(data, '$.finish'), '') = 'stop')`).get(sessionId);
125
+ return typeof row?.count === "number" ? row.count : 0;
126
+ }
127
+ var trackedSessions = new Map;
128
+ var pendingParts = new Map;
129
+ var probeLogObserverForTests;
130
+ function logProbeFailureOnce(resolution, error) {
131
+ const failure = recordOpenCodeDbReadFailure(resolution, error);
132
+ if (!claimOpenCodeDbDiagnosticOnce("session-state-probe", resolution))
133
+ return;
134
+ const message = `[magic-context] OpenCode DB probe failed: path=${resolution.path} source=${resolution.source} cause=${failure.message}`;
135
+ probeLogObserverForTests?.(message);
136
+ log2(message);
137
+ }
138
+ function getMessageTimesFromOpenCodeDb(sessionId, messageIds) {
139
+ const result = new Map;
140
+ if (messageIds.length === 0 || !harnessOwnsOpenCodeStore2())
141
+ return result;
142
+ try {
143
+ const placeholders = messageIds.map(() => "?").join(",");
144
+ const rows = getHarness2() === "opencode2" ? getReadOnlySessionDb("v2").prepare(`SELECT id, COALESCE(time_created, json_extract(data, '$.time.created')) AS time_created
145
+ FROM session_message WHERE +session_id = ? AND id IN (${placeholders})`).all(sessionId, ...messageIds) : withReadOnlySessionDb((db) => db.prepare(`SELECT id, time_created FROM message WHERE +session_id = ? AND id IN (${placeholders})`).all(sessionId, ...messageIds));
146
+ for (const row of rows) {
147
+ if (typeof row.id === "string" && typeof row.time_created === "number") {
148
+ result.set(row.id, row.time_created);
149
+ }
150
+ }
151
+ } catch (error) {
152
+ logProbeFailureOnce(resolveOpenCodeDbPath(), error);
153
+ }
154
+ return result;
155
+ }
156
+ // ../plugin/src/shared/historian-tool-defaults.json
157
+ var historian_tool_defaults_default = {
158
+ ctx_note: "Note ${input.action} ${input.note_ids}: ${input.content} → ${output.truncate(160)}",
159
+ ctx_memory: "Memory ${input.action} ${input.category} ${input.ids}: ${input.content} → ${output.truncate(160)}",
160
+ todowrite: 'Todos (${input.todos.count}): ${input.todos.each("${status}: ${content}")}',
161
+ question: 'Asked user: ${input.questions[*].question.join(" / ")} → ${output}',
162
+ task: "Task ${input.subagent_type}: ${input.prompt.truncate(600)} → ${output.truncate(200)}",
163
+ ask: 'Asked: ${input.question} [options: ${input.options.join(" / ")}] ${input.text}${input.resolution} → ${output.truncate(300)}',
164
+ peer_send: "PM ${input.recipient}: ${input.message}",
165
+ board: 'Board ${input.verb}${input.board_lane}: ${input.ops.each("${op} ${lane_label} ${item}${props.text}${lane.items} ${state}${props.state}${lane.status}${id}${title}")}',
166
+ room: "Room ${input.action} ${input.room_label}: ${input.room_detail}",
167
+ work: "Work ${input.action} ${input.title}${input.id}: ${input.prompt.truncate(600)}${input.notes.truncate(600)} → ${output.truncate(160)}",
168
+ knowhow: "Looked up how-to: ${input.query}${input.id}"
169
+ };
170
+ // ../plugin/src/shared/historian-tool-preview-defaults.json
171
+ var historian_tool_preview_defaults_default = {
172
+ ctx_note: "Note ${input.action} ${input.note_ids}: ${input.content} → ${output.truncate(160)}",
173
+ ctx_memory: "Memory ${input.action} ${input.category} ${input.ids}: ${input.content} → ${output.truncate(160)}",
174
+ todowrite: 'Todos (${input.todos.count}): ${input.todos.each("${status}: ${content}")}',
175
+ question: 'Asked user: ${input.questions[*].question.join(" / ")} → ${output}',
176
+ task: "Task ${input.subagent_type}: ${input.prompt} → ${output.truncate(200)}",
177
+ ask: 'Asked: ${input.question.truncate(250)} [options: ${input.options.join(" / ")}] ${input.resolution} → ${output.truncate(300)}',
178
+ peer_send: "PM to ${input.agent}${input.agent_id}: ${input.message.truncate(400)}",
179
+ board: 'Board ${input.verb}: ${input.ops.each("${op} ${item}${lane.title} ${state}${lane.status}${props.text} ${lane.items[*].text}")}',
180
+ room: "Room ${input.action} ${input.room_id}: ${input.text.truncate(400)}",
181
+ work: "Work ${input.action} ${input.id}: ${input.prompt_file}${input.prompt.truncate(200)}${input.notes.truncate(200)} → ${output.truncate(160)}",
182
+ knowhow: "Looked up how-to: ${input.query}${input.id}"
183
+ };
184
+
185
+ // ../plugin/src/shared/historian-tool-expansions.ts
186
+ function builtinInput(tool, input) {
187
+ if (!input || typeof input !== "object")
188
+ return input;
189
+ const i = input;
190
+ if (tool === "peer_send") {
191
+ const external = i.external;
192
+ const recipient = i.reply_to_pmid ? `reply to ${i.reply_to_pmid}` : i.agent || i.agent_id ? `to ${i.agent || i.agent_id}` : external?.session_id || i.session_id ? `to session ${external?.session_id || i.session_id}` : "to unknown recipient";
193
+ return { ...i, recipient };
194
+ }
195
+ if (tool === "room") {
196
+ return {
197
+ ...i,
198
+ room_label: i.room_id || i.title,
199
+ room_detail: i.action === "create" || i.action === "invite" ? `invitees: ${renderToolTemplate("${input.invitees}", i)}` : i.text
200
+ };
201
+ }
202
+ if (tool === "board") {
203
+ return {
204
+ ...i,
205
+ board_lane: i.lane ? ` ${i.lane}` : "",
206
+ ops: Array.isArray(i.ops) ? i.ops.map((op) => op && typeof op === "object" ? {
207
+ ...op,
208
+ lane_label: typeof op.lane === "string" ? op.lane : op.lane?.title || op.lane?.id
209
+ } : op) : i.ops
210
+ };
211
+ }
212
+ return input;
213
+ }
214
+ function expandToolPart(part, overrides, legacyPreview = false) {
215
+ if (!part || typeof part !== "object")
216
+ return null;
217
+ const p = part;
218
+ if (p.type !== "tool" || typeof p.tool !== "string")
219
+ return null;
220
+ const builtinDefaults = legacyPreview ? historian_tool_preview_defaults_default : historian_tool_defaults_default;
221
+ const overridden = overrides && Object.hasOwn(overrides, p.tool);
222
+ const template = overridden ? overrides[p.tool] : Object.hasOwn(builtinDefaults, p.tool) ? builtinDefaults[p.tool] : undefined;
223
+ if (typeof template !== "string")
224
+ return null;
225
+ const state = p.state;
226
+ const input = overridden || legacyPreview ? state?.input : builtinInput(p.tool, state?.input);
227
+ return renderToolTemplate(template, input, state?.output ?? state?.error, legacyPreview);
228
+ }
229
+
230
+ // ../plugin/src/hooks/magic-context/ask-answer-notice.ts
231
+ var ANSWER_HEADER_PREFIX = /^Inbox [^\n]* notice from user via user_answer \(user_answer\)/;
232
+ var ANSWER_TRAILER = /\n([\s\S]*?)\nThis ask is now closed; no dismiss is needed\. Continue accordingly\.$/;
233
+ var ANSWER_ANSWER_LINE = /^The user answered your parked question (\S+)\.\nQuestion: ([^\n]+)\nAnswer: /;
234
+ var ANSWER_QUESTION_LINE = /^Question: ([^\n]+)\nAnswer: /;
235
+ var reminderEnvelopePattern = /<system-reminder>([\s\S]*?)<\/system-reminder>/gi;
236
+ function reminderBodies(text) {
237
+ reminderEnvelopePattern.lastIndex = 0;
238
+ const bodies = [];
239
+ for (const match of text.matchAll(reminderEnvelopePattern)) {
240
+ const body = match[1];
241
+ if (body !== undefined)
242
+ bodies.push(body);
243
+ }
244
+ return bodies;
245
+ }
246
+ function parseAnswerBody(body) {
247
+ const lines = body.replace(/\r\n/g, `
248
+ `).replace(/^\n+|\n+$/g, "");
249
+ if (!ANSWER_HEADER_PREFIX.test(lines))
250
+ return null;
251
+ if (lines.includes("The user dismissed this question"))
252
+ return null;
253
+ const framed = ANSWER_TRAILER.exec(lines);
254
+ if (framed === null)
255
+ return null;
256
+ const content = framed[1] ?? "";
257
+ const narrated = ANSWER_ANSWER_LINE.exec(content);
258
+ if (narrated !== null) {
259
+ const question = narrated[2] ?? "";
260
+ const answer = content.slice(narrated[0].length);
261
+ return closedAnswer(question, answer);
262
+ }
263
+ const bare = ANSWER_QUESTION_LINE.exec(content);
264
+ if (bare !== null) {
265
+ const question = bare[1] ?? "";
266
+ const answer = content.slice(bare[0].length);
267
+ return closedAnswer(question, answer);
268
+ }
269
+ return null;
270
+ }
271
+ function closedAnswer(question, answer) {
272
+ if (question.trim().length === 0)
273
+ return null;
274
+ if (answer.trim().length === 0)
275
+ return null;
276
+ return { question, answer };
277
+ }
278
+ function extractAskAnswerNotices(text) {
279
+ const notices = [];
280
+ for (const body of reminderBodies(text)) {
281
+ const notice = parseAnswerBody(body);
282
+ if (notice !== null)
283
+ notices.push(notice);
284
+ }
285
+ return notices;
286
+ }
287
+ function formatAskAnswerNotice(notice) {
288
+ return `U (answered "${notice.question}"): ${notice.answer}`;
289
+ }
290
+ function askAnswerLines(text) {
291
+ return extractAskAnswerNotices(text).map(formatAskAnswerNotice);
292
+ }
293
+
294
+ // ../plugin/src/hooks/magic-context/compartment-commit-hashes.ts
295
+ function rawCommitHashes(value) {
296
+ if (typeof value === "string") {
297
+ return Array.from(value.matchAll(/\b[0-9a-f]{7,40}\b/gi), (match) => match[0].toLowerCase());
298
+ }
299
+ if (value === null || typeof value !== "object")
300
+ return [];
301
+ return Object.values(value).flatMap(rawCommitHashes);
302
+ }
303
+ function removeUnsupportedCommitHashes(text, supported) {
304
+ return text.replace(/`?\b([0-9a-f]{7,40})\b`?/gi, (token, hash) => {
305
+ const normalized = hash.toLowerCase();
306
+ if (!/[a-f]/.test(normalized))
307
+ return token;
308
+ return Array.from(supported).some((source) => source.startsWith(normalized)) ? token : "";
309
+ });
310
+ }
311
+
312
+ // ../plugin/src/hooks/magic-context/read-session-true-raw-tokens.ts
313
+ function completedToolArcCrossesBoundary(invOrdinal, resOrdinal, boundary) {
314
+ return invOrdinal < boundary && boundary <= resOrdinal;
315
+ }
316
+ var MAX_MESSAGE_CACHE_ENTRIES = 1e5;
317
+ var MAX_MESSAGE_CACHE_KEY_BYTES = 64 * 1024 * 1024;
318
+ var FNV1A_32_OFFSET = 2166136261;
319
+ var FNV1A_32_PRIME = 16777619;
320
+ var messageEstimateCache = new Map;
321
+ var messageEstimateKeysByField = new Map;
322
+ var messageEstimateCacheBytes = 0;
323
+ var EMPTY_BREAKDOWN = {
324
+ text: 0,
325
+ reasoning: 0,
326
+ toolInput: 0,
327
+ toolOutput: 0,
328
+ image: 0,
329
+ other: 0,
330
+ total: 0
331
+ };
332
+ function addBreakdown(target, kind, value) {
333
+ if (kind === "total")
334
+ return;
335
+ const safeValue = Number.isFinite(value) && value > 0 ? Math.round(value) : 0;
336
+ target[kind] += safeValue;
337
+ target.total += safeValue;
338
+ }
339
+ function estimateStructured(value) {
340
+ if (typeof value === "string")
341
+ return estimateTokens(value);
342
+ if (value === undefined || value === null)
343
+ return 0;
344
+ return estimateTokens(stableStringify(value));
345
+ }
346
+ function firstStringField(record, fields) {
347
+ for (const field of fields) {
348
+ const value = record[field];
349
+ if (typeof value === "string" && value.length > 0)
350
+ return value;
351
+ }
352
+ return null;
353
+ }
354
+ function stringValue(value) {
355
+ if (typeof value === "string")
356
+ return value;
357
+ if (value === undefined || value === null)
358
+ return "";
359
+ return stableStringify(value);
360
+ }
361
+ function textFromToolResultContent(content) {
362
+ if (typeof content === "string")
363
+ return content;
364
+ if (Array.isArray(content)) {
365
+ const pieces = [];
366
+ for (const entry of content) {
367
+ if (typeof entry === "string") {
368
+ pieces.push(entry);
369
+ } else if (isRecord(entry)) {
370
+ const text = firstStringField(entry, ["text", "content", "value"]);
371
+ pieces.push(text ?? stableStringify(entry));
372
+ } else if (entry !== null && entry !== undefined) {
373
+ pieces.push(String(entry));
374
+ }
375
+ }
376
+ return pieces.join(`
377
+ `);
378
+ }
379
+ return stringValue(content);
380
+ }
381
+ function looksImageLike(part) {
382
+ const type = typeof part.type === "string" ? part.type.toLowerCase() : "";
383
+ const mime = typeof part.mime === "string" ? part.mime.toLowerCase() : "";
384
+ const mediaType = typeof part.mediaType === "string" ? part.mediaType.toLowerCase() : "";
385
+ return type.includes("image") || mime.startsWith("image/") || mediaType.startsWith("image/") || part.image_url !== undefined || part.imageUrl !== undefined || part.image !== undefined || type.includes("file") && (typeof part.url === "string" && part.url.startsWith("data:image/") || typeof part.data === "string" && /^(?:data:image\/|\/9j\/|iVBORw0KGgo|R0lGOD)/.test(part.data));
386
+ }
387
+ function defaultImageTokenHeuristic(part) {
388
+ if (isRecord(part)) {
389
+ const width = part.width;
390
+ const height = part.height;
391
+ if (typeof width === "number" && typeof height === "number" && width > 0 && height > 0) {
392
+ return Math.max(256, Math.min(4096, Math.ceil(width * height / 750)));
393
+ }
394
+ }
395
+ return 1024;
396
+ }
397
+ function partType(part) {
398
+ return typeof part.type === "string" ? part.type : "";
399
+ }
400
+ function hasOwn(record, key) {
401
+ return Object.hasOwn(record, key);
402
+ }
403
+ function recursiveByteLength(value) {
404
+ if (value === null || value === undefined)
405
+ return 0;
406
+ if (typeof value === "string")
407
+ return value.length;
408
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
409
+ return String(value).length;
410
+ }
411
+ if (Array.isArray(value)) {
412
+ return value.reduce((sum, item) => sum + recursiveByteLength(item), value.length);
413
+ }
414
+ if (isRecord(value)) {
415
+ let total = Object.keys(value).length;
416
+ for (const [key, child] of Object.entries(value)) {
417
+ total += key.length + recursiveByteLength(child);
418
+ }
419
+ return total;
420
+ }
421
+ return String(value).length;
422
+ }
423
+ function updateFnv1a32(hash, text) {
424
+ let next = hash;
425
+ for (let index = 0;index < text.length; index += 1) {
426
+ next ^= text.charCodeAt(index);
427
+ next = Math.imul(next, FNV1A_32_PRIME) >>> 0;
428
+ }
429
+ return next;
430
+ }
431
+ function contentStringsHash(fields) {
432
+ let hash = FNV1A_32_OFFSET;
433
+ for (const field of fields) {
434
+ hash = updateFnv1a32(hash, `${field.length}:`);
435
+ hash = updateFnv1a32(hash, field);
436
+ hash = updateFnv1a32(hash, "\x00");
437
+ }
438
+ return hash.toString(16).padStart(8, "0");
439
+ }
440
+ function rawPartVersion(part) {
441
+ return part.__magicContextPartUpdatedAt ?? part.updated_at ?? part.updatedAt ?? part.version ?? part.revision ?? "";
442
+ }
443
+ function callIdFromPart(part) {
444
+ const direct = firstStringField(part, ["callID", "callId", "toolCallId", "tool_call_id", "id"]);
445
+ if (direct)
446
+ return direct;
447
+ const state = isRecord(part.state) ? part.state : null;
448
+ return state ? firstStringField(state, ["callID", "callId", "toolCallId", "tool_call_id", "id"]) ?? "" : "";
449
+ }
450
+ function toolSignalFromPart(part, withText = true) {
451
+ if (!isRecord(part))
452
+ return null;
453
+ const type = partType(part);
454
+ const state = isRecord(part.state) ? part.state : null;
455
+ const callId = callIdFromPart(part);
456
+ if (!callId && type !== "tool")
457
+ return null;
458
+ if (type === "tool") {
459
+ const hasInput = state !== null && hasOwn(state, "input");
460
+ const outputKey = state ? hasOwn(state, "output") ? "output" : hasOwn(state, "error") ? "error" : hasOwn(state, "result") ? "result" : null : null;
461
+ const hasOutput = outputKey !== null;
462
+ const outputValue = outputKey && state ? state[outputKey] : undefined;
463
+ const providerExecuted = part.providerExecuted === true;
464
+ const openInvocation = !providerExecuted && !hasOutput;
465
+ return {
466
+ callId,
467
+ hasInput: hasInput || openInvocation,
468
+ hasOutput,
469
+ inputText: withText && hasInput && state ? stringValue(state.input) : "",
470
+ outputText: withText && hasOutput ? stringValue(outputValue) : ""
471
+ };
472
+ }
473
+ if (type === "tool-invocation") {
474
+ const args = part.args ?? part.input;
475
+ return {
476
+ callId,
477
+ hasInput: args !== undefined,
478
+ hasOutput: false,
479
+ inputText: withText && args !== undefined ? stringValue(args) : "",
480
+ outputText: ""
481
+ };
482
+ }
483
+ if (type === "tool_use") {
484
+ const input = part.input;
485
+ return {
486
+ callId,
487
+ hasInput: input !== undefined,
488
+ hasOutput: false,
489
+ inputText: withText && input !== undefined ? stringValue(input) : "",
490
+ outputText: ""
491
+ };
492
+ }
493
+ if (type === "tool_result") {
494
+ const content = part.content ?? part.output ?? part.result;
495
+ return {
496
+ callId,
497
+ hasInput: false,
498
+ hasOutput: content !== undefined,
499
+ inputText: "",
500
+ outputText: withText && content !== undefined ? textFromToolResultContent(content) : ""
501
+ };
502
+ }
503
+ return null;
504
+ }
505
+ function partCheapFingerprint(part) {
506
+ if (!isRecord(part))
507
+ return `${typeof part}:${recursiveByteLength(part)}`;
508
+ const version = rawPartVersion(part);
509
+ const type = typeof part.type === "string" ? part.type : "";
510
+ return `${type}:${String(version)}:${recursiveByteLength(providerVisiblePart(part))}`;
511
+ }
512
+ function messageCacheKey(message, options) {
513
+ const namespace = "cacheNamespace" in options ? options.cacheNamespace : "estimate";
514
+ const cheapFingerprint = message.parts.map(partCheapFingerprint).join("|");
515
+ return [
516
+ namespace,
517
+ options.providerShapeVersion,
518
+ message.id || `ordinal:${message.ordinal}`,
519
+ message.role,
520
+ message.parts.length,
521
+ cheapFingerprint
522
+ ].join("\x00");
523
+ }
524
+ function setCachedEstimate(key, breakdown) {
525
+ const keyEstimateBytes = key.length * 2 + 64;
526
+ const existing = messageEstimateCache.get(key);
527
+ if (existing)
528
+ messageEstimateCacheBytes -= existing.keyEstimateBytes;
529
+ else {
530
+ for (const field of new Set(key.split("\x00").slice(1, -1))) {
531
+ const keys = messageEstimateKeysByField.get(field) ?? new Set;
532
+ keys.add(key);
533
+ messageEstimateKeysByField.set(field, keys);
534
+ }
535
+ }
536
+ messageEstimateCache.set(key, { breakdown, keyEstimateBytes });
537
+ messageEstimateCacheBytes += keyEstimateBytes;
538
+ while (messageEstimateCache.size > MAX_MESSAGE_CACHE_ENTRIES || messageEstimateCacheBytes > MAX_MESSAGE_CACHE_KEY_BYTES) {
539
+ const first = messageEstimateCache.keys().next().value;
540
+ if (typeof first !== "string")
541
+ break;
542
+ deleteCachedEstimate(first);
543
+ }
544
+ }
545
+ function deleteCachedEstimate(key) {
546
+ const removed = messageEstimateCache.get(key);
547
+ if (!removed)
548
+ return;
549
+ messageEstimateCacheBytes -= removed.keyEstimateBytes;
550
+ messageEstimateCache.delete(key);
551
+ for (const field of new Set(key.split("\x00").slice(1, -1))) {
552
+ const keys = messageEstimateKeysByField.get(field);
553
+ keys?.delete(key);
554
+ if (keys?.size === 0)
555
+ messageEstimateKeysByField.delete(field);
556
+ }
557
+ }
558
+ function cloneBreakdown(value) {
559
+ return { ...value };
560
+ }
561
+ function estimateNonToolPart(part, options, breakdown) {
562
+ if (!isRecord(part)) {
563
+ if (part !== null && part !== undefined)
564
+ addBreakdown(breakdown, "other", estimateStructured(part));
565
+ return true;
566
+ }
567
+ const type = partType(part);
568
+ if (type === "step-start" || type === "step-finish" || type === "meta" && Object.keys(part).length <= 1) {
569
+ return true;
570
+ }
571
+ if (type === "text") {
572
+ const text = firstStringField(part, ["text", "content"]);
573
+ if (text)
574
+ addBreakdown(breakdown, "text", estimateTokens(text));
575
+ return true;
576
+ }
577
+ if (type === "reasoning" || type === "thinking" || type === "redacted_thinking") {
578
+ const text = firstStringField(part, ["thinking", "text", "content", "reasoning"]);
579
+ if (text) {
580
+ addBreakdown(breakdown, "reasoning", estimateTokens(text));
581
+ } else {
582
+ addBreakdown(breakdown, "other", estimateStructured(part));
583
+ }
584
+ return true;
585
+ }
586
+ const reasoningText = firstStringField(part, ["thinking", "reasoning"]);
587
+ if (reasoningText && type.length === 0) {
588
+ addBreakdown(breakdown, "reasoning", estimateTokens(reasoningText));
589
+ return true;
590
+ }
591
+ if (looksImageLike(part)) {
592
+ addBreakdown(breakdown, "image", options.imageTokenHeuristic?.(part) ?? defaultImageTokenHeuristic(part));
593
+ const altText = firstStringField(part, ["alt", "text", "description"]);
594
+ if (altText)
595
+ addBreakdown(breakdown, "text", estimateTokens(altText));
596
+ return true;
597
+ }
598
+ if (type.includes("file") || type === "source") {
599
+ const content = firstStringField(part, ["content", "text", "source"]);
600
+ if (content)
601
+ addBreakdown(breakdown, "text", estimateTokens(content));
602
+ else
603
+ addBreakdown(breakdown, "other", estimateStructured(part));
604
+ return true;
605
+ }
606
+ return false;
607
+ }
608
+ function estimateTrueRawMessageTokens(message, options) {
609
+ const breakdown = cloneBreakdown(EMPTY_BREAKDOWN);
610
+ const countedInput = new Set;
611
+ const countedOutput = new Set;
612
+ let ordinalToolIndex = 0;
613
+ for (const part of message.parts) {
614
+ const signal = toolSignalFromPart(part);
615
+ if (signal) {
616
+ const localKey = `${signal.callId || "tool"}:${message.ordinal}:${ordinalToolIndex}`;
617
+ ordinalToolIndex += 1;
618
+ if (signal.hasInput) {
619
+ const key = `${signal.callId}:input:${message.ordinal}`;
620
+ if (!countedInput.has(key)) {
621
+ countedInput.add(key);
622
+ addBreakdown(breakdown, "toolInput", estimateTokens(signal.inputText));
623
+ }
624
+ }
625
+ if (signal.hasOutput) {
626
+ const key = `${signal.callId}:output:${message.ordinal}:${localKey}`;
627
+ if (!countedOutput.has(key)) {
628
+ countedOutput.add(key);
629
+ addBreakdown(breakdown, "toolOutput", estimateTokens(signal.outputText));
630
+ }
631
+ }
632
+ continue;
633
+ }
634
+ if (!estimateNonToolPart(part, options, breakdown)) {
635
+ addBreakdown(breakdown, "other", estimateStructured(part));
636
+ }
637
+ }
638
+ return breakdown;
639
+ }
640
+ function buildToolArcs(messages) {
641
+ const openQueues = new Map;
642
+ const arcs = [];
643
+ for (const message of messages) {
644
+ for (const part of message.parts) {
645
+ const signal = toolSignalFromPart(part, false);
646
+ if (!signal || signal.callId.length === 0)
647
+ continue;
648
+ if (signal.hasInput && signal.hasOutput) {
649
+ arcs.push({
650
+ callId: signal.callId,
651
+ invOrdinal: message.ordinal,
652
+ resOrdinal: message.ordinal
653
+ });
654
+ continue;
655
+ }
656
+ if (signal.hasInput) {
657
+ const queue = openQueues.get(signal.callId) ?? [];
658
+ queue.push(message.ordinal);
659
+ openQueues.set(signal.callId, queue);
660
+ continue;
661
+ }
662
+ if (signal.hasOutput) {
663
+ const queue = openQueues.get(signal.callId) ?? [];
664
+ const invOrdinal = queue.shift();
665
+ if (queue.length === 0)
666
+ openQueues.delete(signal.callId);
667
+ else
668
+ openQueues.set(signal.callId, queue);
669
+ if (invOrdinal !== undefined) {
670
+ arcs.push({ callId: signal.callId, invOrdinal, resOrdinal: message.ordinal });
671
+ }
672
+ }
673
+ }
674
+ }
675
+ for (const [callId, queue] of openQueues) {
676
+ for (const invOrdinal of queue) {
677
+ arcs.push({ callId, invOrdinal, resOrdinal: null });
678
+ }
679
+ }
680
+ return arcs.sort((a, b) => a.invOrdinal - b.invOrdinal || (a.resOrdinal ?? Number.MAX_SAFE_INTEGER) - (b.resOrdinal ?? Number.MAX_SAFE_INTEGER));
681
+ }
682
+ function fenceBoundaryForCompletedToolArcs(candidate, arcs, publicationFloorOrdinal, observeComponent) {
683
+ const completed = arcs.filter((arc) => arc.resOrdinal !== null).map((arc) => ({ invocation: arc.invOrdinal, result: arc.resOrdinal }));
684
+ const component = completed.filter((arc) => completedToolArcCrossesBoundary(arc.invocation, arc.result, candidate));
685
+ if (component.length === 0)
686
+ return candidate;
687
+ for (let pass = 0;pass <= completed.length; pass += 1) {
688
+ const minInvocation = Math.min(...component.map((arc) => arc.invocation));
689
+ const maxResult = Math.max(...component.map((arc) => arc.result));
690
+ const before = component.length;
691
+ for (const arc of completed) {
692
+ if (arc.invocation <= maxResult && arc.result >= minInvocation && !component.includes(arc)) {
693
+ component.push(arc);
694
+ }
695
+ }
696
+ if (component.length === before)
697
+ break;
698
+ }
699
+ const minInvocation = Math.min(...component.map((arc) => arc.invocation));
700
+ const maxResult = Math.max(...component.map((arc) => arc.result));
701
+ observeComponent?.(component);
702
+ return minInvocation < publicationFloorOrdinal ? maxResult + 1 : minInvocation;
703
+ }
704
+ function fenceBoundaryForToolArcs(candidate, arcs, lastCompartmentEndOrdinal, recentOpenArcCutoff) {
705
+ let boundary = fenceBoundaryForCompletedToolArcs(candidate, arcs, lastCompartmentEndOrdinal + 1);
706
+ for (const arc of arcs) {
707
+ if (arc.resOrdinal !== null)
708
+ continue;
709
+ if (arc.invOrdinal < recentOpenArcCutoff)
710
+ continue;
711
+ if (arc.invOrdinal >= lastCompartmentEndOrdinal + 1 && arc.invOrdinal < boundary) {
712
+ boundary = arc.invOrdinal;
713
+ break;
714
+ }
715
+ if (arc.invOrdinal >= boundary) {
716
+ boundary = arc.invOrdinal;
717
+ break;
718
+ }
719
+ }
720
+ return fenceBoundaryForCompletedToolArcs(boundary, arcs, 1);
721
+ }
722
+ function tokenForMessage(message, options) {
723
+ const key = messageCacheKey(message, options);
724
+ const cached = messageEstimateCache.get(key);
725
+ if (cached)
726
+ return cloneBreakdown(cached.breakdown);
727
+ const breakdown = estimateTrueRawMessageTokens(message, options);
728
+ setCachedEstimate(key, breakdown);
729
+ return cloneBreakdown(breakdown);
730
+ }
731
+ function buildTrueRawTokenIndex(sessionId, messages, options) {
732
+ const ordered = [...messages].sort((a, b) => a.ordinal - b.ordinal);
733
+ const sliceCount = ordered.length;
734
+ const firstOrdinal = ordered.length > 0 ? ordered[0].ordinal : 1;
735
+ const terminalOrdinal = ordered.length > 0 ? ordered[ordered.length - 1].ordinal : 0;
736
+ const rawMessageCount = Math.max(sliceCount, terminalOrdinal, options.absoluteMessageCount ?? sliceCount);
737
+ const ordinalSpan = terminalOrdinal >= firstOrdinal ? terminalOrdinal - firstOrdinal + 1 : 0;
738
+ const tokensByOrdinal = new Map;
739
+ const idsByOrdinal = new Map;
740
+ const prefix = new Array(ordinalSpan + 1).fill(0);
741
+ for (const message of ordered) {
742
+ const stored = options.storedTotalForMessage?.(message);
743
+ let total;
744
+ if (stored !== undefined && stored !== null) {
745
+ total = stored;
746
+ } else {
747
+ const raw = tokenForMessage(message, options);
748
+ const seed = options.calibration;
749
+ total = options.measure === "summary-removed" ? raw.text * (seed?.proseRatio ?? 1) + raw.toolInput * (seed?.toolsRatio ?? 1) : seed ? (raw.toolInput + raw.toolOutput) * seed.toolsRatio + (raw.text + raw.reasoning + raw.other) * seed.proseRatio + raw.image : raw.total;
750
+ }
751
+ tokensByOrdinal.set(message.ordinal, total);
752
+ idsByOrdinal.set(message.ordinal, message.id);
753
+ const relative = message.ordinal - firstOrdinal + 1;
754
+ if (relative >= 1 && relative <= ordinalSpan) {
755
+ prefix[relative] = total;
756
+ }
757
+ }
758
+ for (let k = 1;k <= ordinalSpan; k += 1) {
759
+ prefix[k] += prefix[k - 1];
760
+ }
761
+ const ordinalToIndex = (ordinal) => Math.max(0, Math.min(ordinalSpan, ordinal - firstOrdinal));
762
+ return {
763
+ sessionId,
764
+ providerShapeVersion: options.providerShapeVersion,
765
+ rawMessageCount,
766
+ tokenForOrdinal(ordinal) {
767
+ return tokensByOrdinal.get(ordinal) ?? 0;
768
+ },
769
+ messageIdAtOrdinal(ordinal) {
770
+ return idsByOrdinal.get(ordinal) ?? null;
771
+ },
772
+ suffixTokensFromOrdinal(ordinal) {
773
+ if (ordinal <= firstOrdinal)
774
+ return prefix[ordinalSpan];
775
+ if (ordinal > terminalOrdinal)
776
+ return 0;
777
+ return prefix[ordinalSpan] - prefix[ordinalToIndex(ordinal)];
778
+ },
779
+ rangeTokens(startInclusive, endExclusive) {
780
+ const start = Math.max(firstOrdinal, startInclusive);
781
+ const end = Math.max(start, Math.min(terminalOrdinal + 1, endExclusive));
782
+ return prefix[end - firstOrdinal] - prefix[start - firstOrdinal];
783
+ },
784
+ findSuffixStartForTokens(tokens) {
785
+ if (!Number.isFinite(tokens) || tokens <= 0)
786
+ return terminalOrdinal + 1;
787
+ const target = Math.max(0, Math.floor(tokens));
788
+ const total = prefix[ordinalSpan];
789
+ if (total < target)
790
+ return firstOrdinal;
791
+ const cut = total - target;
792
+ let lo = 0;
793
+ let hi = ordinalSpan;
794
+ let best = 0;
795
+ while (lo <= hi) {
796
+ const mid = lo + hi >> 1;
797
+ if (prefix[mid] <= cut) {
798
+ best = mid;
799
+ lo = mid + 1;
800
+ } else {
801
+ hi = mid - 1;
802
+ }
803
+ }
804
+ return firstOrdinal + best;
805
+ },
806
+ findHeadEndForCap(startInclusive, endExclusive, capTokens) {
807
+ const start = Math.max(firstOrdinal, Math.min(terminalOrdinal + 1, startInclusive));
808
+ const end = Math.max(start, Math.min(terminalOrdinal + 1, endExclusive));
809
+ if (!Number.isFinite(capTokens) || capTokens <= 0)
810
+ return start;
811
+ const startIndex = start - firstOrdinal;
812
+ const endIndex = end - firstOrdinal;
813
+ const cut = prefix[startIndex] + Math.floor(capTokens);
814
+ let lo = startIndex + 1;
815
+ let hi = endIndex;
816
+ let bestEndIndex = startIndex;
817
+ while (lo <= hi) {
818
+ const mid = lo + hi >> 1;
819
+ if (prefix[mid] <= cut) {
820
+ bestEndIndex = mid;
821
+ lo = mid + 1;
822
+ } else {
823
+ hi = mid - 1;
824
+ }
825
+ }
826
+ let bestEnd = firstOrdinal + bestEndIndex;
827
+ if (bestEnd === start && start < end)
828
+ bestEnd = start + 1;
829
+ return Math.min(bestEnd, end);
830
+ }
831
+ };
832
+ }
833
+ function partContentFingerprint(part) {
834
+ if (!isRecord(part))
835
+ return `${typeof part}:${recursiveByteLength(part)}`;
836
+ const tool = toolSignalFromPart(part);
837
+ if (tool) {
838
+ return contentStringsHash([tool.inputText, tool.outputText]);
839
+ }
840
+ const text = firstStringField(part, ["text", "thinking", "reasoning", "content", "url"]) ?? "";
841
+ return contentStringsHash([text]);
842
+ }
843
+ function computeRawRangeFingerprint(messages, startInclusive, endExclusive) {
844
+ const pieces = [];
845
+ for (const message of messages) {
846
+ if (message.ordinal < startInclusive || message.ordinal >= endExclusive)
847
+ continue;
848
+ const partFingerprint = message.parts.map(partContentFingerprint).join(",");
849
+ pieces.push(`${message.ordinal}:${message.id}:${message.parts.length}:${partFingerprint}`);
850
+ }
851
+ return pieces.join("|");
852
+ }
853
+ function invalidateTrueRawTokenCache(args) {
854
+ const sessionNeedle = args.sessionId ? `${args.sessionId}` : null;
855
+ const messageNeedle = args.messageId ? `\x00${args.messageId}\x00` : null;
856
+ const keys = args.messageId && !args.messageId.includes("\x00") ? messageEstimateKeysByField.get(args.messageId) ?? [] : messageEstimateCache.keys();
857
+ for (const key of keys) {
858
+ const sessionMatches = sessionNeedle === null || key.includes(sessionNeedle);
859
+ const messageMatches = messageNeedle === null || key.includes(messageNeedle);
860
+ if (sessionMatches && messageMatches) {
861
+ deleteCachedEstimate(key);
862
+ }
863
+ }
864
+ args.reason;
865
+ }
866
+
867
+ // ../plugin/src/hooks/magic-context/system-injection-stripper.ts
868
+ var SYSTEM_INJECTION_MARKERS = [
869
+ "<!-- OMO_INTERNAL_INITIATOR -->",
870
+ "[SYSTEM DIRECTIVE: MAGIC-CONTEXT",
871
+ "[SYSTEM DIRECTIVE: OH-MY-OPENCODE",
872
+ "[Category+Skill Reminder]",
873
+ "[EDIT ERROR - IMMEDIATE ACTION REQUIRED]",
874
+ "[task CALL FAILED - IMMEDIATE RETRY REQUIRED]",
875
+ "[EMERGENCY CONTEXT WINDOW WARNING]",
876
+ "Unstable background agent appears idle",
877
+ "**THE SUBAGENT JUST CLAIMED THIS TASK IS DONE."
878
+ ];
879
+ var SYSTEM_REMINDER_REGEX = /<system-reminder>[\s\S]*?<\/system-reminder>/gi;
880
+ var OMO_MARKER_REGEX = /<!-- OMO_INTERNAL_INITIATOR -->/g;
881
+ var STEERING_WRAPPER_REGEX = /<system-reminder>\nThe user sent the following message:\n[\s\S]*?\n\nPlease address this message and continue with your tasks\.\n<\/system-reminder>/g;
882
+ function stripSystemInjection(text) {
883
+ STEERING_WRAPPER_REGEX.lastIndex = 0;
884
+ if (!STEERING_WRAPPER_REGEX.test(text))
885
+ return stripInjectedRegions(text);
886
+ STEERING_WRAPPER_REGEX.lastIndex = 0;
887
+ let result = "";
888
+ let changed = false;
889
+ let cursor = 0;
890
+ const keepOrStrip = (segment) => {
891
+ const stripped = stripInjectedRegions(segment);
892
+ if (stripped === null) {
893
+ result += segment;
894
+ } else {
895
+ result += stripped;
896
+ changed = true;
897
+ }
898
+ };
899
+ for (const match of text.matchAll(STEERING_WRAPPER_REGEX)) {
900
+ keepOrStrip(text.slice(cursor, match.index));
901
+ result += match[0];
902
+ cursor = match.index + match[0].length;
903
+ }
904
+ keepOrStrip(text.slice(cursor));
905
+ return changed ? result.trim() : null;
906
+ }
907
+ function stripOutsideSteeringWrappers(text, strip) {
908
+ STEERING_WRAPPER_REGEX.lastIndex = 0;
909
+ let result = "";
910
+ let cursor = 0;
911
+ for (const match of text.matchAll(STEERING_WRAPPER_REGEX)) {
912
+ result += strip(text.slice(cursor, match.index));
913
+ result += match[0];
914
+ cursor = match.index + match[0].length;
915
+ }
916
+ return result + strip(text.slice(cursor));
917
+ }
918
+ function stripInjectedRegions(text) {
919
+ let hasInjection = false;
920
+ for (const marker of SYSTEM_INJECTION_MARKERS) {
921
+ if (text.includes(marker)) {
922
+ hasInjection = true;
923
+ break;
924
+ }
925
+ }
926
+ if (SYSTEM_REMINDER_REGEX.test(text))
927
+ hasInjection = true;
928
+ SYSTEM_REMINDER_REGEX.lastIndex = 0;
929
+ if (!hasInjection)
930
+ return null;
931
+ let cleaned = text;
932
+ cleaned = cleaned.replace(SYSTEM_REMINDER_REGEX, "");
933
+ cleaned = cleaned.replace(OMO_MARKER_REGEX, "");
934
+ cleaned = cleaned.replace(/\[SYSTEM DIRECTIVE: OH-MY-(?:OPENCODE|CLAUDE)[^\]]*\][\s\S]*?(?=\n\n(?!\s*[-*])|$)/g, "");
935
+ for (const marker of SYSTEM_INJECTION_MARKERS) {
936
+ if (marker.startsWith("<!-- ") || marker.startsWith("[SYSTEM DIRECTIVE"))
937
+ continue;
938
+ const idx = cleaned.indexOf(marker);
939
+ if (idx === -1)
940
+ continue;
941
+ const blockEnd = cleaned.indexOf(`
942
+
943
+ `, idx + marker.length);
944
+ cleaned = blockEnd !== -1 ? cleaned.slice(0, idx) + cleaned.slice(blockEnd) : cleaned.slice(0, idx);
945
+ }
946
+ return cleaned.trim();
947
+ }
948
+
949
+ // ../plugin/src/hooks/magic-context/tag-part-guards.ts
950
+ function isTextPart(part) {
951
+ if (part === null || typeof part !== "object")
952
+ return false;
953
+ const p = part;
954
+ return p.type === "text" && typeof p.text === "string";
955
+ }
956
+ function isFilePart(part) {
957
+ if (part === null || typeof part !== "object")
958
+ return false;
959
+ const p = part;
960
+ return p.type === "file" && typeof p.url === "string";
961
+ }
962
+
963
+ // ../plugin/src/shared/user-answer.ts
964
+ function hasUserAnswerMetadata(value) {
965
+ if (!isRecord(value))
966
+ return false;
967
+ if (value.userAnswer === true)
968
+ return true;
969
+ if (Array.isArray(value.answers))
970
+ return true;
971
+ if (typeof value.answer === "string")
972
+ return true;
973
+ if (Array.isArray(value.selectedOptions) || typeof value.customInput === "string")
974
+ return true;
975
+ return Array.isArray(value.results) && value.results.some(hasUserAnswerMetadata);
976
+ }
977
+
978
+ // ../plugin/src/features/magic-context/dreamer/token-budget.ts
979
+ class DreamTokenBudgetExceeded extends Error {
980
+ sessionId;
981
+ spent;
982
+ constructor(sessionId, spent) {
983
+ super(`Dreamer child ${sessionId} spent ${spent} prompt tokens (token_budget)`);
984
+ this.sessionId = sessionId;
985
+ this.spent = spent;
986
+ this.name = "DreamTokenBudgetExceeded";
987
+ }
988
+ }
989
+ var TOKEN_BUDGET_FINALIZE_MESSAGE = "You're out of token budget. Stop investigating: make no more tool calls and output your result now, covering only what you've already checked; leave the rest out.";
990
+ var TOKEN_BUDGET_TOOL_REFUSAL = "Out of token budget: no more tool calls. Output your result now.";
991
+ var finalizingChildren = new Map;
992
+ function registerBudgetFinalizeChild(sessionId, guard) {
993
+ finalizingChildren.set(sessionId, guard);
994
+ }
995
+ function releaseBudgetFinalizeChild(sessionId) {
996
+ finalizingChildren.delete(sessionId);
997
+ }
998
+ function createDreamTokenBudget(budget) {
999
+ if (!Number.isSafeInteger(budget) || budget <= 0)
1000
+ throw new Error("Invalid token budget");
1001
+ let spent = 0;
1002
+ let finalizeFired = false;
1003
+ let refusedCalls = 0;
1004
+ let forcedStop = false;
1005
+ const snapshot = () => ({
1006
+ budget,
1007
+ spent,
1008
+ finalizeFired,
1009
+ refusedCalls,
1010
+ hardStopped: forcedStop || spent >= budget || refusedCalls >= 2
1011
+ });
1012
+ return {
1013
+ snapshot,
1014
+ finalize() {
1015
+ if (finalizeFired)
1016
+ return "continue";
1017
+ finalizeFired = true;
1018
+ return "finalize";
1019
+ },
1020
+ charge(input, cacheRead, cacheWrite, completed = false, canFinalize = true) {
1021
+ for (const value of [input, cacheRead, cacheWrite]) {
1022
+ if (!Number.isSafeInteger(value) || value < 0)
1023
+ throw new Error("Invalid prompt usage");
1024
+ }
1025
+ spent += input + cacheRead + cacheWrite;
1026
+ if (completed)
1027
+ return "continue";
1028
+ if (spent >= budget)
1029
+ return "stop";
1030
+ if (!completed && !finalizeFired && spent >= budget * 0.8) {
1031
+ if (!canFinalize) {
1032
+ forcedStop = true;
1033
+ return "stop";
1034
+ }
1035
+ finalizeFired = true;
1036
+ return "finalize";
1037
+ }
1038
+ return "continue";
1039
+ },
1040
+ refuseTool() {
1041
+ if (!finalizeFired && !snapshot().hardStopped)
1042
+ return null;
1043
+ refusedCalls += 1;
1044
+ return { message: TOKEN_BUDGET_TOOL_REFUSAL, hardStopped: snapshot().hardStopped };
1045
+ }
1046
+ };
1047
+ }
1048
+
1049
+ // ../plugin/src/hooks/magic-context/dropped-input-guard.ts
1050
+ var LEGACY_TRUNCATED_VALUE = /^[\s\S]{0,5}\.\.\.\[truncated\]$/;
1051
+ var MAX_QUOTED_ARGUMENTS = 160;
1052
+ var MAX_LISTED_PARAMETERS = 12;
1053
+ var MAX_TRACKED_SESSIONS = 1000;
1054
+ function isDroppedPlaceholderString(value) {
1055
+ return value.startsWith("[dropped §") && value.endsWith("§]") || LEGACY_TRUNCATED_VALUE.test(value) || value === "[object]" || /^\[\d+ items\]$/.test(value);
1056
+ }
1057
+ function droppedInputMarker(tagId) {
1058
+ return { dropped: `[dropped §${tagId}§]` };
1059
+ }
1060
+ function containsDroppedInputPlaceholder(value) {
1061
+ const seen = new WeakSet;
1062
+ const visit = (candidate) => {
1063
+ if (typeof candidate === "string")
1064
+ return isDroppedPlaceholderString(candidate);
1065
+ if (candidate === null || typeof candidate !== "object")
1066
+ return false;
1067
+ if (seen.has(candidate))
1068
+ return false;
1069
+ seen.add(candidate);
1070
+ if (Array.isArray(candidate))
1071
+ return candidate.some(visit);
1072
+ return Object.values(candidate).some(visit);
1073
+ };
1074
+ return visit(value);
1075
+ }
1076
+ function isRecord2(value) {
1077
+ return value !== null && typeof value === "object";
1078
+ }
1079
+ function isOptionalZodField(field) {
1080
+ if (!isRecord2(field))
1081
+ return false;
1082
+ const isOptional = field.isOptional;
1083
+ if (typeof isOptional === "function") {
1084
+ try {
1085
+ return isOptional.call(field) === true;
1086
+ } catch {}
1087
+ }
1088
+ const internals = field._zod;
1089
+ return internals?.optin === "optional";
1090
+ }
1091
+ function toolParameterNames(schema) {
1092
+ if (!isRecord2(schema))
1093
+ return;
1094
+ const properties = schema.properties;
1095
+ if (isRecord2(properties) && !Array.isArray(properties)) {
1096
+ const names = Object.keys(properties);
1097
+ const requiredList = Array.isArray(schema.required) ? schema.required : [];
1098
+ const required = new Set(requiredList.filter((name) => typeof name === "string"));
1099
+ return {
1100
+ required: names.filter((name) => required.has(name)),
1101
+ optional: names.filter((name) => !required.has(name))
1102
+ };
1103
+ }
1104
+ let shape;
1105
+ try {
1106
+ shape = schema.shape;
1107
+ } catch {
1108
+ shape = undefined;
1109
+ }
1110
+ if (isRecord2(shape) && !Array.isArray(shape)) {
1111
+ const result = { required: [], optional: [] };
1112
+ for (const [name, field] of Object.entries(shape)) {
1113
+ (isOptionalZodField(field) ? result.optional : result.required).push(name);
1114
+ }
1115
+ return result;
1116
+ }
1117
+ return;
1118
+ }
1119
+ var recordedToolParameters = new Map;
1120
+ function quoteArguments(input) {
1121
+ let text;
1122
+ try {
1123
+ text = JSON.stringify(input) ?? String(input);
1124
+ } catch {
1125
+ text = String(input);
1126
+ }
1127
+ return text.length > MAX_QUOTED_ARGUMENTS ? `${text.slice(0, MAX_QUOTED_ARGUMENTS - 1)}…` : text;
1128
+ }
1129
+ function ordinal(value) {
1130
+ const lastTwo = value % 100;
1131
+ if (lastTwo >= 11 && lastTwo <= 13)
1132
+ return `${value}th`;
1133
+ switch (value % 10) {
1134
+ case 1:
1135
+ return `${value}st`;
1136
+ case 2:
1137
+ return `${value}nd`;
1138
+ case 3:
1139
+ return `${value}rd`;
1140
+ default:
1141
+ return `${value}th`;
1142
+ }
1143
+ }
1144
+ function describeParameters(names) {
1145
+ if (!names || names.required.length + names.optional.length === 0) {
1146
+ return "the tool's own parameters";
1147
+ }
1148
+ const listed = [...names.required.map((name) => `${name} (required)`), ...names.optional];
1149
+ const shown = listed.slice(0, MAX_LISTED_PARAMETERS);
1150
+ const more = listed.length > shown.length ? ", …" : "";
1151
+ return `its parameters: ${shown.join(", ")}${more}`;
1152
+ }
1153
+ function droppedInputRefusalMessage(refusal) {
1154
+ const tool = refusal.toolName ? `\`${refusal.toolName}\`` : undefined;
1155
+ const names = toolParameterNames(refusal.parameters) ?? (refusal.toolName ? recordedToolParameters.get(refusal.toolName) : undefined);
1156
+ const lines = [];
1157
+ if (refusal.consecutive >= 2) {
1158
+ lines.push(`This is the ${ordinal(refusal.consecutive)} call in a row with placeholder arguments.`);
1159
+ }
1160
+ lines.push(`Not executed: your arguments${tool ? ` to ${tool}` : ""} were ${quoteArguments(refusal.input)}. That is the placeholder Magic Context shows in place of an earlier call's arguments, not a value to send. Nothing is wrong with the session or the tool.`, `Call ${tool ?? "the tool"} again with real values for ${describeParameters(names)}.`, "Only if you need the original arguments of an earlier dropped call, recover them with ctx_expand first.");
1161
+ return lines.join(`
1162
+ `);
1163
+ }
1164
+ function createDroppedInputGuard(options = {}) {
1165
+ const consecutiveBySession = new Map;
1166
+ return {
1167
+ check(call) {
1168
+ const session = call.sessionID ?? "";
1169
+ if (!containsDroppedInputPlaceholder(call.input)) {
1170
+ consecutiveBySession.delete(session);
1171
+ return;
1172
+ }
1173
+ const consecutive = (consecutiveBySession.get(session) ?? 0) + 1;
1174
+ consecutiveBySession.delete(session);
1175
+ consecutiveBySession.set(session, consecutive);
1176
+ if (consecutiveBySession.size > MAX_TRACKED_SESSIONS) {
1177
+ const oldest = consecutiveBySession.keys().next().value;
1178
+ if (oldest !== undefined)
1179
+ consecutiveBySession.delete(oldest);
1180
+ }
1181
+ let parameters;
1182
+ if (call.toolName && options.parametersFor) {
1183
+ try {
1184
+ parameters = options.parametersFor(call.toolName);
1185
+ } catch {
1186
+ parameters = undefined;
1187
+ }
1188
+ }
1189
+ return droppedInputRefusalMessage({
1190
+ toolName: call.toolName,
1191
+ input: call.input,
1192
+ parameters,
1193
+ consecutive
1194
+ });
1195
+ }
1196
+ };
1197
+ }
1198
+
1199
+ // ../plugin/src/hooks/magic-context/edit-marker.ts
1200
+ var TRUNCATION_SENTINEL = "...[truncated]";
1201
+ var EDIT_REGION_HINT_LEN = 40;
1202
+ var PATH_KEYS = new Set(["filePath", "file_path", "path"]);
1203
+ var DIFF_KEYS = new Set(["oldString", "newString", "content", "old_string", "new_string"]);
1204
+ function safeSlice(str, maxLen) {
1205
+ if (str.length <= maxLen)
1206
+ return str;
1207
+ const lastCharCode = str.charCodeAt(maxLen - 1);
1208
+ if (lastCharCode >= 55296 && lastCharCode <= 56319) {
1209
+ return str.slice(0, maxLen - 1);
1210
+ }
1211
+ return str.slice(0, maxLen);
1212
+ }
1213
+ function isEditTool(name) {
1214
+ return name === "edit" || name === "write";
1215
+ }
1216
+ function applyEditMarkerToInput(input) {
1217
+ for (const key of Object.keys(input)) {
1218
+ if (PATH_KEYS.has(key))
1219
+ continue;
1220
+ const value = input[key];
1221
+ if (typeof value !== "string" || !DIFF_KEYS.has(key))
1222
+ continue;
1223
+ if (value.endsWith(TRUNCATION_SENTINEL))
1224
+ continue;
1225
+ input[key] = value.length > EDIT_REGION_HINT_LEN ? `${safeSlice(value, EDIT_REGION_HINT_LEN)}${TRUNCATION_SENTINEL}` : value;
1226
+ }
1227
+ }
1228
+
1229
+ // ../plugin/src/hooks/magic-context/tool-input-size.ts
1230
+ var SKELETON_REAL_INPUT_MAX_BYTES = 1024;
1231
+ var encoder = new TextEncoder;
1232
+ function toolInputStringBytes(value) {
1233
+ const seen = new WeakSet;
1234
+ const visit = (candidate) => {
1235
+ if (typeof candidate === "string")
1236
+ return encoder.encode(candidate).length;
1237
+ if (candidate === null || typeof candidate !== "object")
1238
+ return 0;
1239
+ if (seen.has(candidate))
1240
+ return 0;
1241
+ seen.add(candidate);
1242
+ let total = 0;
1243
+ const values = Array.isArray(candidate) ? candidate : Object.values(candidate);
1244
+ for (const item of values)
1245
+ total += visit(item);
1246
+ return total;
1247
+ };
1248
+ return visit(value);
1249
+ }
1250
+
1251
+ // ../plugin/src/hooks/magic-context/tool-drop-target.ts
1252
+ var IGNORE_PART_TYPES = new Set([
1253
+ "thinking",
1254
+ "reasoning",
1255
+ "redacted_thinking",
1256
+ "meta",
1257
+ "step-start",
1258
+ "step-finish"
1259
+ ]);
1260
+ function isToolCallId(value) {
1261
+ return typeof value === "string" && value.length > 0;
1262
+ }
1263
+ function extractToolCallObservation(part) {
1264
+ if (!isRecord(part))
1265
+ return null;
1266
+ if (part.type === "tool" && isToolCallId(part.callID)) {
1267
+ return { callId: part.callID, kind: "result" };
1268
+ }
1269
+ if (part.type === "tool-invocation" && isToolCallId(part.callID)) {
1270
+ return { callId: part.callID, kind: "invocation" };
1271
+ }
1272
+ if (part.type === "tool_use" && isToolCallId(part.id)) {
1273
+ return { callId: part.id, kind: "invocation" };
1274
+ }
1275
+ if (part.type === "tool_result" && isToolCallId(part.tool_use_id)) {
1276
+ return { callId: part.tool_use_id, kind: "result" };
1277
+ }
1278
+ return null;
1279
+ }
1280
+
1281
+ // ../plugin/src/hooks/magic-context/read-session-chunk.ts
1282
+ var BLOCK_TOKEN_MEMO_MAX = 2048;
1283
+ var blockTokenMemo = new Map;
1284
+ function estimateBlockTokens(blockText) {
1285
+ const cached = blockTokenMemo.get(blockText);
1286
+ if (cached !== undefined) {
1287
+ blockTokenMemo.delete(blockText);
1288
+ blockTokenMemo.set(blockText, cached);
1289
+ return cached;
1290
+ }
1291
+ const count = estimateTokens(blockText);
1292
+ if (blockTokenMemo.size >= BLOCK_TOKEN_MEMO_MAX) {
1293
+ const oldest = blockTokenMemo.keys().next().value;
1294
+ if (oldest !== undefined)
1295
+ blockTokenMemo.delete(oldest);
1296
+ }
1297
+ blockTokenMemo.set(blockText, count);
1298
+ return count;
1299
+ }
1300
+ var activeRawMessageCache = null;
1301
+ var activeAbsoluteCountCache = null;
1302
+ var sessionProviders = new Map;
1303
+ function resolveHostServedBoundaryId2(sessionId, messageId) {
1304
+ if (messageId.length === 0)
1305
+ return messageId;
1306
+ return sessionProviders.get(sessionId)?.provider.readServedBoundaryId?.(messageId) ?? messageId;
1307
+ }
1308
+ function hasRawMessageProvider2(sessionId) {
1309
+ return sessionProviders.has(sessionId);
1310
+ }
1311
+ function rawMessageWorkerSource2(sessionId) {
1312
+ return sessionProviders.get(sessionId)?.provider.workerSource;
1313
+ }
1314
+ function rawMessageOffThreadRangeReader2(sessionId) {
1315
+ const provider = sessionProviders.get(sessionId)?.provider;
1316
+ return provider?.readMessageIdOrdinalsForRangeOffThread?.bind(provider);
1317
+ }
1318
+ function setRawMessageProvider2(sessionId, provider) {
1319
+ const current = sessionProviders.get(sessionId);
1320
+ const registration = current?.provider === provider ? current : { provider, scopes: 0 };
1321
+ registration.scopes += 1;
1322
+ sessionProviders.set(sessionId, registration);
1323
+ let active = true;
1324
+ return () => {
1325
+ if (!active)
1326
+ return;
1327
+ active = false;
1328
+ registration.scopes -= 1;
1329
+ if (registration.scopes === 0 && sessionProviders.get(sessionId) === registration) {
1330
+ sessionProviders.delete(sessionId);
1331
+ }
1332
+ };
1333
+ }
1334
+ var boundedProviderWrappers = new WeakMap;
1335
+ function setBoundedRawMessageProvider2(sessionId, provider) {
1336
+ let wrapper = boundedProviderWrappers.get(provider);
1337
+ if (!wrapper) {
1338
+ wrapper = {
1339
+ ...provider,
1340
+ readMessages: () => {
1341
+ throw new Error("Bounded raw-message providers cannot read complete history; full reads are reserved for store-generation conversion");
1342
+ }
1343
+ };
1344
+ boundedProviderWrappers.set(provider, wrapper);
1345
+ }
1346
+ return setRawMessageProvider2(sessionId, wrapper);
1347
+ }
1348
+ function withRawMessageProvider2(sessionId, provider, fn) {
1349
+ const cleanup = setRawMessageProvider2(sessionId, provider);
1350
+ let result;
1351
+ try {
1352
+ result = fn();
1353
+ } catch (error) {
1354
+ cleanup();
1355
+ throw error;
1356
+ }
1357
+ if (result !== null && typeof result === "object" && typeof result.then === "function") {
1358
+ return result.finally(cleanup);
1359
+ }
1360
+ cleanup();
1361
+ return result;
1362
+ }
1363
+ function cleanUserText2(text) {
1364
+ return stripOutsideSteeringWrappers(text, (segment) => removeSystemReminders(segment).replace(OMO_INTERNAL_INITIATOR_MARKER, "")).trim();
1365
+ }
1366
+ function answerLineParts(rawText) {
1367
+ return askAnswerLines(rawText).map(normalizeText).filter((value) => value.length > 0);
1368
+ }
1369
+ function hasMeaningfulChunkUserText(parts) {
1370
+ for (const part of parts) {
1371
+ if (part === null || typeof part !== "object")
1372
+ continue;
1373
+ const candidate = part;
1374
+ if (candidate.type !== "text" || typeof candidate.text !== "string")
1375
+ continue;
1376
+ if (candidate.ignored === true)
1377
+ continue;
1378
+ const cleaned = cleanUserText2(candidate.text);
1379
+ if (!cleaned)
1380
+ continue;
1381
+ if (isSystemDirective(cleaned))
1382
+ continue;
1383
+ return true;
1384
+ }
1385
+ return parts.some((part) => part !== null && typeof part === "object" && part.type === "text" && typeof part.text === "string" && part.ignored !== true && askAnswerLines(part.text).length > 0);
1386
+ }
1387
+ function withRawSessionMessageCache2(fn) {
1388
+ const outerCache = activeRawMessageCache;
1389
+ if (!outerCache) {
1390
+ activeRawMessageCache = new Map;
1391
+ activeAbsoluteCountCache = new Map;
1392
+ }
1393
+ try {
1394
+ return fn();
1395
+ } finally {
1396
+ if (!outerCache) {
1397
+ activeRawMessageCache = null;
1398
+ activeAbsoluteCountCache = null;
1399
+ }
1400
+ }
1401
+ }
1402
+ function readRawSessionMessages2(sessionId) {
1403
+ if (activeRawMessageCache) {
1404
+ const cached = activeRawMessageCache.get(sessionId);
1405
+ if (cached?.coveredFromOrdinal === 1 && cached.coveredToOrdinal === null) {
1406
+ return cached.messages;
1407
+ }
1408
+ const messages = readRawSessionMessagesFromSource(sessionId);
1409
+ if (!cached) {
1410
+ activeRawMessageCache.set(sessionId, {
1411
+ messages,
1412
+ coveredFromOrdinal: 1,
1413
+ coveredToOrdinal: null
1414
+ });
1415
+ }
1416
+ return messages;
1417
+ }
1418
+ return readRawSessionMessagesFromSource(sessionId);
1419
+ }
1420
+ function readRawSessionMessagePage2(sessionId, afterOrdinal, limit, finalWatermark, after) {
1421
+ const provider = sessionProviders.get(sessionId)?.provider;
1422
+ if (provider?.readMessagePage) {
1423
+ return provider.readMessagePage(afterOrdinal, limit, finalWatermark, after);
1424
+ }
1425
+ if (provider) {
1426
+ return provider.readMessages().filter((message) => message.ordinal > afterOrdinal && message.ordinal <= finalWatermark).slice(0, limit);
1427
+ }
1428
+ if (!openCodeDbExists())
1429
+ return [];
1430
+ return withReadOnlySessionDb((db) => readRawSessionMessagePageFromDb2(db, sessionId, afterOrdinal, limit, finalWatermark, after));
1431
+ }
1432
+ function getRawSessionMessageOrdinalCount2(sessionId) {
1433
+ const provider = sessionProviders.get(sessionId)?.provider;
1434
+ if (provider) {
1435
+ if (provider.getMessageCount)
1436
+ return provider.getMessageCount();
1437
+ const messages = provider.readMessages();
1438
+ return messages.reduce((maximum, message) => Math.max(maximum, message.ordinal), messages.length);
1439
+ }
1440
+ if (!openCodeDbExists())
1441
+ return 0;
1442
+ return withReadOnlySessionDb((db) => countRawSessionMessageOrdinalsFromDb2(db, sessionId));
1443
+ }
1444
+ var RAW_MESSAGE_RANGE_PAGE_SIZE = 100;
1445
+ function readRawSessionMessageRangeFromSource(sessionId, fromOrdinal, toOrdinal) {
1446
+ const provider = sessionProviders.get(sessionId)?.provider;
1447
+ if (provider?.iterateMessageRange)
1448
+ return [...provider.iterateMessageRange(fromOrdinal, toOrdinal)];
1449
+ if (provider && !provider.readMessagePage) {
1450
+ return provider.readMessages().filter((message) => message.ordinal >= fromOrdinal && message.ordinal <= toOrdinal);
1451
+ }
1452
+ if (!provider && !openCodeDbExists())
1453
+ return [];
1454
+ const messages = [];
1455
+ let afterOrdinal = fromOrdinal - 1;
1456
+ let after;
1457
+ while (afterOrdinal < toOrdinal) {
1458
+ const limit = Math.min(RAW_MESSAGE_RANGE_PAGE_SIZE, toOrdinal - afterOrdinal);
1459
+ const page = provider?.readMessagePage ? provider.readMessagePage(afterOrdinal, limit, toOrdinal, after) : withReadOnlySessionDb((db) => readRawSessionMessagePageFromDb2(db, sessionId, afterOrdinal, limit, toOrdinal, after));
1460
+ if (page.length === 0)
1461
+ break;
1462
+ let nextOrdinal = afterOrdinal;
1463
+ for (const message of page) {
1464
+ if (message.ordinal < fromOrdinal || message.ordinal > toOrdinal)
1465
+ continue;
1466
+ messages.push(message);
1467
+ nextOrdinal = Math.max(nextOrdinal, message.ordinal);
1468
+ }
1469
+ if (nextOrdinal <= afterOrdinal)
1470
+ break;
1471
+ afterOrdinal = nextOrdinal;
1472
+ const last = page.at(-1);
1473
+ after = last ? { timeCreated: last.createdAt ?? 0, id: last.id } : undefined;
1474
+ }
1475
+ return messages;
1476
+ }
1477
+ var RAW_MESSAGE_VISIT_PAGE_SIZE2 = 50;
1478
+ function visitRawSessionMessages2(sessionId, fromOrdinal, toOrdinal, visit, options = {}) {
1479
+ const from = Math.max(1, Math.floor(fromOrdinal));
1480
+ const to = Math.floor(toOrdinal);
1481
+ if (to < from)
1482
+ return;
1483
+ const provider = sessionProviders.get(sessionId)?.provider;
1484
+ if (provider?.iterateMessageRange) {
1485
+ for (const message of provider.iterateMessageRange(from, to)) {
1486
+ if (!visit(message))
1487
+ return;
1488
+ }
1489
+ return;
1490
+ }
1491
+ if (provider && !provider.readMessagePage) {
1492
+ for (const message of provider.readMessages()) {
1493
+ if (message.ordinal < from || message.ordinal > to)
1494
+ continue;
1495
+ if (!visit(message))
1496
+ return;
1497
+ }
1498
+ return;
1499
+ }
1500
+ if (!provider && !openCodeDbExists())
1501
+ return;
1502
+ const pageSize = Math.max(1, Math.floor(options.pageSize ?? RAW_MESSAGE_VISIT_PAGE_SIZE2));
1503
+ let afterOrdinal = from - 1;
1504
+ let after;
1505
+ while (afterOrdinal < to) {
1506
+ const limit = Math.min(pageSize, to - afterOrdinal);
1507
+ const cursor = afterOrdinal;
1508
+ const page = provider?.readMessagePage ? provider.readMessagePage(cursor, limit, to, after) : withReadOnlySessionDb((db) => options.summary ? readRawSessionMessageSummaryPageFromDb2(db, sessionId, cursor, limit, to, after) : readRawSessionMessagePageFromDb2(db, sessionId, cursor, limit, to, after));
1509
+ if (page.length === 0)
1510
+ return;
1511
+ let nextOrdinal = afterOrdinal;
1512
+ for (const message of page) {
1513
+ if (message.ordinal < from || message.ordinal > to)
1514
+ continue;
1515
+ if (!visit(message))
1516
+ return;
1517
+ nextOrdinal = Math.max(nextOrdinal, message.ordinal);
1518
+ }
1519
+ if (nextOrdinal <= afterOrdinal)
1520
+ return;
1521
+ afterOrdinal = nextOrdinal;
1522
+ const last = page.at(-1);
1523
+ after = last ? { timeCreated: last.createdAt ?? 0, id: last.id } : undefined;
1524
+ }
1525
+ }
1526
+ async function visitRawSessionMessagesAsync2(sessionId, fromOrdinal, toOrdinal, visit, options = {}) {
1527
+ const from = Math.max(1, Math.floor(fromOrdinal));
1528
+ const to = Math.floor(toOrdinal);
1529
+ if (to < from)
1530
+ return;
1531
+ const provider = sessionProviders.get(sessionId)?.provider;
1532
+ if (!provider?.iterateMessageRangeAsync) {
1533
+ visitRawSessionMessages2(sessionId, from, to, visit, options);
1534
+ return;
1535
+ }
1536
+ for await (const message of provider.iterateMessageRangeAsync(from, to)) {
1537
+ if (!visit(message))
1538
+ return;
1539
+ }
1540
+ }
1541
+ function readRawSessionMessageRange2(sessionId, fromOrdinal, toOrdinal) {
1542
+ const from = Math.max(1, Math.floor(fromOrdinal));
1543
+ const to = Math.floor(toOrdinal);
1544
+ if (to < from)
1545
+ return [];
1546
+ const cached = activeRawMessageCache?.get(sessionId);
1547
+ if (!cached)
1548
+ return readRawSessionMessageRangeFromSource(sessionId, from, to);
1549
+ const coveredTo = cached.coveredToOrdinal ?? Number.POSITIVE_INFINITY;
1550
+ const overlapFrom = Math.max(from, cached.coveredFromOrdinal);
1551
+ const overlapTo = Math.min(to, coveredTo);
1552
+ if (overlapTo < overlapFrom) {
1553
+ return readRawSessionMessageRangeFromSource(sessionId, from, to);
1554
+ }
1555
+ const messages = [];
1556
+ if (from < overlapFrom) {
1557
+ messages.push(...readRawSessionMessageRangeFromSource(sessionId, from, overlapFrom - 1));
1558
+ }
1559
+ messages.push(...cached.messages.filter((message) => message.ordinal >= overlapFrom && message.ordinal <= overlapTo));
1560
+ if (overlapTo < to) {
1561
+ messages.push(...readRawSessionMessageRangeFromSource(sessionId, overlapTo + 1, to));
1562
+ }
1563
+ return messages;
1564
+ }
1565
+ readRawSessionMessages2.readPage = readRawSessionMessagePage2;
1566
+ readRawSessionMessages2.getCount = getRawSessionMessageOrdinalCount2;
1567
+ readRawSessionMessages2.prepare = prepareRawSessionOrdinals2;
1568
+ async function prepareRawSessionOrdinals2(sessionId) {
1569
+ if (sessionProviders.get(sessionId)?.provider)
1570
+ return true;
1571
+ if (!openCodeDbExists())
1572
+ return true;
1573
+ const db = withReadOnlySessionDb((connection) => connection);
1574
+ let timer;
1575
+ const deadline = Date.now() + 250;
1576
+ const prepare = async () => {
1577
+ for (let attempt = 0;attempt < 3 && Date.now() < deadline; attempt++) {
1578
+ if (await prewarmRawSessionOrdinalsForDb(db, sessionId) === "warm")
1579
+ return true;
1580
+ }
1581
+ return false;
1582
+ };
1583
+ try {
1584
+ const ready = await Promise.race([
1585
+ prepare(),
1586
+ new Promise((resolve) => {
1587
+ timer = setTimeout(() => resolve(false), 250);
1588
+ })
1589
+ ]);
1590
+ if (!ready) {
1591
+ sessionLog2(sessionId, "WARN canonical ordinal preparation unavailable within 250ms; exact reads must defer or retry");
1592
+ }
1593
+ return ready;
1594
+ } finally {
1595
+ clearTimeout(timer);
1596
+ }
1597
+ }
1598
+ function primeTailRawMessageCache2(args) {
1599
+ const { sessionId, lastCompartmentEnd, anchorMessageId } = args;
1600
+ if (!activeRawMessageCache)
1601
+ return false;
1602
+ if (activeRawMessageCache.has(sessionId))
1603
+ return false;
1604
+ if (lastCompartmentEnd < 1 || !anchorMessageId)
1605
+ return false;
1606
+ const provider = sessionProviders.get(sessionId)?.provider;
1607
+ if (provider) {
1608
+ if (!provider.readMessagePage || !provider.getMessageCount)
1609
+ return false;
1610
+ const absoluteMessageCount = provider.getMessageCount();
1611
+ const messages = readRawSessionMessageRange2(sessionId, lastCompartmentEnd, absoluteMessageCount);
1612
+ if (messages.find((message) => message.ordinal === lastCompartmentEnd)?.id !== anchorMessageId)
1613
+ return false;
1614
+ activeRawMessageCache.set(sessionId, {
1615
+ messages,
1616
+ coveredFromOrdinal: lastCompartmentEnd,
1617
+ coveredToOrdinal: lastCompartmentEnd === 1 ? null : absoluteMessageCount
1618
+ });
1619
+ activeAbsoluteCountCache?.set(sessionId, absoluteMessageCount);
1620
+ return true;
1621
+ }
1622
+ if (!openCodeDbExists())
1623
+ return false;
1624
+ const result = withReadOnlySessionDb((db) => readRawSessionTailFromDb2(db, sessionId, lastCompartmentEnd, anchorMessageId));
1625
+ if (!result)
1626
+ return false;
1627
+ activeRawMessageCache.set(sessionId, {
1628
+ messages: result.messages,
1629
+ coveredFromOrdinal: lastCompartmentEnd,
1630
+ coveredToOrdinal: lastCompartmentEnd === 1 ? null : result.absoluteMessageCount
1631
+ });
1632
+ activeAbsoluteCountCache?.set(sessionId, result.absoluteMessageCount);
1633
+ return true;
1634
+ }
1635
+ function getCachedAbsoluteMessageCount2(sessionId) {
1636
+ return activeAbsoluteCountCache?.get(sessionId) ?? null;
1637
+ }
1638
+ function primeInMemoryTailRawMessageCache2(args) {
1639
+ const { sessionId, messages, absoluteMessageCount } = args;
1640
+ if (!activeRawMessageCache)
1641
+ return false;
1642
+ if (activeRawMessageCache.has(sessionId))
1643
+ return false;
1644
+ const coveredFromOrdinal = messages[0]?.ordinal ?? absoluteMessageCount + 1;
1645
+ activeRawMessageCache.set(sessionId, {
1646
+ messages,
1647
+ coveredFromOrdinal,
1648
+ coveredToOrdinal: coveredFromOrdinal === 1 ? null : absoluteMessageCount
1649
+ });
1650
+ activeAbsoluteCountCache?.set(sessionId, absoluteMessageCount);
1651
+ return true;
1652
+ }
1653
+ function readRawSessionMessageOrdinalPage2(sessionId, after, limit) {
1654
+ const provider = sessionProviders.get(sessionId)?.provider;
1655
+ if (provider?.readMessageOrdinalPage)
1656
+ return provider.readMessageOrdinalPage(after, limit);
1657
+ if (provider) {
1658
+ const rows = provider.readMessages().map((message) => ({
1659
+ id: message.id,
1660
+ timeCreated: message.createdAt ?? message.ordinal,
1661
+ contributesOrdinal: true,
1662
+ hasValidInfo: true
1663
+ })).filter((row) => !after || row.timeCreated > after.timeCreated || row.timeCreated === after.timeCreated && row.id > after.id).sort((left, right) => left.timeCreated - right.timeCreated || left.id.localeCompare(right.id));
1664
+ return rows.slice(0, Math.max(1, Math.floor(limit)));
1665
+ }
1666
+ if (!openCodeDbExists())
1667
+ return [];
1668
+ return withReadOnlySessionDb((db) => readRawSessionMessageOrdinalPageFromDb2(db, sessionId, after, limit));
1669
+ }
1670
+ function getRawSessionStoredMessageCount2(sessionId) {
1671
+ const provider = sessionProviders.get(sessionId)?.provider;
1672
+ if (provider?.getStoredMessageCount)
1673
+ return provider.getStoredMessageCount();
1674
+ if (provider)
1675
+ return provider.readMessages().length;
1676
+ if (!openCodeDbExists())
1677
+ return 0;
1678
+ return withReadOnlySessionDb((db) => countStoredRawSessionMessagesFromDb2(db, sessionId));
1679
+ }
1680
+ function readRawSessionMessageIdOrdinalsForRange2(sessionId, fromOrdinal, toOrdinal) {
1681
+ const from = Math.max(1, Math.floor(fromOrdinal));
1682
+ const to = Math.floor(toOrdinal);
1683
+ if (to < from)
1684
+ return new Map;
1685
+ const provider = sessionProviders.get(sessionId)?.provider;
1686
+ if (provider?.readMessageIdOrdinalsForRange) {
1687
+ return provider.readMessageIdOrdinalsForRange(from, to);
1688
+ }
1689
+ if (!provider) {
1690
+ return !openCodeDbExists() ? new Map : withReadOnlySessionDb((db) => readRawSessionMessageIdOrdinalsForRangeFromDb2(db, sessionId, from, to));
1691
+ }
1692
+ const all = provider?.readMessageIdOrdinals ? provider.readMessageIdOrdinals() : new Map(provider.readMessages().map((message) => [message.id, message.ordinal]));
1693
+ return new Map([...all].filter(([, ordinal]) => ordinal >= from && ordinal <= to));
1694
+ }
1695
+ function readRawSessionMessageIdOrdinals2(sessionId) {
1696
+ const count = getRawSessionMessageOrdinalCount2(sessionId);
1697
+ return readRawSessionMessageIdOrdinalsForRange2(sessionId, 1, count);
1698
+ }
1699
+ function readRawSessionMessagePartsById2(sessionId, messageId, onQuery) {
1700
+ const provider = sessionProviders.get(sessionId)?.provider;
1701
+ if (provider?.readMessagePartsById)
1702
+ return provider.readMessagePartsById(messageId);
1703
+ if (provider?.readMessageById)
1704
+ return provider.readMessageById(messageId);
1705
+ if (provider) {
1706
+ return provider.readMessages().find((message) => message.id === messageId) ?? null;
1707
+ }
1708
+ if (!openCodeDbExists())
1709
+ return null;
1710
+ return withReadOnlySessionDb((db) => readRawSessionMessagePartsByIdFromDb2(db, sessionId, messageId, onQuery));
1711
+ }
1712
+ function readRawSessionBoundaryEndpoints2(sessionId, ids, blockIds) {
1713
+ if (sessionProviders.get(sessionId)?.provider)
1714
+ return null;
1715
+ if (!openCodeDbExists())
1716
+ return new Map(ids.map((id) => [id, null]));
1717
+ return withReadOnlySessionDb((db) => readRawSessionBoundaryEndpointsFromDb2(db, sessionId, ids, blockIds));
1718
+ }
1719
+ function hasRawSessionMessageById2(sessionId, messageId) {
1720
+ const provider = sessionProviders.get(sessionId)?.provider;
1721
+ if (provider?.hasMessageById)
1722
+ return provider.hasMessageById(messageId);
1723
+ if (!provider)
1724
+ return openCodeDbExists() && withReadOnlySessionDb((db) => hasRawSessionMessageByIdFromDb2(db, sessionId, messageId));
1725
+ return readRawSessionMessageById2(sessionId, messageId) !== null;
1726
+ }
1727
+ function readRawSessionMessageOrdinalById2(sessionId, messageId) {
1728
+ const provider = sessionProviders.get(sessionId)?.provider;
1729
+ if (provider?.readMessageOrdinalById) {
1730
+ return provider.readMessageOrdinalById(messageId);
1731
+ }
1732
+ if (provider?.readMessageIdOrdinals) {
1733
+ return provider.readMessageIdOrdinals().get(messageId) ?? null;
1734
+ }
1735
+ if (provider?.readMessageOrdinalPage) {
1736
+ let after = null;
1737
+ let ordinal = 0;
1738
+ while (true) {
1739
+ const page = provider.readMessageOrdinalPage(after, 500);
1740
+ if (page.length === 0)
1741
+ return null;
1742
+ for (const entry of page) {
1743
+ if (entry.contributesOrdinal)
1744
+ ordinal += 1;
1745
+ if (entry.id === messageId)
1746
+ return entry.contributesOrdinal ? ordinal : null;
1747
+ }
1748
+ const last = page.at(-1);
1749
+ if (!last || page.length < 500)
1750
+ return null;
1751
+ after = { timeCreated: last.timeCreated, id: last.id };
1752
+ }
1753
+ }
1754
+ if (provider?.readMessageById) {
1755
+ return provider.readMessageById(messageId)?.ordinal ?? null;
1756
+ }
1757
+ if (provider) {
1758
+ return provider.readMessages().find((message) => message.id === messageId)?.ordinal ?? null;
1759
+ }
1760
+ if (!openCodeDbExists())
1761
+ return null;
1762
+ return withReadOnlySessionDb((db) => readRawSessionMessageOrdinalByIdFromDb2(db, sessionId, messageId));
1763
+ }
1764
+ function resolveHistorianChunkStart2(sessionId, newest) {
1765
+ if (!newest)
1766
+ return 1;
1767
+ const fallback = newest.endMessage + 1;
1768
+ if (hasRawMessageProvider2(sessionId))
1769
+ return fallback;
1770
+ const endId = newest.endMessageId;
1771
+ if (typeof endId !== "string" || endId.length === 0)
1772
+ return fallback;
1773
+ const ordinal = readRawSessionMessageOrdinalById2(sessionId, endId);
1774
+ if (typeof ordinal !== "number" || !Number.isFinite(ordinal) || ordinal < 1)
1775
+ return fallback;
1776
+ return ordinal + 1;
1777
+ }
1778
+ function readRawSessionMessageOrderPosition(sessionId, messageId) {
1779
+ const provider = sessionProviders.get(sessionId)?.provider;
1780
+ if (provider) {
1781
+ return provider.readMessageOrderById ? provider.readMessageOrderById(messageId) : provider.readMessageOrdinalById?.(messageId) ?? null;
1782
+ }
1783
+ return readRawSessionMessageOrdinalById2(sessionId, messageId);
1784
+ }
1785
+ function compareRawSessionMessageOrder2(sessionId, leftId, rightId) {
1786
+ const provider = sessionProviders.get(sessionId)?.provider;
1787
+ if (provider) {
1788
+ if (!provider.readMessageOrderById && !provider.readMessageOrdinalById)
1789
+ return null;
1790
+ const left = readRawSessionMessageOrderPosition(sessionId, leftId);
1791
+ const right = readRawSessionMessageOrderPosition(sessionId, rightId);
1792
+ return left === null || right === null ? null : left - right;
1793
+ }
1794
+ if (!openCodeDbExists())
1795
+ return null;
1796
+ return withReadOnlySessionDb((db) => {
1797
+ const lookup = db.prepare("SELECT time_created, id FROM message WHERE session_id = ? AND id = ? LIMIT 1");
1798
+ const left = lookup.get(sessionId, leftId);
1799
+ const right = lookup.get(sessionId, rightId);
1800
+ if (typeof left?.time_created !== "number" || typeof right?.time_created !== "number" || typeof left.id !== "string" || typeof right.id !== "string") {
1801
+ return null;
1802
+ }
1803
+ if (left.time_created !== right.time_created) {
1804
+ return left.time_created - right.time_created;
1805
+ }
1806
+ return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
1807
+ });
1808
+ }
1809
+ function readRawSessionMessageById2(sessionId, messageId) {
1810
+ const provider = sessionProviders.get(sessionId)?.provider;
1811
+ if (provider?.readMessageById) {
1812
+ return provider.readMessageById(messageId);
1813
+ }
1814
+ if (provider) {
1815
+ return provider.readMessages().find((message) => message.id === messageId) ?? null;
1816
+ }
1817
+ if (!openCodeDbExists())
1818
+ return null;
1819
+ return withReadOnlySessionDb((db) => readRawSessionMessageByIdFromDb2(db, sessionId, messageId));
1820
+ }
1821
+ readRawSessionMessageById2.prepare = prepareRawSessionOrdinals2;
1822
+ function readRawSessionMessagesFromSource(sessionId) {
1823
+ const provider = sessionProviders.get(sessionId)?.provider;
1824
+ if (provider)
1825
+ return provider.readMessages();
1826
+ if (!openCodeDbExists())
1827
+ return [];
1828
+ return withReadOnlySessionDb((db) => readRawSessionMessagesFromDb2(db, sessionId));
1829
+ }
1830
+ function getRawSessionMessageCount2(sessionId) {
1831
+ const provider = sessionProviders.get(sessionId)?.provider;
1832
+ if (provider) {
1833
+ if (provider.getMessageCount)
1834
+ return provider.getMessageCount();
1835
+ const messages = provider.readMessages();
1836
+ return messages.reduce((maximum, message) => Math.max(maximum, message.ordinal), messages.length);
1837
+ }
1838
+ if (!openCodeDbExists())
1839
+ return 0;
1840
+ return withReadOnlySessionDb((db) => getRawSessionMessageCountFromDb(db, sessionId));
1841
+ }
1842
+ var RAW_SESSION_TAG_KEY_PAGE_SIZE2 = 32;
1843
+ function yieldRawSessionTagKeyPage() {
1844
+ return new Promise((resolve) => {
1845
+ const immediate = globalThis.setImmediate;
1846
+ if (typeof immediate === "function") {
1847
+ immediate(resolve);
1848
+ return;
1849
+ }
1850
+ setTimeout(resolve, 0);
1851
+ });
1852
+ }
1853
+ async function getRawSessionTagKeysThrough2(sessionId, upToMessageIndex, options = {}) {
1854
+ const messageFileKeys = new Set;
1855
+ const toolObservations = new Map;
1856
+ const unpairedInvocations = new Map;
1857
+ const candidateOwnersByCallId = new Map;
1858
+ const messageTimesById = new Map;
1859
+ const finalWatermark = Number.isFinite(upToMessageIndex) ? Math.max(0, Math.floor(upToMessageIndex)) : getRawSessionMessageOrdinalCount2(sessionId);
1860
+ const pageSize = Number.isFinite(options.pageSize) ? Math.max(1, Math.floor(options.pageSize ?? RAW_SESSION_TAG_KEY_PAGE_SIZE2)) : RAW_SESSION_TAG_KEY_PAGE_SIZE2;
1861
+ const yieldToEventLoop = options.yieldToEventLoop ?? yieldRawSessionTagKeyPage;
1862
+ const nearestPersistedOwner = (callId, currentMessageId) => {
1863
+ if (!options.db)
1864
+ return null;
1865
+ let candidates = candidateOwnersByCallId.get(callId);
1866
+ if (!candidates) {
1867
+ candidates = getCandidateToolOwners2(options.db, sessionId, callId);
1868
+ candidateOwnersByCallId.set(callId, candidates);
1869
+ }
1870
+ if (candidates.length === 0)
1871
+ return null;
1872
+ const ids = [...candidates, currentMessageId];
1873
+ const unresolved = ids.filter((id) => !messageTimesById.has(id));
1874
+ if (unresolved.length > 0) {
1875
+ const resolved = getMessageTimesFromOpenCodeDb(sessionId, unresolved);
1876
+ for (const id of unresolved) {
1877
+ messageTimesById.set(id, resolved.get(id) ?? null);
1878
+ }
1879
+ }
1880
+ const times = new Map;
1881
+ for (const id of ids) {
1882
+ const time = messageTimesById.get(id);
1883
+ if (typeof time === "number")
1884
+ times.set(id, time);
1885
+ }
1886
+ return pickNearestPriorOwner2(candidates, currentMessageId, times);
1887
+ };
1888
+ const firstOrdinal = Number.isFinite(options.fromMessageIndex) ? Math.max(1, Math.floor(options.fromMessageIndex ?? 1)) : 1;
1889
+ let afterOrdinal = firstOrdinal - 1;
1890
+ let after;
1891
+ while (afterOrdinal < finalWatermark) {
1892
+ const messages = readRawSessionMessages2.readPage(sessionId, afterOrdinal, pageSize, finalWatermark, after);
1893
+ if (messages.length === 0)
1894
+ break;
1895
+ let nextOrdinal = afterOrdinal;
1896
+ for (const message of messages) {
1897
+ if (message.ordinal <= afterOrdinal || message.ordinal > finalWatermark)
1898
+ continue;
1899
+ nextOrdinal = Math.max(nextOrdinal, message.ordinal);
1900
+ messageTimesById.set(message.id, typeof message.createdAt === "number" ? message.createdAt : null);
1901
+ for (const [partIndex, part] of message.parts.entries()) {
1902
+ if (isTextPart(part)) {
1903
+ messageFileKeys.add(`${message.id}:p${partIndex}`);
1904
+ continue;
1905
+ }
1906
+ if (isFilePart(part)) {
1907
+ messageFileKeys.add(`${message.id}:file${partIndex}`);
1908
+ continue;
1909
+ }
1910
+ const observation = extractToolCallObservation(part);
1911
+ if (!observation)
1912
+ continue;
1913
+ let ownerMessageId;
1914
+ if (observation.kind === "invocation") {
1915
+ ownerMessageId = message.id;
1916
+ const queue = unpairedInvocations.get(observation.callId) ?? [];
1917
+ queue.push(message.id);
1918
+ unpairedInvocations.set(observation.callId, queue);
1919
+ } else {
1920
+ const queue = unpairedInvocations.get(observation.callId);
1921
+ const pairedOwner = queue?.shift();
1922
+ if (queue?.length === 0)
1923
+ unpairedInvocations.delete(observation.callId);
1924
+ ownerMessageId = pairedOwner ?? nearestPersistedOwner(observation.callId, message.id) ?? message.id;
1925
+ }
1926
+ const owners = toolObservations.get(observation.callId) ?? new Set;
1927
+ owners.add(ownerMessageId);
1928
+ toolObservations.set(observation.callId, owners);
1929
+ }
1930
+ }
1931
+ if (nextOrdinal <= afterOrdinal)
1932
+ break;
1933
+ afterOrdinal = nextOrdinal;
1934
+ const last = messages.at(-1);
1935
+ after = last ? { timeCreated: last.createdAt ?? 0, id: last.id } : undefined;
1936
+ if (afterOrdinal < finalWatermark)
1937
+ await yieldToEventLoop();
1938
+ }
1939
+ return { messageFileKeys, toolObservations };
1940
+ }
1941
+ var PROTECTED_TAIL_USER_TURNS = 5;
1942
+ function getLegacyProtectedTailStartOrdinal2(sessionId) {
1943
+ const count = getRawSessionMessageOrdinalCount2(sessionId);
1944
+ const userOrdinals = [];
1945
+ let toOrdinal = count;
1946
+ while (toOrdinal >= 1 && userOrdinals.length < PROTECTED_TAIL_USER_TURNS) {
1947
+ const fromOrdinal = Math.max(1, toOrdinal - RAW_MESSAGE_RANGE_PAGE_SIZE + 1);
1948
+ const messages = readRawSessionMessageRange2(sessionId, fromOrdinal, toOrdinal);
1949
+ for (let index = messages.length - 1;index >= 0; index--) {
1950
+ const message = messages[index];
1951
+ if (message?.role === "user" && hasMeaningfulUserText2(message.parts)) {
1952
+ userOrdinals.push(message.ordinal);
1953
+ if (userOrdinals.length === PROTECTED_TAIL_USER_TURNS)
1954
+ break;
1955
+ }
1956
+ }
1957
+ toOrdinal = fromOrdinal - 1;
1958
+ }
1959
+ return userOrdinals.length < PROTECTED_TAIL_USER_TURNS ? 1 : userOrdinals[PROTECTED_TAIL_USER_TURNS - 1] ?? 1;
1960
+ }
1961
+ function getProtectedTailStartOrdinal2(sessionId) {
1962
+ return getLegacyProtectedTailStartOrdinal2(sessionId);
1963
+ }
1964
+ function readSessionChunk2(sessionId, tokenBudget, offset = 1, eligibleEndOrdinal, options = {}) {
1965
+ const totalMessageCount = getCachedAbsoluteMessageCount2(sessionId) ?? getRawSessionMessageOrdinalCount2(sessionId);
1966
+ const startOrdinal = Math.max(1, offset);
1967
+ const finalOrdinal = eligibleEndOrdinal === undefined ? totalMessageCount : Math.min(totalMessageCount, eligibleEndOrdinal - 1);
1968
+ const messages = readRawSessionMessageRange2(sessionId, Math.max(1, startOrdinal - 1), finalOrdinal);
1969
+ const expandedParts = new Map;
1970
+ const expandedResults = new Set;
1971
+ if (options.expand !== false) {
1972
+ const calls = new Map;
1973
+ for (const message of messages)
1974
+ for (const part of message.parts) {
1975
+ if (!part || typeof part !== "object")
1976
+ continue;
1977
+ const p = part;
1978
+ if (p.type !== "tool")
1979
+ continue;
1980
+ const state = p.state;
1981
+ if (state?.input !== undefined && typeof p.callID === "string")
1982
+ calls.set(p.callID, p);
1983
+ expandedParts.set(part, expandToolPart(part, options.expandTools));
1984
+ if (state?.input === undefined && state?.output !== undefined && typeof p.callID === "string") {
1985
+ const call = calls.get(p.callID);
1986
+ if (call) {
1987
+ const expansion = expandToolPart({
1988
+ ...call,
1989
+ state: { ...call.state, output: state.output }
1990
+ }, options.expandTools);
1991
+ if (expansion !== null) {
1992
+ expandedParts.set(call, expansion);
1993
+ expandedResults.add(part);
1994
+ }
1995
+ calls.delete(p.callID);
1996
+ }
1997
+ }
1998
+ }
1999
+ }
2000
+ const completedToolArcs = buildToolArcs(messages).flatMap((arc) => arc.resOrdinal === null ? [] : [{ start: arc.invOrdinal, end: arc.resOrdinal }]);
2001
+ const completedToolComponents = [];
2002
+ for (const arc of completedToolArcs) {
2003
+ const component = completedToolComponents[completedToolComponents.length - 1];
2004
+ if (component && arc.start <= component.end)
2005
+ component.end = Math.max(component.end, arc.end);
2006
+ else
2007
+ completedToolComponents.push({ ...arc });
2008
+ }
2009
+ const lines = [];
2010
+ const lineMeta = [];
2011
+ const flushedToolOnlyBlocks = [];
2012
+ let totalTokens = 0;
2013
+ let messagesProcessed = 0;
2014
+ let lastOrdinal = startOrdinal - 1;
2015
+ let highestScannedOrdinal = startOrdinal - 1;
2016
+ let lastMessageId = "";
2017
+ let firstMessageId = "";
2018
+ let currentBlock = null;
2019
+ let pendingNoiseMeta = [];
2020
+ let commitClusters = 0;
2021
+ let lastFlushedRole = "";
2022
+ let admittedOversizeComponentEnd = null;
2023
+ let currentBlockApproxTokens = 0;
2024
+ let formattedBudgetCrossed = false;
2025
+ let sourceCharacters = 0;
2026
+ const toolResultBoundaries = [];
2027
+ function pinComponentWhenFormattedBudgetCrosses(ordinal, appendedText) {
2028
+ if (admittedOversizeComponentEnd !== null || formattedBudgetCrossed || !currentBlock)
2029
+ return;
2030
+ currentBlockApproxTokens += estimateTokens(appendedText) + (currentBlock.parts.length > 1 ? 1 : 0);
2031
+ if (totalTokens + currentBlockApproxTokens + 64 <= tokenBudget)
2032
+ return;
2033
+ const previewTokens = totalTokens + estimateTokens(formatBlock(currentBlock));
2034
+ if (previewTokens <= tokenBudget)
2035
+ return;
2036
+ formattedBudgetCrossed = true;
2037
+ const component = completedToolComponents.find((candidate) => candidate.start <= ordinal && candidate.end >= ordinal);
2038
+ if (component)
2039
+ admittedOversizeComponentEnd = component.end;
2040
+ }
2041
+ function recordFilteredNoise(meta) {
2042
+ pendingNoiseMeta.push(meta);
2043
+ if (!currentBlock) {
2044
+ highestScannedOrdinal = Math.max(highestScannedOrdinal, meta.ordinal);
2045
+ }
2046
+ }
2047
+ function flushCurrentBlock() {
2048
+ if (!currentBlock)
2049
+ return true;
2050
+ const blockText = formatBlock(currentBlock);
2051
+ const blockTokens = estimateBlockTokens(blockText);
2052
+ if (totalTokens + blockTokens > tokenBudget && totalTokens > 0) {
2053
+ const splitsCompletedArc = completedToolArcs.some((arc) => arc.start <= lastOrdinal && arc.end > lastOrdinal);
2054
+ if (!splitsCompletedArc)
2055
+ return false;
2056
+ }
2057
+ if (currentBlock.role === "A" && currentBlock.commitHashes.length > 0 && lastFlushedRole !== "A") {
2058
+ commitClusters++;
2059
+ }
2060
+ lastFlushedRole = currentBlock.role;
2061
+ if (!firstMessageId)
2062
+ firstMessageId = currentBlock.meta[0]?.messageId ?? "";
2063
+ lastOrdinal = currentBlock.meta[currentBlock.meta.length - 1]?.ordinal ?? currentBlock.endOrdinal;
2064
+ highestScannedOrdinal = Math.max(highestScannedOrdinal, lastOrdinal);
2065
+ lastMessageId = currentBlock.meta[currentBlock.meta.length - 1]?.messageId ?? "";
2066
+ messagesProcessed += currentBlock.meta.length;
2067
+ const lineStart = sourceCharacters + (lines.length > 0 ? 1 : 0);
2068
+ const renderedParts = currentBlock.parts.join(" / ");
2069
+ let partOffset = lineStart + (blockText.length - renderedParts.length);
2070
+ for (let index = 0;index < currentBlock.parts.length; index++) {
2071
+ const part = currentBlock.parts[index] ?? "";
2072
+ const partMeta = currentBlock.partMeta[index];
2073
+ if (partMeta && partMeta.toolResultBodyTokens > 0) {
2074
+ toolResultBoundaries.push({
2075
+ ordinal: partMeta.ordinal,
2076
+ sourceOffset: partOffset,
2077
+ bodyTokens: partMeta.toolResultBodyTokens
2078
+ });
2079
+ }
2080
+ partOffset += part.length + (index + 1 < currentBlock.parts.length ? 3 : 0);
2081
+ }
2082
+ lines.push(blockText);
2083
+ sourceCharacters = lineStart + blockText.length;
2084
+ lineMeta.push(...currentBlock.meta);
2085
+ totalTokens += blockTokens;
2086
+ if (currentBlock.isToolOnly) {
2087
+ flushedToolOnlyBlocks.push({
2088
+ start: currentBlock.startOrdinal,
2089
+ end: currentBlock.endOrdinal
2090
+ });
2091
+ }
2092
+ currentBlock = null;
2093
+ currentBlockApproxTokens = 0;
2094
+ return true;
2095
+ }
2096
+ for (const msg of messages) {
2097
+ if (eligibleEndOrdinal !== undefined && msg.ordinal >= eligibleEndOrdinal)
2098
+ break;
2099
+ if (admittedOversizeComponentEnd !== null && msg.ordinal > admittedOversizeComponentEnd) {
2100
+ break;
2101
+ }
2102
+ if (msg.ordinal < startOrdinal)
2103
+ continue;
2104
+ const commitHashes = rawCommitHashes(msg.parts);
2105
+ const meta = {
2106
+ ordinal: msg.ordinal,
2107
+ messageId: msg.id
2108
+ };
2109
+ Object.defineProperty(meta, "commitHashes", { value: commitHashes });
2110
+ if (isHostUnservedRow(msg))
2111
+ markHostUnservedRow(meta);
2112
+ if (msg.role === "system") {
2113
+ recordFilteredNoise(meta);
2114
+ continue;
2115
+ }
2116
+ if (msg.role === "user" && !hasMeaningfulChunkUserText(msg.parts)) {
2117
+ const tcSummaries = msg.parts.flatMap((part) => {
2118
+ if (expandedResults.has(part))
2119
+ return [];
2120
+ const expansion = expandedParts.get(part) ?? null;
2121
+ return expansion === null ? extractToolCallSummaries([part]) : [`TC: ${expansion}`];
2122
+ });
2123
+ if (tcSummaries.length === 0) {
2124
+ recordFilteredNoise(meta);
2125
+ continue;
2126
+ }
2127
+ const tcText = tcSummaries.join(" / ");
2128
+ if (currentBlock && currentBlock.role === "A") {
2129
+ currentBlock.endOrdinal = msg.ordinal;
2130
+ currentBlock.parts.push(tcText);
2131
+ currentBlock.partMeta.push({
2132
+ ordinal: msg.ordinal,
2133
+ toolResultBodyTokens: extractToolResultBodyTokens(msg.parts)
2134
+ });
2135
+ currentBlock.meta.push(...pendingNoiseMeta, meta);
2136
+ pendingNoiseMeta = [];
2137
+ } else {
2138
+ if (!flushCurrentBlock())
2139
+ break;
2140
+ currentBlock = {
2141
+ role: "A",
2142
+ startOrdinal: pendingNoiseMeta[0]?.ordinal ?? msg.ordinal,
2143
+ endOrdinal: msg.ordinal,
2144
+ parts: [tcText],
2145
+ partMeta: [
2146
+ {
2147
+ ordinal: msg.ordinal,
2148
+ toolResultBodyTokens: extractToolResultBodyTokens(msg.parts)
2149
+ }
2150
+ ],
2151
+ meta: [...pendingNoiseMeta, meta],
2152
+ commitHashes: [],
2153
+ isToolOnly: true
2154
+ };
2155
+ pendingNoiseMeta = [];
2156
+ }
2157
+ pinComponentWhenFormattedBudgetCrosses(msg.ordinal, tcText);
2158
+ continue;
2159
+ }
2160
+ const role = compactRole(msg.role);
2161
+ const textParts = extractTexts2(msg.parts).map((t) => msg.role === "user" ? cleanUserText2(t) : t).map(normalizeText).filter((value) => value.length > 0);
2162
+ const answerParts = msg.role === "user" ? extractTexts2(msg.parts).flatMap((text) => answerLineParts(text)) : [];
2163
+ const userParts = answerParts.length > 0 ? [...textParts, ...answerParts] : textParts;
2164
+ const allParts = options.expand === false ? [
2165
+ ...userParts,
2166
+ ...textParts.length === 0 ? extractToolCallSummaries(msg.parts) : []
2167
+ ] : msg.parts.flatMap((part) => {
2168
+ if (expandedResults.has(part))
2169
+ return [];
2170
+ const expansion = expandedParts.get(part) ?? null;
2171
+ if (expansion !== null)
2172
+ return [`TC: ${expansion}`];
2173
+ const texts = extractTexts2([part]).map((t) => msg.role === "user" ? cleanUserText2(t) : t).map(normalizeText).filter(Boolean);
2174
+ if (msg.role === "user") {
2175
+ texts.push(...extractTexts2([part]).flatMap((text) => answerLineParts(text)));
2176
+ }
2177
+ return texts.length ? texts : textParts.length === 0 ? extractToolCallSummaries([part]) : [];
2178
+ });
2179
+ const compacted = compactTextForSummary(allParts.join(" / "), msg.role);
2180
+ const text = compacted.text;
2181
+ if (!text) {
2182
+ recordFilteredNoise(meta);
2183
+ continue;
2184
+ }
2185
+ const msgHasNarrative = userParts.length > 0;
2186
+ if (currentBlock && currentBlock.role === role) {
2187
+ currentBlock.endOrdinal = msg.ordinal;
2188
+ currentBlock.parts.push(text);
2189
+ currentBlock.partMeta.push({
2190
+ ordinal: msg.ordinal,
2191
+ toolResultBodyTokens: extractToolResultBodyTokens(msg.parts)
2192
+ });
2193
+ currentBlock.meta.push(...pendingNoiseMeta, meta);
2194
+ currentBlock.commitHashes = mergeCommitHashes(currentBlock.commitHashes, compacted.commitHashes);
2195
+ if (msgHasNarrative)
2196
+ currentBlock.isToolOnly = false;
2197
+ pendingNoiseMeta = [];
2198
+ pinComponentWhenFormattedBudgetCrosses(msg.ordinal, text);
2199
+ continue;
2200
+ }
2201
+ if (!flushCurrentBlock())
2202
+ break;
2203
+ currentBlock = {
2204
+ role,
2205
+ startOrdinal: pendingNoiseMeta[0]?.ordinal ?? msg.ordinal,
2206
+ endOrdinal: msg.ordinal,
2207
+ parts: [text],
2208
+ partMeta: [
2209
+ {
2210
+ ordinal: msg.ordinal,
2211
+ toolResultBodyTokens: extractToolResultBodyTokens(msg.parts)
2212
+ }
2213
+ ],
2214
+ meta: [...pendingNoiseMeta, meta],
2215
+ commitHashes: [...compacted.commitHashes],
2216
+ isToolOnly: !msgHasNarrative
2217
+ };
2218
+ pendingNoiseMeta = [];
2219
+ pinComponentWhenFormattedBudgetCrosses(msg.ordinal, text);
2220
+ }
2221
+ if (flushCurrentBlock() && pendingNoiseMeta.length > 0) {
2222
+ const lastNoise = pendingNoiseMeta[pendingNoiseMeta.length - 1];
2223
+ if (messagesProcessed > 0 && lastNoise) {
2224
+ lineMeta.push(...pendingNoiseMeta);
2225
+ messagesProcessed += pendingNoiseMeta.length;
2226
+ lastOrdinal = lastNoise.ordinal;
2227
+ lastMessageId = lastNoise.messageId;
2228
+ pendingNoiseMeta = [];
2229
+ }
2230
+ highestScannedOrdinal = Math.max(highestScannedOrdinal, pendingNoiseMeta[pendingNoiseMeta.length - 1]?.ordinal ?? highestScannedOrdinal);
2231
+ }
2232
+ const toolOnlyRanges = [];
2233
+ for (const range of flushedToolOnlyBlocks) {
2234
+ const last = toolOnlyRanges[toolOnlyRanges.length - 1];
2235
+ if (last && range.start === last.end + 1) {
2236
+ last.end = range.end;
2237
+ } else {
2238
+ toolOnlyRanges.push({ start: range.start, end: range.end });
2239
+ }
2240
+ }
2241
+ const text = lines.join(`
2242
+ `);
2243
+ const oversizeAtomicUnit = estimateBlockTokens(text) > tokenBudget && completedToolArcs.some((arc) => arc.start <= lastOrdinal && arc.end >= startOrdinal);
2244
+ return {
2245
+ startIndex: startOrdinal,
2246
+ endIndex: lastOrdinal,
2247
+ startMessageId: firstMessageId,
2248
+ endMessageId: lastMessageId,
2249
+ messageCount: messagesProcessed,
2250
+ tokenEstimate: totalTokens,
2251
+ ...oversizeAtomicUnit ? { oversizeAtomicUnit: true } : {},
2252
+ hasMore: Math.max(lastOrdinal, highestScannedOrdinal) < (eligibleEndOrdinal !== undefined ? Math.min(eligibleEndOrdinal - 1, totalMessageCount) : totalMessageCount),
2253
+ text,
2254
+ lines: lineMeta,
2255
+ ...messagesProcessed === 0 && text.length === 0 ? { filteredNoiseLines: pendingNoiseMeta } : {},
2256
+ commitClusterCount: commitClusters,
2257
+ toolOnlyRanges,
2258
+ completedToolArcs,
2259
+ toolResultBoundaries
2260
+ };
2261
+ }
2262
+ function getRawSessionMessageIdsThrough2(sessionId, endOrdinal) {
2263
+ if (endOrdinal < 1)
2264
+ return [];
2265
+ return [...readRawSessionMessageIdOrdinalsForRange2(sessionId, 1, endOrdinal).entries()].sort((left, right) => left[1] - right[1]).map(([id]) => id);
2266
+ }
2267
+ function readRawSessionSeedTail2(sessionId, boundaryId, onQuery) {
2268
+ const provider = sessionProviders.get(sessionId)?.provider;
2269
+ if (provider) {
2270
+ const boundaryOrdinal = boundaryId === null ? 1 : readRawSessionMessageOrdinalById2(sessionId, boundaryId);
2271
+ if (boundaryOrdinal === null)
2272
+ throw new Error("state_sync materialized boundary is missing from raw provider");
2273
+ const messages = readRawSessionMessageRange2(sessionId, boundaryOrdinal, getRawSessionMessageOrdinalCount2(sessionId));
2274
+ return new Map(messages.map((message) => [message.id, message]));
2275
+ }
2276
+ if (!openCodeDbExists()) {
2277
+ if (boundaryId !== null)
2278
+ throw new Error("state_sync raw storage is unavailable for materialized boundary");
2279
+ return new Map;
2280
+ }
2281
+ return withReadOnlySessionDb((db) => {
2282
+ onQuery?.();
2283
+ return readRawSeedTailFromDb2(db, sessionId, boundaryId);
2284
+ });
2285
+ }
2286
+
2287
+ export { withReadOnlySessionDb, expandToolPart, askAnswerLines, removeUnsupportedCommitHashes, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripSystemInjection, isFilePart, hasUserAnswerMetadata, DreamTokenBudgetExceeded, TOKEN_BUDGET_FINALIZE_MESSAGE, TOKEN_BUDGET_TOOL_REFUSAL, registerBudgetFinalizeChild, releaseBudgetFinalizeChild, createDreamTokenBudget, droppedInputMarker, createDroppedInputGuard, isEditTool, applyEditMarkerToInput, SKELETON_REAL_INPUT_MAX_BYTES, toolInputStringBytes, resolveHostServedBoundaryId2, hasRawMessageProvider2, rawMessageWorkerSource2, rawMessageOffThreadRangeReader2, setRawMessageProvider2, setBoundedRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, RAW_MESSAGE_VISIT_PAGE_SIZE2, visitRawSessionMessages2, visitRawSessionMessagesAsync2, readRawSessionMessageRange2, prepareRawSessionOrdinals2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageOrdinalPage2, getRawSessionStoredMessageCount2, readRawSessionMessageIdOrdinalsForRange2, readRawSessionMessageIdOrdinals2, readRawSessionMessagePartsById2, readRawSessionBoundaryEndpoints2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, resolveHistorianChunkStart2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, RAW_SESSION_TAG_KEY_PAGE_SIZE2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, getProtectedTailStartOrdinal2, readSessionChunk2, getRawSessionMessageIdsThrough2, readRawSessionSeedTail2 };