@cortexkit/pi-magic-context 0.37.0 → 0.38.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.
@@ -9032,7 +9032,7 @@ import {
9032
9032
  statSync as statSync3,
9033
9033
  unlinkSync as unlinkSync2
9034
9034
  } from "node:fs";
9035
- import { basename as basename2, dirname as dirname3, join as join4 } from "node:path";
9035
+ import { basename as basename2, dirname as dirname3, join as join4, resolve as resolve2 } from "node:path";
9036
9036
 
9037
9037
  // ../plugin/src/shared/error-message.ts
9038
9038
  function getErrorMessage(error) {
@@ -9254,6 +9254,51 @@ function readPsProcessCommand(pid) {
9254
9254
  return null;
9255
9255
  }
9256
9256
  }
9257
+ function readProcessCommand(pid) {
9258
+ if (!Number.isInteger(pid) || pid <= 0)
9259
+ return null;
9260
+ return rpcIdentityPlatform === "linux" ? readLinuxProcessCommand(pid) : rpcIdentityPlatform === "win32" ? readWindowsProcess(pid).command ?? null : readPsProcessCommand(pid);
9261
+ }
9262
+ function executableName(token) {
9263
+ return (token ?? "").replace(/^['"]|['"]$/g, "").split("/").at(-1) ?? "";
9264
+ }
9265
+ function commandTokens(command) {
9266
+ return command.toLowerCase().replaceAll("\\", "/").replaceAll("\x00", " ").split(/\s+/).map((token) => token.replace(/^['"]|['"]$/g, "")).filter(Boolean);
9267
+ }
9268
+ function commandHasOpenCodeExecutable(tokens) {
9269
+ return tokens.findIndex((token) => {
9270
+ const executable = executableName(token).replace(/\.(?:exe|cmd)$/, "");
9271
+ return executable === "opencode" || executable.endsWith("/opencode");
9272
+ });
9273
+ }
9274
+ function commandHasPiExecutable(tokens) {
9275
+ for (let index = 0;index < tokens.length; index += 1) {
9276
+ const executable = executableName(tokens[index]).replace(/\.(?:exe|cmd)$/, "");
9277
+ if (["pi", "omp", "oh-my-pi"].includes(executable))
9278
+ return true;
9279
+ if (["node", "bun", "deno"].includes(executable)) {
9280
+ const script = executableName(tokens[index + 1]).replace(/\.(?:exe|cmd)$/, "");
9281
+ if (["pi", "pi.js", "pi.mjs", "pi.cjs"].includes(script) || tokens[index + 1]?.includes("pi-coding-agent")) {
9282
+ return true;
9283
+ }
9284
+ }
9285
+ }
9286
+ return false;
9287
+ }
9288
+ function classifyProcessKind(command) {
9289
+ if (!command)
9290
+ return "process";
9291
+ const tokens = commandTokens(command);
9292
+ const openCodeIndex = commandHasOpenCodeExecutable(tokens);
9293
+ if (openCodeIndex >= 0) {
9294
+ const args = tokens.slice(openCodeIndex + 1);
9295
+ if (args.some((token) => token === "serve" || token === "--serve" || token.startsWith("--serve="))) {
9296
+ return "OpenCode server";
9297
+ }
9298
+ return "OpenCode instance (TUI/CLI)";
9299
+ }
9300
+ return commandHasPiExecutable(tokens) ? "Pi" : "process";
9301
+ }
9257
9302
  function commandLooksLikeOpenCode(command) {
9258
9303
  const normalized = command.toLowerCase();
9259
9304
  return OPEN_CODE_COMMAND_MARKERS.some((marker) => normalized.includes(marker));
@@ -9275,12 +9320,12 @@ function isPidIdentityPlausible(record) {
9275
9320
  function commandLooksLikePi(command) {
9276
9321
  const normalized = command.trim().toLowerCase().replaceAll("\\", "/");
9277
9322
  const tokens = normalized.split(/\s+/).filter(Boolean);
9278
- const executableName = (token) => (token ?? "").split("/").at(-1) ?? "";
9279
- const first = executableName(tokens[0]).replace(/\.exe$/, "");
9323
+ const executableName2 = (token) => (token ?? "").split("/").at(-1) ?? "";
9324
+ const first = executableName2(tokens[0]).replace(/\.exe$/, "");
9280
9325
  if (["pi", "pi.cmd", "omp", "oh-my-pi"].includes(first))
9281
9326
  return true;
9282
9327
  if (["node", "bun", "deno"].includes(first)) {
9283
- const script = executableName(tokens[1]);
9328
+ const script = executableName2(tokens[1]);
9284
9329
  return ["pi", "pi.js", "pi.mjs", "pi.cjs"].includes(script) || normalized.includes("pi-coding-agent");
9285
9330
  }
9286
9331
  return false;
@@ -9347,6 +9392,8 @@ function parseRpcPortFile(content, fallbackPid = 0) {
9347
9392
  port: port2,
9348
9393
  pid,
9349
9394
  started_at: Number.isFinite(startedAt) ? startedAt : 0,
9395
+ kind: typeof parsed.kind === "string" ? parsed.kind : undefined,
9396
+ harness: typeof parsed.harness === "string" ? parsed.harness : undefined,
9350
9397
  token: typeof parsed.token === "string" ? parsed.token : undefined,
9351
9398
  instance_id: typeof parsed.instance_id === "string" ? parsed.instance_id : undefined
9352
9399
  };
@@ -12818,6 +12865,28 @@ function invalidDiscoveryReason(raw) {
12818
12865
  }
12819
12866
  return "parse-invalid";
12820
12867
  }
12868
+ function classifyDiscoveryRecordKind(record) {
12869
+ for (const value of [record.kind, record.harness]) {
12870
+ const normalized = value?.trim().toLowerCase();
12871
+ if (!normalized)
12872
+ continue;
12873
+ if (normalized === "process")
12874
+ return "process";
12875
+ if (normalized === "opencode server" || normalized === "server") {
12876
+ return "OpenCode server";
12877
+ }
12878
+ if (normalized === "opencode instance" || normalized === "opencode instance (tui/cli)" || normalized === "opencode" || normalized === "tui" || normalized === "cli") {
12879
+ return "OpenCode instance (TUI/CLI)";
12880
+ }
12881
+ if (normalized === "pi" || normalized === "pi harness" || normalized === "omp" || normalized === "oh-my-pi") {
12882
+ return "Pi";
12883
+ }
12884
+ }
12885
+ return null;
12886
+ }
12887
+ function classifyRpcProcess(record) {
12888
+ return classifyDiscoveryRecordKind(record) ?? classifyProcessKind(readProcessCommand(record.pid));
12889
+ }
12821
12890
  function classifyJunkDiscovery(portFile, raw, staleFiles) {
12822
12891
  let mtimeMs;
12823
12892
  try {
@@ -12870,6 +12939,7 @@ function inspectRpcServerDiscovery(storageDir) {
12870
12939
  return { state: "absent", serverPids: [], staleFiles: [] };
12871
12940
  }
12872
12941
  const pids = new Set;
12942
+ const processByPid = new Map;
12873
12943
  const staleFiles = [];
12874
12944
  const inconclusivePids = new Set;
12875
12945
  for (const portFile of portFiles) {
@@ -12895,6 +12965,14 @@ function inspectRpcServerDiscovery(storageDir) {
12895
12965
  const identity = liveness === "dead" ? "implausible" : isPidIdentityPlausible(record);
12896
12966
  if (liveness === "alive" && identity === "plausible") {
12897
12967
  pids.add(record.pid);
12968
+ const detected = {
12969
+ kind: classifyRpcProcess(record),
12970
+ pid: record.pid
12971
+ };
12972
+ const previous = processByPid.get(record.pid);
12973
+ if (!previous || previous.kind === "process" && detected.kind !== "process") {
12974
+ processByPid.set(record.pid, detected);
12975
+ }
12898
12976
  } else if (liveness === "dead" || identity === "implausible") {
12899
12977
  staleFiles.push(portFile);
12900
12978
  } else {
@@ -12910,7 +12988,12 @@ function inspectRpcServerDiscovery(storageDir) {
12910
12988
  }
12911
12989
  const serverPids = [...pids].sort((a, b) => a - b);
12912
12990
  if (serverPids.length > 0) {
12913
- return { state: "live", serverPids, staleFiles };
12991
+ return {
12992
+ state: "live",
12993
+ serverPids,
12994
+ serverProcesses: serverPids.map((pid) => processByPid.get(pid) ?? { kind: "process", pid }),
12995
+ staleFiles
12996
+ };
12914
12997
  }
12915
12998
  const uncertainPids = [...inconclusivePids].sort((a, b) => a - b);
12916
12999
  if (uncertainPids.length > 0) {
@@ -12935,6 +13018,25 @@ function logInconclusiveMigrationProbes(dbPath, discovery, piProbeState) {
12935
13018
  log(`[magic-context] storage warning: continuing migration for ${dbPath}; the Pi/OMP process-list probe could not run, which commonly means an OS sandbox denied ps. No live Pi harness was confirmed.`);
12936
13019
  }
12937
13020
  }
13021
+ function isDefaultSharedDatabasePath(dbPath) {
13022
+ if (!process.env.XDG_DATA_HOME && (process.env.MAGIC_CONTEXT_TEST_DATA_DIR || false)) {
13023
+ return false;
13024
+ }
13025
+ return resolve2(dbPath) === resolve2(join4(getMagicContextStorageDir(), "context.db"));
13026
+ }
13027
+ function migrationBlockingPiPids(dbPath, discovery, discoveredPiPids) {
13028
+ if (isDefaultSharedDatabasePath(dbPath))
13029
+ return [...discoveredPiPids];
13030
+ const sameDataDirPids = new Set(discovery.serverPids);
13031
+ return discoveredPiPids.filter((pid) => sameDataDirPids.has(pid));
13032
+ }
13033
+ function formatLiveProcessMigrationRefusal(dbPath, persistedVersion, latestSupportedVersion, serverPids, piPids) {
13034
+ const blockers = [
13035
+ ...serverPids.map((pid) => `confirmed OpenCode server PID ${pid}`),
13036
+ ...piPids.map((pid) => `confirmed Pi harness PID ${pid}`)
13037
+ ];
13038
+ return `[magic-context] storage fatal: refusing to migrate ${dbPath} from upstream migration v${persistedVersion} to v${latestSupportedVersion} while ${blockers.join(", ")} still use the old plugin build. Restart the blocking harness, then retry this process.`;
13039
+ }
12938
13040
  function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion) {
12939
13041
  const persistedVersion = getPersistedSchemaVersion(db);
12940
13042
  if (persistedVersion >= latestSupportedVersion) {
@@ -12943,7 +13045,12 @@ function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)
12943
13045
  }
12944
13046
  const discovery = inspectRpcServerDiscovery(dbDir);
12945
13047
  const piDiscovery = inspectLivePiProcesses();
12946
- const piPids = piDiscovery.processIds;
13048
+ const piPids = migrationBlockingPiPids(dbPath, discovery, piDiscovery.processIds);
13049
+ const serverProcesses = discovery.serverProcesses ?? (discovery.state === "live" ? discovery.serverPids.map((pid) => ({ kind: "process", pid })) : []);
13050
+ const blockingProcesses = [
13051
+ ...serverProcesses,
13052
+ ...piPids.map((pid) => ({ kind: "Pi", pid }))
13053
+ ];
12947
13054
  if ((discovery.state === "absent" || discovery.state === "stale" || discovery.state === "inconclusive") && piPids.length === 0) {
12948
13055
  lastMigrationOnOpenRefusal = null;
12949
13056
  logInconclusiveMigrationProbes(dbPath, discovery, piDiscovery.state);
@@ -12954,6 +13061,7 @@ function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)
12954
13061
  persistedVersion,
12955
13062
  supportedVersion: latestSupportedVersion,
12956
13063
  serverPids: blockingPids,
13064
+ blockingProcesses,
12957
13065
  ...discovery.unreadableFile ? { unreadableFile: discovery.unreadableFile } : {},
12958
13066
  ...discovery.unreadableArm ? { unreadableArm: discovery.unreadableArm } : {}
12959
13067
  };
@@ -12963,11 +13071,7 @@ function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)
12963
13071
  const recovery = arm === "io" ? `If no OpenCode server is running, it is safe to delete ${unreadableFile} and retry.` : `Retry after the file is older than the ten-minute grace window, or stop OpenCode before deleting it.`;
12964
13072
  log(`[magic-context] storage fatal: refusing to migrate ${dbPath} from upstream migration v${persistedVersion} to v${latestSupportedVersion} because RPC discovery file ${unreadableFile} is uncertain (${arm} arm), so the absence of a live OpenCode server cannot be proven. ${recovery}`);
12965
13073
  } else {
12966
- const blockers = [
12967
- ...discovery.serverPids.map((pid) => `confirmed OpenCode server PID ${pid}`),
12968
- ...piPids.map((pid) => `confirmed Pi harness PID ${pid}`)
12969
- ];
12970
- log(`[magic-context] storage fatal: refusing to migrate ${dbPath} from upstream migration v${persistedVersion} to v${latestSupportedVersion} while ${blockers.join(", ")} still use the old plugin build. Restart the blocking harness, then retry this process.`);
13074
+ log(formatLiveProcessMigrationRefusal(dbPath, persistedVersion, latestSupportedVersion, discovery.serverPids, piPids));
12971
13075
  }
12972
13076
  return false;
12973
13077
  }
@@ -14125,11 +14229,11 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
14125
14229
  ensureColumn(db, "message_history_index", "harness", "TEXT NOT NULL DEFAULT 'opencode'");
14126
14230
  ensureColumn(db, "workspaces", "share_categories", `TEXT NOT NULL DEFAULT '["CONSTRAINTS"]'`);
14127
14231
  }
14128
- var CHANNEL2_CLAIM_TTL_MS = 120000;
14232
+ var CHANNEL2_CLAIM_TTL_MS = 10 * 60000;
14129
14233
  function healWedgedChannel2Claims(db) {
14130
14234
  try {
14131
14235
  const staleBefore = Date.now() - CHANNEL2_CLAIM_TTL_MS;
14132
- db.prepare("UPDATE session_meta SET channel2_nudge_state = 'pending', channel2_nudge_claimed_at = 0, channel2_nudge_claim_token = '' WHERE channel2_nudge_state = 'claimed' AND (channel2_nudge_claimed_at IS NULL OR channel2_nudge_claimed_at = 0 OR channel2_nudge_claimed_at <= ?)").run(staleBefore);
14236
+ db.prepare("UPDATE session_meta SET channel2_nudge_state = '', channel2_nudge_claimed_at = 0, channel2_nudge_claim_token = '' WHERE channel2_nudge_state = 'claimed' AND (channel2_nudge_claimed_at IS NULL OR channel2_nudge_claimed_at = 0 OR channel2_nudge_claimed_at <= ?)").run(staleBefore);
14133
14237
  } catch {}
14134
14238
  }
14135
14239
  function openDatabase(dbPathOrOptions) {
@@ -15113,6 +15217,16 @@ function getChannel2NudgeState(db, sessionId) {
15113
15217
  const raw = result.channel2_nudge_state;
15114
15218
  return raw === "pending" || raw === "claimed" || raw === "delivered" ? raw : "";
15115
15219
  }
15220
+ function getChannel2NudgeClaim(db, sessionId) {
15221
+ const result = db.prepare("SELECT channel2_nudge_state, channel2_nudge_claimed_at, channel2_nudge_claim_token FROM session_meta WHERE session_id = ?").get(sessionId);
15222
+ const rawState = typeof result?.channel2_nudge_state === "string" ? result.channel2_nudge_state : "";
15223
+ const state = rawState === "pending" || rawState === "claimed" || rawState === "delivered" ? rawState : "";
15224
+ return {
15225
+ state,
15226
+ claimedAt: typeof result?.channel2_nudge_claimed_at === "number" ? result.channel2_nudge_claimed_at : 0,
15227
+ claimToken: typeof result?.channel2_nudge_claim_token === "string" ? result.channel2_nudge_claim_token : ""
15228
+ };
15229
+ }
15116
15230
  function setChannel2NudgeState(db, sessionId, state) {
15117
15231
  db.transaction(() => {
15118
15232
  ensureSessionMetaRow(db, sessionId);
@@ -15130,6 +15244,26 @@ function casChannel2NudgeState(db, sessionId, from, to) {
15130
15244
  })();
15131
15245
  return changed;
15132
15246
  }
15247
+ function claimChannel2NudgeState(db, sessionId, claimToken) {
15248
+ let changed = false;
15249
+ db.transaction(() => {
15250
+ ensureSessionMetaRow(db, sessionId);
15251
+ const result = db.prepare("UPDATE session_meta SET channel2_nudge_state = 'claimed', channel2_nudge_claimed_at = ?, channel2_nudge_claim_token = ? WHERE session_id = ? AND channel2_nudge_state = 'pending'").run(Date.now(), claimToken, sessionId);
15252
+ changed = (result.changes ?? 0) > 0;
15253
+ })();
15254
+ return changed;
15255
+ }
15256
+ function casChannel2NudgeClaim(db, sessionId, to, claimToken) {
15257
+ let changed = false;
15258
+ db.transaction(() => {
15259
+ ensureSessionMetaRow(db, sessionId);
15260
+ const claimedAt = to === "claimed" ? Date.now() : 0;
15261
+ const nextClaimToken = to === "claimed" ? claimToken : "";
15262
+ const result = db.prepare("UPDATE session_meta SET channel2_nudge_state = ?, channel2_nudge_claimed_at = ?, channel2_nudge_claim_token = ? WHERE session_id = ? AND channel2_nudge_state = 'claimed' AND channel2_nudge_claim_token = ?").run(to, claimedAt, nextClaimToken, sessionId, claimToken);
15263
+ changed = (result.changes ?? 0) > 0;
15264
+ })();
15265
+ return changed;
15266
+ }
15133
15267
  function getPersistedNoteNudge(db, sessionId) {
15134
15268
  const result = db.prepare("SELECT note_nudge_trigger_pending, note_nudge_trigger_message_id, note_nudge_sticky_text, note_nudge_sticky_message_id FROM session_meta WHERE session_id = ?").get(sessionId);
15135
15269
  if (!isPersistedNoteNudgeRow(result)) {
@@ -17505,6 +17639,113 @@ function clearSession(db, sessionId) {
17505
17639
  clearIndexedMessages(db, sessionId);
17506
17640
  })();
17507
17641
  }
17642
+ // ../plugin/src/hooks/magic-context/todo-view.ts
17643
+ import { createHash as createHash5 } from "node:crypto";
17644
+ var TODO_STATUS_PENDING = "pending";
17645
+ var TODO_STATUS_IN_PROGRESS = "in_progress";
17646
+ var TODO_STATUS_COMPLETED = "completed";
17647
+ var TODO_STATUS_CANCELLED = "cancelled";
17648
+ var TODO_PRIORITY_HIGH = "high";
17649
+ var TODO_PRIORITY_MEDIUM = "medium";
17650
+ var TODO_PRIORITY_LOW = "low";
17651
+ var TODO_STATUSES = [
17652
+ TODO_STATUS_PENDING,
17653
+ TODO_STATUS_IN_PROGRESS,
17654
+ TODO_STATUS_COMPLETED,
17655
+ TODO_STATUS_CANCELLED
17656
+ ];
17657
+ var TODO_PRIORITIES = [
17658
+ TODO_PRIORITY_HIGH,
17659
+ TODO_PRIORITY_MEDIUM,
17660
+ TODO_PRIORITY_LOW
17661
+ ];
17662
+ var TODO_STATUS_SET = new Set(TODO_STATUSES);
17663
+ var TODO_PRIORITY_SET = new Set(TODO_PRIORITIES);
17664
+ var TERMINAL_STATUSES = new Set([
17665
+ TODO_STATUS_COMPLETED,
17666
+ TODO_STATUS_CANCELLED
17667
+ ]);
17668
+ var TITLE_DONE_STATUSES = new Set([TODO_STATUS_COMPLETED]);
17669
+ var SYNTHETIC_CALL_ID_PREFIX = "mc_synthetic_todo_";
17670
+ function normalizeTodoStateJson(todos) {
17671
+ if (!Array.isArray(todos))
17672
+ return null;
17673
+ const normalized = [];
17674
+ for (const todo of todos) {
17675
+ if (!isTodoItem(todo))
17676
+ return null;
17677
+ normalized.push({
17678
+ content: todo.content,
17679
+ status: todo.status,
17680
+ priority: todo.priority ?? TODO_PRIORITY_MEDIUM
17681
+ });
17682
+ }
17683
+ return JSON.stringify(normalized);
17684
+ }
17685
+ function buildSyntheticTodoPart(stateJson) {
17686
+ const todos = parseTodoState(stateJson);
17687
+ if (todos === null || todos.length === 0)
17688
+ return null;
17689
+ if (todos.every((t) => TERMINAL_STATUSES.has(t.status)))
17690
+ return null;
17691
+ const callID = computeSyntheticCallId(stateJson);
17692
+ const activeCount = todos.filter((t) => !TITLE_DONE_STATUSES.has(t.status)).length;
17693
+ const output = JSON.stringify(todos, null, 2);
17694
+ const ts = 0;
17695
+ return {
17696
+ type: "tool",
17697
+ callID,
17698
+ tool: "todowrite",
17699
+ state: {
17700
+ status: "completed",
17701
+ input: { todos },
17702
+ output,
17703
+ title: `${activeCount} todos`,
17704
+ metadata: { todos, truncated: false },
17705
+ time: { start: ts, end: ts }
17706
+ },
17707
+ syntheticTodoMarker: true
17708
+ };
17709
+ }
17710
+ function computeSyntheticCallId(stateJson) {
17711
+ const hash = createHash5("sha256").update(stateJson).digest("hex").slice(0, 16);
17712
+ return `${SYNTHETIC_CALL_ID_PREFIX}${hash}`;
17713
+ }
17714
+ function parseTodoState(stateJson) {
17715
+ if (stateJson.length === 0)
17716
+ return null;
17717
+ try {
17718
+ const parsed = JSON.parse(stateJson);
17719
+ if (!Array.isArray(parsed))
17720
+ return null;
17721
+ const result = [];
17722
+ for (const item of parsed) {
17723
+ if (!isTodoItem(item))
17724
+ return null;
17725
+ result.push({
17726
+ content: item.content,
17727
+ status: item.status,
17728
+ priority: item.priority ?? TODO_PRIORITY_MEDIUM
17729
+ });
17730
+ }
17731
+ return result;
17732
+ } catch {
17733
+ return null;
17734
+ }
17735
+ }
17736
+ function isTodoStatus(value) {
17737
+ return typeof value === "string" && TODO_STATUS_SET.has(value);
17738
+ }
17739
+ function isTodoPriority(value) {
17740
+ return typeof value === "string" && TODO_PRIORITY_SET.has(value);
17741
+ }
17742
+ function isTodoItem(value) {
17743
+ if (value === null || typeof value !== "object")
17744
+ return false;
17745
+ const todo = value;
17746
+ return typeof todo.content === "string" && isTodoStatus(todo.status) && (todo.priority === undefined || isTodoPriority(todo.priority));
17747
+ }
17748
+
17508
17749
  // ../plugin/src/features/magic-context/compartment-lease.ts
17509
17750
  var COMPARTMENT_LEASE_TTL_MS = 5 * 60 * 1000;
17510
17751
  var COMPARTMENT_LEASE_RENEWAL_MS = 60 * 1000;
@@ -17705,7 +17946,7 @@ function escapeXmlContent(s) {
17705
17946
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
17706
17947
  }
17707
17948
  // ../plugin/src/features/magic-context/project-docs-hash.ts
17708
- import { createHash as createHash5 } from "node:crypto";
17949
+ import { createHash as createHash6 } from "node:crypto";
17709
17950
  import { lstatSync, readFileSync as readFileSync5, statSync as statSync4 } from "node:fs";
17710
17951
  import path2 from "node:path";
17711
17952
  var PROJECT_DOC_FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
@@ -17803,7 +18044,7 @@ function hashCanonicalPieces(hashPieces) {
17803
18044
  if (hashPieces.length === 0) {
17804
18045
  return "";
17805
18046
  }
17806
- return createHash5("sha256").update(hashPieces.join(PROJECT_DOCS_DELIMITER), "utf8").digest("hex");
18047
+ return createHash6("sha256").update(hashPieces.join(PROJECT_DOCS_DELIMITER), "utf8").digest("hex");
17807
18048
  }
17808
18049
  function readProjectDocsCanonical(projectDirectory) {
17809
18050
  const canonicalDirectory = path2.resolve(projectDirectory);
@@ -18074,10 +18315,10 @@ function copySessionStateForClone(db, sourceSessionId, destinationSessionId, fil
18074
18315
  });
18075
18316
  }
18076
18317
  // ../plugin/src/features/magic-context/storage-embedding-measurements.ts
18077
- import { createHash as createHash6 } from "node:crypto";
18318
+ import { createHash as createHash7 } from "node:crypto";
18078
18319
  function normalizedQueryHash(query) {
18079
18320
  const normalized = query.trim().replace(/\s+/g, " ").toLowerCase();
18080
- return createHash6("sha256").update(normalized).digest("hex");
18321
+ return createHash7("sha256").update(normalized).digest("hex");
18081
18322
  }
18082
18323
  var MEASUREMENT_CORPUS_SESSION_ROW_CAP = 2000;
18083
18324
  function recordEmbeddingMeasurement(db, input) {
@@ -18952,6 +19193,436 @@ function getLatestHistorianInvocationId(db, sessionId) {
18952
19193
  return null;
18953
19194
  }
18954
19195
  }
19196
+ // ../plugin/src/features/magic-context/reclaim-protection.ts
19197
+ var CTX_REDUCE_KEEP = 3;
19198
+ function newestCtxReduceTagNumbers(tags) {
19199
+ return new Set(tags.filter((tag) => tag.toolName === "ctx_reduce").sort((left, right) => right.tagNumber - left.tagNumber).slice(0, CTX_REDUCE_KEEP).map((tag) => tag.tagNumber));
19200
+ }
19201
+
19202
+ // ../plugin/src/hooks/magic-context/image-token-estimate.ts
19203
+ var IMAGE_TOKEN_DIVISOR = 750;
19204
+ var IMAGE_FALLBACK_TOKENS = 1200;
19205
+ var IMAGE_TOKEN_CAP = 4500;
19206
+ function estimateImageTokensFromDataUrl(url) {
19207
+ const comma = url.indexOf(",");
19208
+ if (comma < 0)
19209
+ return IMAGE_FALLBACK_TOKENS;
19210
+ const header = url.slice(0, comma);
19211
+ const payload = url.slice(comma + 1);
19212
+ const sliceLen = Math.min(512, payload.length);
19213
+ const preview = payload.slice(0, sliceLen);
19214
+ let bytes;
19215
+ try {
19216
+ bytes = base64Decode(preview);
19217
+ } catch {
19218
+ return IMAGE_FALLBACK_TOKENS;
19219
+ }
19220
+ if (header.includes("image/png")) {
19221
+ const dims = parsePngDimensions(bytes);
19222
+ if (dims)
19223
+ return clampImageTokens(Math.ceil(dims.w * dims.h / IMAGE_TOKEN_DIVISOR));
19224
+ } else if (header.includes("image/jpeg") || header.includes("image/jpg")) {
19225
+ const dims = parseJpegDimensions(bytes);
19226
+ if (dims)
19227
+ return clampImageTokens(Math.ceil(dims.w * dims.h / IMAGE_TOKEN_DIVISOR));
19228
+ } else if (header.includes("image/webp")) {
19229
+ const dims = parseWebpDimensions(bytes);
19230
+ if (dims)
19231
+ return clampImageTokens(Math.ceil(dims.w * dims.h / IMAGE_TOKEN_DIVISOR));
19232
+ } else if (header.includes("image/gif")) {
19233
+ const dims = parseGifDimensions(bytes);
19234
+ if (dims)
19235
+ return clampImageTokens(Math.ceil(dims.w * dims.h / IMAGE_TOKEN_DIVISOR));
19236
+ }
19237
+ return IMAGE_FALLBACK_TOKENS;
19238
+ }
19239
+ function clampImageTokens(n) {
19240
+ if (n < 1)
19241
+ return 1;
19242
+ if (n > IMAGE_TOKEN_CAP)
19243
+ return IMAGE_TOKEN_CAP;
19244
+ return n;
19245
+ }
19246
+ function base64Decode(b64) {
19247
+ const pad = b64.length % 4;
19248
+ const padded = pad === 0 ? b64 : b64 + "=".repeat(4 - pad);
19249
+ const binary = atob(padded);
19250
+ const out = new Uint8Array(binary.length);
19251
+ for (let i = 0;i < binary.length; i++)
19252
+ out[i] = binary.charCodeAt(i);
19253
+ return out;
19254
+ }
19255
+ function parsePngDimensions(b) {
19256
+ if (b.length < 24)
19257
+ return null;
19258
+ if (b[0] !== 137 || b[1] !== 80 || b[2] !== 78 || b[3] !== 71 || b[4] !== 13 || b[5] !== 10 || b[6] !== 26 || b[7] !== 10)
19259
+ return null;
19260
+ const w = readUint32BE(b, 16);
19261
+ const h = readUint32BE(b, 20);
19262
+ if (!w || !h)
19263
+ return null;
19264
+ return { w, h };
19265
+ }
19266
+ function parseJpegDimensions(b) {
19267
+ if (b.length < 4 || b[0] !== 255 || b[1] !== 216)
19268
+ return null;
19269
+ let i = 2;
19270
+ while (i < b.length - 8) {
19271
+ if (b[i] !== 255) {
19272
+ i++;
19273
+ continue;
19274
+ }
19275
+ const marker = b[i + 1];
19276
+ if (marker === undefined)
19277
+ break;
19278
+ if (isSofMarker(marker)) {
19279
+ const h = b[i + 5] << 8 | b[i + 6];
19280
+ const w = b[i + 7] << 8 | b[i + 8];
19281
+ if (w && h)
19282
+ return { w, h };
19283
+ return null;
19284
+ }
19285
+ if (marker === 216 || marker === 217 || marker === 1) {
19286
+ i += 2;
19287
+ continue;
19288
+ }
19289
+ const segLen = b[i + 2] << 8 | b[i + 3];
19290
+ if (segLen < 2)
19291
+ return null;
19292
+ i += 2 + segLen;
19293
+ }
19294
+ return null;
19295
+ }
19296
+ function isSofMarker(m) {
19297
+ if (m >= 192 && m <= 195)
19298
+ return true;
19299
+ if (m >= 197 && m <= 199)
19300
+ return true;
19301
+ if (m >= 201 && m <= 203)
19302
+ return true;
19303
+ if (m >= 205 && m <= 207)
19304
+ return true;
19305
+ return false;
19306
+ }
19307
+ function parseWebpDimensions(b) {
19308
+ if (b.length < 30)
19309
+ return null;
19310
+ if (b[0] !== 82 || b[1] !== 73 || b[2] !== 70 || b[3] !== 70)
19311
+ return null;
19312
+ if (b[8] !== 87 || b[9] !== 69 || b[10] !== 66 || b[11] !== 80)
19313
+ return null;
19314
+ const variant = String.fromCharCode(b[12], b[13], b[14], b[15]);
19315
+ if (variant === "VP8 ") {
19316
+ const w = (b[26] | b[27] << 8) & 16383;
19317
+ const h = (b[28] | b[29] << 8) & 16383;
19318
+ if (w && h)
19319
+ return { w, h };
19320
+ } else if (variant === "VP8L") {
19321
+ const b0 = b[21];
19322
+ const b1 = b[22];
19323
+ const b2 = b[23];
19324
+ const b3 = b[24];
19325
+ const w = 1 + ((b0 | b1 << 8) & 16383);
19326
+ const h = 1 + ((b1 >> 6 | b2 << 2 | b3 << 10) & 16383);
19327
+ if (w && h)
19328
+ return { w, h };
19329
+ } else if (variant === "VP8X") {
19330
+ const w = 1 + (b[24] | b[25] << 8 | b[26] << 16);
19331
+ const h = 1 + (b[27] | b[28] << 8 | b[29] << 16);
19332
+ if (w && h)
19333
+ return { w, h };
19334
+ }
19335
+ return null;
19336
+ }
19337
+ function parseGifDimensions(b) {
19338
+ if (b.length < 10)
19339
+ return null;
19340
+ if (b[0] !== 71 || b[1] !== 73 || b[2] !== 70)
19341
+ return null;
19342
+ const w = b[6] | b[7] << 8;
19343
+ const h = b[8] | b[9] << 8;
19344
+ if (!w || !h)
19345
+ return null;
19346
+ return { w, h };
19347
+ }
19348
+ function readUint32BE(b, offset) {
19349
+ return (b[offset] << 24 | b[offset + 1] << 16 | b[offset + 2] << 8 | b[offset + 3]) >>> 0;
19350
+ }
19351
+
19352
+ // ../plugin/src/hooks/magic-context/tail-hygiene-walk.ts
19353
+ var MAX_CONTENT_MEMO_BYTES = 64 * 1024 * 1024;
19354
+ var contentMemo = new Map;
19355
+ var CHANNEL1_REMINDER_OPEN = `
19356
+
19357
+ <system-reminder>
19358
+ `;
19359
+ var CHANNEL1_REMINDER_CLOSE = `
19360
+ </system-reminder>`;
19361
+ function stripChannel1ReminderSpans(output) {
19362
+ let stripped = output;
19363
+ while (stripped.endsWith(CHANNEL1_REMINDER_CLOSE)) {
19364
+ const opener = stripped.lastIndexOf(CHANNEL1_REMINDER_OPEN);
19365
+ if (opener < 0)
19366
+ break;
19367
+ stripped = stripped.slice(0, opener);
19368
+ }
19369
+ return stripped;
19370
+ }
19371
+ function effectiveTailHygiene(baseline) {
19372
+ const t = Math.max(0, baseline.baselineT + baseline.turnDeltaT);
19373
+ const u = Math.min(t, Math.max(0, baseline.baselineU + baseline.turnDeltaU));
19374
+ return { u, t };
19375
+ }
19376
+
19377
+ // ../plugin/src/hooks/magic-context/ctx-reduce-nudge.ts
19378
+ var CHANNEL1_SENTINEL = "<system-reminder>";
19379
+ var TOKENS_PER_BYTE = 0.25;
19380
+ var CHANNEL1_MIN_TOKENS = 60000;
19381
+ var CHANNEL1_FLOOR_TOKENS = 25000;
19382
+ var CHANNEL1_REFIRE_FLOOR_TOKENS = 25000;
19383
+ var S_GENTLE = 0.2;
19384
+ var S_FIRM = 0.4;
19385
+ var S_URGENT = 0.6;
19386
+ var LEVEL_RANK = { gentle: 1, firm: 2, urgent: 3 };
19387
+ function channel1RefireTokens(tailTokens) {
19388
+ const scaled = Math.round(0.08 * Math.max(0, tailTokens));
19389
+ return Math.max(CHANNEL1_REFIRE_FLOOR_TOKENS, scaled);
19390
+ }
19391
+ function decideChannel1(input) {
19392
+ const tailTokens = Math.max(0, input.baselineT + input.turnDeltaT);
19393
+ const undroppedTokens = Math.min(tailTokens, Math.max(0, input.baselineU + input.turnDeltaU));
19394
+ const severity = Math.min(1, Math.max(0, undroppedTokens / Math.max(tailTokens, 1)));
19395
+ const resetCycle = input.hasRecentReduce || undroppedTokens < input.lastNudgeUndropped;
19396
+ const lastNudge = resetCycle ? 0 : input.lastNudgeUndropped;
19397
+ const lastLevel = resetCycle ? "" : input.lastNudgeLevel;
19398
+ const quiet = () => ({
19399
+ fire: false,
19400
+ level: "gentle",
19401
+ undroppedTokens,
19402
+ tailTokens,
19403
+ severity,
19404
+ nextLastNudge: lastNudge,
19405
+ nextLastNudgeLevel: lastLevel
19406
+ });
19407
+ if (input.evaluable === false || input.generationInvalidated === true)
19408
+ return quiet();
19409
+ if (input.hasRecentReduce)
19410
+ return quiet();
19411
+ if (tailTokens < CHANNEL1_MIN_TOKENS)
19412
+ return quiet();
19413
+ if (undroppedTokens < CHANNEL1_FLOOR_TOKENS || undroppedTokens === 0)
19414
+ return quiet();
19415
+ if (severity < S_GENTLE)
19416
+ return quiet();
19417
+ let level;
19418
+ if (severity >= S_URGENT)
19419
+ level = "urgent";
19420
+ else if (severity >= S_FIRM)
19421
+ level = "firm";
19422
+ else
19423
+ level = "gentle";
19424
+ const escalated = lastLevel === "" || LEVEL_RANK[level] > LEVEL_RANK[lastLevel];
19425
+ const cadenceReached = lastLevel !== "" && undroppedTokens - lastNudge >= channel1RefireTokens(tailTokens);
19426
+ if (!escalated && !cadenceReached)
19427
+ return quiet();
19428
+ return {
19429
+ fire: true,
19430
+ level,
19431
+ undroppedTokens,
19432
+ tailTokens,
19433
+ severity,
19434
+ nextLastNudge: undroppedTokens,
19435
+ nextLastNudgeLevel: level
19436
+ };
19437
+ }
19438
+ var CHANNEL2_SEVERITY_THRESHOLD = 0.75;
19439
+ var CHANNEL2_FLOOR_TOKENS = 50000;
19440
+ function evaluateChannel2(input) {
19441
+ const values = input ? [input.baselineU, input.baselineT, input.turnDeltaU, input.turnDeltaT] : [];
19442
+ if (input?.evaluable !== true || input.generationInvalidated === true || values.some((value) => !Number.isFinite(value))) {
19443
+ return {
19444
+ evaluable: false,
19445
+ shouldTrigger: false,
19446
+ reclaimableTokens: 0,
19447
+ tailTokens: 0,
19448
+ severity: 0
19449
+ };
19450
+ }
19451
+ const tailTokens = Math.max(0, input.baselineT + input.turnDeltaT);
19452
+ const reclaimableTokens = Math.min(tailTokens, Math.max(0, input.baselineU + input.turnDeltaU));
19453
+ const severity = Math.min(1, Math.max(0, reclaimableTokens / Math.max(tailTokens, 1)));
19454
+ return {
19455
+ evaluable: true,
19456
+ shouldTrigger: tailTokens >= CHANNEL1_MIN_TOKENS && reclaimableTokens >= CHANNEL2_FLOOR_TOKENS && severity >= CHANNEL2_SEVERITY_THRESHOLD,
19457
+ reclaimableTokens,
19458
+ tailTokens,
19459
+ severity
19460
+ };
19461
+ }
19462
+ function approxThousands(tokens) {
19463
+ return `${Math.round(tokens / 1000)}k`;
19464
+ }
19465
+ function formatOldestReclaimableHint(hint) {
19466
+ if (!hint || hint.length === 0)
19467
+ return "";
19468
+ const rendered = hint.slice(0, 4).map((tag) => `§${tag.tagNumber}§ ${tag.toolName ?? "tool"}`).join(" · ");
19469
+ return rendered.length > 0 ? `
19470
+ oldest reclaimable: ${rendered}.` : "";
19471
+ }
19472
+ function buildChannel2Reminder(undroppedTokens, hint) {
19473
+ const amount = approxThousands(undroppedTokens);
19474
+ const hintText = formatOldestReclaimableHint(hint);
19475
+ return `<system-reminder>
19476
+ ` + `Routine context housekeeping is near: a large span of this session will be comparted soon, ` + `and ~${amount} tokens of tool output remain unreduced. Drop spent outputs with ctx_reduce ` + `first so the archived span is the part that matters.${hintText}
19477
+ ` + `</system-reminder>`;
19478
+ }
19479
+ function buildChannel1Reminder(level, undroppedTokens, hint) {
19480
+ const amount = approxThousands(undroppedTokens);
19481
+ const hintText = formatOldestReclaimableHint(hint);
19482
+ let body;
19483
+ switch (level) {
19484
+ case "gentle":
19485
+ body = `You have ~${amount} tokens of content you have not reduced. ` + `When you are done with earlier outputs, dropping them with ctx_reduce keeps context lean.`;
19486
+ break;
19487
+ case "firm":
19488
+ body = `~${amount} tokens of unreduced content has built up. ` + `At your next natural stopping point, consider dropping what you have already processed with ctx_reduce.`;
19489
+ break;
19490
+ case "urgent":
19491
+ body = `~${amount} tokens of unreduced content remain across most of the live tail. ` + `Consider dropping spent outputs with ctx_reduce so the archived span is the part that matters.`;
19492
+ break;
19493
+ }
19494
+ return `
19495
+
19496
+ <system-reminder>
19497
+ ${body}${hintText}
19498
+ </system-reminder>`;
19499
+ }
19500
+
19501
+ // ../plugin/src/hooks/magic-context/emergency-drop.ts
19502
+ var TARGET_FRACTION = 0.3;
19503
+ var TIER_RECENCY_RESERVE = 0.2;
19504
+ var EMERGENCY_REARM_MIN_TOKENS = 2000;
19505
+ var T1_TOOLS = new Set(["read", "todowrite", "task", "aft_outline", "aft_zoom"]);
19506
+ var T2_TOOLS = new Set(["edit", "write", "apply_patch", "grep", "glob", "aft_search"]);
19507
+ function normalizeToolName(toolName) {
19508
+ if (!toolName)
19509
+ return "";
19510
+ let name = toolName.toLowerCase();
19511
+ if (name.startsWith("mcp_"))
19512
+ name = name.slice(4);
19513
+ return name;
19514
+ }
19515
+ function resolveToolTier(toolName) {
19516
+ const name = normalizeToolName(toolName);
19517
+ if (T1_TOOLS.has(name))
19518
+ return 1;
19519
+ if (T2_TOOLS.has(name))
19520
+ return 2;
19521
+ return 3;
19522
+ }
19523
+ function tagReclaimBytes(tag) {
19524
+ return tag.byteSize + tag.inputByteSize + tag.reasoningByteSize;
19525
+ }
19526
+ function estimateEmergencyDropReclaimTokens(tag) {
19527
+ return Math.round(tagReclaimBytes(tag) * TOKENS_PER_BYTE);
19528
+ }
19529
+ function planEmergencyDrop(input) {
19530
+ const {
19531
+ tags,
19532
+ floorTags,
19533
+ maxTag,
19534
+ protectedTags,
19535
+ currentTotalInputTokens,
19536
+ ceilingTokens,
19537
+ priorInputSample,
19538
+ hasPriorDrop
19539
+ } = input;
19540
+ const noop = (reason) => ({
19541
+ shouldDrop: false,
19542
+ tagNumbers: [],
19543
+ reclaimTokens: 0,
19544
+ reason
19545
+ });
19546
+ if (!Number.isFinite(ceilingTokens) || ceilingTokens <= 0) {
19547
+ return noop("unknown-ceiling");
19548
+ }
19549
+ if (!Number.isFinite(currentTotalInputTokens) || currentTotalInputTokens <= 0) {
19550
+ return noop("unknown-usage");
19551
+ }
19552
+ if (hasPriorDrop && currentTotalInputTokens === priorInputSample) {
19553
+ return noop("same-input-sample (awaiting fresh usage after prior drop)");
19554
+ }
19555
+ let tailTokens = 0;
19556
+ for (const tag of floorTags) {
19557
+ if (tag.status !== "active")
19558
+ continue;
19559
+ tailTokens += estimateEmergencyDropReclaimTokens(tag);
19560
+ }
19561
+ const fixedFloor = Math.max(currentTotalInputTokens - tailTokens, 0);
19562
+ const workingSpan = Math.max(ceilingTokens - fixedFloor, 0);
19563
+ const target = fixedFloor + TARGET_FRACTION * workingSpan;
19564
+ const reclaimTokens = Math.round(currentTotalInputTokens - target);
19565
+ if (reclaimTokens <= EMERGENCY_REARM_MIN_TOKENS) {
19566
+ return noop(`reclaim<=min (${reclaimTokens} <= ${EMERGENCY_REARM_MIN_TOKENS})`);
19567
+ }
19568
+ const protectedCutoff = maxTag - protectedTags;
19569
+ const tierActive = { 1: [], 2: [] };
19570
+ for (const tag of tags) {
19571
+ if (tag.status !== "active" || tag.type !== "tool")
19572
+ continue;
19573
+ const tier = resolveToolTier(tag.toolName);
19574
+ if (tier === 1 || tier === 2)
19575
+ tierActive[tier].push(tag.tagNumber);
19576
+ }
19577
+ const reserved = new Set;
19578
+ for (const tier of [1, 2]) {
19579
+ const nums = tierActive[tier];
19580
+ if (nums.length === 0)
19581
+ continue;
19582
+ nums.sort((a, b) => b - a);
19583
+ const reserveCount = Math.ceil(TIER_RECENCY_RESERVE * nums.length);
19584
+ for (let i = 0;i < reserveCount && i < nums.length; i++) {
19585
+ reserved.add(nums[i]);
19586
+ }
19587
+ }
19588
+ const protectedCtxReduceTags = newestCtxReduceTagNumbers(floorTags.filter((tag) => tag.status === "active" && tag.type === "tool"));
19589
+ const byTier = { 1: [], 2: [], 3: [] };
19590
+ for (const tag of tags) {
19591
+ if (tag.status !== "active" || tag.type !== "tool")
19592
+ continue;
19593
+ if (tag.tagNumber > protectedCutoff)
19594
+ continue;
19595
+ if (protectedCtxReduceTags.has(tag.tagNumber))
19596
+ continue;
19597
+ const tier = resolveToolTier(tag.toolName);
19598
+ if ((tier === 1 || tier === 2) && reserved.has(tag.tagNumber))
19599
+ continue;
19600
+ byTier[tier].push(tag);
19601
+ }
19602
+ const selected = [];
19603
+ let reclaimed = 0;
19604
+ outer:
19605
+ for (const tier of [3, 2, 1]) {
19606
+ const group = byTier[tier];
19607
+ group.sort((a, b) => a.tagNumber - b.tagNumber);
19608
+ for (const tag of group) {
19609
+ selected.push(tag.tagNumber);
19610
+ reclaimed += estimateEmergencyDropReclaimTokens(tag);
19611
+ if (reclaimed >= reclaimTokens)
19612
+ break outer;
19613
+ }
19614
+ }
19615
+ if (selected.length === 0) {
19616
+ return noop("no-candidates");
19617
+ }
19618
+ return {
19619
+ shouldDrop: true,
19620
+ tagNumbers: selected,
19621
+ reclaimTokens,
19622
+ reason: `tiered drop: ${selected.length} tags, reclaim≈${reclaimed}/${reclaimTokens} tokens (floor≈${fixedFloor}, ceiling=${Math.round(ceilingTokens)})`
19623
+ };
19624
+ }
19625
+
18955
19626
  // ../plugin/src/features/magic-context/storage-tags.ts
18956
19627
  var insertTagStatements = new WeakMap;
18957
19628
  var updateTagStatusStatements = new WeakMap;
@@ -19014,32 +19685,23 @@ function ownerMessageIdForTagRow(row) {
19014
19685
  }
19015
19686
  return row.message_id.replace(CONTENT_ID_SUFFIX, "");
19016
19687
  }
19017
- function getActiveTagTokenAggregate(db, sessionId, protectedTags = 0) {
19018
- const toolOutputExpr = protectedTags > 0 ? `COALESCE(SUM(CASE WHEN type = 'tool' AND tag_number < (
19019
- SELECT tag_number FROM tags
19020
- WHERE session_id = ? AND status = 'active'
19021
- ORDER BY tag_number DESC LIMIT 1 OFFSET ?
19022
- ) THEN COALESCE(token_count, 0) ELSE 0 END), 0)` : `COALESCE(SUM(CASE WHEN type = 'tool' THEN COALESCE(token_count, 0) ELSE 0 END), 0)`;
19023
- const sql = `SELECT
19024
- COALESCE(SUM(CASE WHEN type != 'tool' THEN COALESCE(token_count, 0) ELSE 0 END), 0)
19025
- + COALESCE(SUM(COALESCE(reasoning_token_count, 0)), 0) AS conversation,
19026
- COALESCE(SUM(CASE WHEN type = 'tool' THEN COALESCE(token_count, 0) + COALESCE(input_token_count, 0) ELSE 0 END), 0) AS tool_call,
19027
- ${toolOutputExpr} AS tool_output,
19028
- COALESCE(SUM(CASE WHEN token_count IS NULL THEN 1 ELSE 0 END), 0) AS null_count
19029
- FROM tags
19030
- WHERE session_id = ? AND status = 'active'`;
19031
- const params = protectedTags > 0 ? [sessionId, protectedTags - 1, sessionId] : [sessionId];
19032
- const row = db.prepare(sql).get(...params);
19033
- return {
19034
- conversation: row?.conversation ?? 0,
19035
- toolCall: row?.tool_call ?? 0,
19036
- toolOutput: row?.tool_output ?? 0,
19037
- nullCount: row?.null_count ?? 0
19038
- };
19039
- }
19040
- var RECLAIM_HINT_EXCLUDED_TOOLS = ["todowrite"];
19688
+ var RECLAIM_HINT_EXCLUDED_TOOLS = new Set([
19689
+ "ask",
19690
+ "bash_kill",
19691
+ "bash_status",
19692
+ "board",
19693
+ "task",
19694
+ "todoread",
19695
+ "todowrite",
19696
+ "work"
19697
+ ]);
19041
19698
  var AGE_RECLAIM_MIN_TOKENS = 250;
19042
- var RECLAIM_HINT_EXCLUDED_LIST = RECLAIM_HINT_EXCLUDED_TOOLS.map((name) => `'${name.replace(/'/g, "''")}'`).join(", ");
19699
+ function isReclaimHintExcludedTool(toolName) {
19700
+ if (!toolName)
19701
+ return false;
19702
+ const normalized = toolName.toLowerCase().replace(/^mcp_/, "");
19703
+ return normalized.startsWith("ctx_") || RECLAIM_HINT_EXCLUDED_TOOLS.has(normalized);
19704
+ }
19043
19705
  function getOldestActiveUnprotectedToolTags(db, sessionId, protectedTags = 0, limit = 4) {
19044
19706
  if (limit <= 0)
19045
19707
  return [];
@@ -19049,24 +19711,21 @@ function getOldestActiveUnprotectedToolTags(db, sessionId, protectedTags = 0, li
19049
19711
  WHERE session_id = ? AND status = 'active'
19050
19712
  ORDER BY tag_number DESC LIMIT 1 OFFSET ?
19051
19713
  )` : "";
19052
- const excludeStateTools = RECLAIM_HINT_EXCLUDED_LIST ? `AND (tool_name IS NULL OR tool_name NOT IN (${RECLAIM_HINT_EXCLUDED_LIST}))` : "";
19053
19714
  const valueFloor = `AND (
19054
19715
  (token_count IS NULL AND input_token_count IS NULL)
19055
19716
  OR (COALESCE(token_count, 0) + COALESCE(input_token_count, 0)) >= ?
19056
19717
  )`;
19057
- const params = protectedTags > 0 ? [sessionId, AGE_RECLAIM_MIN_TOKENS, sessionId, protectedTags - 1, boundedLimit] : [sessionId, AGE_RECLAIM_MIN_TOKENS, boundedLimit];
19718
+ const params = protectedTags > 0 ? [sessionId, AGE_RECLAIM_MIN_TOKENS, sessionId, protectedTags - 1] : [sessionId, AGE_RECLAIM_MIN_TOKENS];
19058
19719
  const rows = db.prepare(`SELECT tag_number, tool_name
19059
19720
  FROM tags
19060
19721
  WHERE session_id = ? AND status = 'active' AND type = 'tool'
19061
- ${excludeStateTools}
19062
19722
  ${valueFloor}
19063
19723
  ${whereProtected}
19064
- ORDER BY tag_number ASC, id ASC
19065
- LIMIT ?`).all(...params);
19724
+ ORDER BY tag_number ASC, id ASC`).all(...params);
19066
19725
  return rows.filter((row) => typeof row.tag_number === "number").map((row) => ({
19067
19726
  tagNumber: row.tag_number,
19068
19727
  toolName: typeof row.tool_name === "string" ? row.tool_name : null
19069
- }));
19728
+ })).filter((tag) => !isReclaimHintExcludedTool(tag.toolName)).sort((left, right) => resolveToolTier(right.toolName) - resolveToolTier(left.toolName) || left.tagNumber - right.tagNumber).slice(0, boundedLimit);
19070
19729
  }
19071
19730
  var getActiveToolTagsForAgeReclaimStatements = new WeakMap;
19072
19731
  function getActiveToolTagsForAgeReclaim(db, sessionId) {
@@ -19079,7 +19738,7 @@ function getActiveToolTagsForAgeReclaim(db, sessionId) {
19079
19738
  getActiveToolTagsForAgeReclaimStatements.set(db, stmt);
19080
19739
  }
19081
19740
  const rows = stmt.all(sessionId);
19082
- return rows.filter((row) => typeof row.tag_number === "number").map((row) => {
19741
+ const tags = rows.filter((row) => typeof row.tag_number === "number").map((row) => {
19083
19742
  const outputTokens = typeof row.token_count === "number" ? row.token_count : null;
19084
19743
  const inputTokens = typeof row.input_token_count === "number" ? row.input_token_count : null;
19085
19744
  return {
@@ -19088,6 +19747,8 @@ function getActiveToolTagsForAgeReclaim(db, sessionId) {
19088
19747
  reclaimableTokens: outputTokens === null && inputTokens === null ? null : (outputTokens ?? 0) + (inputTokens ?? 0)
19089
19748
  };
19090
19749
  });
19750
+ const protectedCtxReduceTags = newestCtxReduceTagNumbers(tags);
19751
+ return tags.filter((tag) => !protectedCtxReduceTags.has(tag.tagNumber));
19091
19752
  }
19092
19753
  function getTriggerTagTokenUpperBound(db, sessionId, floor = 0) {
19093
19754
  const sql = floor > 0 ? `SELECT
@@ -19532,6 +20193,7 @@ function getTagsBySession(db, sessionId) {
19532
20193
  return rows.map(toTagEntry);
19533
20194
  }
19534
20195
  var getActiveTagsBySessionStatements = new WeakMap;
20196
+ var getNullOwnerToolTagsBySessionStatements = new WeakMap;
19535
20197
  var getDroppedTagsBySessionStatements = new WeakMap;
19536
20198
  var getMaxDroppedTagNumberStatements = new WeakMap;
19537
20199
  function getActiveTagsBySessionStatement(db) {
@@ -19673,116 +20335,9 @@ var ERROR_CLASSES = new Set([
19673
20335
  "permission_denied",
19674
20336
  "unknown"
19675
20337
  ]);
19676
- // ../plugin/src/hooks/magic-context/todo-view.ts
19677
- import { createHash as createHash7 } from "node:crypto";
19678
- var TODO_STATUS_PENDING = "pending";
19679
- var TODO_STATUS_IN_PROGRESS = "in_progress";
19680
- var TODO_STATUS_COMPLETED = "completed";
19681
- var TODO_STATUS_CANCELLED = "cancelled";
19682
- var TODO_PRIORITY_HIGH = "high";
19683
- var TODO_PRIORITY_MEDIUM = "medium";
19684
- var TODO_PRIORITY_LOW = "low";
19685
- var TODO_STATUSES = [
19686
- TODO_STATUS_PENDING,
19687
- TODO_STATUS_IN_PROGRESS,
19688
- TODO_STATUS_COMPLETED,
19689
- TODO_STATUS_CANCELLED
19690
- ];
19691
- var TODO_PRIORITIES = [
19692
- TODO_PRIORITY_HIGH,
19693
- TODO_PRIORITY_MEDIUM,
19694
- TODO_PRIORITY_LOW
19695
- ];
19696
- var TODO_STATUS_SET = new Set(TODO_STATUSES);
19697
- var TODO_PRIORITY_SET = new Set(TODO_PRIORITIES);
19698
- var TERMINAL_STATUSES = new Set([
19699
- TODO_STATUS_COMPLETED,
19700
- TODO_STATUS_CANCELLED
19701
- ]);
19702
- var TITLE_DONE_STATUSES = new Set([TODO_STATUS_COMPLETED]);
19703
- var SYNTHETIC_CALL_ID_PREFIX = "mc_synthetic_todo_";
19704
- function normalizeTodoStateJson(todos) {
19705
- if (!Array.isArray(todos))
19706
- return null;
19707
- const normalized = [];
19708
- for (const todo of todos) {
19709
- if (!isTodoItem(todo))
19710
- return null;
19711
- normalized.push({
19712
- content: todo.content,
19713
- status: todo.status,
19714
- priority: todo.priority ?? TODO_PRIORITY_MEDIUM
19715
- });
19716
- }
19717
- return JSON.stringify(normalized);
19718
- }
19719
- function buildSyntheticTodoPart(stateJson) {
19720
- const todos = parseTodoState(stateJson);
19721
- if (todos === null || todos.length === 0)
19722
- return null;
19723
- if (todos.every((t) => TERMINAL_STATUSES.has(t.status)))
19724
- return null;
19725
- const callID = computeSyntheticCallId(stateJson);
19726
- const activeCount = todos.filter((t) => !TITLE_DONE_STATUSES.has(t.status)).length;
19727
- const output = JSON.stringify(todos, null, 2);
19728
- const ts = 0;
19729
- return {
19730
- type: "tool",
19731
- callID,
19732
- tool: "todowrite",
19733
- state: {
19734
- status: "completed",
19735
- input: { todos },
19736
- output,
19737
- title: `${activeCount} todos`,
19738
- metadata: { todos, truncated: false },
19739
- time: { start: ts, end: ts }
19740
- },
19741
- syntheticTodoMarker: true
19742
- };
19743
- }
19744
- function computeSyntheticCallId(stateJson) {
19745
- const hash = createHash7("sha256").update(stateJson).digest("hex").slice(0, 16);
19746
- return `${SYNTHETIC_CALL_ID_PREFIX}${hash}`;
19747
- }
19748
- function parseTodoState(stateJson) {
19749
- if (stateJson.length === 0)
19750
- return null;
19751
- try {
19752
- const parsed = JSON.parse(stateJson);
19753
- if (!Array.isArray(parsed))
19754
- return null;
19755
- const result = [];
19756
- for (const item of parsed) {
19757
- if (!isTodoItem(item))
19758
- return null;
19759
- result.push({
19760
- content: item.content,
19761
- status: item.status,
19762
- priority: item.priority ?? TODO_PRIORITY_MEDIUM
19763
- });
19764
- }
19765
- return result;
19766
- } catch {
19767
- return null;
19768
- }
19769
- }
19770
- function isTodoStatus(value) {
19771
- return typeof value === "string" && TODO_STATUS_SET.has(value);
19772
- }
19773
- function isTodoPriority(value) {
19774
- return typeof value === "string" && TODO_PRIORITY_SET.has(value);
19775
- }
19776
- function isTodoItem(value) {
19777
- if (value === null || typeof value !== "object")
19778
- return false;
19779
- const todo = value;
19780
- return typeof todo.content === "string" && isTodoStatus(todo.status) && (todo.priority === undefined || isTodoPriority(todo.priority));
19781
- }
19782
-
19783
20338
  // ../plugin/src/shared/prompt-surface-runtime.ts
19784
20339
  import { existsSync as existsSync8, readFileSync as readFileSync7, statSync as statSync5 } from "node:fs";
19785
- import { dirname as dirname4, isAbsolute as isAbsolute2, resolve as resolve2 } from "node:path";
20340
+ import { dirname as dirname4, isAbsolute as isAbsolute2, resolve as resolve3 } from "node:path";
19786
20341
 
19787
20342
  // ../plugin/src/tools/light-descriptions.ts
19788
20343
  var CTX_REDUCE_LIGHT_DESCRIPTION = `For ctx_reduce users, mark spent §N§ outputs discardable; release is QUEUED, not immediate, so content stays visible until space is needed. Newest tags stay protected until they age out. Released content becomes a placeholder; recover it only by rerunning the source or recovery tool, so mark only genuinely finished material. Mark analyzed, redundant, persisted, or merely confirmatory outputs; keep user messages, unresolved errors, unextracted evidence, and exact wording. NEVER blanket-mark a large range: review every tag first.`;
@@ -19989,7 +20544,7 @@ function promptSurfaceHashMaterial(systemContent, preset = "full") {
19989
20544
  var PROMPT_SURFACE_TOOL_ID_SET = new Set(ACTIVE_TOOL_IDS);
19990
20545
  function resolveUserConfigDirectory(options) {
19991
20546
  if (options.userConfigDirectory)
19992
- return resolve2(options.userConfigDirectory);
20547
+ return resolve3(options.userConfigDirectory);
19993
20548
  const sharedBase = cortexKitUserConfigBasePath();
19994
20549
  const shared = detectConfigFile(sharedBase);
19995
20550
  if (shared.format !== "none")
@@ -20016,7 +20571,7 @@ function createPromptSurfaceRuntime(options) {
20016
20571
  const readGuidanceOverride = (configuredPath) => {
20017
20572
  if (!configuredPath)
20018
20573
  return;
20019
- const path3 = isAbsolute2(configuredPath) ? configuredPath : resolve2(userConfigDirectory, configuredPath);
20574
+ const path3 = isAbsolute2(configuredPath) ? configuredPath : resolve3(userConfigDirectory, configuredPath);
20020
20575
  let content;
20021
20576
  try {
20022
20577
  if (!statSync5(path3).isFile()) {
@@ -35504,7 +36059,7 @@ var MagicContextConfigSchema = exports_external.object({
35504
36059
  output_reserve: exports_external.union([
35505
36060
  exports_external.number().min(0),
35506
36061
  exports_external.object({ default: exports_external.number().min(0) }).catchall(exports_external.number().min(0))
35507
- ]).optional().describe('User-only output-token reservation override. Number or per-model object ({ default: 16384, "provider/model": 8192 }); 0 disables reservation. When unset, Magic Context reserves the catalog output limit (capped at 25% of context) for shared-window providers and keeps proven separate-quota Google/Gemini windows unchanged.'),
36062
+ ]).optional().describe('User-only output-token reservation override. Number or per-model object ({ default: 16384, "provider/model": 8192 }); 0 disables reservation. Takes precedence over every derived source: an explicit value here always wins against catalog output limits, provider window-geometry facts, and the 25%-of-context fallback (usable window = context window minus this reserve). When unset, Magic Context reserves the catalog output limit (capped at 25% of context) for shared-window providers and keeps proven separate-quota Google/Gemini windows unchanged.'),
35508
36063
  models: exports_external.object({
35509
36064
  window_overlay_path: exports_external.string().trim().min(1).optional()
35510
36065
  }).optional().describe("User-only Fusiform window-overlay settings. The path defaults to <dataDir>/fusiform/window-overlay.json."),
@@ -35559,7 +36114,7 @@ var MagicContextConfigSchema = exports_external.object({
35559
36114
  overlay: exports_external.boolean().default(true).describe("Pi only: show the persistent todo overlay above the editor while tasks are active.")
35560
36115
  }).default({ enabled: true, overlay: true }).describe("Pi-only todowrite tool and overlay controls. Pi registers tools and widgets at extension boot, so changing this after /cd requires /reload or restart."),
35561
36116
  pi: PiConfigSchema.describe("Pi-only child-process extension controls. This setting is user-level only; project configuration cannot choose which extensions a user's subagent children load."),
35562
- smart_drops: exports_external.boolean().default(false).describe("Content-aware reclaim of provably-superseded tool output, layered on the existing execute-pass auto-drop. When on: superseded todowrite (keep newest 1), spent ctx_reduce (keep newest 5), and zero-value meta (bash_status, bash_kill, ctx_note read/dismiss) outputs are dropped; older edits to a file are compressed to a filePath-preserving marker while the newest edit per file stays full. Only acts on passes already busting the cache, so it never originates a cache bust. Honors the protected-tag reserve. Experimental: opt-in, default off until cache stability is proven; when off the wire is byte-identical to the positional-only reclaim. Requires a restart."),
36117
+ smart_drops: exports_external.boolean().default(false).describe("Content-aware reclaim of provably-superseded tool output, layered on the existing execute-pass auto-drop. When on: superseded todowrite (keep newest 1), spent ctx_reduce (keep newest 3), and zero-value meta (bash_status, bash_kill, ctx_note read/dismiss) outputs are dropped; older edits to a file are compressed to a filePath-preserving marker while the newest edit per file stays full. Only acts on passes already busting the cache, so it never originates a cache bust. Honors the protected-tag reserve. Experimental: opt-in, default off until cache stability is proven; when off the wire is byte-identical to the positional-only reclaim. Requires a restart."),
35563
36118
  caveman_text_compression: exports_external.object({
35564
36119
  enabled: exports_external.boolean().default(false).describe("Apply deterministic caveman-style text compression to old conversation text. Active for primary sessions when enabled; never for subagents. Compresses user/assistant text in oldest-first tiers: ultra (oldest 20%), full, lite, untouched (newest 40%)."),
35565
36120
  min_chars: exports_external.number().min(100).max(1e4).default(500).describe("Text parts shorter than this (characters) stay untouched. Min 100, max 10000. Default: 500.")
@@ -35950,16 +36505,16 @@ function dropInheritedEmbeddingKeyOnRedirect(projectRaw, mergedRaw, userRaw) {
35950
36505
  // ../plugin/src/config/variable.ts
35951
36506
  import { existsSync as existsSync9, readFileSync as readFileSync8 } from "node:fs";
35952
36507
  import { homedir as homedir5 } from "node:os";
35953
- import { dirname as dirname5, isAbsolute as isAbsolute3, resolve as resolve3 } from "node:path";
36508
+ import { dirname as dirname5, isAbsolute as isAbsolute3, resolve as resolve4 } from "node:path";
35954
36509
  var ENV_PATTERN = /\{env:([^}]+)\}/g;
35955
36510
  var FILE_PATTERN = /\{file:([^}]+)\}/g;
35956
36511
  function sensitiveFilePathReason(resolvedPath) {
35957
36512
  const home = homedir5();
35958
36513
  const sensitiveDirs = [
35959
- { dir: resolve3(home, ".ssh"), label: "SSH keys" },
35960
- { dir: resolve3(home, ".aws"), label: "AWS credentials" },
35961
- { dir: resolve3(home, ".gnupg"), label: "GnuPG keyring" },
35962
- { dir: resolve3(home, ".config", "gh"), label: "GitHub CLI auth" }
36514
+ { dir: resolve4(home, ".ssh"), label: "SSH keys" },
36515
+ { dir: resolve4(home, ".aws"), label: "AWS credentials" },
36516
+ { dir: resolve4(home, ".gnupg"), label: "GnuPG keyring" },
36517
+ { dir: resolve4(home, ".config", "gh"), label: "GitHub CLI auth" }
35963
36518
  ];
35964
36519
  for (const { dir, label } of sensitiveDirs) {
35965
36520
  if (resolvedPath === dir || resolvedPath.startsWith(`${dir}/`)) {
@@ -36017,9 +36572,9 @@ function substituteConfigVariables(input) {
36017
36572
  }
36018
36573
  let filePath = rawPath.trim();
36019
36574
  if (filePath.startsWith("~/")) {
36020
- filePath = resolve3(homedir5(), filePath.slice(2));
36575
+ filePath = resolve4(homedir5(), filePath.slice(2));
36021
36576
  } else if (!isAbsolute3(filePath)) {
36022
- filePath = resolve3(configDir, filePath);
36577
+ filePath = resolve4(configDir, filePath);
36023
36578
  }
36024
36579
  const sensitiveReason = sensitiveFilePathReason(filePath);
36025
36580
  if (sensitiveReason) {
@@ -36095,28 +36650,6 @@ function isRecord2(value) {
36095
36650
  function isFinitePositive(value) {
36096
36651
  return typeof value === "number" && Number.isFinite(value) && value > 0;
36097
36652
  }
36098
- function modelKeyLookupOrder2(providerID, modelID) {
36099
- const candidates = [...modelRefLookupOrder(`${providerID}/${modelID}`), modelID];
36100
- const colon = modelID.lastIndexOf(":");
36101
- if (colon > 0) {
36102
- const bareModel = modelID.slice(0, colon);
36103
- candidates.push(...modelRefLookupOrder(`${providerID}/${bareModel}`), bareModel);
36104
- }
36105
- return [...new Set(candidates)];
36106
- }
36107
- function configuredOutputReserve(config2, providerID, modelID) {
36108
- if (typeof config2 === "number") {
36109
- return Number.isFinite(config2) && config2 >= 0 ? config2 : undefined;
36110
- }
36111
- if (!config2)
36112
- return;
36113
- for (const candidate of modelKeyLookupOrder2(providerID, modelID)) {
36114
- const value = config2[candidate];
36115
- if (typeof value === "number" && Number.isFinite(value) && value >= 0)
36116
- return value;
36117
- }
36118
- return Number.isFinite(config2.default) && config2.default >= 0 ? config2.default : undefined;
36119
- }
36120
36653
  function scalarizeFact(value) {
36121
36654
  if (value.kind === "stated")
36122
36655
  return isFinitePositive(value.value) ? value.value : undefined;
@@ -36353,21 +36886,34 @@ function deriveWindowGeometry(providerID, modelID, catalogLimit, options = {}) {
36353
36886
  const geometryFact = overlayGeometry(options.overlay);
36354
36887
  const geometry = geometryFact?.kind === "stated" ? geometryFact.value : geometryFact?.kind === "unknown" ? "shared_upfront" : PROVIDER_GEOMETRY[providerID] ?? "shared_upfront";
36355
36888
  const geometryOverride = geometryFact?.kind === "stated" ? geometryFact.value : undefined;
36889
+ const preCarvedInput = isFinitePositive(input) && (!isFinitePositive(softContext) || input < softContext);
36890
+ const outputReserveOverride = typeof options.outputReserveOverride === "number" && Number.isFinite(options.outputReserveOverride) && options.outputReserveOverride >= 0 ? options.outputReserveOverride : undefined;
36891
+ let derivationWindow = softContext ?? input;
36356
36892
  let usableSoft;
36357
36893
  let softReserve = 0;
36358
36894
  let reserveSource = "none";
36359
- if (isFinitePositive(input) && (!isFinitePositive(softContext) || input < softContext)) {
36895
+ if (outputReserveOverride !== undefined) {
36896
+ const reserveWindow = preCarvedInput ? input : softContext ?? input;
36897
+ if (!isFinitePositive(reserveWindow))
36898
+ return;
36899
+ derivationWindow = reserveWindow;
36900
+ softReserve = outputReserveOverride;
36901
+ reserveSource = "output_config";
36902
+ const floor = Math.max(MIN_PLAUSIBLE_CONTEXT_LIMIT, reserveWindow * 0.5);
36903
+ const flooredReserve = Math.min(softReserve, Math.max(0, reserveWindow - floor));
36904
+ if (flooredReserve < softReserve) {
36905
+ logGeometryClampOnce(`soft-floor|${providerID}/${modelID}|${softReserve}|${flooredReserve}`, `output reserve clamped by the half-window floor for ${providerID}/${modelID}: reserve ${softReserve} → ${flooredReserve}`, options.log);
36906
+ }
36907
+ softReserve = flooredReserve;
36908
+ usableSoft = Math.floor(reserveWindow - softReserve);
36909
+ } else if (preCarvedInput) {
36360
36910
  usableSoft = input;
36361
36911
  if (isFinitePositive(softContext)) {
36362
36912
  softReserve = Math.max(0, softContext - input);
36363
36913
  reserveSource = "output_catalog";
36364
36914
  }
36365
36915
  } else if (isFinitePositive(softContext)) {
36366
- const configuredReserve = configuredOutputReserve(options.reserveConfig, providerID, modelID);
36367
- if (configuredReserve !== undefined) {
36368
- softReserve = configuredReserve;
36369
- reserveSource = "output_config";
36370
- } else if (geometry === "separate" && (options.overlay === undefined || options.harness === "pi" || geometryOverride !== undefined)) {
36916
+ if (geometry === "separate" && (options.overlay === undefined || options.harness === "pi" || geometryOverride !== undefined)) {
36371
36917
  softReserve = 0;
36372
36918
  reserveSource = "none";
36373
36919
  } else {
@@ -36407,13 +36953,14 @@ function deriveWindowGeometry(providerID, modelID, catalogLimit, options = {}) {
36407
36953
  logGeometryClampOnce(`${providerID}/${modelID}|${usableSoft}|${usableHard}`, `usable hard limit clamped for ${providerID}/${modelID}: ${usableHard} → ${usableSoft} (overlay/provider inversion)`, options.log);
36408
36954
  usableHard = usableSoft;
36409
36955
  }
36956
+ const resolvedWindow = derivationWindow ?? usableSoft;
36410
36957
  return {
36411
36958
  usableSoft,
36412
36959
  usableHard,
36413
36960
  geometry,
36414
36961
  derivation: {
36415
- window: Math.floor(softContext ?? usableSoft),
36416
- reserve: Math.floor(Math.max(0, (softContext ?? usableSoft) - usableSoft)),
36962
+ window: Math.floor(resolvedWindow),
36963
+ reserve: Math.floor(Math.max(0, resolvedWindow - usableSoft)),
36417
36964
  reserveSource,
36418
36965
  geometry
36419
36966
  }
@@ -36483,7 +37030,7 @@ function loadPersistedApiCacheOnce() {
36483
37030
  function isFinitePositive2(value) {
36484
37031
  return typeof value === "number" && Number.isFinite(value) && value > 0;
36485
37032
  }
36486
- function modelKeyLookupOrder3(providerID, modelID) {
37033
+ function modelKeyLookupOrder2(providerID, modelID) {
36487
37034
  const candidates = [...modelRefLookupOrder(`${providerID}/${modelID}`), modelID];
36488
37035
  const colon = modelID.lastIndexOf(":");
36489
37036
  if (colon > 0) {
@@ -36492,12 +37039,12 @@ function modelKeyLookupOrder3(providerID, modelID) {
36492
37039
  }
36493
37040
  return [...new Set(candidates)];
36494
37041
  }
36495
- function configuredOutputReserve2(config2, providerID, modelID) {
37042
+ function resolveOutputReserve(providerID, modelID, config2 = outputReserveConfig) {
36496
37043
  if (typeof config2 === "number")
36497
37044
  return Number.isFinite(config2) && config2 >= 0 ? config2 : undefined;
36498
37045
  if (!config2)
36499
37046
  return;
36500
- for (const candidate of modelKeyLookupOrder3(providerID, modelID)) {
37047
+ for (const candidate of modelKeyLookupOrder2(providerID, modelID)) {
36501
37048
  const value = config2[candidate];
36502
37049
  if (typeof value === "number" && Number.isFinite(value) && value >= 0)
36503
37050
  return value;
@@ -36522,7 +37069,7 @@ function resolveLimit(limit, providerID, modelID, reserveConfig = outputReserveC
36522
37069
  return input;
36523
37070
  if (context === undefined)
36524
37071
  return;
36525
- const configuredReserve = configuredOutputReserve2(reserveConfig, providerID, modelID);
37072
+ const configuredReserve = resolveOutputReserve(providerID, modelID, reserveConfig);
36526
37073
  let reserve;
36527
37074
  if (configuredReserve !== undefined) {
36528
37075
  reserve = configuredReserve;
@@ -36557,7 +37104,7 @@ function getSdkWindowGeometry(providerID, modelID, detectedContextLimit, options
36557
37104
  output: metadata.outputLimit
36558
37105
  }, {
36559
37106
  overlay: resolveWindowOverlayFacts(providerID, modelID, getWindowOverlay()),
36560
- reserveConfig: outputReserveConfig,
37107
+ outputReserveOverride: resolveOutputReserve(providerID, modelID),
36561
37108
  harness: options?.harness ?? "opencode",
36562
37109
  contextCap: promptOnlyDetected === undefined && isFinitePositive2(detectedContextLimit) ? detectedContextLimit : undefined
36563
37110
  });
@@ -38056,7 +38603,7 @@ class SubcSocket {
38056
38603
  return this.sock.localPort ?? null;
38057
38604
  }
38058
38605
  static connect(host, port, deadlineMs) {
38059
- return new Promise((resolve4, reject) => {
38606
+ return new Promise((resolve5, reject) => {
38060
38607
  const sock = net.connect({ host, port });
38061
38608
  sock.setNoDelay(true);
38062
38609
  const timer = setTimeout(() => {
@@ -38065,7 +38612,7 @@ class SubcSocket {
38065
38612
  }, Math.max(0, deadlineMs - Date.now()));
38066
38613
  sock.once("connect", () => {
38067
38614
  clearTimeout(timer);
38068
- resolve4(new SubcSocket(sock));
38615
+ resolve5(new SubcSocket(sock));
38069
38616
  });
38070
38617
  sock.once("error", (err) => {
38071
38618
  clearTimeout(timer);
@@ -38097,7 +38644,7 @@ class SubcSocket {
38097
38644
  }
38098
38645
  if (n === 0)
38099
38646
  return Promise.resolve(new Uint8Array(0));
38100
- return new Promise((resolve4, reject) => {
38647
+ return new Promise((resolve5, reject) => {
38101
38648
  let timer = null;
38102
38649
  if (Number.isFinite(deadlineMs)) {
38103
38650
  const remaining = deadlineMs - Date.now();
@@ -38110,7 +38657,7 @@ class SubcSocket {
38110
38657
  reject(new SocketTimeoutError(`timed out waiting for ${n} bytes`));
38111
38658
  }, remaining);
38112
38659
  }
38113
- this.waiter = { need: n, resolve: resolve4, reject, timer };
38660
+ this.waiter = { need: n, resolve: resolve5, reject, timer };
38114
38661
  this.tryServe();
38115
38662
  });
38116
38663
  }
@@ -38134,7 +38681,7 @@ class SubcSocket {
38134
38681
  let queued = false;
38135
38682
  let settled = false;
38136
38683
  let timer = null;
38137
- const completed = new Promise((resolve4, reject) => {
38684
+ const completed = new Promise((resolve5, reject) => {
38138
38685
  const settle = (run) => {
38139
38686
  if (settled)
38140
38687
  return;
@@ -38158,7 +38705,7 @@ class SubcSocket {
38158
38705
  if (err) {
38159
38706
  reject(new SocketWriteQueuedError("subc socket reported a write error after bytes were handed to the socket", err instanceof Error ? err : new Error(String(err))));
38160
38707
  } else {
38161
- resolve4();
38708
+ resolve5();
38162
38709
  }
38163
38710
  });
38164
38711
  });
@@ -38374,14 +38921,14 @@ class SubcClient {
38374
38921
  const admission = opts.admissionClass ?? AdmissionClass.Normal;
38375
38922
  const corr = this.allocateCorr();
38376
38923
  const key = pendingKey(handle, corr);
38377
- const closed = new Promise((resolve4, reject) => {
38924
+ const closed = new Promise((resolve5, reject) => {
38378
38925
  if (this.closedErr) {
38379
38926
  reject(this.closedErr);
38380
38927
  return;
38381
38928
  }
38382
38929
  this.pending.set(key, {
38383
38930
  handle,
38384
- resolve: () => resolve4(),
38931
+ resolve: () => resolve5(),
38385
38932
  reject,
38386
38933
  onProgress: onEvent,
38387
38934
  timer: null,
@@ -38466,11 +39013,11 @@ class SubcClient {
38466
39013
  const waiters = [];
38467
39014
  for (const pending of this.pending.values()) {
38468
39015
  if (pending.handle === handle && !pending.subscription) {
38469
- waiters.push(new Promise((resolve4) => {
39016
+ waiters.push(new Promise((resolve5) => {
38470
39017
  const previous = pending.onSettle;
38471
39018
  pending.onSettle = () => {
38472
39019
  previous?.();
38473
- resolve4();
39020
+ resolve5();
38474
39021
  };
38475
39022
  }));
38476
39023
  }
@@ -38526,11 +39073,11 @@ class SubcClient {
38526
39073
  const channel = handle?.channel ?? 0;
38527
39074
  const epoch = handle?.epoch ?? 0;
38528
39075
  const frame = buildFrame(FrameType.Request, buildFlags(false, priority, false, admission), channel, epoch, corr, body);
38529
- return new Promise((resolve4, reject) => {
39076
+ return new Promise((resolve5, reject) => {
38530
39077
  const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
38531
39078
  const pending = {
38532
39079
  handle,
38533
- resolve: resolve4,
39080
+ resolve: resolve5,
38534
39081
  reject,
38535
39082
  onProgress,
38536
39083
  timer: null,
@@ -38604,11 +39151,11 @@ class SubcClient {
38604
39151
  }
38605
39152
  return this.outcomeUnknownCallError("connection dropped before the managed call returned a response", error51);
38606
39153
  };
38607
- return new Promise((resolve4, reject) => {
39154
+ return new Promise((resolve5, reject) => {
38608
39155
  const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
38609
39156
  const pending = {
38610
39157
  handle,
38611
- resolve: resolve4,
39158
+ resolve: resolve5,
38612
39159
  reject,
38613
39160
  onProgress,
38614
39161
  timer: null,
@@ -38996,7 +39543,7 @@ function normalizeConnectOptions(opts) {
38996
39543
  identity: opts.identity,
38997
39544
  targetKind: opts.targetKind ?? DEFAULT_MANAGED_TARGET_KIND,
38998
39545
  reconnectBackoff: opts.reconnectBackoff ?? DEFAULT_RECONNECT_BACKOFF,
38999
- sleep: opts.sleep ?? ((ms) => new Promise((resolve4) => setTimeout(resolve4, ms))),
39546
+ sleep: opts.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms))),
39000
39547
  timeoutArbitrationGraceMs: opts.timeoutArbitrationGraceMs ?? TIMEOUT_ARBITRATION_GRACE_MS
39001
39548
  };
39002
39549
  }
@@ -39053,8 +39600,8 @@ class AsyncPermitPool {
39053
39600
  this.available -= 1;
39054
39601
  return this.releaseOnce();
39055
39602
  }
39056
- await new Promise((resolve4) => {
39057
- this.waiters.push(resolve4);
39603
+ await new Promise((resolve5) => {
39604
+ this.waiters.push(resolve5);
39058
39605
  });
39059
39606
  return this.releaseOnce();
39060
39607
  }
@@ -39110,8 +39657,8 @@ class SubcProvider {
39110
39657
  this.currentConn = currentConn;
39111
39658
  this.opts = opts;
39112
39659
  this.storage = storage;
39113
- this.closed = new Promise((resolve4) => {
39114
- this.resolveClosed = resolve4;
39660
+ this.closed = new Promise((resolve5) => {
39661
+ this.resolveClosed = resolve5;
39115
39662
  });
39116
39663
  this.readLoop(sock, this.generation);
39117
39664
  this.enqueueConnectionState({ state: "connected", epoch: this.connectionEpoch });
@@ -39131,13 +39678,13 @@ class SubcProvider {
39131
39678
  const key = routeKey(handle, corr);
39132
39679
  const timeoutMs = opts.timeoutMs ?? WRITE_TIMEOUT_MS;
39133
39680
  const frame = buildFrame(FrameType.Request, buildFlags(false, opts.priority ?? Priority.Interactive, false, opts.admissionClass ?? AdmissionClass.Normal), handle.channel, handle.epoch, corr, body);
39134
- return await new Promise((resolve4, reject) => {
39681
+ return await new Promise((resolve5, reject) => {
39135
39682
  const timer = setTimeout(() => {
39136
39683
  if (this.pending.delete(key))
39137
39684
  reject(new SubcProviderError("reverse request timed out", "request_timeout"));
39138
39685
  }, timeoutMs);
39139
39686
  this.pending.set(key, {
39140
- resolve: (response) => resolve4(response.body),
39687
+ resolve: (response) => resolve5(response.body),
39141
39688
  reject,
39142
39689
  timer
39143
39690
  });
@@ -39609,7 +40156,7 @@ function normalizeProviderConnectOptions(opts) {
39609
40156
  onBound: opts.onBound,
39610
40157
  onRouteGone: opts.onRouteGone,
39611
40158
  reconnectBackoff: opts.reconnectBackoff ?? DEFAULT_RECONNECT_BACKOFF,
39612
- sleep: opts.sleep ?? ((ms) => new Promise((resolve4) => setTimeout(resolve4, ms))),
40159
+ sleep: opts.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms))),
39613
40160
  restoredDebounceMs: opts.restoredDebounceMs ?? DEFAULT_RESTORED_DEBOUNCE_MS,
39614
40161
  onConnectionState: opts.onConnectionState,
39615
40162
  launchNonce: opts.launchNonce
@@ -39654,7 +40201,7 @@ function errorCode2(err) {
39654
40201
  return;
39655
40202
  }
39656
40203
  async function pauseBeforeStateRetry() {
39657
- await new Promise((resolve4) => setTimeout(resolve4, 0));
40204
+ await new Promise((resolve5) => setTimeout(resolve5, 0));
39658
40205
  }
39659
40206
  function controlFlags() {
39660
40207
  return buildFlags(false, Priority.Passive, false);
@@ -39892,7 +40439,7 @@ function classifyError(value) {
39892
40439
  });
39893
40440
  }
39894
40441
  function wait(ms) {
39895
- return new Promise((resolve4) => setTimeout(resolve4, ms));
40442
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
39896
40443
  }
39897
40444
  function sha256(value) {
39898
40445
  return createHash9("sha256").update(value).digest("hex");
@@ -40411,7 +40958,7 @@ async function acquireModelLoadLock(lockPath) {
40411
40958
  if (Date.now() - waitStart > MAX_LOCK_WAIT_MS) {
40412
40959
  throw new Error(`[magic-context] embedding-load lock wait exceeded ${MAX_LOCK_WAIT_MS}ms; another process is still loading the model. Skipping this init attempt to avoid an unsynchronized native load.`);
40413
40960
  }
40414
- await new Promise((resolve4) => setTimeout(resolve4, LOCK_POLL_MS));
40961
+ await new Promise((resolve5) => setTimeout(resolve5, LOCK_POLL_MS));
40415
40962
  }
40416
40963
  }
40417
40964
  }
@@ -40616,7 +41163,7 @@ class LocalEmbeddingProvider {
40616
41163
  }
40617
41164
  const delayMs = 300 * attempt + Math.floor(Math.random() * 200);
40618
41165
  log(`[magic-context] embedding model load attempt ${attempt}/${MAX_ATTEMPTS} failed transiently, retrying in ${delayMs}ms`);
40619
- await new Promise((resolve4) => setTimeout(resolve4, delayMs));
41166
+ await new Promise((resolve5) => setTimeout(resolve5, delayMs));
40620
41167
  }
40621
41168
  }
40622
41169
  if (this.pipeline) {
@@ -40649,8 +41196,8 @@ class LocalEmbeddingProvider {
40649
41196
  if (this.inFlight === 0) {
40650
41197
  return Promise.resolve();
40651
41198
  }
40652
- return new Promise((resolve4) => {
40653
- this.inFlightWaiters.push(resolve4);
41199
+ return new Promise((resolve5) => {
41200
+ this.inFlightWaiters.push(resolve5);
40654
41201
  });
40655
41202
  }
40656
41203
  finishInFlight() {
@@ -42363,7 +42910,7 @@ async function runShadowWorker() {
42363
42910
  }
42364
42911
  processed += item.ids.length;
42365
42912
  processedBytes += itemBytes;
42366
- await new Promise((resolve4) => setTimeout(resolve4, 0));
42913
+ await new Promise((resolve5) => setTimeout(resolve5, 0));
42367
42914
  }
42368
42915
  }
42369
42916
  function registerProjectInObservationMode(db, projectIdentity, sourceDirectory, failedConfig, failureSummary) {
@@ -42724,7 +43271,7 @@ async function embedCandidateChunkBatch(db, projectIdentity, modelId, candidates
42724
43271
  if (Date.now() - attemptStart >= EMBED_SLOW_FAILURE_NO_RETRY_MS)
42725
43272
  break;
42726
43273
  if (attempt < EMBED_SLICE_RETRY_ATTEMPTS - 1) {
42727
- await new Promise((resolve4) => setTimeout(resolve4, EMBED_SLICE_RETRY_BASE_MS * 2 ** attempt));
43274
+ await new Promise((resolve5) => setTimeout(resolve5, EMBED_SLICE_RETRY_BASE_MS * 2 ** attempt));
42728
43275
  }
42729
43276
  }
42730
43277
  embedded += persistedIds.size;
@@ -42809,7 +43356,7 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
42809
43356
  }
42810
43357
  embedded += n;
42811
43358
  options?.onProgress?.({ embedded: Math.min(embedded, total), total });
42812
- await new Promise((resolve4) => setTimeout(resolve4, 0));
43359
+ await new Promise((resolve5) => setTimeout(resolve5, 0));
42813
43360
  }
42814
43361
  } finally {
42815
43362
  clearInterval(renewal);
@@ -49818,7 +50365,7 @@ import { isAbsolute as isAbsolute5 } from "node:path";
49818
50365
  // ../retina-local-fs/src/path-fence.ts
49819
50366
  import { lstat, readlink, realpath } from "node:fs/promises";
49820
50367
  import { homedir as homedir6 } from "node:os";
49821
- import { basename as basename3, dirname as dirname7, isAbsolute as isAbsolute4, join as join9, relative, resolve as resolve4, sep } from "node:path";
50368
+ import { basename as basename3, dirname as dirname7, isAbsolute as isAbsolute4, join as join9, relative, resolve as resolve5, sep } from "node:path";
49822
50369
 
49823
50370
  // ../retina-local-fs/src/errors.ts
49824
50371
  class ProviderError extends Error {
@@ -49834,7 +50381,7 @@ class ProviderError extends Error {
49834
50381
  async function resolveAndFenceProviderPath(configuredPath, options) {
49835
50382
  const { home, dataDirectory } = await resolveFenceRoots(options);
49836
50383
  const expanded = configuredPath.startsWith("~/") ? join9(home, configuredPath.slice(2)) : configuredPath === "~" ? home : configuredPath;
49837
- const absolute = isAbsolute4(expanded) ? resolve4(expanded) : resolve4(options.cwd ?? process.cwd(), expanded);
50384
+ const absolute = isAbsolute4(expanded) ? resolve5(expanded) : resolve5(options.cwd ?? process.cwd(), expanded);
49838
50385
  const canonical = await canonicalPath(absolute, options.allowMissing);
49839
50386
  if (isFencedPath(canonical, home, dataDirectory)) {
49840
50387
  throw new ProviderError("fenced_path", `Refusing fenced path: ${canonical}`);
@@ -49842,14 +50389,14 @@ async function resolveAndFenceProviderPath(configuredPath, options) {
49842
50389
  return canonical;
49843
50390
  }
49844
50391
  async function resolveFenceRoots(options) {
49845
- const configuredHomePath = resolve4(options.homeDirectory ?? process.env.HOME ?? homedir6());
50392
+ const configuredHomePath = resolve5(options.homeDirectory ?? process.env.HOME ?? homedir6());
49846
50393
  let home;
49847
50394
  try {
49848
50395
  home = await realpath(configuredHomePath);
49849
50396
  } catch (error51) {
49850
50397
  throw fsError(configuredHomePath, error51);
49851
50398
  }
49852
- const configuredDataDirectory = resolve4(options.dataDirectory ?? process.env.XDG_DATA_HOME ?? join9(home, ".local", "share"));
50399
+ const configuredDataDirectory = resolve5(options.dataDirectory ?? process.env.XDG_DATA_HOME ?? join9(home, ".local", "share"));
49853
50400
  const dataDirectory = await canonicalPath(configuredDataDirectory, true);
49854
50401
  return { home, dataDirectory };
49855
50402
  }
@@ -49867,7 +50414,7 @@ async function canonicalPath(path4, allowMissing) {
49867
50414
  const metadata = await lstat(candidate);
49868
50415
  if (metadata.isSymbolicLink()) {
49869
50416
  const target2 = await readlink(candidate);
49870
- const resolvedTarget = resolve4(dirname7(candidate), target2);
50417
+ const resolvedTarget = resolve5(dirname7(candidate), target2);
49871
50418
  return canonicalPath(join9(resolvedTarget, ...suffix), true);
49872
50419
  }
49873
50420
  } catch (candidateError) {
@@ -49891,8 +50438,8 @@ async function canonicalPath(path4, allowMissing) {
49891
50438
  }
49892
50439
  }
49893
50440
  }
49894
- function isFencedPath(canonicalPath2, homeDirectory, dataDirectory = process.env.XDG_DATA_HOME ?? join9(resolve4(homeDirectory), ".local", "share")) {
49895
- const cortexkitRoot = join9(resolve4(dataDirectory), "cortexkit");
50441
+ function isFencedPath(canonicalPath2, homeDirectory, dataDirectory = process.env.XDG_DATA_HOME ?? join9(resolve5(homeDirectory), ".local", "share")) {
50442
+ const cortexkitRoot = join9(resolve5(dataDirectory), "cortexkit");
49896
50443
  const relativeToCortexkit = relative(cortexkitRoot, canonicalPath2);
49897
50444
  const insideCortexkit = relativeToCortexkit !== "" && relativeToCortexkit !== ".." && !relativeToCortexkit.startsWith(`..${sep}`) && !isAbsolute4(relativeToCortexkit);
49898
50445
  const parts = insideCortexkit ? relativeToCortexkit.split(sep) : [];
@@ -54405,4 +54952,4 @@ function registerMagicContextTools(pi, opts) {
54405
54952
  }
54406
54953
  }
54407
54954
 
54408
- export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, Database, closeQuietly, isMidTurn, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, isRecord, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isEditTool, applyEditMarkerToInput, setRawMessageProvider, withRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, getCachedAbsoluteMessageCount, primeInMemoryTailRawMessageCache, getRawSessionMessageCount, getRawSessionTagKeysThrough, getLegacyProtectedTailStartOrdinal, readSessionChunk, clearCompressionDepth, clearCompressionDepthRange, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordSessionProjectIdentity, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, isCompartmentLeaseHeld, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, copySessionStateForClone, getErrorMessage, describeError, setStoragePrivatePermissionEnforcement, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getLastNudgeLevel, setLastNudgeLevel, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, setChannel2NudgeState, casChannel2NudgeState, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, peekDeferredExecutePending, setDeferredExecutePendingIfAbsent, clearDeferredExecutePendingIfMatches, setSessionWorkMetrics, getSessionWorkMetrics, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, updateTagByteSize, getActiveTagTokenAggregate, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, BoundedSessionMap, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, formatWindowDerivationLine, isSaneLimit, getSdkContextLimit, resolveModelConfigOrDefault, normalizeTodoStateJson, buildSyntheticTodoPart, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, isMidTurnPi, readPiSessionMessages, findLastModelKeyFromBranch, convertEntriesToRawMessages, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath2 as getOpenCodeDbPath, parseCron, nextOccurrence, nextDueAtMs, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, wakePlaneStatus, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, ensureProjectRegisteredFromPiDirectory, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, registerMagicContextTools };
54955
+ export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, Database, closeQuietly, isMidTurn, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, isRecord, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isEditTool, applyEditMarkerToInput, setRawMessageProvider, withRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, getCachedAbsoluteMessageCount, primeInMemoryTailRawMessageCache, getRawSessionMessageCount, getRawSessionTagKeysThrough, getLegacyProtectedTailStartOrdinal, readSessionChunk, clearCompressionDepth, clearCompressionDepthRange, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordSessionProjectIdentity, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, isCompartmentLeaseHeld, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, copySessionStateForClone, getErrorMessage, describeError, setStoragePrivatePermissionEnforcement, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getLastNudgeLevel, setLastNudgeLevel, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, peekDeferredExecutePending, setDeferredExecutePendingIfAbsent, clearDeferredExecutePendingIfMatches, setSessionWorkMetrics, getSessionWorkMetrics, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, CTX_REDUCE_KEEP, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, updateTagByteSize, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, BoundedSessionMap, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, formatWindowDerivationLine, isSaneLimit, resolveOutputReserve, getSdkContextLimit, resolveModelConfigOrDefault, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, isMidTurnPi, readPiSessionMessages, findLastModelKeyFromBranch, convertEntriesToRawMessages, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath2 as getOpenCodeDbPath, parseCron, nextOccurrence, nextDueAtMs, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, wakePlaneStatus, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, ensureProjectRegisteredFromPiDirectory, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, registerMagicContextTools };