@cortexkit/pi-magic-context 0.46.0 → 0.47.0

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.
@@ -0,0 +1,107 @@
1
+ import {
2
+ setEmbeddingSessionBusy,
3
+ getProjectEmbeddings,
4
+ getMemoriesByProject,
5
+ installProjectEmbeddingSearchBridge,
6
+ ensureMemoryEmbeddings,
7
+ unifiedSearch
8
+ } from "./index-qaa5j277.js";
9
+ import {
10
+ setHarness
11
+ } from "./index-7n8gb6j3.js";
12
+ import"./index-vgcemg0n.js";
13
+ import"./index-spk5vrhy.js";
14
+ import"./index-266qrgss.js";
15
+ import {
16
+ Database
17
+ } from "./index-0qejsd7f.js";
18
+ import"./index-xpbh1ypk.js";
19
+ import"./index-7s8vw2y0.js";
20
+ import"./index-td885aah.js";
21
+ import"./index-2p1e8706.js";
22
+
23
+ // ../plugin/src/hooks/magic-context/auto-search-worker.ts
24
+ import { parentPort, workerData } from "node:worker_threads";
25
+ var port = parentPort;
26
+ if (!port)
27
+ throw new Error("auto-search worker requires a parent port");
28
+ var input = workerData;
29
+ setHarness(input.harness);
30
+ setEmbeddingSessionBusy(input.sessionId, input.embeddingHostBusy === true);
31
+ var nextId = 0;
32
+ var pending = new Map;
33
+ var queryDimensions = null;
34
+ var db;
35
+ port.on("message", (reply) => {
36
+ if (reply.embeddingHostBusy !== undefined)
37
+ setEmbeddingSessionBusy(input.sessionId, reply.embeddingHostBusy);
38
+ const vector = reply.result instanceof Float32Array ? reply.result : reply.result?.vector;
39
+ if (vector)
40
+ queryDimensions = vector.length;
41
+ pending.get(reply.id)?.(reply);
42
+ pending.delete(reply.id);
43
+ });
44
+ function request(message) {
45
+ return new Promise((resolve, reject) => {
46
+ const id = ++nextId;
47
+ pending.set(id, (reply) => reply.error ? reject(new Error(reply.error)) : resolve(reply));
48
+ port?.postMessage({ ...message, id });
49
+ });
50
+ }
51
+ if (input.snapshot) {
52
+ installProjectEmbeddingSearchBridge(input.snapshot, {
53
+ modelId: input.snapshot.modelId,
54
+ initialize: async () => true,
55
+ isLoaded: () => true,
56
+ dispose: async () => {},
57
+ embed: async (text) => {
58
+ const result = (await request({ kind: "query", text })).result;
59
+ return result instanceof Float32Array ? result : result?.vector ?? null;
60
+ },
61
+ embedBatch: async (texts, _signal, purpose = "passage") => {
62
+ const passage = (await request({ kind: "batch", texts, purpose })).passage;
63
+ const captured = input.snapshot;
64
+ if (!passage || !captured || passage.generation !== captured.generation || passage.modelId !== captured.modelId || passage.providerIdentity !== captured.providerIdentity || passage.runtimeFingerprint !== captured.runtimeFingerprint || !queryDimensions || passage.dimensions !== queryDimensions || passage.vectors.length !== texts.length)
65
+ return texts.map(() => null);
66
+ return passage.vectors.map((vector) => vector && vector.length === queryDimensions && vector.every(Number.isFinite) ? vector : null);
67
+ }
68
+ });
69
+ }
70
+ db = new Database(input.path, input.job === "backfill" ? undefined : { readonly: true });
71
+ db.exec("PRAGMA busy_timeout = 250");
72
+ try {
73
+ if (input.job === "backfill") {
74
+ if (input.snapshot?.enabled && input.snapshot.features.memoryEnabled) {
75
+ await request({ kind: "query", text: input.query });
76
+ if (queryDimensions) {
77
+ const existingEmbeddings = getProjectEmbeddings(db, input.projectPath, input.snapshot.modelId);
78
+ const memories = getMemoriesByProject(db, input.projectPath).filter((memory) => !existingEmbeddings.has(memory.id)).slice(0, 50);
79
+ await ensureMemoryEmbeddings({
80
+ db,
81
+ projectIdentity: input.projectPath,
82
+ memories,
83
+ existingEmbeddings
84
+ });
85
+ }
86
+ }
87
+ port.postMessage({ kind: "result", results: [] });
88
+ } else {
89
+ const results = await unifiedSearch(db, input.sessionId, input.projectPath, input.query, {
90
+ ...input.options,
91
+ backfillMemoryEmbeddings: false,
92
+ countRetrievals: false,
93
+ measurementDisabled: true,
94
+ embedQuery: async (text) => (await request({ kind: "query", text })).result ?? null,
95
+ isEmbeddingRuntimeEnabled: () => input.embeddingRuntimeEnabled
96
+ });
97
+ port.postMessage({ kind: "result", results });
98
+ }
99
+ } catch (error) {
100
+ port.postMessage({
101
+ kind: "error",
102
+ error: error instanceof Error ? error.message : String(error)
103
+ });
104
+ } finally {
105
+ db.close();
106
+ port.close();
107
+ }
@@ -6,8 +6,8 @@ import {
6
6
  resolveLocalEmbeddingWorkerRuntime,
7
7
  getLocalEmbeddingNativeMemoryStats,
8
8
  LocalEmbeddingProvider
9
- } from "./index-sg8zbjs0.js";
10
- import"./index-phh7e055.js";
9
+ } from "./index-vgcemg0n.js";
10
+ import"./index-spk5vrhy.js";
11
11
  import"./index-266qrgss.js";
12
12
  import {
13
13
  setStoragePrivatePermissionEnforcement
@@ -69,6 +69,8 @@ function installTransactionRouting(db, readonly) {
69
69
  configurable: true,
70
70
  writable: true,
71
71
  value: (sql) => {
72
+ if (/^\s*(?:COMMIT|END)\b/i.test(sql))
73
+ assertTransformWrite();
72
74
  if (/^\s*BEGIN\s+(?:IMMEDIATE|EXCLUSIVE)(?:\s+TRANSACTION)?\s*;?\s*$/i.test(sql)) {
73
75
  openWriterTransactions.delete(db);
74
76
  if (transformPassScope.getStore()?.active || backgroundWriterScope.getStore())
@@ -205,6 +207,14 @@ function buildNodeSqliteDatabaseClass(DatabaseSync) {
205
207
  return NodeSqliteDatabase;
206
208
  }
207
209
  var Database = TrackedDatabase;
210
+ function getSqliteDatabasePath(db) {
211
+ for (const connection of trackedSqliteConnections.values()) {
212
+ if (connection.reference.deref() === db) {
213
+ return connection.filename === ":memory:" || connection.filename === "<buffer>" ? null : connection.filename;
214
+ }
215
+ }
216
+ return null;
217
+ }
208
218
  function pragmaValue(db, name) {
209
219
  const row = db.prepare(`PRAGMA ${name}`).get();
210
220
  if (!row)
@@ -298,6 +308,15 @@ function withSqliteTransformPass(operation) {
298
308
  function withoutSqliteTransformPass(operation) {
299
309
  return transformPassScope.run(undefined, operation);
300
310
  }
311
+ function guardSqliteTransformPass(guard) {
312
+ const lease = transformPassScope.getStore();
313
+ if (lease)
314
+ lease.guard = guard;
315
+ }
316
+ function assertTransformWrite() {
317
+ if (!backgroundWriterScope.getStore())
318
+ transformPassScope.getStore()?.guard?.assert();
319
+ }
301
320
  function isTransientSqliteError(error) {
302
321
  if (!error || typeof error !== "object")
303
322
  return false;
@@ -316,6 +335,7 @@ class SqliteAcquisitionBusyError extends Error {
316
335
  }
317
336
  var SHORT_BUSY_TIMEOUT_MS = 25;
318
337
  var FOREGROUND_IN_PASS_BUSY_TIMEOUT_MS = 250;
338
+ var FOREGROUND_ACQUISITION_BUDGET_MS = 16500;
319
339
  var SLOW_WRITER_LOG_MS = 250;
320
340
  var WRITER_TRANSACTION_END = /^\s*(?:COMMIT|END|ROLLBACK)(?:\s+TRANSACTION)?\s*;?\s*$/i;
321
341
  var writerAcquisitionScope = new AsyncLocalStorage;
@@ -325,6 +345,7 @@ function foregroundWaitLease() {
325
345
  return lease?.active && !admissionScope.getStore() && !backgroundWriterScope.getStore() ? lease : undefined;
326
346
  }
327
347
  function withAutocommitTimeout(db, operation) {
348
+ assertTransformWrite();
328
349
  const lease = foregroundWaitLease();
329
350
  if (isInTransaction(db) || !lease && !backgroundWriterScope.getStore())
330
351
  return operation();
@@ -345,6 +366,7 @@ function withAutocommitTimeout(db, operation) {
345
366
  }
346
367
  }
347
368
  function acquireShort(db, acquire, site) {
369
+ assertTransformWrite();
348
370
  const started = performance.now();
349
371
  const previous = pragmaNumber(db, "busy_timeout");
350
372
  const outer = writerAcquisitionScope.getStore();
@@ -356,7 +378,7 @@ function acquireShort(db, acquire, site) {
356
378
  let acquiredAt;
357
379
  try {
358
380
  const lease = foregroundWaitLease();
359
- const timeout = lease ? Math.floor(lease.remainingWaitMs) : SHORT_BUSY_TIMEOUT_MS;
381
+ const timeout = Math.floor(Math.min(lease ? lease.remainingWaitMs : SHORT_BUSY_TIMEOUT_MS, owner?.remainingMs?.() ?? lease?.guard?.remainingMs() ?? Infinity));
360
382
  db.exec(`PRAGMA busy_timeout=${timeout}`);
361
383
  acquire();
362
384
  acquiredAt = performance.now();
@@ -402,6 +424,56 @@ function endWriterTransaction(db, end, sql) {
402
424
  }
403
425
  }
404
426
  }
427
+ async function withAsyncPrivilegedWriter(db, operation, options = {}) {
428
+ const started = performance.now();
429
+ const budgetMs = Math.max(0, Math.min(FOREGROUND_ACQUISITION_BUDGET_MS, options.budgetMs ?? Infinity));
430
+ let attempts = 0;
431
+ for (;; ) {
432
+ options.signal?.throwIfAborted();
433
+ options.assertCurrentPass?.();
434
+ attempts++;
435
+ let entered = false;
436
+ try {
437
+ const acquisition = {
438
+ site: "privileged_writer",
439
+ lane: "foreground",
440
+ startedAt: started,
441
+ attempts,
442
+ claimed: false,
443
+ remainingMs: () => Math.max(0, budgetMs - (performance.now() - started))
444
+ };
445
+ return admissionScope.run(true, () => withSqliteTransformPass(() => writerAcquisitionScope.run(acquisition, () => withPrivilegedWriter(db, () => {
446
+ entered = true;
447
+ return operation();
448
+ }))));
449
+ } catch (error) {
450
+ if (entered || !(error instanceof SqliteAcquisitionBusyError))
451
+ throw error;
452
+ options.beforeRetry?.(error);
453
+ const elapsed = performance.now() - started;
454
+ if (elapsed >= budgetMs) {
455
+ reportSqliteDiagnostic(`sqlite writer site=privileged_writer lane=foreground acquire_ms=${Math.round(elapsed)} attempts=${attempts} outcome=busy`);
456
+ throw error;
457
+ }
458
+ const backoff = attempts === 1 ? 500 : 1000;
459
+ const delay = Math.min(options.jitter ? backoff * (0.8 + Math.random() * 0.4) : backoff, budgetMs - elapsed);
460
+ await new Promise((resolve, reject) => {
461
+ const abort = () => {
462
+ clearTimeout(timer);
463
+ options.signal?.removeEventListener("abort", abort);
464
+ reject(options.signal?.reason ?? new Error("Writer wait aborted"));
465
+ };
466
+ const timer = setTimeout(() => {
467
+ options.signal?.removeEventListener("abort", abort);
468
+ resolve();
469
+ }, delay);
470
+ options.signal?.addEventListener("abort", abort, { once: true });
471
+ if (options.signal?.aborted)
472
+ abort();
473
+ });
474
+ }
475
+ }
476
+ }
405
477
  function isInTransaction(db) {
406
478
  const candidate = db;
407
479
  return candidate.inTransaction === true || candidate.isTransaction === true;
@@ -461,4 +533,4 @@ function withPrivilegedWriter(db, operation) {
461
533
  }
462
534
  }
463
535
 
464
- export { registerSlowWriteReporter, registerSqliteDiagnosticSink, detectSqliteRuntime, Database, prepareCachedStatement, withSqliteBackgroundWriter, withSqliteTransformPass, withoutSqliteTransformPass, isTransientSqliteError, withPrivilegedWriter };
536
+ export { registerSlowWriteReporter, registerSqliteDiagnosticSink, detectSqliteRuntime, Database, getSqliteDatabasePath, prepareCachedStatement, withSqliteBackgroundWriter, withSqliteTransformPass, withoutSqliteTransformPass, guardSqliteTransformPass, assertTransformWrite, isTransientSqliteError, withAsyncPrivilegedWriter, withPrivilegedWriter };
@@ -35,10 +35,10 @@ import {
35
35
  DEFAULT_PROTECTED_TOOLS,
36
36
  normalizeProtectedToolName,
37
37
  mergeProtectedTools
38
- } from "./index-phh7e055.js";
38
+ } from "./index-spk5vrhy.js";
39
39
  import {
40
40
  Database
41
- } from "./index-wv28nczk.js";
41
+ } from "./index-0qejsd7f.js";
42
42
 
43
43
  // ../plugin/src/hooks/magic-context/tokenizer-calibration-seeds.json
44
44
  var tokenizer_calibration_seeds_default = [
@@ -1794,6 +1794,17 @@ function getAllStatusTagTokenTotalsFlat(db, sessionId, floor = 0, calibration =
1794
1794
  }
1795
1795
  return { totals, nullMessageIds };
1796
1796
  }
1797
+ function getReasoningTokenEstimatesByMessage(db, sessionId, proseRatio) {
1798
+ const rows = db.prepare(`SELECT type, message_id, tool_owner_message_id, reasoning_token_count FROM tags WHERE session_id = ? AND reasoning_token_count IS NOT NULL`).all(sessionId);
1799
+ const totals = new Map;
1800
+ for (const row of rows) {
1801
+ if (row.type !== "message")
1802
+ continue;
1803
+ const id = ownerMessageIdForTagRow(row);
1804
+ totals.set(id, Math.max(totals.get(id) ?? 0, row.reasoning_token_count * proseRatio));
1805
+ }
1806
+ return totals;
1807
+ }
1797
1808
  function updateTagInputTokenCount(db, sessionId, tagNumber, newInputTokenCount) {
1798
1809
  getUpdateTagInputTokenCountStatement(db).run(newInputTokenCount, sessionId, tagNumber);
1799
1810
  }
@@ -2117,7 +2128,7 @@ function findPiFallbackToolOwnerTags(db, sessionId) {
2117
2128
  AND tool_owner_message_id LIKE 'pi-msg-%'
2118
2129
  ORDER BY tag_number ASC`).all(sessionId).filter(isPiFallbackToolOwnerTag);
2119
2130
  }
2120
- function adoptPiFallbackToolOwnerTag(db, sessionId, tagNumber, callId, oldOwnerMessageId, newOwnerMessageId) {
2131
+ function adoptPiFallbackToolOwnerTag(db, sessionId, tagNumber, callId, oldOwnerMessageId, newOwnerMessageId, servedTagNumbers = new Set) {
2121
2132
  const survivor = getPiFallbackFoldTagRowByNumber(db, sessionId, tagNumber);
2122
2133
  if (survivor === null || survivor.type !== "tool" || survivor.messageId !== callId || survivor.toolOwnerMessageId !== oldOwnerMessageId) {
2123
2134
  return { action: "skipped" };
@@ -2136,6 +2147,14 @@ function adoptPiFallbackToolOwnerTag(db, sessionId, tagNumber, callId, oldOwnerM
2136
2147
  if (existing.tagNumber === tagNumber) {
2137
2148
  return { action: "skipped" };
2138
2149
  }
2150
+ if (servedTagNumbers.has(survivor.tagNumber)) {
2151
+ if (servedTagNumbers.has(existing.tagNumber)) {
2152
+ throw new Error("Conflicting served Pi tool tag numbers; refusing identity adoption");
2153
+ }
2154
+ foldDuplicateIntoSurvivor(db, sessionId, survivor, existing);
2155
+ db.prepare("UPDATE tags SET tool_owner_message_id = ? WHERE session_id = ? AND tag_number = ?").run(newOwnerMessageId, sessionId, tagNumber);
2156
+ return { action: "folded", tagNumber, deletedTagNumbers: [existing.tagNumber] };
2157
+ }
2139
2158
  foldDuplicateIntoSurvivor(db, sessionId, existing, survivor);
2140
2159
  return {
2141
2160
  action: "folded",
@@ -2143,7 +2162,7 @@ function adoptPiFallbackToolOwnerTag(db, sessionId, tagNumber, callId, oldOwnerM
2143
2162
  deletedTagNumbers: [tagNumber]
2144
2163
  };
2145
2164
  }
2146
- function adoptPiFallbackMessageTag(db, sessionId, tagNumber, oldFallbackMessageId, newRealMessageId) {
2165
+ function adoptPiFallbackMessageTag(db, sessionId, tagNumber, oldFallbackMessageId, newRealMessageId, servedTagNumbers = new Set) {
2147
2166
  if (oldFallbackMessageId.startsWith(WHITESPACE_ASSISTANT_INERT_MESSAGE_PREFIX)) {
2148
2167
  return { action: "skipped" };
2149
2168
  }
@@ -2161,15 +2180,23 @@ function adoptPiFallbackMessageTag(db, sessionId, tagNumber, oldFallbackMessageI
2161
2180
  AND message_id = ?`).run(newRealMessageId, sessionId, tagNumber, oldFallbackMessageId);
2162
2181
  return (result.changes ?? 0) > 0 ? { action: "rekeyed", tagNumber } : { action: "skipped" };
2163
2182
  }
2164
- const realSurvivor = duplicates[0];
2183
+ const servedRows = [survivor, ...duplicates].filter((row) => servedTagNumbers.has(row.tagNumber));
2184
+ if (servedRows.length > 1) {
2185
+ throw new Error("Conflicting served Pi message tag numbers; refusing identity adoption");
2186
+ }
2187
+ const realSurvivor = servedRows[0] ?? duplicates[0];
2165
2188
  if (!realSurvivor)
2166
2189
  return { action: "skipped" };
2167
- const deletedTagNumbers = [tagNumber];
2168
- foldDuplicateIntoSurvivor(db, sessionId, realSurvivor, survivor);
2169
- for (const duplicate of duplicates.slice(1)) {
2190
+ const deletedTagNumbers = [];
2191
+ for (const duplicate of [survivor, ...duplicates]) {
2192
+ if (duplicate.tagNumber === realSurvivor.tagNumber)
2193
+ continue;
2170
2194
  foldDuplicateIntoSurvivor(db, sessionId, realSurvivor, duplicate);
2171
2195
  deletedTagNumbers.push(duplicate.tagNumber);
2172
2196
  }
2197
+ if (realSurvivor.tagNumber === tagNumber) {
2198
+ db.prepare("UPDATE tags SET message_id = ? WHERE session_id = ? AND tag_number = ?").run(newRealMessageId, sessionId, tagNumber);
2199
+ }
2173
2200
  return {
2174
2201
  action: "folded",
2175
2202
  tagNumber: realSurvivor.tagNumber,
@@ -2456,6 +2483,20 @@ function pickNearestPriorOwner(candidates, currentMessageId, times) {
2456
2483
  }
2457
2484
  // ../plugin/src/shared/historian-tool-defaults.json
2458
2485
  var historian_tool_defaults_default = {
2486
+ ctx_note: "Note ${input.action} ${input.note_ids}: ${input.content} → ${output.truncate(160)}",
2487
+ ctx_memory: "Memory ${input.action} ${input.category} ${input.ids}: ${input.content} → ${output.truncate(160)}",
2488
+ todowrite: 'Todos (${input.todos.count}): ${input.todos.each("${status}: ${content}")}',
2489
+ question: 'Asked user: ${input.questions[*].question.join(" / ")} → ${output}',
2490
+ task: "Task ${input.subagent_type}: ${input.prompt.truncate(600)} → ${output.truncate(200)}",
2491
+ ask: 'Asked: ${input.question} [options: ${input.options.join(" / ")}] ${input.text}${input.resolution} → ${output.truncate(300)}',
2492
+ peer_send: "PM ${input.recipient}: ${input.message}",
2493
+ 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}")}',
2494
+ room: "Room ${input.action} ${input.room_label}: ${input.room_detail}",
2495
+ work: "Work ${input.action} ${input.title}${input.id}: ${input.prompt.truncate(600)}${input.notes.truncate(600)} → ${output.truncate(160)}",
2496
+ knowhow: "Looked up how-to: ${input.query}${input.id}"
2497
+ };
2498
+ // ../plugin/src/shared/historian-tool-preview-defaults.json
2499
+ var historian_tool_preview_defaults_default = {
2459
2500
  ctx_note: "Note ${input.action} ${input.note_ids}: ${input.content} → ${output.truncate(160)}",
2460
2501
  ctx_memory: "Memory ${input.action} ${input.category} ${input.ids}: ${input.content} → ${output.truncate(160)}",
2461
2502
  todowrite: 'Todos (${input.todos.count}): ${input.todos.each("${status}: ${content}")}',
@@ -2470,17 +2511,48 @@ var historian_tool_defaults_default = {
2470
2511
  };
2471
2512
 
2472
2513
  // ../plugin/src/shared/historian-tool-expansions.ts
2473
- function expandToolPart(part, overrides) {
2514
+ function builtinInput(tool, input) {
2515
+ if (!input || typeof input !== "object")
2516
+ return input;
2517
+ const i = input;
2518
+ if (tool === "peer_send") {
2519
+ const external = i.external;
2520
+ 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";
2521
+ return { ...i, recipient };
2522
+ }
2523
+ if (tool === "room") {
2524
+ return {
2525
+ ...i,
2526
+ room_label: i.room_id || i.title,
2527
+ room_detail: i.action === "create" || i.action === "invite" ? `invitees: ${renderToolTemplate("${input.invitees}", i)}` : i.text
2528
+ };
2529
+ }
2530
+ if (tool === "board") {
2531
+ return {
2532
+ ...i,
2533
+ board_lane: i.lane ? ` ${i.lane}` : "",
2534
+ ops: Array.isArray(i.ops) ? i.ops.map((op) => op && typeof op === "object" ? {
2535
+ ...op,
2536
+ lane_label: typeof op.lane === "string" ? op.lane : op.lane?.title || op.lane?.id
2537
+ } : op) : i.ops
2538
+ };
2539
+ }
2540
+ return input;
2541
+ }
2542
+ function expandToolPart(part, overrides, legacyPreview = false) {
2474
2543
  if (!part || typeof part !== "object")
2475
2544
  return null;
2476
2545
  const p = part;
2477
2546
  if (p.type !== "tool" || typeof p.tool !== "string")
2478
2547
  return null;
2479
- const template = overrides && Object.hasOwn(overrides, p.tool) ? overrides[p.tool] : Object.hasOwn(historian_tool_defaults_default, p.tool) ? historian_tool_defaults_default[p.tool] : undefined;
2548
+ const builtinDefaults = legacyPreview ? historian_tool_preview_defaults_default : historian_tool_defaults_default;
2549
+ const overridden = overrides && Object.hasOwn(overrides, p.tool);
2550
+ const template = overridden ? overrides[p.tool] : Object.hasOwn(builtinDefaults, p.tool) ? builtinDefaults[p.tool] : undefined;
2480
2551
  if (typeof template !== "string")
2481
2552
  return null;
2482
2553
  const state = p.state;
2483
- return renderToolTemplate(template, state?.input, state?.output ?? state?.error);
2554
+ const input = overridden || legacyPreview ? state?.input : builtinInput(p.tool, state?.input);
2555
+ return renderToolTemplate(template, input, state?.output ?? state?.error, legacyPreview);
2484
2556
  }
2485
2557
 
2486
2558
  // ../plugin/src/hooks/magic-context/host-served-rows.ts
@@ -3411,20 +3483,22 @@ function fenceBoundaryForCompletedToolArcs(candidate, arcs, publicationFloorOrdi
3411
3483
  return minInvocation < publicationFloorOrdinal ? maxResult + 1 : minInvocation;
3412
3484
  }
3413
3485
  function fenceBoundaryForToolArcs(candidate, arcs, lastCompartmentEndOrdinal, recentOpenArcCutoff) {
3414
- const boundary = fenceBoundaryForCompletedToolArcs(candidate, arcs, lastCompartmentEndOrdinal + 1);
3486
+ let boundary = fenceBoundaryForCompletedToolArcs(candidate, arcs, lastCompartmentEndOrdinal + 1);
3415
3487
  for (const arc of arcs) {
3416
3488
  if (arc.resOrdinal !== null)
3417
3489
  continue;
3418
3490
  if (arc.invOrdinal < recentOpenArcCutoff)
3419
3491
  continue;
3420
3492
  if (arc.invOrdinal >= lastCompartmentEndOrdinal + 1 && arc.invOrdinal < boundary) {
3421
- return arc.invOrdinal;
3493
+ boundary = arc.invOrdinal;
3494
+ break;
3422
3495
  }
3423
3496
  if (arc.invOrdinal >= boundary) {
3424
- return arc.invOrdinal;
3497
+ boundary = arc.invOrdinal;
3498
+ break;
3425
3499
  }
3426
3500
  }
3427
- return boundary;
3501
+ return fenceBoundaryForCompletedToolArcs(boundary, arcs, 1);
3428
3502
  }
3429
3503
  function tokenForMessage(message, options) {
3430
3504
  const key = messageCacheKey(message, options);
@@ -4060,10 +4134,15 @@ function detectThinkingBindingMismatch(error) {
4060
4134
  ...firstChangedPath ? { firstChangedPath } : {}
4061
4135
  };
4062
4136
  }
4137
+ function detectLatestTurnThinkingMismatch(error) {
4138
+ const status = extractExplicitHttpStatus(error);
4139
+ return (status === undefined || status === 400) && /(?:thinking|redacted_thinking)[\s\S]*latest assistant (?:message|turn)[\s\S]*cannot be modified/i.test(extractErrorMessage(error));
4140
+ }
4063
4141
  var PREFIX_BOUND_THINKING_MODELS = [
4064
4142
  ["fable", 5, 1],
4065
4143
  ["opus", 5, 5],
4066
- ["sonnet", 5, 5]
4144
+ ["sonnet", 5, 5],
4145
+ ["haiku", 5, 5]
4067
4146
  ];
4068
4147
  var PREFIX_BOUND_THINKING_PATTERN = new RegExp(`(?:^|[-_.:/])(?:${PREFIX_BOUND_THINKING_MODELS.map(([family, major, minor]) => `${family}[-_.]?${major}[-_.]${minor}`).join("|")})(?:$|[-_.:/@])`, "i");
4069
4148
  function isPrefixBoundThinkingModel(_providerID, modelID) {
@@ -4146,6 +4225,11 @@ function parseReportedLimit(message) {
4146
4225
  function modelAcceptsEmptyContent(providerID) {
4147
4226
  return providerID === "anthropic";
4148
4227
  }
4228
+ function isAnthropicFamilyRoute(providerID, modelID) {
4229
+ const provider = (providerID ?? "").toLowerCase();
4230
+ const model = (modelID ?? "").toLowerCase();
4231
+ return provider.includes("anthropic") || model.includes("claude") || model.includes("anthropic");
4232
+ }
4149
4233
  var REMOVED_REASONING_MARK = Symbol.for("magic-context.removed-reasoning");
4150
4234
  var NEUTRALIZED_ORIGINALS = new WeakMap;
4151
4235
  var VARIANT_CACHE_PRESERVING_MODELS = {
@@ -5120,4 +5204,4 @@ function readRawSessionSeedTail2(sessionId, boundaryId, onQuery) {
5120
5204
  });
5121
5205
  }
5122
5206
 
5123
- export { detectThinkingBindingMismatch, isPrefixBoundThinkingModel, detectOverflow, UNKNOWN_FIT_RATIO, resolveDecisionCalibration, hasMeasuredDecisionCalibration, providerMass, localBudget, calibrationForModelKey, historyLocalBudget, adoptedProtectedToolsPolicy, protectedToolTagNumbers, protectedToolTokenCount, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isRecord, TEXT_TAG_IDENTITY_MARKER, contentTagOwnerMessageId, estimateImageTokensFromDataUrl, TODO_STATUSES, TODO_PRIORITIES, TITLE_DONE_STATUSES, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, compareMeasuredTailPrefix, formatTailHygienePrefixMismatch, freezeTailHygieneMeasurement, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, measureEmergencyTag, queuePendingOp, queuePendingDropForUnchangedTag, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, updateTagByteSize, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, getInertWhitespaceAssistantTags, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, getAssignableTagNumberByMessageId, deriveTagLoadFloor, TAG_SELECT_COLUMNS, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getNewestToolTagNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getTagById, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, withReadOnlySessionDb, expandToolPart, retreatPastHostUnservedRows, RAW_SUMMARY_TEXT_MAX_CHARS, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripSystemInjection, hasUserAnswerMetadata, DreamTokenBudgetExceeded, TOKEN_BUDGET_FINALIZE_MESSAGE, TOKEN_BUDGET_TOOL_REFUSAL, registerBudgetFinalizeChild, releaseBudgetFinalizeChild, createDreamTokenBudget, droppedInputMarker, createDroppedInputGuard, isEditTool, applyEditMarkerToInput, modelAcceptsEmptyContent, variantChangeBustsProviderCache, SKELETON_REAL_INPUT_MAX_BYTES, toolInputStringBytes, resolveHostServedBoundaryId2, hasRawMessageProvider2, setRawMessageProvider2, setBoundedRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, RAW_MESSAGE_VISIT_PAGE_SIZE2, visitRawSessionMessages2, readRawSessionMessageRange2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageOrdinalPage2, getRawSessionStoredMessageCount2, readRawSessionMessageIdOrdinalsForRange2, readRawSessionMessageIdOrdinals2, readRawSessionMessagePartsById2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, RAW_SESSION_TAG_KEY_PAGE_SIZE2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, getProtectedTailStartOrdinal2, readSessionChunk2, getRawSessionMessageIdsThrough2, readRawSessionSeedTail2 };
5207
+ export { detectThinkingBindingMismatch, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, UNKNOWN_FIT_RATIO, resolveDecisionCalibration, hasMeasuredDecisionCalibration, providerMass, localBudget, calibrationForModelKey, historyLocalBudget, adoptedProtectedToolsPolicy, protectedToolTagNumbers, protectedToolTokenCount, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isRecord, TEXT_TAG_IDENTITY_MARKER, contentTagOwnerMessageId, estimateImageTokensFromDataUrl, TODO_STATUSES, TODO_PRIORITIES, TITLE_DONE_STATUSES, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, compareMeasuredTailPrefix, formatTailHygienePrefixMismatch, freezeTailHygieneMeasurement, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, measureEmergencyTag, queuePendingOp, queuePendingDropForUnchangedTag, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, updateTagByteSize, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, getReasoningTokenEstimatesByMessage, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, getInertWhitespaceAssistantTags, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, getAssignableTagNumberByMessageId, deriveTagLoadFloor, TAG_SELECT_COLUMNS, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getNewestToolTagNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getTagById, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, withReadOnlySessionDb, expandToolPart, retreatPastHostUnservedRows, RAW_SUMMARY_TEXT_MAX_CHARS, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripSystemInjection, hasUserAnswerMetadata, DreamTokenBudgetExceeded, TOKEN_BUDGET_FINALIZE_MESSAGE, TOKEN_BUDGET_TOOL_REFUSAL, registerBudgetFinalizeChild, releaseBudgetFinalizeChild, createDreamTokenBudget, droppedInputMarker, createDroppedInputGuard, isEditTool, applyEditMarkerToInput, modelAcceptsEmptyContent, isAnthropicFamilyRoute, variantChangeBustsProviderCache, SKELETON_REAL_INPUT_MAX_BYTES, toolInputStringBytes, resolveHostServedBoundaryId2, hasRawMessageProvider2, setRawMessageProvider2, setBoundedRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, RAW_MESSAGE_VISIT_PAGE_SIZE2, visitRawSessionMessages2, readRawSessionMessageRange2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageOrdinalPage2, getRawSessionStoredMessageCount2, readRawSessionMessageIdOrdinalsForRange2, readRawSessionMessageIdOrdinals2, readRawSessionMessagePartsById2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, RAW_SESSION_TAG_KEY_PAGE_SIZE2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, getProtectedTailStartOrdinal2, readSessionChunk2, getRawSessionMessageIdsThrough2, readRawSessionSeedTail2 };