@cortexkit/pi-magic-context 0.38.1 → 0.39.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.
@@ -50,7 +50,7 @@ var require_esprima = __commonJS(function(exports, module) {
50
50
  var jsx_parser_1 = __webpack_require__(3);
51
51
  var parser_1 = __webpack_require__(8);
52
52
  var tokenizer_1 = __webpack_require__(15);
53
- function parse5(code, options, delegate) {
53
+ function parse6(code, options, delegate) {
54
54
  var commentHandler = null;
55
55
  var proxyDelegate = function(node, metadata) {
56
56
  if (delegate) {
@@ -95,17 +95,17 @@ var require_esprima = __commonJS(function(exports, module) {
95
95
  }
96
96
  return ast;
97
97
  }
98
- exports2.parse = parse5;
98
+ exports2.parse = parse6;
99
99
  function parseModule(code, options, delegate) {
100
100
  var parsingOptions = options || {};
101
101
  parsingOptions.sourceType = "module";
102
- return parse5(code, parsingOptions, delegate);
102
+ return parse6(code, parsingOptions, delegate);
103
103
  }
104
104
  exports2.parseModule = parseModule;
105
105
  function parseScript(code, options, delegate) {
106
106
  var parsingOptions = options || {};
107
107
  parsingOptions.sourceType = "script";
108
- return parse5(code, parsingOptions, delegate);
108
+ return parse6(code, parsingOptions, delegate);
109
109
  }
110
110
  exports2.parseScript = parseScript;
111
111
  function tokenize(code, options, delegate) {
@@ -7564,7 +7564,7 @@ var require_parse = __commonJS(function(exports, module) {
7564
7564
  return {};
7565
7565
  }
7566
7566
  }
7567
- var parse5 = (code, rev, options) => {
7567
+ var parse6 = (code, rev, options) => {
7568
7568
  clean();
7569
7569
  const {
7570
7570
  no_comments,
@@ -7601,7 +7601,7 @@ var require_parse = __commonJS(function(exports, module) {
7601
7601
  return result;
7602
7602
  };
7603
7603
  module.exports = {
7604
- parse: parse5,
7604
+ parse: parse6,
7605
7605
  tokenize
7606
7606
  };
7607
7607
  });
@@ -7696,10 +7696,10 @@ var require_stringify = __commonJS(function(exports, module) {
7696
7696
  replacer = null;
7697
7697
  indent = EMPTY;
7698
7698
  };
7699
- var join8 = (one, two, gap) => one ? two ? one + two.trim() + LF + gap : one.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(one)), gap) : two ? two.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(two)), gap) : EMPTY;
7699
+ var join9 = (one, two, gap) => one ? two ? one + two.trim() + LF + gap : one.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(one)), gap) : two ? two.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(two)), gap) : EMPTY;
7700
7700
  var join_content = (inside, value, gap) => {
7701
7701
  const comment = process_comments(value, PREFIX_BEFORE, gap + indent, true);
7702
- return join8(comment, inside, gap);
7702
+ return join9(comment, inside, gap);
7703
7703
  };
7704
7704
  var stringify_string = (holder, key, value) => {
7705
7705
  const raw = get_raw_string_literal(holder, key);
@@ -7721,13 +7721,13 @@ var require_stringify = __commonJS(function(exports, module) {
7721
7721
  if (i !== 0) {
7722
7722
  inside += COMMA;
7723
7723
  }
7724
- const before = join8(after_comma, process_comments(value, BEFORE(i), deeper_gap), deeper_gap);
7724
+ const before = join9(after_comma, process_comments(value, BEFORE(i), deeper_gap), deeper_gap);
7725
7725
  inside += before || LF + deeper_gap;
7726
7726
  inside += stringify(i, value, deeper_gap) || STR_NULL;
7727
7727
  inside += process_comments(value, AFTER_VALUE(i), deeper_gap);
7728
7728
  after_comma = process_comments(value, AFTER(i), deeper_gap);
7729
7729
  }
7730
- inside += join8(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
7730
+ inside += join9(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
7731
7731
  return BRACKET_OPEN + join_content(inside, value, gap) + BRACKET_CLOSE;
7732
7732
  };
7733
7733
  var object_stringify = (value, gap) => {
@@ -7748,13 +7748,13 @@ var require_stringify = __commonJS(function(exports, module) {
7748
7748
  inside += COMMA;
7749
7749
  }
7750
7750
  first = false;
7751
- const before = join8(after_comma, process_comments(value, BEFORE(key), deeper_gap), deeper_gap);
7751
+ const before = join9(after_comma, process_comments(value, BEFORE(key), deeper_gap), deeper_gap);
7752
7752
  inside += before || LF + deeper_gap;
7753
7753
  inside += quote(key) + process_comments(value, AFTER_PROP(key), deeper_gap) + COLON + process_comments(value, AFTER_COLON(key), deeper_gap) + SPACE + sv + process_comments(value, AFTER_VALUE(key), deeper_gap);
7754
7754
  after_comma = process_comments(value, AFTER(key), deeper_gap);
7755
7755
  };
7756
7756
  keys.forEach(iteratee);
7757
- inside += join8(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
7757
+ inside += join9(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
7758
7758
  return CURLY_BRACKET_OPEN + join_content(inside, value, gap) + CURLY_BRACKET_CLOSE;
7759
7759
  };
7760
7760
  function stringify(key, holder, gap) {
@@ -7816,7 +7816,7 @@ var require_stringify = __commonJS(function(exports, module) {
7816
7816
 
7817
7817
  // ../../node_modules/.bun/comment-json@5.0.0/node_modules/comment-json/src/index.js
7818
7818
  var require_src2 = __commonJS(function(exports, module) {
7819
- var { parse: parse5, tokenize } = require_parse();
7819
+ var { parse: parse6, tokenize } = require_parse();
7820
7820
  var stringify = require_stringify();
7821
7821
  var { CommentArray } = require_array();
7822
7822
  var {
@@ -7840,7 +7840,7 @@ var require_src2 = __commonJS(function(exports, module) {
7840
7840
  PREFIX_AFTER,
7841
7841
  PREFIX_BEFORE_ALL,
7842
7842
  PREFIX_AFTER_ALL,
7843
- parse: parse5,
7843
+ parse: parse6,
7844
7844
  stringify,
7845
7845
  tokenize,
7846
7846
  CommentArray,
@@ -12298,6 +12298,37 @@ var MIGRATIONS = [
12298
12298
  ensureColumn(db, "transform_decisions", "m0_model_key_prev", "TEXT");
12299
12299
  ensureColumn(db, "transform_decisions", "m0_model_key_new", "TEXT");
12300
12300
  }
12301
+ },
12302
+ {
12303
+ version: 80,
12304
+ description: "record observed m[0] tool-set hash comparisons",
12305
+ up(db) {
12306
+ if (!tableExists2(db, "transform_decisions"))
12307
+ return;
12308
+ ensureColumn(db, "transform_decisions", "m0_tool_set_hash_prev", "TEXT");
12309
+ ensureColumn(db, "transform_decisions", "m0_tool_set_hash_new", "TEXT");
12310
+ }
12311
+ },
12312
+ {
12313
+ version: 81,
12314
+ description: "persist last-known-good transform snapshots across restarts",
12315
+ up(db) {
12316
+ db.exec(`
12317
+ CREATE TABLE IF NOT EXISTS lkg_slots (
12318
+ session_id TEXT PRIMARY KEY,
12319
+ json_prefix TEXT NOT NULL,
12320
+ input_id_seq TEXT NOT NULL,
12321
+ input_content_digests TEXT NOT NULL,
12322
+ input_content_signatures TEXT,
12323
+ last_input_message_id TEXT NOT NULL,
12324
+ model_key TEXT,
12325
+ provider_key TEXT,
12326
+ captured_at INTEGER NOT NULL,
12327
+ row_version INTEGER,
12328
+ capture_sequence INTEGER
12329
+ );
12330
+ `);
12331
+ }
12301
12332
  }
12302
12333
  ];
12303
12334
  var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
@@ -12732,7 +12763,7 @@ function getSchemaFenceRejection() {
12732
12763
  function getMigrationOnOpenRefusal() {
12733
12764
  return lastMigrationOnOpenRefusal;
12734
12765
  }
12735
- var LATEST_SUPPORTED_VERSION = 79;
12766
+ var LATEST_SUPPORTED_VERSION = 81;
12736
12767
  var PERMISSIONS_ENFORCEABLE = process.platform !== "win32";
12737
12768
  var defaultStoragePermissionFs = { chmodSync, mkdirSync: mkdirSync2 };
12738
12769
  var storagePermissionFs = defaultStoragePermissionFs;
@@ -13884,10 +13915,12 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
13884
13915
  decision TEXT NOT NULL,
13885
13916
  materialized INTEGER NOT NULL DEFAULT 0,
13886
13917
  materialize_reason TEXT,
13887
- system_hash_prev TEXT,
13888
- system_hash_new TEXT,
13889
- m0_model_key_prev TEXT,
13890
- m0_model_key_new TEXT,
13918
+ system_hash_prev TEXT,
13919
+ system_hash_new TEXT,
13920
+ m0_tool_set_hash_prev TEXT,
13921
+ m0_tool_set_hash_new TEXT,
13922
+ m0_model_key_prev TEXT,
13923
+ m0_model_key_new TEXT,
13891
13924
  emergency INTEGER NOT NULL DEFAULT 0,
13892
13925
  dropped_tokens INTEGER NOT NULL DEFAULT 0,
13893
13926
  dropped_count INTEGER NOT NULL DEFAULT 0,
@@ -14225,10 +14258,12 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
14225
14258
  decision TEXT NOT NULL,
14226
14259
  materialized INTEGER NOT NULL DEFAULT 0,
14227
14260
  materialize_reason TEXT,
14228
- system_hash_prev TEXT,
14229
- system_hash_new TEXT,
14230
- m0_model_key_prev TEXT,
14231
- m0_model_key_new TEXT,
14261
+ system_hash_prev TEXT,
14262
+ system_hash_new TEXT,
14263
+ m0_tool_set_hash_prev TEXT,
14264
+ m0_tool_set_hash_new TEXT,
14265
+ m0_model_key_prev TEXT,
14266
+ m0_model_key_new TEXT,
14232
14267
  emergency INTEGER NOT NULL DEFAULT 0,
14233
14268
  dropped_tokens INTEGER NOT NULL DEFAULT 0,
14234
14269
  dropped_count INTEGER NOT NULL DEFAULT 0,
@@ -14682,9 +14717,10 @@ function persistCachedM0(db, sessionId, payload) {
14682
14717
  cached_m0_session_facts_version = ?,
14683
14718
  cached_m0_upgrade_state = ?,
14684
14719
  cached_m0_system_hash = ?,
14720
+ cached_m0_tool_set_hash = ?,
14685
14721
  cached_m0_model_key = ?,
14686
14722
  cached_m0_project_identity = ?
14687
- WHERE session_id = ?`).run(Buffer2.from(payload.m0Bytes), payload.muralDataUrl ?? null, payload.muralHash ?? null, payload.projectMemoryEpoch, payload.workspaceFingerprint ?? null, payload.projectUserProfileVersion, payload.maxCompartmentSeq, payload.maxMemoryId, payload.maxMutationId, payload.maxMemoryMutationId ?? null, payload.m1Bytes ? Buffer2.from(payload.m1Bytes) : null, payload.projectDocsHash, payload.materializedAt, payload.sessionFactsVersion, payload.upgradeState, payload.systemHash ?? "", payload.modelKey ? piModelRefToCanonical(payload.modelKey) : "", payload.projectIdentity ?? null, sessionId);
14723
+ WHERE session_id = ?`).run(Buffer2.from(payload.m0Bytes), payload.muralDataUrl ?? null, payload.muralHash ?? null, payload.projectMemoryEpoch, payload.workspaceFingerprint ?? null, payload.projectUserProfileVersion, payload.maxCompartmentSeq, payload.maxMemoryId, payload.maxMutationId, payload.maxMemoryMutationId ?? null, payload.m1Bytes ? Buffer2.from(payload.m1Bytes) : null, payload.projectDocsHash, payload.materializedAt, payload.sessionFactsVersion, payload.upgradeState, payload.systemHash ?? "", payload.toolSetHash ?? "", payload.modelKey ? piModelRefToCanonical(payload.modelKey) : "", payload.projectIdentity ?? null, sessionId);
14688
14724
  }
14689
14725
  function clearCachedM0M1(db, sessionId) {
14690
14726
  ensureSessionMetaRow(db, sessionId);
@@ -15189,6 +15225,7 @@ function clearEmergencyDropSample(db, sessionId) {
15189
15225
  db.prepare("UPDATE session_meta SET last_emergency_input_sample = 0 WHERE session_id = ?").run(sessionId);
15190
15226
  })();
15191
15227
  }
15228
+ var EMPTY_CHANNEL1_NUDGE_STATE = { level: "", ordinal: 0 };
15192
15229
  function isLastNudgeUndroppedRow(row) {
15193
15230
  return typeof row === "object" && row !== null && typeof row.last_nudge_undropped === "number";
15194
15231
  }
@@ -15198,6 +15235,24 @@ function isLastNudgeLevelRow(row) {
15198
15235
  function normalizeLastNudgeLevel(value) {
15199
15236
  return value === "gentle" || value === "firm" || value === "urgent" ? value : "";
15200
15237
  }
15238
+ function parseChannel1NudgeState(raw) {
15239
+ try {
15240
+ const parsed = JSON.parse(raw);
15241
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
15242
+ return {
15243
+ level: normalizeLastNudgeLevel(parsed.level),
15244
+ ordinal: typeof parsed.ordinal === "number" ? Math.max(0, Math.round(parsed.ordinal)) : 0
15245
+ };
15246
+ }
15247
+ } catch {}
15248
+ return { level: normalizeLastNudgeLevel(raw), ordinal: 0 };
15249
+ }
15250
+ function serializeChannel1NudgeState(value) {
15251
+ return JSON.stringify({
15252
+ level: normalizeLastNudgeLevel(value.level),
15253
+ ordinal: Math.max(0, Math.round(value.ordinal))
15254
+ });
15255
+ }
15201
15256
  function getLastNudgeUndropped(db, sessionId) {
15202
15257
  const result = db.prepare("SELECT last_nudge_undropped FROM session_meta WHERE session_id = ?").get(sessionId);
15203
15258
  return isLastNudgeUndroppedRow(result) ? result.last_nudge_undropped : 0;
@@ -15208,27 +15263,27 @@ function setLastNudgeUndropped(db, sessionId, value) {
15208
15263
  db.prepare("UPDATE session_meta SET last_nudge_undropped = ? WHERE session_id = ?").run(Math.max(0, Math.round(value)), sessionId);
15209
15264
  })();
15210
15265
  }
15211
- function getLastNudgeLevel(db, sessionId) {
15266
+ function getChannel1NudgeState(db, sessionId) {
15212
15267
  const result = db.prepare("SELECT last_nudge_level FROM session_meta WHERE session_id = ?").get(sessionId);
15213
- return isLastNudgeLevelRow(result) ? normalizeLastNudgeLevel(result.last_nudge_level) : "";
15268
+ return isLastNudgeLevelRow(result) ? parseChannel1NudgeState(result.last_nudge_level) : EMPTY_CHANNEL1_NUDGE_STATE;
15214
15269
  }
15215
- function setLastNudgeLevel(db, sessionId, value) {
15270
+ function setChannel1NudgeState(db, sessionId, value) {
15216
15271
  db.transaction(() => {
15217
15272
  ensureSessionMetaRow(db, sessionId);
15218
- db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(normalizeLastNudgeLevel(value), sessionId);
15273
+ db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(value), sessionId);
15219
15274
  })();
15220
15275
  }
15221
15276
  function resetLastNudgeCycle(db, sessionId) {
15222
15277
  db.transaction(() => {
15223
15278
  ensureSessionMetaRow(db, sessionId);
15224
- db.prepare("UPDATE session_meta SET last_nudge_undropped = 0, last_nudge_level = '' WHERE session_id = ?").run(sessionId);
15279
+ db.prepare("UPDATE session_meta SET last_nudge_undropped = 0, last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(EMPTY_CHANNEL1_NUDGE_STATE), sessionId);
15225
15280
  })();
15226
15281
  }
15227
15282
  function resetLastNudgeCycleIfTailShrank(db, sessionId, measuredUndropped) {
15228
15283
  let changed = false;
15229
15284
  db.transaction(() => {
15230
15285
  ensureSessionMetaRow(db, sessionId);
15231
- const result = db.prepare("UPDATE session_meta SET last_nudge_undropped = 0, last_nudge_level = '' WHERE session_id = ? AND last_nudge_undropped > ?").run(sessionId, Math.max(0, Math.round(measuredUndropped)));
15286
+ const result = db.prepare("UPDATE session_meta SET last_nudge_undropped = 0, last_nudge_level = ? WHERE session_id = ? AND last_nudge_undropped > ?").run(serializeChannel1NudgeState(EMPTY_CHANNEL1_NUDGE_STATE), sessionId, Math.max(0, Math.round(measuredUndropped)));
15232
15287
  changed = (result.changes ?? 0) > 0;
15233
15288
  })();
15234
15289
  return changed;
@@ -15895,7 +15950,8 @@ var SESSION_SCOPED_TABLES = [
15895
15950
  { table: "pending_session_cleanup", harnessScoped: true },
15896
15951
  { table: "message_history_fts" },
15897
15952
  { table: "message_history_source", harnessScoped: true },
15898
- { table: "message_history_index", harnessScoped: true }
15953
+ { table: "message_history_index", harnessScoped: true },
15954
+ { table: "lkg_slots" }
15899
15955
  ];
15900
15956
  function deleteSessionScopedRows(db, sessionIds, harness) {
15901
15957
  if (sessionIds.length === 0)
@@ -19440,26 +19496,44 @@ function formatOldestReclaimableHint(hint) {
19440
19496
  return rendered.length > 0 ? `
19441
19497
  oldest reclaimable: ${rendered}.` : "";
19442
19498
  }
19443
- function buildChannel2Reminder(undroppedTokens, hint) {
19499
+ function buildChannel2Reminder(undroppedTokens, usableWindowTokens, hint) {
19444
19500
  const amount = approxThousands(undroppedTokens);
19501
+ const usableWindow = approxThousands(usableWindowTokens);
19445
19502
  const hintText = formatOldestReclaimableHint(hint);
19446
19503
  return `<system-reminder>
19447
- ` + `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}
19504
+ ` + `Routine housekeeping: an older span of this session folds into compact history automatically — nothing is lost and nothing pauses. ` + `Drop spent tool outputs with ctx_reduce first so the archive keeps only what matters (~${amount} of ~${usableWindow} reclaimable).${hintText}
19448
19505
  ` + `</system-reminder>`;
19449
19506
  }
19450
- function buildChannel1Reminder(level, undroppedTokens, hint) {
19451
- const amount = approxThousands(undroppedTokens);
19507
+ var CHANNEL1_STICKY_REAL_USER_TURN_GAP = 3;
19508
+ function shouldUseStickyChannel1Reminder(input) {
19509
+ if (input.lastLevel !== input.level)
19510
+ return false;
19511
+ if (input.lastOrdinal > input.currentRealUserTurnCount)
19512
+ return false;
19513
+ const gap = input.currentRealUserTurnCount - input.lastOrdinal;
19514
+ return gap >= 0 && gap < CHANNEL1_STICKY_REAL_USER_TURN_GAP;
19515
+ }
19516
+ function buildChannel1Reminder(level, undroppedTokens, usableWindowTokens, hint, sticky = false) {
19452
19517
  const hintText = formatOldestReclaimableHint(hint);
19518
+ if (sticky) {
19519
+ return `
19520
+
19521
+ <system-reminder>
19522
+ Reminder: ctx_reduce housekeeping still pending —${hintText}
19523
+ </system-reminder>`;
19524
+ }
19525
+ const amount = approxThousands(undroppedTokens);
19526
+ const usableWindow = approxThousands(usableWindowTokens);
19453
19527
  let body;
19454
19528
  switch (level) {
19455
19529
  case "gentle":
19456
- 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.`;
19530
+ body = `Housekeeping: some earlier tool outputs are spent and can be dropped with ctx_reduce when you are done with them. ` + `Context is managed automatically — this is tidiness, never a reason to rush or narrow scope.`;
19457
19531
  break;
19458
19532
  case "firm":
19459
- 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.`;
19533
+ body = `Housekeeping: ~${amount} of this session's ~${usableWindow} window is spent tool output. ` + `Drop what you have already processed with ctx_reduce at a natural stopping point. ` + `Not a limit — nothing is lost either way.`;
19460
19534
  break;
19461
19535
  case "urgent":
19462
- 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.`;
19536
+ body = `Housekeeping backlog: ~${amount} of this session's ~${usableWindow} window is spent tool output — worth a ctx_reduce pass now. ` + `This is routine and lossless; it is never a reason to change scope.`;
19463
19537
  break;
19464
19538
  }
19465
19539
  return `
@@ -19689,8 +19763,14 @@ function getOldestActiveUnprotectedToolTags(db, sessionId, protectedTags = 0, li
19689
19763
  const params = protectedTags > 0 ? [sessionId, AGE_RECLAIM_MIN_TOKENS, sessionId, protectedTags - 1] : [sessionId, AGE_RECLAIM_MIN_TOKENS];
19690
19764
  const rows = db.prepare(`SELECT tag_number, tool_name
19691
19765
  FROM tags
19692
- WHERE session_id = ? AND status = 'active' AND type = 'tool'
19693
- ${valueFloor}
19766
+ WHERE session_id = ? AND status = 'active' AND type = 'tool'
19767
+ AND NOT EXISTS (
19768
+ SELECT 1 FROM pending_ops
19769
+ WHERE pending_ops.session_id = tags.session_id
19770
+ AND pending_ops.tag_id = tags.tag_number
19771
+ AND pending_ops.operation = 'drop'
19772
+ )
19773
+ ${valueFloor}
19694
19774
  ${whereProtected}
19695
19775
  ORDER BY tag_number ASC, id ASC`).all(...params);
19696
19776
  return rows.filter((row) => typeof row.tag_number === "number").map((row) => ({
@@ -20373,6 +20453,42 @@ function stripJsonComments(content) {
20373
20453
  }
20374
20454
  return result;
20375
20455
  }
20456
+ function stripTrailingCommas(content) {
20457
+ let result = "";
20458
+ let inString = false;
20459
+ let escaped = false;
20460
+ for (let index = 0;index < content.length; index += 1) {
20461
+ const char = content[index];
20462
+ if (inString) {
20463
+ result += char;
20464
+ if (escaped) {
20465
+ escaped = false;
20466
+ } else if (char === "\\") {
20467
+ escaped = true;
20468
+ } else if (char === '"') {
20469
+ inString = false;
20470
+ }
20471
+ continue;
20472
+ }
20473
+ if (char === '"') {
20474
+ inString = true;
20475
+ result += char;
20476
+ continue;
20477
+ }
20478
+ if (char === ",") {
20479
+ let lookahead = index + 1;
20480
+ while (lookahead < content.length && /\s/.test(content[lookahead] ?? "")) {
20481
+ lookahead += 1;
20482
+ }
20483
+ const next = content[lookahead];
20484
+ if (next === "}" || next === "]") {
20485
+ continue;
20486
+ }
20487
+ }
20488
+ result += char;
20489
+ }
20490
+ return result;
20491
+ }
20376
20492
  var PROTOTYPE_POLLUTION_KEYS = new Set(["__proto__", "constructor", "prototype"]);
20377
20493
  function isPrototypePollutionKey(key) {
20378
20494
  return PROTOTYPE_POLLUTION_KEYS.has(key);
@@ -20403,6 +20519,10 @@ function sanitizeParsedJson(value, options = {}, path3 = []) {
20403
20519
  }
20404
20520
  return sanitized;
20405
20521
  }
20522
+ function parseJsonc(content, options = {}) {
20523
+ const normalized = stripTrailingCommas(stripJsonComments(content));
20524
+ return sanitizeParsedJson(JSON.parse(normalized), options);
20525
+ }
20406
20526
  function detectConfigFile(basePath) {
20407
20527
  const jsoncPath = `${basePath}.jsonc`;
20408
20528
  const jsonPath = `${basePath}.json`;
@@ -20967,7 +21087,7 @@ function pruneNestedConfigLeaf(block, relativePath) {
20967
21087
  }
20968
21088
 
20969
21089
  // src/config/index.ts
20970
- import { existsSync as existsSync10, readFileSync as readFileSync11 } from "node:fs";
21090
+ import { existsSync as existsSync11 } from "node:fs";
20971
21091
 
20972
21092
  // ../plugin/src/config/migrate-dreamer-v2.ts
20973
21093
  var OLD_VERIFY_TASK = "verify";
@@ -35841,16 +35961,103 @@ var PromptSurfaceConfigSchema = exports_external.object({
35841
35961
  message: "tool description values must not be empty or whitespace-only"
35842
35962
  })).optional().describe("USER-LEVEL ONLY top-level description overrides keyed by ctx_* tool ID; parameter schemas and descriptions are unchanged.")
35843
35963
  }).describe("Prompt-surface preset routing. Project config may select default/models, while guidance_override_path and tool_descriptions are user-level only.");
35964
+ var PER_HARNESS_MIGRATION_INVENTORY = {
35965
+ historian: {
35966
+ retained: [
35967
+ "temperature",
35968
+ "top_p",
35969
+ "prompt",
35970
+ "tools",
35971
+ "disable",
35972
+ "description",
35973
+ "mode",
35974
+ "color",
35975
+ "maxSteps",
35976
+ "permission",
35977
+ "maxTokens",
35978
+ "two_pass",
35979
+ "disallowed_tools"
35980
+ ],
35981
+ migrated_execution: ["model", "fallback_models", "variant", "thinking_level"]
35982
+ },
35983
+ dreamer: {
35984
+ retained: [
35985
+ "temperature",
35986
+ "top_p",
35987
+ "prompt",
35988
+ "tools",
35989
+ "disable",
35990
+ "description",
35991
+ "mode",
35992
+ "color",
35993
+ "maxSteps",
35994
+ "permission",
35995
+ "maxTokens",
35996
+ "inject_docs"
35997
+ ],
35998
+ migrated_execution: ["model", "fallback_models", "variant", "thinking_level"]
35999
+ },
36000
+ task: {
36001
+ retained: ["schedule", "promotion_threshold"],
36002
+ migrated_execution: [
36003
+ "model",
36004
+ "fallback_models",
36005
+ "variant",
36006
+ "thinking_level",
36007
+ "timeout_minutes"
36008
+ ]
36009
+ }
36010
+ };
36011
+ var OcEntryObjectSchema = exports_external.object({
36012
+ model: exports_external.string().describe("OpenCode model ID (for example, provider/model)."),
36013
+ variant: exports_external.string().optional().describe("OpenCode reasoning variant for this entry.")
36014
+ }).strict();
36015
+ var OcEntrySchema = exports_external.union([exports_external.string(), OcEntryObjectSchema]);
36016
+ var PiEntryObjectSchema = exports_external.object({
36017
+ model: exports_external.string().describe("Pi model ID (for example, provider/model)."),
36018
+ thinking_level: PiThinkingLevelSchema.describe("Pi thinking level for this entry.")
36019
+ }).strict();
36020
+ var PiEntrySchema = exports_external.union([exports_external.string(), PiEntryObjectSchema]);
36021
+ var OpenCodeHarnessBlockSchema = exports_external.object({
36022
+ model: OcEntrySchema.optional().describe("Primary OpenCode model entry."),
36023
+ fallback_models: exports_external.array(OcEntrySchema).optional().describe("Ordered fallback OpenCode entries. New-shape configuration requires an array; legacy singleton values migrate to a one-element array."),
36024
+ variant: exports_external.string().optional().describe("OpenCode reasoning variant for the primary entry when it declares none. Fallback entries declare variants per-entry.")
36025
+ }).strict().describe("Strict OpenCode model-resolution block. It accepts no Pi vocabulary.");
36026
+ var PiHarnessBlockSchema = exports_external.object({
36027
+ model: PiEntrySchema.optional().describe("Primary Pi model entry."),
36028
+ fallback_models: exports_external.array(PiEntrySchema).optional().describe("Ordered fallback Pi entries. New-shape configuration requires an array; legacy singleton values migrate to a one-element array."),
36029
+ thinking_level: PiThinkingLevelSchema.describe("Pi thinking level for the primary entry when it declares none. Fallback entries declare thinking levels per-entry.")
36030
+ }).strict().describe("Strict Pi model-resolution block. It accepts no OpenCode vocabulary.");
36031
+ var OpenCodeTaskExecutionSchema = exports_external.object({
36032
+ model: OcEntrySchema.optional().describe("OpenCode model entry for this task."),
36033
+ fallback_models: exports_external.array(OcEntrySchema).optional().describe("Ordered OpenCode fallback entries for this task."),
36034
+ variant: exports_external.string().optional().describe("OpenCode reasoning variant for this task's primary entry when it declares none. Fallback entries declare variants per-entry."),
36035
+ timeout_minutes: exports_external.number().min(5).optional().describe("Minutes allowed for this task before it is aborted.")
36036
+ }).strict();
36037
+ var PiTaskExecutionSchema = exports_external.object({
36038
+ model: PiEntrySchema.optional().describe("Pi model entry for this task."),
36039
+ fallback_models: exports_external.array(PiEntrySchema).optional().describe("Ordered Pi fallback entries for this task."),
36040
+ thinking_level: PiThinkingLevelSchema.describe("Pi thinking level for this task's primary entry when it declares none. Fallback entries declare thinking levels per-entry."),
36041
+ timeout_minutes: exports_external.number().min(5).optional().describe("Minutes allowed for this task before it is aborted.")
36042
+ }).strict();
36043
+ var DreamerOpenCodeHarnessBlockSchema = exports_external.object({
36044
+ model: OcEntrySchema.optional().describe("Primary OpenCode model entry."),
36045
+ fallback_models: exports_external.array(OcEntrySchema).optional().describe("Ordered fallback OpenCode entries. New-shape configuration requires an array; legacy singleton values migrate to a one-element array."),
36046
+ variant: exports_external.string().optional().describe("OpenCode reasoning variant for the primary entry when it declares none. Fallback entries declare variants per-entry."),
36047
+ tasks: exports_external.record(exports_external.string(), OpenCodeTaskExecutionSchema).optional().describe("OpenCode task execution overrides. Each named task accepts only model, fallback_models, variant, and timeout_minutes.")
36048
+ }).strict().describe("Strict OpenCode dreamer model-resolution block. It accepts no Pi vocabulary.");
36049
+ var DreamerPiHarnessBlockSchema = exports_external.object({
36050
+ model: PiEntrySchema.optional().describe("Primary Pi model entry."),
36051
+ fallback_models: exports_external.array(PiEntrySchema).optional().describe("Ordered fallback Pi entries. New-shape configuration requires an array; legacy singleton values migrate to a one-element array."),
36052
+ thinking_level: PiThinkingLevelSchema.describe("Pi thinking level for the primary entry when it declares none. Fallback entries declare thinking levels per-entry."),
36053
+ tasks: exports_external.record(exports_external.string(), PiTaskExecutionSchema).optional().describe("Pi task execution overrides. Each named task accepts only model, fallback_models, thinking_level, and timeout_minutes.")
36054
+ }).strict().describe("Strict Pi dreamer model-resolution block. It accepts no OpenCode vocabulary.");
35844
36055
  var CronScheduleSchema = exports_external.string().refine((s) => s.trim() === "" || isValidCron(s), {
35845
36056
  message: 'Invalid schedule: use a 5-field cron expression (e.g. "0 3 * * *" for 3am daily, "0 3 * * 0" for Sunday 3am, "0 */6 * * *" every 6h) or "" to disable.'
35846
36057
  }).describe('5-field cron schedule (e.g. "0 3 * * *"), or "" to disable this task.');
35847
36058
  var DreamTaskBaseConfigSchema = exports_external.object({
35848
- schedule: CronScheduleSchema.default(""),
35849
- model: exports_external.string().optional().describe("Per-task model override (inherits dreamer.model)"),
35850
- fallback_models: exports_external.union([exports_external.string(), exports_external.array(exports_external.string())]).optional().describe("Per-task fallback chain (inherits dreamer.fallback_models)"),
35851
- thinking_level: PiThinkingLevelSchema.describe("Pi only: per-task thinking level"),
35852
- timeout_minutes: exports_external.number().min(5).default(20).describe("Minutes allowed for this task before it is aborted")
35853
- });
36059
+ schedule: CronScheduleSchema.default("")
36060
+ }).strict();
35854
36061
  var PromotionThresholdSchema = exports_external.number().min(2).max(20).optional().describe("review-user-memories: min candidate observations before promotion is considered (default: 3)");
35855
36062
  var PrimerPromotionThresholdSchema = exports_external.number().min(2).max(20).optional().describe("promote-primers: min recurring source days before promotion is considered (default: 2)");
35856
36063
  var DreamTaskConfigSchema = DreamTaskBaseConfigSchema.extend({
@@ -35897,20 +36104,35 @@ var DreamTasksSchema = exports_external.object({
35897
36104
  "review-user-memories": ReviewUserMemoriesTaskConfigSchema.default(() => ReviewUserMemoriesTaskConfigSchema.parse(defaultTaskConfig("review-user-memories"))),
35898
36105
  "promote-primers": PromotePrimersTaskConfigSchema.default(() => PromotePrimersTaskConfigSchema.parse(defaultTaskConfig("promote-primers"))),
35899
36106
  "refresh-primers": DreamTaskBaseConfigSchema.default(() => DreamTaskBaseConfigSchema.parse(defaultTaskConfig("refresh-primers")))
35900
- }).describe("Per-task scheduling + model config. Each task has its own cron schedule and may override the dreamer-level model.");
35901
- var DreamerConfigSchema = AgentOverrideConfigSchema.merge(exports_external.object({
36107
+ }).describe("Harness-independent task metadata. schedule, promotion_threshold, and other task metadata remain here; execution settings live under dreamer.opencode.tasks or dreamer.pi.tasks.");
36108
+ var AgentMetadataSchema = AgentOverrideConfigSchema.pick({
36109
+ temperature: true,
36110
+ top_p: true,
36111
+ prompt: true,
36112
+ tools: true,
36113
+ disable: true,
36114
+ description: true,
36115
+ mode: true,
36116
+ color: true,
36117
+ maxSteps: true,
36118
+ permission: true,
36119
+ maxTokens: true
36120
+ });
36121
+ var DreamerConfigSchema = AgentMetadataSchema.extend({
36122
+ opencode: DreamerOpenCodeHarnessBlockSchema.optional(),
36123
+ pi: DreamerPiHarnessBlockSchema.optional(),
35902
36124
  tasks: DreamTasksSchema.default(() => DreamTasksSchema.parse({})),
35903
- inject_docs: exports_external.boolean().default(true).describe("Inject ARCHITECTURE.md and STRUCTURE.md into the m[0] `<project-docs>` block (default true)"),
35904
- thinking_level: PiThinkingLevelSchema.describe("Pi only: default thinking level for dreamer subagent invocations. See historian.thinking_level.")
35905
- }));
36125
+ inject_docs: exports_external.boolean().default(true).describe("Inject ARCHITECTURE.md and STRUCTURE.md into the m[0] `<project-docs>` block (default true)")
36126
+ });
35906
36127
  var SidekickConfigSchema = AgentOverrideConfigSchema.extend({
35907
36128
  timeout_ms: exports_external.number().default(30000).describe("Timeout for sidekick calls in milliseconds"),
35908
36129
  system_prompt: exports_external.string().optional().describe("Custom system prompt for sidekick"),
35909
- thinking_level: PiThinkingLevelSchema.describe("Pi only: explicit thinking level for sidekick subagent invocations. See historian.thinking_level.")
36130
+ thinking_level: PiThinkingLevelSchema.describe("Pi only: explicit thinking level for sidekick subagent invocations. See historian.pi.thinking_level.")
35910
36131
  }).optional();
35911
- var HistorianConfigSchema = AgentOverrideConfigSchema.extend({
36132
+ var HistorianConfigSchema = AgentMetadataSchema.extend({
36133
+ opencode: OpenCodeHarnessBlockSchema.optional(),
36134
+ pi: PiHarnessBlockSchema.optional(),
35912
36135
  two_pass: exports_external.boolean().default(false).describe("Run a second editor pass over historian output to clean low-signal U: lines and cross-compartment duplicates. Adds ~1 extra API call and ~1.3x cost per historian run. Useful for models without extended thinking support. (default: false)"),
35913
- thinking_level: PiThinkingLevelSchema.describe("Pi only: explicit thinking level passed as --thinking <level> to Pi historian subagent invocations. Required when using reasoning models (e.g. github-copilot/gpt-5.4) because Pi's default thinking-level resolution can pick a value the provider rejects. OpenCode users set variant instead. Valid: off | minimal | low | medium | high | xhigh | max"),
35914
36136
  disallowed_tools: exports_external.array(exports_external.enum(["*", "read", "aft_outline", "aft_zoom", "aft_search"])).default([]).describe(`OpenCode only. Tools to REMOVE from the historian's default allow-list [read, aft_outline, aft_zoom, aft_search]. Applies to both historian and historian-editor agents. Use ["*"] to strip all tool definitions from the model request — this prevents weak instruction-following models (e.g. mistral-small-latest) from entering tool-calling loops. Individual tool names remove just that tool. Note: a user-supplied historian.permission override can re-allow a tool that disallowed_tools removed — disallowed_tools sets the baseline, permission overrides take precedence. (default: [])`)
35915
36137
  }).optional();
35916
36138
  var EmbeddingFallbackProviderSchema = exports_external.enum(["local", "openai-compatible", "off"]);
@@ -36020,8 +36242,8 @@ var MagicContextConfigSchema = exports_external.object({
36020
36242
  transform_mode: exports_external.enum(["ts", "rust"]).default("ts").describe('Experimental: routes the entire Magic Context runtime for the project through the ck-mc Rust module over subc (requires user-level `subc` config); "ts" is the current TypeScript pipeline.'),
36021
36243
  auto_update: exports_external.boolean().optional().describe("Enable automatic npm self-update checks for the OpenCode plugin. Security: USER-only in config loader, so hostile project configs cannot suppress updates."),
36022
36244
  language: exports_external.string().trim().toLowerCase().refine((s) => isValidLanguageCode(s), 'language must be a 2-letter ISO 639-1 code (e.g. "tr", "es", "de")').optional().describe("Output language for Magic Context's generated content and guidance, as a " + '2-letter ISO 639-1 code (e.g. "tr", "es", "de", "ja", "pt"). When set, the ' + "historian, dreamer, sidekick, and the agent-guidance block instruct the model to " + "write its PROSE in this language while keeping all structural tokens (XML tags, " + "the five memory category names, code identifiers, file paths) in English. " + "USER-LEVEL ONLY (ignored in project config for security). Unset = today's " + "behavior (model mirrors the conversation; English scaffolding). Changing it " + "triggers one cache re-materialization; existing compartments/memories keep their " + "original language until naturally rewritten."),
36023
- historian: HistorianConfigSchema.describe("Historian agent configuration (model, fallback_models, variant, temperature, maxTokens, permission, two_pass, etc.)"),
36024
- dreamer: DreamerConfigSchema.optional().describe("Dreamer agent + scheduling configuration (model, fallback_models, disable, schedule, tasks, etc.)"),
36245
+ historian: HistorianConfigSchema.describe("Historian metadata plus independent strict OpenCode and Pi execution blocks. Retained metadata stays at historian; model, fallback_models, variant, and thinking_level belong only in historian.opencode or historian.pi."),
36246
+ dreamer: DreamerConfigSchema.optional().describe("Dreamer metadata and scheduling plus independent strict OpenCode and Pi execution blocks. schedule and promotion_threshold stay at dreamer.tasks; model, fallback_models, variant, thinking_level, and timeout_minutes belong only in the matching harness block."),
36025
36247
  smart_notes: exports_external.object({
36026
36248
  retina_handoff: exports_external.boolean().default(false).describe("When true, dreamer skips smart notes whose surface conditions compiled to retina provider configs at authoring time. Default false keeps both paths active until the retina consumer is deployed.")
36027
36249
  }).default({ retina_handoff: false }).describe("Smart-note ownership transition controls."),
@@ -36123,7 +36345,8 @@ var MagicContextConfigSchema = exports_external.object({
36123
36345
 
36124
36346
  // ../plugin/src/config/project-security.ts
36125
36347
  var HIDDEN_AGENT_KEYS = ["historian", "dreamer", "sidekick"];
36126
- var HISTORIAN_USER_ONLY_FIELDS = ["model", "fallback_models"];
36348
+ var HARNESS_KEYS = ["opencode", "pi"];
36349
+ var HISTORIAN_USER_ONLY_FIELDS = PER_HARNESS_MIGRATION_INVENTORY.historian.migrated_execution;
36127
36350
  var PROMPT_SURFACE_USER_ONLY_FIELDS = ["guidance_override_path", "tool_descriptions"];
36128
36351
  var AGENT_ESCALATION_FIELDS = ["prompt", "permission", "tools", "system_prompt"];
36129
36352
  var EMBEDDING_DESTINATION_FIELDS = ["endpoint", "provider", "fallback_provider"];
@@ -36133,6 +36356,38 @@ var TOKEN_THRESHOLD_INTRODUCTION_REASON = "security: a repository cannot introdu
36133
36356
  function isPlainObject3(value) {
36134
36357
  return typeof value === "object" && value !== null && !Array.isArray(value);
36135
36358
  }
36359
+ function stripListedFields(target, fields, path3, removed) {
36360
+ for (const field of fields) {
36361
+ if (field in target) {
36362
+ delete target[field];
36363
+ removed.push(path3.length > 0 ? `${path3}.${field}` : field);
36364
+ }
36365
+ }
36366
+ }
36367
+ function stripEscalationAtExecutableSite(block, path3, removed) {
36368
+ stripListedFields(block, AGENT_ESCALATION_FIELDS, path3, removed);
36369
+ if (isPlainObject3(block.model)) {
36370
+ stripListedFields(block.model, AGENT_ESCALATION_FIELDS, `${path3}.model`, removed);
36371
+ }
36372
+ if (Array.isArray(block.fallback_models)) {
36373
+ for (let index = 0;index < block.fallback_models.length; index++) {
36374
+ const entry = block.fallback_models[index];
36375
+ if (isPlainObject3(entry)) {
36376
+ stripListedFields(entry, AGENT_ESCALATION_FIELDS, `${path3}.fallback_models.${index}`, removed);
36377
+ }
36378
+ }
36379
+ }
36380
+ }
36381
+ function stripNestedMuralModels(node, path3, removed) {
36382
+ for (const [key, value] of Object.entries(node)) {
36383
+ if (key === "mural" && isPlainObject3(value) && "model" in value) {
36384
+ delete value.model;
36385
+ removed.push(`${path3}.${key}.model`);
36386
+ } else if (isPlainObject3(value)) {
36387
+ stripNestedMuralModels(value, `${path3}.${key}`, removed);
36388
+ }
36389
+ }
36390
+ }
36136
36391
  function isValidPercentageThreshold(value) {
36137
36392
  return typeof value === "number" && Number.isFinite(value) && value >= 20 && value <= 80;
36138
36393
  }
@@ -36302,6 +36557,38 @@ function stripUnsafeProjectConfigFields(projectRaw) {
36302
36557
  warnings.push(`Ignoring embedding.${removed.join("/")} from project config ` + "(security: a repository cannot choose where private text is embedded).");
36303
36558
  }
36304
36559
  }
36560
+ for (const agentKey of HIDDEN_AGENT_KEYS) {
36561
+ const block = projectRaw[agentKey];
36562
+ if (!isPlainObject3(block))
36563
+ continue;
36564
+ const removed = [];
36565
+ stripEscalationAtExecutableSite(block, agentKey, removed);
36566
+ for (const harness of HARNESS_KEYS) {
36567
+ const harnessBlock = block[harness];
36568
+ if (!isPlainObject3(harnessBlock))
36569
+ continue;
36570
+ stripEscalationAtExecutableSite(harnessBlock, `${agentKey}.${harness}`, removed);
36571
+ const tasks = harnessBlock.tasks;
36572
+ if (isPlainObject3(tasks)) {
36573
+ for (const [taskName, taskBlock] of Object.entries(tasks)) {
36574
+ if (isPlainObject3(taskBlock)) {
36575
+ stripEscalationAtExecutableSite(taskBlock, `${agentKey}.${harness}.tasks.${taskName}`, removed);
36576
+ }
36577
+ }
36578
+ }
36579
+ }
36580
+ const schedulingTasks = block.tasks;
36581
+ if (isPlainObject3(schedulingTasks)) {
36582
+ for (const [taskName, taskBlock] of Object.entries(schedulingTasks)) {
36583
+ if (isPlainObject3(taskBlock)) {
36584
+ stripListedFields(taskBlock, AGENT_ESCALATION_FIELDS, `${agentKey}.tasks.${taskName}`, removed);
36585
+ }
36586
+ }
36587
+ }
36588
+ if (removed.length > 0) {
36589
+ warnings.push(`Ignoring ${removed.join(", ")} from project config ` + "(security: a repository cannot reprogram or re-permission hidden agents).");
36590
+ }
36591
+ }
36305
36592
  const historian = projectRaw.historian;
36306
36593
  if (isPlainObject3(historian)) {
36307
36594
  const removed = [];
@@ -36311,8 +36598,19 @@ function stripUnsafeProjectConfigFields(projectRaw) {
36311
36598
  removed.push(field);
36312
36599
  }
36313
36600
  }
36601
+ for (const harness of HARNESS_KEYS) {
36602
+ const harnessBlock = historian[harness];
36603
+ if (!isPlainObject3(harnessBlock))
36604
+ continue;
36605
+ for (const field of HISTORIAN_USER_ONLY_FIELDS) {
36606
+ if (field in harnessBlock) {
36607
+ delete harnessBlock[field];
36608
+ removed.push(`${harness}.${field}`);
36609
+ }
36610
+ }
36611
+ }
36314
36612
  if (removed.length > 0) {
36315
- warnings.push(`Ignoring historian.${removed.join("/")} from project config ` + "(security: historian model selection is user-level only; a repository cannot force extra compaction cost).");
36613
+ warnings.push(`Ignoring ${removed.map((path3) => `historian.${path3}`).join(", ")} from project config ` + "(security: historian model selection is user-level only; a repository cannot force extra compaction cost).");
36316
36614
  }
36317
36615
  }
36318
36616
  const mural = projectRaw.mural;
@@ -36326,20 +36624,15 @@ function stripUnsafeProjectConfigFields(projectRaw) {
36326
36624
  delete legacyMural.model;
36327
36625
  warnings.push("Ignoring experimental.mural.model from project config (security: the mural cue-compressor model is a user-level setting; use user-level mural.model).");
36328
36626
  }
36627
+ const nestedMuralRemoved = [];
36329
36628
  for (const agentKey of HIDDEN_AGENT_KEYS) {
36330
36629
  const block = projectRaw[agentKey];
36331
36630
  if (!isPlainObject3(block))
36332
36631
  continue;
36333
- const removed = [];
36334
- for (const field of AGENT_ESCALATION_FIELDS) {
36335
- if (field in block) {
36336
- delete block[field];
36337
- removed.push(field);
36338
- }
36339
- }
36340
- if (removed.length > 0) {
36341
- warnings.push(`Ignoring ${agentKey}.${removed.join("/")} from project config ` + "(security: a repository cannot reprogram or re-permission hidden agents).");
36342
- }
36632
+ stripNestedMuralModels(block, agentKey, nestedMuralRemoved);
36633
+ }
36634
+ if (nestedMuralRemoved.length > 0) {
36635
+ warnings.push(`Ignoring ${nestedMuralRemoved.join(", ")} from project config (security: the mural cue-compressor model is a user-level setting; a repository cannot choose where project memory is sent).`);
36343
36636
  }
36344
36637
  return warnings;
36345
36638
  }
@@ -36473,10 +36766,1755 @@ function dropInheritedEmbeddingKeyOnRedirect(projectRaw, mergedRaw, userRaw) {
36473
36766
  ];
36474
36767
  }
36475
36768
 
36769
+ // ../plugin/src/config/raw-loader.ts
36770
+ import {
36771
+ closeSync as closeSync2,
36772
+ existsSync as existsSync9,
36773
+ linkSync,
36774
+ openSync as openSync2,
36775
+ readFileSync as readFileSync8,
36776
+ renameSync as renameSync2,
36777
+ statSync as statSync6,
36778
+ unlinkSync as unlinkSync3,
36779
+ writeFileSync as writeFileSync2
36780
+ } from "node:fs";
36781
+ import { basename as basename3, dirname as dirname5, join as join6 } from "node:path";
36782
+
36783
+ // ../../node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js
36784
+ function createScanner(text, ignoreTrivia = false) {
36785
+ const len = text.length;
36786
+ let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
36787
+ function scanHexDigits(count, exact) {
36788
+ let digits = 0;
36789
+ let value2 = 0;
36790
+ while (digits < count || !exact) {
36791
+ let ch = text.charCodeAt(pos);
36792
+ if (ch >= 48 && ch <= 57) {
36793
+ value2 = value2 * 16 + ch - 48;
36794
+ } else if (ch >= 65 && ch <= 70) {
36795
+ value2 = value2 * 16 + ch - 65 + 10;
36796
+ } else if (ch >= 97 && ch <= 102) {
36797
+ value2 = value2 * 16 + ch - 97 + 10;
36798
+ } else {
36799
+ break;
36800
+ }
36801
+ pos++;
36802
+ digits++;
36803
+ }
36804
+ if (digits < count) {
36805
+ value2 = -1;
36806
+ }
36807
+ return value2;
36808
+ }
36809
+ function setPosition(newPosition) {
36810
+ pos = newPosition;
36811
+ value = "";
36812
+ tokenOffset = 0;
36813
+ token = 16;
36814
+ scanError = 0;
36815
+ }
36816
+ function scanNumber() {
36817
+ let start = pos;
36818
+ if (text.charCodeAt(pos) === 48) {
36819
+ pos++;
36820
+ } else {
36821
+ pos++;
36822
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
36823
+ pos++;
36824
+ }
36825
+ }
36826
+ if (pos < text.length && text.charCodeAt(pos) === 46) {
36827
+ pos++;
36828
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
36829
+ pos++;
36830
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
36831
+ pos++;
36832
+ }
36833
+ } else {
36834
+ scanError = 3;
36835
+ return text.substring(start, pos);
36836
+ }
36837
+ }
36838
+ let end = pos;
36839
+ if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
36840
+ pos++;
36841
+ if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) {
36842
+ pos++;
36843
+ }
36844
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
36845
+ pos++;
36846
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
36847
+ pos++;
36848
+ }
36849
+ end = pos;
36850
+ } else {
36851
+ scanError = 3;
36852
+ }
36853
+ }
36854
+ return text.substring(start, end);
36855
+ }
36856
+ function scanString() {
36857
+ let result = "", start = pos;
36858
+ while (true) {
36859
+ if (pos >= len) {
36860
+ result += text.substring(start, pos);
36861
+ scanError = 2;
36862
+ break;
36863
+ }
36864
+ const ch = text.charCodeAt(pos);
36865
+ if (ch === 34) {
36866
+ result += text.substring(start, pos);
36867
+ pos++;
36868
+ break;
36869
+ }
36870
+ if (ch === 92) {
36871
+ result += text.substring(start, pos);
36872
+ pos++;
36873
+ if (pos >= len) {
36874
+ scanError = 2;
36875
+ break;
36876
+ }
36877
+ const ch2 = text.charCodeAt(pos++);
36878
+ switch (ch2) {
36879
+ case 34:
36880
+ result += '"';
36881
+ break;
36882
+ case 92:
36883
+ result += "\\";
36884
+ break;
36885
+ case 47:
36886
+ result += "/";
36887
+ break;
36888
+ case 98:
36889
+ result += "\b";
36890
+ break;
36891
+ case 102:
36892
+ result += "\f";
36893
+ break;
36894
+ case 110:
36895
+ result += `
36896
+ `;
36897
+ break;
36898
+ case 114:
36899
+ result += "\r";
36900
+ break;
36901
+ case 116:
36902
+ result += "\t";
36903
+ break;
36904
+ case 117:
36905
+ const ch3 = scanHexDigits(4, true);
36906
+ if (ch3 >= 0) {
36907
+ result += String.fromCharCode(ch3);
36908
+ } else {
36909
+ scanError = 4;
36910
+ }
36911
+ break;
36912
+ default:
36913
+ scanError = 5;
36914
+ }
36915
+ start = pos;
36916
+ continue;
36917
+ }
36918
+ if (ch >= 0 && ch <= 31) {
36919
+ if (isLineBreak(ch)) {
36920
+ result += text.substring(start, pos);
36921
+ scanError = 2;
36922
+ break;
36923
+ } else {
36924
+ scanError = 6;
36925
+ }
36926
+ }
36927
+ pos++;
36928
+ }
36929
+ return result;
36930
+ }
36931
+ function scanNext() {
36932
+ value = "";
36933
+ scanError = 0;
36934
+ tokenOffset = pos;
36935
+ lineStartOffset = lineNumber;
36936
+ prevTokenLineStartOffset = tokenLineStartOffset;
36937
+ if (pos >= len) {
36938
+ tokenOffset = len;
36939
+ return token = 17;
36940
+ }
36941
+ let code = text.charCodeAt(pos);
36942
+ if (isWhiteSpace(code)) {
36943
+ do {
36944
+ pos++;
36945
+ value += String.fromCharCode(code);
36946
+ code = text.charCodeAt(pos);
36947
+ } while (isWhiteSpace(code));
36948
+ return token = 15;
36949
+ }
36950
+ if (isLineBreak(code)) {
36951
+ pos++;
36952
+ value += String.fromCharCode(code);
36953
+ if (code === 13 && text.charCodeAt(pos) === 10) {
36954
+ pos++;
36955
+ value += `
36956
+ `;
36957
+ }
36958
+ lineNumber++;
36959
+ tokenLineStartOffset = pos;
36960
+ return token = 14;
36961
+ }
36962
+ switch (code) {
36963
+ case 123:
36964
+ pos++;
36965
+ return token = 1;
36966
+ case 125:
36967
+ pos++;
36968
+ return token = 2;
36969
+ case 91:
36970
+ pos++;
36971
+ return token = 3;
36972
+ case 93:
36973
+ pos++;
36974
+ return token = 4;
36975
+ case 58:
36976
+ pos++;
36977
+ return token = 6;
36978
+ case 44:
36979
+ pos++;
36980
+ return token = 5;
36981
+ case 34:
36982
+ pos++;
36983
+ value = scanString();
36984
+ return token = 10;
36985
+ case 47:
36986
+ const start = pos - 1;
36987
+ if (text.charCodeAt(pos + 1) === 47) {
36988
+ pos += 2;
36989
+ while (pos < len) {
36990
+ if (isLineBreak(text.charCodeAt(pos))) {
36991
+ break;
36992
+ }
36993
+ pos++;
36994
+ }
36995
+ value = text.substring(start, pos);
36996
+ return token = 12;
36997
+ }
36998
+ if (text.charCodeAt(pos + 1) === 42) {
36999
+ pos += 2;
37000
+ const safeLength = len - 1;
37001
+ let commentClosed = false;
37002
+ while (pos < safeLength) {
37003
+ const ch = text.charCodeAt(pos);
37004
+ if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
37005
+ pos += 2;
37006
+ commentClosed = true;
37007
+ break;
37008
+ }
37009
+ pos++;
37010
+ if (isLineBreak(ch)) {
37011
+ if (ch === 13 && text.charCodeAt(pos) === 10) {
37012
+ pos++;
37013
+ }
37014
+ lineNumber++;
37015
+ tokenLineStartOffset = pos;
37016
+ }
37017
+ }
37018
+ if (!commentClosed) {
37019
+ pos++;
37020
+ scanError = 1;
37021
+ }
37022
+ value = text.substring(start, pos);
37023
+ return token = 13;
37024
+ }
37025
+ value += String.fromCharCode(code);
37026
+ pos++;
37027
+ return token = 16;
37028
+ case 45:
37029
+ value += String.fromCharCode(code);
37030
+ pos++;
37031
+ if (pos === len || !isDigit(text.charCodeAt(pos))) {
37032
+ return token = 16;
37033
+ }
37034
+ case 48:
37035
+ case 49:
37036
+ case 50:
37037
+ case 51:
37038
+ case 52:
37039
+ case 53:
37040
+ case 54:
37041
+ case 55:
37042
+ case 56:
37043
+ case 57:
37044
+ value += scanNumber();
37045
+ return token = 11;
37046
+ default:
37047
+ while (pos < len && isUnknownContentCharacter(code)) {
37048
+ pos++;
37049
+ code = text.charCodeAt(pos);
37050
+ }
37051
+ if (tokenOffset !== pos) {
37052
+ value = text.substring(tokenOffset, pos);
37053
+ switch (value) {
37054
+ case "true":
37055
+ return token = 8;
37056
+ case "false":
37057
+ return token = 9;
37058
+ case "null":
37059
+ return token = 7;
37060
+ }
37061
+ return token = 16;
37062
+ }
37063
+ value += String.fromCharCode(code);
37064
+ pos++;
37065
+ return token = 16;
37066
+ }
37067
+ }
37068
+ function isUnknownContentCharacter(code) {
37069
+ if (isWhiteSpace(code) || isLineBreak(code)) {
37070
+ return false;
37071
+ }
37072
+ switch (code) {
37073
+ case 125:
37074
+ case 93:
37075
+ case 123:
37076
+ case 91:
37077
+ case 34:
37078
+ case 58:
37079
+ case 44:
37080
+ case 47:
37081
+ return false;
37082
+ }
37083
+ return true;
37084
+ }
37085
+ function scanNextNonTrivia() {
37086
+ let result;
37087
+ do {
37088
+ result = scanNext();
37089
+ } while (result >= 12 && result <= 15);
37090
+ return result;
37091
+ }
37092
+ return {
37093
+ setPosition,
37094
+ getPosition: () => pos,
37095
+ scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
37096
+ getToken: () => token,
37097
+ getTokenValue: () => value,
37098
+ getTokenOffset: () => tokenOffset,
37099
+ getTokenLength: () => pos - tokenOffset,
37100
+ getTokenStartLine: () => lineStartOffset,
37101
+ getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,
37102
+ getTokenError: () => scanError
37103
+ };
37104
+ }
37105
+ function isWhiteSpace(ch) {
37106
+ return ch === 32 || ch === 9;
37107
+ }
37108
+ function isLineBreak(ch) {
37109
+ return ch === 10 || ch === 13;
37110
+ }
37111
+ function isDigit(ch) {
37112
+ return ch >= 48 && ch <= 57;
37113
+ }
37114
+ var CharacterCodes;
37115
+ (function(CharacterCodes2) {
37116
+ CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
37117
+ CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
37118
+ CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
37119
+ CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
37120
+ CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
37121
+ CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
37122
+ CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
37123
+ CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
37124
+ CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
37125
+ CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
37126
+ CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
37127
+ CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
37128
+ CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
37129
+ CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
37130
+ CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
37131
+ CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
37132
+ CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
37133
+ CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
37134
+ CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
37135
+ CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
37136
+ CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
37137
+ CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
37138
+ CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
37139
+ CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
37140
+ CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
37141
+ CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
37142
+ CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
37143
+ CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
37144
+ CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
37145
+ CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
37146
+ CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
37147
+ CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
37148
+ CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
37149
+ CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
37150
+ CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
37151
+ CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
37152
+ CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
37153
+ CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
37154
+ CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
37155
+ CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
37156
+ CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
37157
+ CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
37158
+ CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
37159
+ CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
37160
+ CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
37161
+ CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
37162
+ CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
37163
+ CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
37164
+ CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
37165
+ CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
37166
+ CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
37167
+ CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
37168
+ CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
37169
+ CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
37170
+ CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
37171
+ CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
37172
+ CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
37173
+ CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
37174
+ CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
37175
+ CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
37176
+ CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
37177
+ CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
37178
+ CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
37179
+ CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
37180
+ CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
37181
+ CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
37182
+ CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
37183
+ CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
37184
+ CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
37185
+ CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
37186
+ CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
37187
+ CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
37188
+ CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
37189
+ CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
37190
+ CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
37191
+ CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
37192
+ CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
37193
+ CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
37194
+ CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
37195
+ CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
37196
+ })(CharacterCodes || (CharacterCodes = {}));
37197
+
37198
+ // ../../node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js
37199
+ var cachedSpaces = new Array(20).fill(0).map((_, index) => {
37200
+ return " ".repeat(index);
37201
+ });
37202
+ var maxCachedValues = 200;
37203
+ var cachedBreakLinesWithSpaces = {
37204
+ " ": {
37205
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
37206
+ return `
37207
+ ` + " ".repeat(index);
37208
+ }),
37209
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
37210
+ return "\r" + " ".repeat(index);
37211
+ }),
37212
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
37213
+ return `\r
37214
+ ` + " ".repeat(index);
37215
+ })
37216
+ },
37217
+ "\t": {
37218
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
37219
+ return `
37220
+ ` + "\t".repeat(index);
37221
+ }),
37222
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
37223
+ return "\r" + "\t".repeat(index);
37224
+ }),
37225
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
37226
+ return `\r
37227
+ ` + "\t".repeat(index);
37228
+ })
37229
+ }
37230
+ };
37231
+ var supportedEols = [`
37232
+ `, "\r", `\r
37233
+ `];
37234
+
37235
+ // ../../node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/format.js
37236
+ function format(documentText, range, options) {
37237
+ let initialIndentLevel;
37238
+ let formatText;
37239
+ let formatTextStart;
37240
+ let rangeStart;
37241
+ let rangeEnd;
37242
+ if (range) {
37243
+ rangeStart = range.offset;
37244
+ rangeEnd = rangeStart + range.length;
37245
+ formatTextStart = rangeStart;
37246
+ while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
37247
+ formatTextStart--;
37248
+ }
37249
+ let endOffset = rangeEnd;
37250
+ while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
37251
+ endOffset++;
37252
+ }
37253
+ formatText = documentText.substring(formatTextStart, endOffset);
37254
+ initialIndentLevel = computeIndentLevel(formatText, options);
37255
+ } else {
37256
+ formatText = documentText;
37257
+ initialIndentLevel = 0;
37258
+ formatTextStart = 0;
37259
+ rangeStart = 0;
37260
+ rangeEnd = documentText.length;
37261
+ }
37262
+ const eol = getEOL(options, documentText);
37263
+ const eolFastPathSupported = supportedEols.includes(eol);
37264
+ let numberLineBreaks = 0;
37265
+ let indentLevel = 0;
37266
+ let indentValue;
37267
+ if (options.insertSpaces) {
37268
+ indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4);
37269
+ } else {
37270
+ indentValue = "\t";
37271
+ }
37272
+ const indentType = indentValue === "\t" ? "\t" : " ";
37273
+ let scanner = createScanner(formatText, false);
37274
+ let hasError = false;
37275
+ function newLinesAndIndent() {
37276
+ if (numberLineBreaks > 1) {
37277
+ return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);
37278
+ }
37279
+ const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);
37280
+ if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) {
37281
+ return eol + repeat(indentValue, initialIndentLevel + indentLevel);
37282
+ }
37283
+ if (amountOfSpaces <= 0) {
37284
+ return eol;
37285
+ }
37286
+ return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];
37287
+ }
37288
+ function scanNext() {
37289
+ let token = scanner.scan();
37290
+ numberLineBreaks = 0;
37291
+ while (token === 15 || token === 14) {
37292
+ if (token === 14 && options.keepLines) {
37293
+ numberLineBreaks += 1;
37294
+ } else if (token === 14) {
37295
+ numberLineBreaks = 1;
37296
+ }
37297
+ token = scanner.scan();
37298
+ }
37299
+ hasError = token === 16 || scanner.getTokenError() !== 0;
37300
+ return token;
37301
+ }
37302
+ const editOperations = [];
37303
+ function addEdit(text, startOffset, endOffset) {
37304
+ if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) {
37305
+ editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
37306
+ }
37307
+ }
37308
+ let firstToken = scanNext();
37309
+ if (options.keepLines && numberLineBreaks > 0) {
37310
+ addEdit(repeat(eol, numberLineBreaks), 0, 0);
37311
+ }
37312
+ if (firstToken !== 17) {
37313
+ let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
37314
+ let initialIndent = indentValue.length * initialIndentLevel < 20 && options.insertSpaces ? cachedSpaces[indentValue.length * initialIndentLevel] : repeat(indentValue, initialIndentLevel);
37315
+ addEdit(initialIndent, formatTextStart, firstTokenStart);
37316
+ }
37317
+ while (firstToken !== 17) {
37318
+ let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
37319
+ let secondToken = scanNext();
37320
+ let replaceContent = "";
37321
+ let needsLineBreak = false;
37322
+ while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
37323
+ let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
37324
+ addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);
37325
+ firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
37326
+ needsLineBreak = secondToken === 12;
37327
+ replaceContent = needsLineBreak ? newLinesAndIndent() : "";
37328
+ secondToken = scanNext();
37329
+ }
37330
+ if (secondToken === 2) {
37331
+ if (firstToken !== 1) {
37332
+ indentLevel--;
37333
+ }
37334
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) {
37335
+ replaceContent = newLinesAndIndent();
37336
+ } else if (options.keepLines) {
37337
+ replaceContent = cachedSpaces[1];
37338
+ }
37339
+ } else if (secondToken === 4) {
37340
+ if (firstToken !== 3) {
37341
+ indentLevel--;
37342
+ }
37343
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) {
37344
+ replaceContent = newLinesAndIndent();
37345
+ } else if (options.keepLines) {
37346
+ replaceContent = cachedSpaces[1];
37347
+ }
37348
+ } else {
37349
+ switch (firstToken) {
37350
+ case 3:
37351
+ case 1:
37352
+ indentLevel++;
37353
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
37354
+ replaceContent = newLinesAndIndent();
37355
+ } else {
37356
+ replaceContent = cachedSpaces[1];
37357
+ }
37358
+ break;
37359
+ case 5:
37360
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
37361
+ replaceContent = newLinesAndIndent();
37362
+ } else {
37363
+ replaceContent = cachedSpaces[1];
37364
+ }
37365
+ break;
37366
+ case 12:
37367
+ replaceContent = newLinesAndIndent();
37368
+ break;
37369
+ case 13:
37370
+ if (numberLineBreaks > 0) {
37371
+ replaceContent = newLinesAndIndent();
37372
+ } else if (!needsLineBreak) {
37373
+ replaceContent = cachedSpaces[1];
37374
+ }
37375
+ break;
37376
+ case 6:
37377
+ if (options.keepLines && numberLineBreaks > 0) {
37378
+ replaceContent = newLinesAndIndent();
37379
+ } else if (!needsLineBreak) {
37380
+ replaceContent = cachedSpaces[1];
37381
+ }
37382
+ break;
37383
+ case 10:
37384
+ if (options.keepLines && numberLineBreaks > 0) {
37385
+ replaceContent = newLinesAndIndent();
37386
+ } else if (secondToken === 6 && !needsLineBreak) {
37387
+ replaceContent = "";
37388
+ }
37389
+ break;
37390
+ case 7:
37391
+ case 8:
37392
+ case 9:
37393
+ case 11:
37394
+ case 2:
37395
+ case 4:
37396
+ if (options.keepLines && numberLineBreaks > 0) {
37397
+ replaceContent = newLinesAndIndent();
37398
+ } else {
37399
+ if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) {
37400
+ replaceContent = cachedSpaces[1];
37401
+ } else if (secondToken !== 5 && secondToken !== 17) {
37402
+ hasError = true;
37403
+ }
37404
+ }
37405
+ break;
37406
+ case 16:
37407
+ hasError = true;
37408
+ break;
37409
+ }
37410
+ if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) {
37411
+ replaceContent = newLinesAndIndent();
37412
+ }
37413
+ }
37414
+ if (secondToken === 17) {
37415
+ if (options.keepLines && numberLineBreaks > 0) {
37416
+ replaceContent = newLinesAndIndent();
37417
+ } else {
37418
+ replaceContent = options.insertFinalNewline ? eol : "";
37419
+ }
37420
+ }
37421
+ const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
37422
+ addEdit(replaceContent, firstTokenEnd, secondTokenStart);
37423
+ firstToken = secondToken;
37424
+ }
37425
+ return editOperations;
37426
+ }
37427
+ function repeat(s, count) {
37428
+ let result = "";
37429
+ for (let i = 0;i < count; i++) {
37430
+ result += s;
37431
+ }
37432
+ return result;
37433
+ }
37434
+ function computeIndentLevel(content, options) {
37435
+ let i = 0;
37436
+ let nChars = 0;
37437
+ const tabSize = options.tabSize || 4;
37438
+ while (i < content.length) {
37439
+ let ch = content.charAt(i);
37440
+ if (ch === cachedSpaces[1]) {
37441
+ nChars++;
37442
+ } else if (ch === "\t") {
37443
+ nChars += tabSize;
37444
+ } else {
37445
+ break;
37446
+ }
37447
+ i++;
37448
+ }
37449
+ return Math.floor(nChars / tabSize);
37450
+ }
37451
+ function getEOL(options, text) {
37452
+ for (let i = 0;i < text.length; i++) {
37453
+ const ch = text.charAt(i);
37454
+ if (ch === "\r") {
37455
+ if (i + 1 < text.length && text.charAt(i + 1) === `
37456
+ `) {
37457
+ return `\r
37458
+ `;
37459
+ }
37460
+ return "\r";
37461
+ } else if (ch === `
37462
+ `) {
37463
+ return `
37464
+ `;
37465
+ }
37466
+ }
37467
+ return options && options.eol || `
37468
+ `;
37469
+ }
37470
+ function isEOL(text, offset) {
37471
+ return `\r
37472
+ `.indexOf(text.charAt(offset)) !== -1;
37473
+ }
37474
+
37475
+ // ../../node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js
37476
+ var ParseOptions;
37477
+ (function(ParseOptions2) {
37478
+ ParseOptions2.DEFAULT = {
37479
+ allowTrailingComma: false
37480
+ };
37481
+ })(ParseOptions || (ParseOptions = {}));
37482
+ function parseTree(text, errors3 = [], options = ParseOptions.DEFAULT) {
37483
+ let currentParent = { type: "array", offset: -1, length: -1, children: [], parent: undefined };
37484
+ function ensurePropertyComplete(endOffset) {
37485
+ if (currentParent.type === "property") {
37486
+ currentParent.length = endOffset - currentParent.offset;
37487
+ currentParent = currentParent.parent;
37488
+ }
37489
+ }
37490
+ function onValue(valueNode) {
37491
+ currentParent.children.push(valueNode);
37492
+ return valueNode;
37493
+ }
37494
+ const visitor = {
37495
+ onObjectBegin: (offset) => {
37496
+ currentParent = onValue({ type: "object", offset, length: -1, parent: currentParent, children: [] });
37497
+ },
37498
+ onObjectProperty: (name, offset, length) => {
37499
+ currentParent = onValue({ type: "property", offset, length: -1, parent: currentParent, children: [] });
37500
+ currentParent.children.push({ type: "string", value: name, offset, length, parent: currentParent });
37501
+ },
37502
+ onObjectEnd: (offset, length) => {
37503
+ ensurePropertyComplete(offset + length);
37504
+ currentParent.length = offset + length - currentParent.offset;
37505
+ currentParent = currentParent.parent;
37506
+ ensurePropertyComplete(offset + length);
37507
+ },
37508
+ onArrayBegin: (offset, length) => {
37509
+ currentParent = onValue({ type: "array", offset, length: -1, parent: currentParent, children: [] });
37510
+ },
37511
+ onArrayEnd: (offset, length) => {
37512
+ currentParent.length = offset + length - currentParent.offset;
37513
+ currentParent = currentParent.parent;
37514
+ ensurePropertyComplete(offset + length);
37515
+ },
37516
+ onLiteralValue: (value, offset, length) => {
37517
+ onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });
37518
+ ensurePropertyComplete(offset + length);
37519
+ },
37520
+ onSeparator: (sep, offset, length) => {
37521
+ if (currentParent.type === "property") {
37522
+ if (sep === ":") {
37523
+ currentParent.colonOffset = offset;
37524
+ } else if (sep === ",") {
37525
+ ensurePropertyComplete(offset);
37526
+ }
37527
+ }
37528
+ },
37529
+ onError: (error51, offset, length) => {
37530
+ errors3.push({ error: error51, offset, length });
37531
+ }
37532
+ };
37533
+ visit(text, visitor, options);
37534
+ const result = currentParent.children[0];
37535
+ if (result) {
37536
+ delete result.parent;
37537
+ }
37538
+ return result;
37539
+ }
37540
+ function findNodeAtLocation(root, path3) {
37541
+ if (!root) {
37542
+ return;
37543
+ }
37544
+ let node = root;
37545
+ for (let segment of path3) {
37546
+ if (typeof segment === "string") {
37547
+ if (node.type !== "object" || !Array.isArray(node.children)) {
37548
+ return;
37549
+ }
37550
+ let found = false;
37551
+ for (const propertyNode of node.children) {
37552
+ if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
37553
+ node = propertyNode.children[1];
37554
+ found = true;
37555
+ break;
37556
+ }
37557
+ }
37558
+ if (!found) {
37559
+ return;
37560
+ }
37561
+ } else {
37562
+ const index = segment;
37563
+ if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
37564
+ return;
37565
+ }
37566
+ node = node.children[index];
37567
+ }
37568
+ }
37569
+ return node;
37570
+ }
37571
+ function getNodeValue(node) {
37572
+ switch (node.type) {
37573
+ case "array":
37574
+ return node.children.map(getNodeValue);
37575
+ case "object":
37576
+ const obj = Object.create(null);
37577
+ for (let prop of node.children) {
37578
+ const valueNode = prop.children[1];
37579
+ if (valueNode) {
37580
+ obj[prop.children[0].value] = getNodeValue(valueNode);
37581
+ }
37582
+ }
37583
+ return obj;
37584
+ case "null":
37585
+ case "string":
37586
+ case "number":
37587
+ case "boolean":
37588
+ return node.value;
37589
+ default:
37590
+ return;
37591
+ }
37592
+ }
37593
+ function visit(text, visitor, options = ParseOptions.DEFAULT) {
37594
+ const _scanner = createScanner(text, false);
37595
+ const _jsonPath = [];
37596
+ let suppressedCallbacks = 0;
37597
+ function toNoArgVisit(visitFunction) {
37598
+ return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
37599
+ }
37600
+ function toOneArgVisit(visitFunction) {
37601
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
37602
+ }
37603
+ function toOneArgVisitWithPath(visitFunction) {
37604
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
37605
+ }
37606
+ function toBeginVisit(visitFunction) {
37607
+ return visitFunction ? () => {
37608
+ if (suppressedCallbacks > 0) {
37609
+ suppressedCallbacks++;
37610
+ } else {
37611
+ let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());
37612
+ if (cbReturn === false) {
37613
+ suppressedCallbacks = 1;
37614
+ }
37615
+ }
37616
+ } : () => true;
37617
+ }
37618
+ function toEndVisit(visitFunction) {
37619
+ return visitFunction ? () => {
37620
+ if (suppressedCallbacks > 0) {
37621
+ suppressedCallbacks--;
37622
+ }
37623
+ if (suppressedCallbacks === 0) {
37624
+ visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());
37625
+ }
37626
+ } : () => true;
37627
+ }
37628
+ const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
37629
+ const disallowComments = options && options.disallowComments;
37630
+ const allowTrailingComma = options && options.allowTrailingComma;
37631
+ function scanNext() {
37632
+ while (true) {
37633
+ const token = _scanner.scan();
37634
+ switch (_scanner.getTokenError()) {
37635
+ case 4:
37636
+ handleError(14);
37637
+ break;
37638
+ case 5:
37639
+ handleError(15);
37640
+ break;
37641
+ case 3:
37642
+ handleError(13);
37643
+ break;
37644
+ case 1:
37645
+ if (!disallowComments) {
37646
+ handleError(11);
37647
+ }
37648
+ break;
37649
+ case 2:
37650
+ handleError(12);
37651
+ break;
37652
+ case 6:
37653
+ handleError(16);
37654
+ break;
37655
+ }
37656
+ switch (token) {
37657
+ case 12:
37658
+ case 13:
37659
+ if (disallowComments) {
37660
+ handleError(10);
37661
+ } else {
37662
+ onComment();
37663
+ }
37664
+ break;
37665
+ case 16:
37666
+ handleError(1);
37667
+ break;
37668
+ case 15:
37669
+ case 14:
37670
+ break;
37671
+ default:
37672
+ return token;
37673
+ }
37674
+ }
37675
+ }
37676
+ function handleError(error51, skipUntilAfter = [], skipUntil = []) {
37677
+ onError(error51);
37678
+ if (skipUntilAfter.length + skipUntil.length > 0) {
37679
+ let token = _scanner.getToken();
37680
+ while (token !== 17) {
37681
+ if (skipUntilAfter.indexOf(token) !== -1) {
37682
+ scanNext();
37683
+ break;
37684
+ } else if (skipUntil.indexOf(token) !== -1) {
37685
+ break;
37686
+ }
37687
+ token = scanNext();
37688
+ }
37689
+ }
37690
+ }
37691
+ function parseString(isValue) {
37692
+ const value = _scanner.getTokenValue();
37693
+ if (isValue) {
37694
+ onLiteralValue(value);
37695
+ } else {
37696
+ onObjectProperty(value);
37697
+ _jsonPath.push(value);
37698
+ }
37699
+ scanNext();
37700
+ return true;
37701
+ }
37702
+ function parseLiteral() {
37703
+ switch (_scanner.getToken()) {
37704
+ case 11:
37705
+ const tokenValue = _scanner.getTokenValue();
37706
+ let value = Number(tokenValue);
37707
+ if (isNaN(value)) {
37708
+ handleError(2);
37709
+ value = 0;
37710
+ }
37711
+ onLiteralValue(value);
37712
+ break;
37713
+ case 7:
37714
+ onLiteralValue(null);
37715
+ break;
37716
+ case 8:
37717
+ onLiteralValue(true);
37718
+ break;
37719
+ case 9:
37720
+ onLiteralValue(false);
37721
+ break;
37722
+ default:
37723
+ return false;
37724
+ }
37725
+ scanNext();
37726
+ return true;
37727
+ }
37728
+ function parseProperty() {
37729
+ if (_scanner.getToken() !== 10) {
37730
+ handleError(3, [], [2, 5]);
37731
+ return false;
37732
+ }
37733
+ parseString(false);
37734
+ if (_scanner.getToken() === 6) {
37735
+ onSeparator(":");
37736
+ scanNext();
37737
+ if (!parseValue()) {
37738
+ handleError(4, [], [2, 5]);
37739
+ }
37740
+ } else {
37741
+ handleError(5, [], [2, 5]);
37742
+ }
37743
+ _jsonPath.pop();
37744
+ return true;
37745
+ }
37746
+ function parseObject() {
37747
+ onObjectBegin();
37748
+ scanNext();
37749
+ let needsComma = false;
37750
+ while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
37751
+ if (_scanner.getToken() === 5) {
37752
+ if (!needsComma) {
37753
+ handleError(4, [], []);
37754
+ }
37755
+ onSeparator(",");
37756
+ scanNext();
37757
+ if (_scanner.getToken() === 2 && allowTrailingComma) {
37758
+ break;
37759
+ }
37760
+ } else if (needsComma) {
37761
+ handleError(6, [], []);
37762
+ }
37763
+ if (!parseProperty()) {
37764
+ handleError(4, [], [2, 5]);
37765
+ }
37766
+ needsComma = true;
37767
+ }
37768
+ onObjectEnd();
37769
+ if (_scanner.getToken() !== 2) {
37770
+ handleError(7, [2], []);
37771
+ } else {
37772
+ scanNext();
37773
+ }
37774
+ return true;
37775
+ }
37776
+ function parseArray() {
37777
+ onArrayBegin();
37778
+ scanNext();
37779
+ let isFirstElement = true;
37780
+ let needsComma = false;
37781
+ while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
37782
+ if (_scanner.getToken() === 5) {
37783
+ if (!needsComma) {
37784
+ handleError(4, [], []);
37785
+ }
37786
+ onSeparator(",");
37787
+ scanNext();
37788
+ if (_scanner.getToken() === 4 && allowTrailingComma) {
37789
+ break;
37790
+ }
37791
+ } else if (needsComma) {
37792
+ handleError(6, [], []);
37793
+ }
37794
+ if (isFirstElement) {
37795
+ _jsonPath.push(0);
37796
+ isFirstElement = false;
37797
+ } else {
37798
+ _jsonPath[_jsonPath.length - 1]++;
37799
+ }
37800
+ if (!parseValue()) {
37801
+ handleError(4, [], [4, 5]);
37802
+ }
37803
+ needsComma = true;
37804
+ }
37805
+ onArrayEnd();
37806
+ if (!isFirstElement) {
37807
+ _jsonPath.pop();
37808
+ }
37809
+ if (_scanner.getToken() !== 4) {
37810
+ handleError(8, [4], []);
37811
+ } else {
37812
+ scanNext();
37813
+ }
37814
+ return true;
37815
+ }
37816
+ function parseValue() {
37817
+ switch (_scanner.getToken()) {
37818
+ case 3:
37819
+ return parseArray();
37820
+ case 1:
37821
+ return parseObject();
37822
+ case 10:
37823
+ return parseString(true);
37824
+ default:
37825
+ return parseLiteral();
37826
+ }
37827
+ }
37828
+ scanNext();
37829
+ if (_scanner.getToken() === 17) {
37830
+ if (options.allowEmptyContent) {
37831
+ return true;
37832
+ }
37833
+ handleError(4, [], []);
37834
+ return false;
37835
+ }
37836
+ if (!parseValue()) {
37837
+ handleError(4, [], []);
37838
+ return false;
37839
+ }
37840
+ if (_scanner.getToken() !== 17) {
37841
+ handleError(9, [], []);
37842
+ }
37843
+ return true;
37844
+ }
37845
+ function getNodeType(value) {
37846
+ switch (typeof value) {
37847
+ case "boolean":
37848
+ return "boolean";
37849
+ case "number":
37850
+ return "number";
37851
+ case "string":
37852
+ return "string";
37853
+ case "object": {
37854
+ if (!value) {
37855
+ return "null";
37856
+ } else if (Array.isArray(value)) {
37857
+ return "array";
37858
+ }
37859
+ return "object";
37860
+ }
37861
+ default:
37862
+ return "null";
37863
+ }
37864
+ }
37865
+
37866
+ // ../../node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/edit.js
37867
+ function setProperty(text, originalPath, value, options) {
37868
+ const path3 = originalPath.slice();
37869
+ const errors3 = [];
37870
+ const root = parseTree(text, errors3);
37871
+ let parent = undefined;
37872
+ let lastSegment = undefined;
37873
+ while (path3.length > 0) {
37874
+ lastSegment = path3.pop();
37875
+ parent = findNodeAtLocation(root, path3);
37876
+ if (parent === undefined && value !== undefined) {
37877
+ if (typeof lastSegment === "string") {
37878
+ value = { [lastSegment]: value };
37879
+ } else {
37880
+ value = [value];
37881
+ }
37882
+ } else {
37883
+ break;
37884
+ }
37885
+ }
37886
+ if (!parent) {
37887
+ if (value === undefined) {
37888
+ throw new Error("Can not delete in empty document");
37889
+ }
37890
+ return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);
37891
+ } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
37892
+ const existing = findNodeAtLocation(parent, [lastSegment]);
37893
+ if (existing !== undefined) {
37894
+ if (value === undefined) {
37895
+ if (!existing.parent) {
37896
+ throw new Error("Malformed AST");
37897
+ }
37898
+ const propertyIndex = parent.children.indexOf(existing.parent);
37899
+ let removeBegin;
37900
+ let removeEnd = existing.parent.offset + existing.parent.length;
37901
+ if (propertyIndex > 0) {
37902
+ let previous = parent.children[propertyIndex - 1];
37903
+ removeBegin = previous.offset + previous.length;
37904
+ } else {
37905
+ removeBegin = parent.offset + 1;
37906
+ if (parent.children.length > 1) {
37907
+ let next = parent.children[1];
37908
+ removeEnd = next.offset;
37909
+ }
37910
+ }
37911
+ return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: "" }, options);
37912
+ } else {
37913
+ return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);
37914
+ }
37915
+ } else {
37916
+ if (value === undefined) {
37917
+ return [];
37918
+ }
37919
+ const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
37920
+ const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p) => p.children[0].value)) : parent.children.length;
37921
+ let edit;
37922
+ if (index > 0) {
37923
+ let previous = parent.children[index - 1];
37924
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
37925
+ } else if (parent.children.length === 0) {
37926
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty };
37927
+ } else {
37928
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty + "," };
37929
+ }
37930
+ return withFormatting(text, edit, options);
37931
+ }
37932
+ } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
37933
+ const insertIndex = lastSegment;
37934
+ if (insertIndex === -1) {
37935
+ const newProperty = `${JSON.stringify(value)}`;
37936
+ let edit;
37937
+ if (parent.children.length === 0) {
37938
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty };
37939
+ } else {
37940
+ const previous = parent.children[parent.children.length - 1];
37941
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
37942
+ }
37943
+ return withFormatting(text, edit, options);
37944
+ } else if (value === undefined && parent.children.length >= 0) {
37945
+ const removalIndex = lastSegment;
37946
+ const toRemove = parent.children[removalIndex];
37947
+ let edit;
37948
+ if (parent.children.length === 1) {
37949
+ edit = { offset: parent.offset + 1, length: parent.length - 2, content: "" };
37950
+ } else if (parent.children.length - 1 === removalIndex) {
37951
+ let previous = parent.children[removalIndex - 1];
37952
+ let offset = previous.offset + previous.length;
37953
+ let parentEndOffset = parent.offset + parent.length;
37954
+ edit = { offset, length: parentEndOffset - 2 - offset, content: "" };
37955
+ } else {
37956
+ edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: "" };
37957
+ }
37958
+ return withFormatting(text, edit, options);
37959
+ } else if (value !== undefined) {
37960
+ let edit;
37961
+ const newProperty = `${JSON.stringify(value)}`;
37962
+ if (!options.isArrayInsertion && parent.children.length > lastSegment) {
37963
+ const toModify = parent.children[lastSegment];
37964
+ edit = { offset: toModify.offset, length: toModify.length, content: newProperty };
37965
+ } else if (parent.children.length === 0 || lastSegment === 0) {
37966
+ edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + "," };
37967
+ } else {
37968
+ const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
37969
+ const previous = parent.children[index - 1];
37970
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
37971
+ }
37972
+ return withFormatting(text, edit, options);
37973
+ } else {
37974
+ throw new Error(`Can not ${value === undefined ? "remove" : options.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`);
37975
+ }
37976
+ } else {
37977
+ throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
37978
+ }
37979
+ }
37980
+ function withFormatting(text, edit, options) {
37981
+ if (!options.formattingOptions) {
37982
+ return [edit];
37983
+ }
37984
+ let newText = applyEdit(text, edit);
37985
+ let begin = edit.offset;
37986
+ let end = edit.offset + edit.content.length;
37987
+ if (edit.length === 0 || edit.content.length === 0) {
37988
+ while (begin > 0 && !isEOL(newText, begin - 1)) {
37989
+ begin--;
37990
+ }
37991
+ while (end < newText.length && !isEOL(newText, end)) {
37992
+ end++;
37993
+ }
37994
+ }
37995
+ const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false });
37996
+ for (let i = edits.length - 1;i >= 0; i--) {
37997
+ const edit2 = edits[i];
37998
+ newText = applyEdit(newText, edit2);
37999
+ begin = Math.min(begin, edit2.offset);
38000
+ end = Math.max(end, edit2.offset + edit2.length);
38001
+ end += edit2.content.length - edit2.length;
38002
+ }
38003
+ const editLength = text.length - (newText.length - end) - begin;
38004
+ return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
38005
+ }
38006
+ function applyEdit(text, edit) {
38007
+ return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
38008
+ }
38009
+
38010
+ // ../../node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js
38011
+ var createScanner2 = createScanner;
38012
+ var ScanError;
38013
+ (function(ScanError2) {
38014
+ ScanError2[ScanError2["None"] = 0] = "None";
38015
+ ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
38016
+ ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
38017
+ ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
38018
+ ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
38019
+ ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
38020
+ ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
38021
+ })(ScanError || (ScanError = {}));
38022
+ var SyntaxKind;
38023
+ (function(SyntaxKind2) {
38024
+ SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
38025
+ SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
38026
+ SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
38027
+ SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
38028
+ SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
38029
+ SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
38030
+ SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
38031
+ SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
38032
+ SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
38033
+ SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
38034
+ SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
38035
+ SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
38036
+ SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
38037
+ SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
38038
+ SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
38039
+ SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
38040
+ SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
38041
+ })(SyntaxKind || (SyntaxKind = {}));
38042
+ var parseTree2 = parseTree;
38043
+ var findNodeAtLocation2 = findNodeAtLocation;
38044
+ var getNodeValue2 = getNodeValue;
38045
+ var ParseErrorCode;
38046
+ (function(ParseErrorCode2) {
38047
+ ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
38048
+ ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
38049
+ ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
38050
+ ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
38051
+ ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
38052
+ ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
38053
+ ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
38054
+ ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
38055
+ ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
38056
+ ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
38057
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
38058
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
38059
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
38060
+ ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
38061
+ ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
38062
+ ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
38063
+ })(ParseErrorCode || (ParseErrorCode = {}));
38064
+ function modify(text, path3, value, options) {
38065
+ return setProperty(text, path3, value, options);
38066
+ }
38067
+ function applyEdits(text, edits) {
38068
+ let sortedEdits = edits.slice(0).sort((a, b) => {
38069
+ const diff = a.offset - b.offset;
38070
+ if (diff === 0) {
38071
+ return a.length - b.length;
38072
+ }
38073
+ return diff;
38074
+ });
38075
+ let lastModifiedOffset = text.length;
38076
+ for (let i = sortedEdits.length - 1;i >= 0; i--) {
38077
+ let e = sortedEdits[i];
38078
+ if (e.offset + e.length <= lastModifiedOffset) {
38079
+ text = applyEdit(text, e);
38080
+ } else {
38081
+ throw new Error("Overlapping edit");
38082
+ }
38083
+ lastModifiedOffset = e.offset;
38084
+ }
38085
+ return text;
38086
+ }
38087
+
38088
+ // ../plugin/src/shared/jsonc-edit.ts
38089
+ var TOKEN_COMMA = 5;
38090
+ var TOKEN_EOF = 17;
38091
+ function parseDocument(text) {
38092
+ const errors3 = [];
38093
+ const root = parseTree2(text, errors3, { allowTrailingComma: true });
38094
+ if (!root || errors3.length > 0) {
38095
+ throw new Error("Cannot edit invalid JSONC");
38096
+ }
38097
+ return root;
38098
+ }
38099
+ function findNode(text, path3) {
38100
+ return findNodeAtLocation2(parseDocument(text), path3);
38101
+ }
38102
+ function findComma(text, start, end) {
38103
+ const scanner = createScanner2(text, false);
38104
+ scanner.setPosition(start);
38105
+ for (;; ) {
38106
+ const kind = scanner.scan();
38107
+ const offset = scanner.getTokenOffset();
38108
+ if (kind === TOKEN_EOF || offset >= end)
38109
+ return;
38110
+ if (kind === TOKEN_COMMA) {
38111
+ return {
38112
+ offset,
38113
+ length: scanner.getTokenLength(),
38114
+ line: scanner.getTokenStartLine()
38115
+ };
38116
+ }
38117
+ }
38118
+ }
38119
+ function setJsoncValue(text, path3, value) {
38120
+ const node = findNode(text, path3);
38121
+ if (node) {
38122
+ if (Object.is(getNodeValue2(node), value))
38123
+ return text;
38124
+ const serialized = JSON.stringify(value);
38125
+ return text.slice(0, node.offset) + serialized + text.slice(node.offset + node.length);
38126
+ }
38127
+ return applyEdits(text, modify(text, path3, value, {}));
38128
+ }
38129
+ function removeObjectProperty(text, object2, key) {
38130
+ const properties = object2.children ?? [];
38131
+ const index = properties.findIndex((property2) => {
38132
+ const propertyKey = property2.children?.[0];
38133
+ return propertyKey !== undefined && getNodeValue2(propertyKey) === key;
38134
+ });
38135
+ if (index === -1)
38136
+ return text;
38137
+ const property = properties[index];
38138
+ if (!property)
38139
+ return text;
38140
+ const closingBrace = object2.offset + object2.length - 1;
38141
+ const next = properties[index + 1];
38142
+ if (next) {
38143
+ const followingComma = findComma(text, property.offset + property.length, next.offset);
38144
+ if (!followingComma)
38145
+ return text;
38146
+ return text.slice(0, property.offset) + text.slice(followingComma.offset + followingComma.length);
38147
+ }
38148
+ const previous = properties[index - 1];
38149
+ const trailingComma = findComma(text, property.offset + property.length, closingBrace);
38150
+ if (!previous) {
38151
+ const afterProperty2 = property.offset + property.length;
38152
+ if (!trailingComma)
38153
+ return text.slice(0, property.offset) + text.slice(afterProperty2);
38154
+ return text.slice(0, property.offset) + text.slice(afterProperty2, trailingComma.offset) + text.slice(trailingComma.offset + trailingComma.length);
38155
+ }
38156
+ const precedingComma = findComma(text, previous.offset + previous.length, property.offset);
38157
+ if (!precedingComma)
38158
+ return text;
38159
+ const afterProperty = property.offset + property.length;
38160
+ const withoutProperty = text.slice(0, precedingComma.offset) + text.slice(precedingComma.offset + precedingComma.length, property.offset) + text.slice(afterProperty);
38161
+ if (!trailingComma)
38162
+ return withoutProperty;
38163
+ const shiftedTrailingComma = trailingComma.offset - 1;
38164
+ return withoutProperty.slice(0, shiftedTrailingComma) + withoutProperty.slice(shiftedTrailingComma + trailingComma.length);
38165
+ }
38166
+ function removeJsoncValue(text, path3) {
38167
+ const key = path3.at(-1);
38168
+ if (typeof key !== "string")
38169
+ return text;
38170
+ const parent = findNode(text, path3.slice(0, -1));
38171
+ if (parent?.type !== "object")
38172
+ return text;
38173
+ return removeObjectProperty(text, parent, key);
38174
+ }
38175
+
38176
+ // ../plugin/src/config/raw-loader.ts
38177
+ var MODEL_FIELDS = ["model", "fallback_models"];
38178
+ var QUALIFIER_FIELDS = ["variant", "thinking_level"];
38179
+ var TASK_MODEL_FIELDS = [...MODEL_FIELDS, ...QUALIFIER_FIELDS, "timeout_minutes"];
38180
+ var PRE_PER_HARNESS_BACKUP_SUFFIX = ".pre-per-harness.bak";
38181
+ var temporaryFileSequence = 0;
38182
+ function isRecord2(value) {
38183
+ return typeof value === "object" && value !== null && !Array.isArray(value);
38184
+ }
38185
+ function asDocument(text) {
38186
+ try {
38187
+ const document = parseJsonc(text.startsWith("\uFEFF") ? text.slice(1) : text);
38188
+ return isRecord2(document) ? document : null;
38189
+ } catch {
38190
+ return null;
38191
+ }
38192
+ }
38193
+ function getAtPath(document, path3) {
38194
+ let current = document;
38195
+ for (const part of path3) {
38196
+ if (!isRecord2(current) || !Object.hasOwn(current, part))
38197
+ return;
38198
+ current = current[part];
38199
+ }
38200
+ return current;
38201
+ }
38202
+ function stableJson(value) {
38203
+ if (Array.isArray(value))
38204
+ return `[${value.map(stableJson).join(",")}]`;
38205
+ if (!isRecord2(value))
38206
+ return JSON.stringify(value);
38207
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(",")}}`;
38208
+ }
38209
+ function valuesMatch(left, right) {
38210
+ return stableJson(left) === stableJson(right);
38211
+ }
38212
+ function valueForDiagnostic(value) {
38213
+ return stableJson(value);
38214
+ }
38215
+ function migrateEntryForHarness(value, harness) {
38216
+ if (Array.isArray(value))
38217
+ return value.map((entry2) => migrateEntryForHarness(entry2, harness));
38218
+ if (!isRecord2(value) || !Object.hasOwn(value, "model"))
38219
+ return value;
38220
+ const entry = { model: value.model };
38221
+ if (harness === "opencode" && Object.hasOwn(value, "variant")) {
38222
+ entry.variant = value.variant;
38223
+ }
38224
+ if (harness === "pi" && Object.hasOwn(value, "thinking_level")) {
38225
+ entry.thinking_level = value.thinking_level;
38226
+ }
38227
+ return entry;
38228
+ }
38229
+ function migrateFallbackForHarness(value, harness) {
38230
+ if (typeof value === "string")
38231
+ return [value];
38232
+ return migrateEntryForHarness(value, harness);
38233
+ }
38234
+ function canCreateAtPath(document, path3) {
38235
+ let current = document;
38236
+ for (const part of path3) {
38237
+ if (current === undefined)
38238
+ return true;
38239
+ if (!isRecord2(current))
38240
+ return false;
38241
+ current = current[part];
38242
+ }
38243
+ return current === undefined || isRecord2(current);
38244
+ }
38245
+ function flatFieldPath(parts) {
38246
+ return parts.join(".");
38247
+ }
38248
+ function updateDocumentForFlatFields(text) {
38249
+ const hasBom = text.startsWith("\uFEFF");
38250
+ const editableText = hasBom ? text.slice(1) : text;
38251
+ const document = asDocument(text);
38252
+ if (!document) {
38253
+ return { text, hasFlatKeys: false, diagnostics: [], flatPaths: [] };
38254
+ }
38255
+ let nextText = editableText;
38256
+ let hasFlatKeys = false;
38257
+ const diagnostics = [];
38258
+ const flatPaths = [];
38259
+ const sourcePathsToRemove = [];
38260
+ const addDestination = (sourcePath, destinationPath, destinationValue) => {
38261
+ const sourceLabel = flatFieldPath(sourcePath);
38262
+ const destinationLabel = flatFieldPath(destinationPath);
38263
+ if (!canCreateAtPath(document, destinationPath.slice(0, -1))) {
38264
+ diagnostics.push({
38265
+ path: sourceLabel,
38266
+ message: `Flat config field "${sourceLabel}" (${valueForDiagnostic(destinationValue)}) conflicts with non-object destination "${destinationLabel}" (${valueForDiagnostic(getAtPath(document, destinationPath.slice(0, -1)))}); kept the destination and ignored the flat field.`
38267
+ });
38268
+ return;
38269
+ }
38270
+ const existing = getAtPath(document, destinationPath);
38271
+ if (existing !== undefined) {
38272
+ if (!valuesMatch(existing, destinationValue)) {
38273
+ diagnostics.push({
38274
+ path: sourceLabel,
38275
+ message: `Flat config field "${sourceLabel}" (${valueForDiagnostic(destinationValue)}) conflicts with "${destinationLabel}" (${valueForDiagnostic(existing)}); kept "${destinationLabel}" and ignored the flat field.`
38276
+ });
38277
+ }
38278
+ return;
38279
+ }
38280
+ nextText = setJsoncValue(nextText, destinationPath, destinationValue);
38281
+ };
38282
+ const migrateAgentFields = (agentName) => {
38283
+ const agent = document[agentName];
38284
+ if (!isRecord2(agent))
38285
+ return;
38286
+ for (const field of MODEL_FIELDS) {
38287
+ if (!Object.hasOwn(agent, field))
38288
+ continue;
38289
+ const sourcePath = [agentName, field];
38290
+ hasFlatKeys = true;
38291
+ flatPaths.push(flatFieldPath(sourcePath));
38292
+ sourcePathsToRemove.push(sourcePath);
38293
+ const migrateValue = field === "fallback_models" ? migrateFallbackForHarness : migrateEntryForHarness;
38294
+ addDestination(sourcePath, [agentName, "opencode", field], migrateValue(agent[field], "opencode"));
38295
+ addDestination(sourcePath, [agentName, "pi", field], migrateValue(agent[field], "pi"));
38296
+ }
38297
+ if (Object.hasOwn(agent, "variant")) {
38298
+ const sourcePath = [agentName, "variant"];
38299
+ hasFlatKeys = true;
38300
+ flatPaths.push(flatFieldPath(sourcePath));
38301
+ sourcePathsToRemove.push(sourcePath);
38302
+ addDestination(sourcePath, [agentName, "opencode", "variant"], agent.variant);
38303
+ }
38304
+ if (Object.hasOwn(agent, "thinking_level")) {
38305
+ const sourcePath = [agentName, "thinking_level"];
38306
+ hasFlatKeys = true;
38307
+ flatPaths.push(flatFieldPath(sourcePath));
38308
+ sourcePathsToRemove.push(sourcePath);
38309
+ addDestination(sourcePath, [agentName, "pi", "thinking_level"], agent.thinking_level);
38310
+ }
38311
+ };
38312
+ migrateAgentFields("historian");
38313
+ migrateAgentFields("dreamer");
38314
+ const dreamer = document.dreamer;
38315
+ const tasks = isRecord2(dreamer) ? dreamer.tasks : undefined;
38316
+ if (isRecord2(tasks)) {
38317
+ for (const taskName of Object.keys(tasks).sort()) {
38318
+ const task = tasks[taskName];
38319
+ if (!isRecord2(task))
38320
+ continue;
38321
+ for (const field of TASK_MODEL_FIELDS) {
38322
+ if (!Object.hasOwn(task, field))
38323
+ continue;
38324
+ const sourcePath = ["dreamer", "tasks", taskName, field];
38325
+ hasFlatKeys = true;
38326
+ flatPaths.push(flatFieldPath(sourcePath));
38327
+ sourcePathsToRemove.push(sourcePath);
38328
+ if (field === "model" || field === "fallback_models") {
38329
+ addDestination(sourcePath, ["dreamer", "opencode", "tasks", taskName, field], field === "fallback_models" ? migrateFallbackForHarness(task[field], "opencode") : migrateEntryForHarness(task[field], "opencode"));
38330
+ addDestination(sourcePath, ["dreamer", "pi", "tasks", taskName, field], field === "fallback_models" ? migrateFallbackForHarness(task[field], "pi") : migrateEntryForHarness(task[field], "pi"));
38331
+ } else if (field === "variant") {
38332
+ addDestination(sourcePath, ["dreamer", "opencode", "tasks", taskName, field], task[field]);
38333
+ } else if (field === "thinking_level") {
38334
+ addDestination(sourcePath, ["dreamer", "pi", "tasks", taskName, field], task[field]);
38335
+ } else {
38336
+ addDestination(sourcePath, ["dreamer", "opencode", "tasks", taskName, field], task[field]);
38337
+ addDestination(sourcePath, ["dreamer", "pi", "tasks", taskName, field], task[field]);
38338
+ }
38339
+ }
38340
+ }
38341
+ }
38342
+ for (const sourcePath of sourcePathsToRemove) {
38343
+ nextText = removeJsoncValue(nextText, sourcePath);
38344
+ }
38345
+ return {
38346
+ text: hasBom ? `\uFEFF${nextText}` : nextText,
38347
+ hasFlatKeys,
38348
+ diagnostics,
38349
+ flatPaths
38350
+ };
38351
+ }
38352
+ function hasFlatKeys(input) {
38353
+ const text = typeof input === "string" ? input : input.toString("utf-8");
38354
+ return updateDocumentForFlatFields(text).hasFlatKeys;
38355
+ }
38356
+ function migrateFlatDetailed(input) {
38357
+ const bytes = typeof input === "string" ? Buffer.from(input, "utf-8") : input;
38358
+ const result = updateDocumentForFlatFields(bytes.toString("utf-8"));
38359
+ return {
38360
+ bytes: Buffer.from(result.text, "utf-8"),
38361
+ hasFlatKeys: result.hasFlatKeys,
38362
+ diagnostics: result.diagnostics
38363
+ };
38364
+ }
38365
+ function writeExclusiveBackup(backupPath, bytes, mode) {
38366
+ const temporaryPath = writeTemporaryCandidate(backupPath, bytes, mode);
38367
+ try {
38368
+ try {
38369
+ linkSync(temporaryPath, backupPath);
38370
+ return;
38371
+ } catch (error51) {
38372
+ if (error51.code !== "EEXIST")
38373
+ throw error51;
38374
+ }
38375
+ const existingBytes = readFileSync8(backupPath);
38376
+ if (existingBytes.equals(bytes))
38377
+ return;
38378
+ if (bytes.subarray(0, existingBytes.length).equals(existingBytes)) {
38379
+ renameSync2(temporaryPath, backupPath);
38380
+ return;
38381
+ }
38382
+ } finally {
38383
+ try {
38384
+ unlinkSync3(temporaryPath);
38385
+ } catch {}
38386
+ }
38387
+ }
38388
+ function writeTemporaryCandidate(configPath, bytes, mode) {
38389
+ const directory = dirname5(configPath);
38390
+ const stem = basename3(configPath);
38391
+ for (let attempt = 0;attempt < 32; attempt++) {
38392
+ temporaryFileSequence += 1;
38393
+ const path3 = join6(directory, `.${stem}.per-harness-${process.pid}-${temporaryFileSequence}.tmp`);
38394
+ let descriptor;
38395
+ try {
38396
+ descriptor = openSync2(path3, "wx", mode);
38397
+ writeFileSync2(descriptor, bytes);
38398
+ closeSync2(descriptor);
38399
+ return path3;
38400
+ } catch (error51) {
38401
+ if (descriptor !== undefined) {
38402
+ try {
38403
+ closeSync2(descriptor);
38404
+ } catch {}
38405
+ }
38406
+ try {
38407
+ unlinkSync3(path3);
38408
+ } catch {}
38409
+ if (error51.code !== "EEXIST")
38410
+ throw error51;
38411
+ }
38412
+ }
38413
+ throw new Error(`Could not allocate a temporary config file beside ${configPath}`);
38414
+ }
38415
+ function migrationWarning(diagnostic) {
38416
+ return diagnostic.message;
38417
+ }
38418
+ function loadRawConfigFile(options) {
38419
+ if (!existsSync9(options.configPath))
38420
+ return null;
38421
+ let observedBytes;
38422
+ try {
38423
+ observedBytes = readFileSync8(options.configPath);
38424
+ } catch (error51) {
38425
+ throw new Error(`failed to read config: ${error51 instanceof Error ? error51.message : String(error51)}`);
38426
+ }
38427
+ const initialMigration = migrateFlatDetailed(observedBytes);
38428
+ if (!initialMigration.hasFlatKeys) {
38429
+ return {
38430
+ configPath: options.configPath,
38431
+ bytes: observedBytes,
38432
+ text: observedBytes.toString("utf-8"),
38433
+ warnings: [],
38434
+ migrated: false
38435
+ };
38436
+ }
38437
+ if (options.tier === "project") {
38438
+ return {
38439
+ configPath: options.configPath,
38440
+ bytes: initialMigration.bytes,
38441
+ text: initialMigration.bytes.toString("utf-8"),
38442
+ warnings: [
38443
+ "Adapted flat model config in memory; use historian.opencode/historian.pi and dreamer.opencode/dreamer.pi instead. Project config files are never rewritten.",
38444
+ ...initialMigration.diagnostics.map(migrationWarning)
38445
+ ],
38446
+ migrated: false
38447
+ };
38448
+ }
38449
+ const backupPath = `${options.configPath}${PRE_PER_HARNESS_BACKUP_SUFFIX}`;
38450
+ for (;; ) {
38451
+ const migration = migrateFlatDetailed(observedBytes);
38452
+ if (!migration.hasFlatKeys) {
38453
+ return {
38454
+ configPath: options.configPath,
38455
+ bytes: observedBytes,
38456
+ text: observedBytes.toString("utf-8"),
38457
+ warnings: [],
38458
+ migrated: false
38459
+ };
38460
+ }
38461
+ let temporaryPath;
38462
+ try {
38463
+ const mode = statSync6(options.configPath).mode & 511;
38464
+ writeExclusiveBackup(backupPath, observedBytes, mode);
38465
+ temporaryPath = writeTemporaryCandidate(options.configPath, migration.bytes, mode);
38466
+ options.afterTemporaryWrite?.();
38467
+ const currentBytes = readFileSync8(options.configPath);
38468
+ if (!hasFlatKeys(currentBytes)) {
38469
+ unlinkSync3(temporaryPath);
38470
+ return {
38471
+ configPath: options.configPath,
38472
+ bytes: currentBytes,
38473
+ text: currentBytes.toString("utf-8"),
38474
+ warnings: [],
38475
+ migrated: false
38476
+ };
38477
+ }
38478
+ if (!currentBytes.equals(observedBytes)) {
38479
+ unlinkSync3(temporaryPath);
38480
+ observedBytes = currentBytes;
38481
+ continue;
38482
+ }
38483
+ renameSync2(temporaryPath, options.configPath);
38484
+ return {
38485
+ configPath: options.configPath,
38486
+ bytes: migration.bytes,
38487
+ text: migration.bytes.toString("utf-8"),
38488
+ warnings: [
38489
+ "Migrated flat historian/dreamer model config to per-harness blocks.",
38490
+ ...migration.diagnostics.map(migrationWarning)
38491
+ ],
38492
+ migrated: true
38493
+ };
38494
+ } catch (error51) {
38495
+ if (temporaryPath) {
38496
+ try {
38497
+ unlinkSync3(temporaryPath);
38498
+ } catch {}
38499
+ }
38500
+ return {
38501
+ configPath: options.configPath,
38502
+ bytes: observedBytes,
38503
+ text: observedBytes.toString("utf-8"),
38504
+ warnings: [
38505
+ `Could not migrate flat model config: ${error51 instanceof Error ? error51.message : String(error51)}. Flat fields were not applied.`,
38506
+ ...migration.diagnostics.map(migrationWarning)
38507
+ ],
38508
+ migrated: false
38509
+ };
38510
+ }
38511
+ }
38512
+ }
38513
+
36476
38514
  // ../plugin/src/config/variable.ts
36477
- import { existsSync as existsSync9, readFileSync as readFileSync8 } from "node:fs";
38515
+ import { existsSync as existsSync10, readFileSync as readFileSync9 } from "node:fs";
36478
38516
  import { homedir as homedir5 } from "node:os";
36479
- import { dirname as dirname5, isAbsolute as isAbsolute3, resolve as resolve4 } from "node:path";
38517
+ import { dirname as dirname6, isAbsolute as isAbsolute3, resolve as resolve4 } from "node:path";
36480
38518
  var ENV_PATTERN = /\{env:([^}]+)\}/g;
36481
38519
  var FILE_PATTERN = /\{file:([^}]+)\}/g;
36482
38520
  function sensitiveFilePathReason(resolvedPath) {
@@ -36525,7 +38563,7 @@ function substituteConfigVariables(input) {
36525
38563
  if (fileMatches.length === 0) {
36526
38564
  return { text, warnings };
36527
38565
  }
36528
- const configDir = input.configPath ? dirname5(input.configPath) : process.cwd();
38566
+ const configDir = input.configPath ? dirname6(input.configPath) : process.cwd();
36529
38567
  let output = "";
36530
38568
  let cursor = 0;
36531
38569
  for (const match of fileMatches) {
@@ -36551,13 +38589,13 @@ function substituteConfigVariables(input) {
36551
38589
  if (sensitiveReason) {
36552
38590
  warnings.push(`${token} resolves to a sensitive path (${sensitiveReason}: ${filePath}); ` + "inlining its contents into config — make sure this is intentional.");
36553
38591
  }
36554
- if (!existsSync9(filePath)) {
38592
+ if (!existsSync10(filePath)) {
36555
38593
  warnings.push(`File not found for ${token} (resolved to ${filePath}); using empty string`);
36556
38594
  continue;
36557
38595
  }
36558
38596
  let contents;
36559
38597
  try {
36560
- contents = readFileSync8(filePath, "utf-8").trim();
38598
+ contents = readFileSync9(filePath, "utf-8").trim();
36561
38599
  } catch (error51) {
36562
38600
  const message = error51 instanceof Error ? error51.message : String(error51);
36563
38601
  warnings.push(`Failed to read file for ${token} (${filePath}): ${message}; using empty string`);
@@ -36570,12 +38608,12 @@ function substituteConfigVariables(input) {
36570
38608
  }
36571
38609
 
36572
38610
  // ../plugin/src/shared/models-dev-cache.ts
36573
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync10, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
36574
- import { join as join7 } from "node:path";
38611
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync11, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
38612
+ import { join as join8 } from "node:path";
36575
38613
 
36576
38614
  // ../plugin/src/shared/window-geometry.ts
36577
- import { readFileSync as readFileSync9 } from "node:fs";
36578
- import { join as join6 } from "node:path";
38615
+ import { readFileSync as readFileSync10 } from "node:fs";
38616
+ import { join as join7 } from "node:path";
36579
38617
  var WINDOW_OVERLAY_SCHEMA = "fusiform-window-overlay/v1";
36580
38618
  var PROMPT_WALL_MARGIN = 4096;
36581
38619
  var PI_OUTPUT_FLOOR = 4096;
@@ -36615,7 +38653,7 @@ var configuredOverlayPath;
36615
38653
  var loadedOverlayPath;
36616
38654
  var loadedOverlay;
36617
38655
  var geometryClampLogSeen = new Set;
36618
- function isRecord2(value) {
38656
+ function isRecord3(value) {
36619
38657
  return typeof value === "object" && value !== null && !Array.isArray(value);
36620
38658
  }
36621
38659
  function isFinitePositive(value) {
@@ -36630,7 +38668,7 @@ function scalarizeFact(value) {
36630
38668
  return;
36631
38669
  }
36632
38670
  function parseFactValue(value) {
36633
- if (!isRecord2(value) || typeof value.kind !== "string")
38671
+ if (!isRecord3(value) || typeof value.kind !== "string")
36634
38672
  return;
36635
38673
  if (value.kind === "stated") {
36636
38674
  if ((typeof value.value !== "number" || !Number.isFinite(value.value)) && typeof value.value !== "string") {
@@ -36662,7 +38700,7 @@ function parseFactValue(value) {
36662
38700
  return;
36663
38701
  }
36664
38702
  function parseFact(key, value) {
36665
- if (!isRecord2(value))
38703
+ if (!isRecord3(value))
36666
38704
  return;
36667
38705
  const parsedValue = parseFactValue(value.value);
36668
38706
  if (!parsedValue || !GRADES.has(value.grade) || !UNITS.has(value.units) || !BOUNDARIES.has(value.boundary) || typeof value.source_ref !== "string" || value.source_ref.length === 0 || typeof value.observed_at !== "string" || value.observed_at.length === 0) {
@@ -36685,7 +38723,7 @@ function parseFact(key, value) {
36685
38723
  };
36686
38724
  }
36687
38725
  function parseWindowOverlay(value) {
36688
- if (!isRecord2(value)) {
38726
+ if (!isRecord3(value)) {
36689
38727
  return { badCells: 0, refusal: "overlay root is not an object" };
36690
38728
  }
36691
38729
  if (value.schema !== WINDOW_OVERLAY_SCHEMA) {
@@ -36700,7 +38738,7 @@ function parseWindowOverlay(value) {
36700
38738
  const cells = [];
36701
38739
  let badCells = 0;
36702
38740
  for (const rawCell of value.cells) {
36703
- if (!isRecord2(rawCell) || typeof rawCell.provider_id !== "string" || rawCell.provider_id.length === 0 || typeof rawCell.model_id !== "string" || rawCell.model_id.length === 0 || !isRecord2(rawCell.facts)) {
38741
+ if (!isRecord3(rawCell) || typeof rawCell.provider_id !== "string" || rawCell.provider_id.length === 0 || typeof rawCell.model_id !== "string" || rawCell.model_id.length === 0 || !isRecord3(rawCell.facts)) {
36704
38742
  badCells++;
36705
38743
  continue;
36706
38744
  }
@@ -36735,12 +38773,12 @@ function parseWindowOverlay(value) {
36735
38773
  };
36736
38774
  }
36737
38775
  function defaultWindowOverlayPath() {
36738
- return join6(getDataDir(), "fusiform", "window-overlay.json");
38776
+ return join7(getDataDir(), "fusiform", "window-overlay.json");
36739
38777
  }
36740
38778
  function readWindowOverlayFile(path3, log2 = (message) => sessionLog("global", message)) {
36741
38779
  let raw;
36742
38780
  try {
36743
- raw = readFileSync9(path3, "utf8");
38781
+ raw = readFileSync10(path3, "utf8");
36744
38782
  } catch (error51) {
36745
38783
  if (error51.code === "ENOENT")
36746
38784
  return;
@@ -36966,14 +39004,14 @@ var reserveClampLogSeen = new Set;
36966
39004
  var apiCache = null;
36967
39005
  var persistSeedLoaded = false;
36968
39006
  function persistFilePath() {
36969
- return join7(getMagicContextStorageDir(), `model-context-limits-${getHarness()}.json`);
39007
+ return join8(getMagicContextStorageDir(), `model-context-limits-${getHarness()}.json`);
36970
39008
  }
36971
39009
  function loadPersistedApiCacheOnce() {
36972
39010
  if (persistSeedLoaded || apiCache !== null)
36973
39011
  return;
36974
39012
  persistSeedLoaded = true;
36975
39013
  try {
36976
- const raw = readFileSync10(persistFilePath(), "utf-8");
39014
+ const raw = readFileSync11(persistFilePath(), "utf-8");
36977
39015
  const obj = JSON.parse(raw);
36978
39016
  const map2 = new Map;
36979
39017
  for (const [key, persisted] of Object.entries(obj)) {
@@ -37143,16 +39181,18 @@ function getUserConfigPaths() {
37143
39181
  return [`${basePath}.jsonc`, `${basePath}.json`];
37144
39182
  }
37145
39183
  function resolveFirstExisting(paths) {
37146
- return paths.find((path3) => existsSync10(path3));
39184
+ return paths.find((path3) => existsSync11(path3));
37147
39185
  }
37148
39186
  function resolvePiLegacyFallback(sources) {
37149
- return sources.find((source) => existsSync10(source.path)) ?? null;
39187
+ return sources.find((source) => existsSync11(source.path)) ?? null;
37150
39188
  }
37151
39189
  function loadConfigFile(path3, scope) {
37152
39190
  try {
37153
- const rawText = readFileSync11(path3, "utf-8");
39191
+ const raw = loadRawConfigFile({ configPath: path3, tier: scope });
39192
+ if (!raw)
39193
+ return null;
37154
39194
  const substituted = substituteConfigVariables({
37155
- text: rawText,
39195
+ text: raw.text,
37156
39196
  configPath: path3,
37157
39197
  isProjectConfig: scope === "project"
37158
39198
  });
@@ -37163,7 +39203,11 @@ function loadConfigFile(path3, scope) {
37163
39203
  path: path3,
37164
39204
  scope,
37165
39205
  config: config2,
37166
- warnings: [...substituted.warnings, ...unsafeKeyWarnings].map((warning) => `${path3}: ${warning}`),
39206
+ warnings: [
39207
+ ...raw.warnings,
39208
+ ...substituted.warnings,
39209
+ ...unsafeKeyWarnings
39210
+ ].map((warning) => `${path3}: ${warning}`),
37167
39211
  loadOutcome: rejectedKeyPaths.length > 0 ? "schema-recovery" : substituted.warnings.length > 0 ? "substitution-failure" : "ok"
37168
39212
  };
37169
39213
  } catch (error51) {
@@ -37244,7 +39288,13 @@ function parsePiConfig(rawConfig, recoveredTopLevelKeys = []) {
37244
39288
  const key = String(topKey);
37245
39289
  errorPaths.add(key);
37246
39290
  const paths = issuePathsByKey.get(key) ?? [];
37247
- paths.push([...issue2.path]);
39291
+ if (issue2.code === "unrecognized_keys") {
39292
+ for (const unrecognizedKey of issue2.keys) {
39293
+ paths.push([...issue2.path, unrecognizedKey]);
39294
+ }
39295
+ } else {
39296
+ paths.push([...issue2.path]);
39297
+ }
37248
39298
  issuePathsByKey.set(key, paths);
37249
39299
  }
37250
39300
  }
@@ -37253,11 +39303,6 @@ function parsePiConfig(rawConfig, recoveredTopLevelKeys = []) {
37253
39303
  for (const key of errorPaths) {
37254
39304
  recoveredTopLevelKeys.push(key);
37255
39305
  const isAgentConfig = key === "historian" || key === "dreamer" || key === "sidekick";
37256
- if (isAgentConfig) {
37257
- delete patched[key];
37258
- warnings.push(`"${key}": invalid agent configuration, ignoring. Check your magic-context.jsonc.`);
37259
- continue;
37260
- }
37261
39306
  const issuePaths = issuePathsByKey.get(key) ?? [];
37262
39307
  const rawValue = migrated[key];
37263
39308
  const allNested = issuePaths.length > 0 && issuePaths.every((p) => p.length >= 2) && typeof rawValue === "object" && rawValue !== null && !Array.isArray(rawValue);
@@ -37274,8 +39319,15 @@ function parsePiConfig(rawConfig, recoveredTopLevelKeys = []) {
37274
39319
  prunedLeaves.push(result.removed);
37275
39320
  }
37276
39321
  }
37277
- patched[key] = prunedBlock;
37278
- warnings.push(`"${key}": invalid nested field(s) ${prunedLeaves.map((l) => `"${l}"`).join(", ")}, using defaults for those.`);
39322
+ if (prunedLeaves.length === issuePaths.length) {
39323
+ patched[key] = prunedBlock;
39324
+ warnings.push(`"${key}": invalid nested field(s) ${prunedLeaves.map((leaf) => `"${key}.${leaf}"`).join(", ")}, using defaults for those.`);
39325
+ continue;
39326
+ }
39327
+ }
39328
+ if (isAgentConfig) {
39329
+ delete patched[key];
39330
+ warnings.push(`"${key}": invalid agent configuration, ignoring. Check your magic-context.jsonc.`);
37279
39331
  continue;
37280
39332
  }
37281
39333
  delete patched[key];
@@ -37303,7 +39355,7 @@ function loadPiConfig(opts = {}) {
37303
39355
  if (loaded)
37304
39356
  loadedFiles.push(loaded);
37305
39357
  }
37306
- const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync10(source.path));
39358
+ const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync11(source.path));
37307
39359
  const userPath = resolveFirstExisting(getUserConfigPaths());
37308
39360
  const userLegacyFallback = userPath ? null : resolvePiLegacyFallback(harnessLegacy.user);
37309
39361
  const userReadPath = userPath ?? userLegacyFallback?.path;
@@ -37312,7 +39364,7 @@ function loadPiConfig(opts = {}) {
37312
39364
  if (loaded)
37313
39365
  loadedFiles.push(loaded);
37314
39366
  }
37315
- const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync10(source.path));
39367
+ const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync11(source.path));
37316
39368
  if (userLegacyFallback) {
37317
39369
  warnings.push(`[user config] reading legacy config from ${userLegacyFallback.path} until migration completes; run \`npx @cortexkit/magic-context doctor\` to consolidate into the shared CortexKit location.`);
37318
39370
  } else if (legacyUserUnmigrated) {
@@ -37424,7 +39476,7 @@ function loadPiConfigDetailed(opts = {}) {
37424
39476
  if (loaded)
37425
39477
  loadedFiles.push(loaded);
37426
39478
  }
37427
- const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync10(source.path));
39479
+ const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync11(source.path));
37428
39480
  const userPath = resolveFirstExisting(getUserConfigPaths());
37429
39481
  const userLegacyFallback = userPath ? null : resolvePiLegacyFallback(harnessLegacy.user);
37430
39482
  const userReadPath = userPath ?? userLegacyFallback?.path;
@@ -37433,7 +39485,7 @@ function loadPiConfigDetailed(opts = {}) {
37433
39485
  if (loaded)
37434
39486
  loadedFiles.push(loaded);
37435
39487
  }
37436
- const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync10(source.path));
39488
+ const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync11(source.path));
37437
39489
  if (userLegacyFallback) {
37438
39490
  warnings.push(`[user config] reading legacy config from ${userLegacyFallback.path} until migration completes; run \`npx @cortexkit/magic-context doctor\` to consolidate into the shared CortexKit location.`);
37439
39491
  } else if (legacyUserUnmigrated) {
@@ -37504,7 +39556,7 @@ function loadPiConfigDetailed(opts = {}) {
37504
39556
  }
37505
39557
 
37506
39558
  // src/embedding-bootstrap.ts
37507
- import { statSync as statSync6 } from "node:fs";
39559
+ import { statSync as statSync7 } from "node:fs";
37508
39560
 
37509
39561
  // ../plugin/src/features/magic-context/compartment-chunk-embedding.ts
37510
39562
  import { createHash as createHash8 } from "node:crypto";
@@ -39630,19 +41682,19 @@ function wait(ms) {
39630
41682
  function sha256(value) {
39631
41683
  return createHash9("sha256").update(value).digest("hex");
39632
41684
  }
39633
- function stableJson(value) {
41685
+ function stableJson2(value) {
39634
41686
  if (Array.isArray(value))
39635
- return `[${value.map(stableJson).join(",")}]`;
41687
+ return `[${value.map(stableJson2).join(",")}]`;
39636
41688
  if (value && typeof value === "object") {
39637
- return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`).join(",")}}`;
41689
+ return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${stableJson2(entry)}`).join(",")}}`;
39638
41690
  }
39639
41691
  return JSON.stringify(value);
39640
41692
  }
39641
41693
  function getSynapseLaneIdentity(model, fingerprint) {
39642
- return `synapse:v1:${sha256(stableJson({ model, fingerprint }))}`;
41694
+ return `synapse:v1:${sha256(stableJson2({ model, fingerprint }))}`;
39643
41695
  }
39644
41696
  function getSynapseBatchRequestKey(args) {
39645
- return sha256(stableJson({
41697
+ return sha256(stableJson2({
39646
41698
  op: "embed.batch",
39647
41699
  model: args.model,
39648
41700
  required_fingerprint: args.fingerprint,
@@ -40104,7 +42156,7 @@ function getEmbeddingProviderIdentity(config2) {
40104
42156
  // ../plugin/src/features/magic-context/memory/embedding-local.ts
40105
42157
  import { chmodSync as chmodSync2, mkdirSync as mkdirSync4 } from "node:fs";
40106
42158
  import { open, stat, unlink, writeFile } from "node:fs/promises";
40107
- import { dirname as dirname6, join as join8 } from "node:path";
42159
+ import { dirname as dirname7, join as join9 } from "node:path";
40108
42160
  import { pathToFileURL as pathToFileURL2 } from "node:url";
40109
42161
  var LOCK_POLL_MS = 150;
40110
42162
  var STALE_LOCK_MS = 3 * 60000;
@@ -40168,7 +42220,7 @@ async function injectWasmOrtForElectron() {
40168
42220
  const { createRequire: createRequireFn } = await import("node:module");
40169
42221
  const requireFn = createRequireFn(import.meta.url);
40170
42222
  const mainEntry = requireFn.resolve("onnxruntime-web");
40171
- const distDir = dirname6(mainEntry);
42223
+ const distDir = dirname7(mainEntry);
40172
42224
  const wasmPathsPrefix = `${pathToFileURL2(distDir).href}/`;
40173
42225
  if (ortWeb.env?.wasm) {
40174
42226
  ortWeb.env.wasm.wasmPaths = wasmPathsPrefix;
@@ -40305,7 +42357,7 @@ class LocalEmbeddingProvider {
40305
42357
  if (LogLevel && "ERROR" in LogLevel) {
40306
42358
  env.logLevel = LogLevel.ERROR;
40307
42359
  }
40308
- const modelCacheDir = join8(getMagicContextStorageDir(), "models");
42360
+ const modelCacheDir = join9(getMagicContextStorageDir(), "models");
40309
42361
  try {
40310
42362
  if (shouldEnforcePrivateStoragePermissions()) {
40311
42363
  mkdirSync4(modelCacheDir, { recursive: true, mode: 448 });
@@ -40322,7 +42374,7 @@ class LocalEmbeddingProvider {
40322
42374
  log("[magic-context] could not create model cache dir, using library default");
40323
42375
  }
40324
42376
  const createPipeline = transformersModule.pipeline;
40325
- const lockPath = join8(modelCacheDir, ".load.lock");
42377
+ const lockPath = join9(modelCacheDir, ".load.lock");
40326
42378
  const releaseLock = await acquireModelLoadLock(lockPath);
40327
42379
  const stopHeartbeat = startLockHeartbeat(lockPath);
40328
42380
  try {
@@ -42785,7 +44837,7 @@ function configCandidatePaths(directory, loadedPaths) {
42785
44837
  function configFingerprint(paths) {
42786
44838
  return paths.map((path3) => {
42787
44839
  try {
42788
- const stat2 = statSync6(path3);
44840
+ const stat2 = statSync7(path3);
42789
44841
  return `${path3}:${stat2.size}:${stat2.mtimeMs}`;
42790
44842
  } catch {
42791
44843
  return `${path3}:missing`;
@@ -43284,7 +45336,7 @@ Two recovery modes for finer detail:
43284
45336
  var CTX_EXPAND_TOKEN_BUDGET = 15000;
43285
45337
 
43286
45338
  // ../plugin/src/tools/ctx-expand/render.ts
43287
- function isRecord3(value) {
45339
+ function isRecord4(value) {
43288
45340
  return value !== null && typeof value === "object" && !Array.isArray(value);
43289
45341
  }
43290
45342
  function roleLabel(role) {
@@ -43313,15 +45365,15 @@ function keyArg(input) {
43313
45365
  function asToolPart(part) {
43314
45366
  const type = typeof part.type === "string" ? part.type : "";
43315
45367
  if (type === "tool") {
43316
- const state = isRecord3(part.state) ? part.state : null;
45368
+ const state = isRecord4(part.state) ? part.state : null;
43317
45369
  const output = state && typeof state.output === "string" ? state.output : state && state.output != null ? JSON.stringify(state.output) : null;
43318
- const metadata = state && isRecord3(state.metadata) ? state.metadata : null;
45370
+ const metadata = state && isRecord4(state.metadata) ? state.metadata : null;
43319
45371
  const title = state && typeof state.title === "string" && state.title || metadata && typeof metadata.title === "string" && metadata.title || null;
43320
45372
  return {
43321
45373
  name: typeof part.tool === "string" ? part.tool : "tool",
43322
45374
  callId: typeof part.callID === "string" ? part.callID : "",
43323
45375
  title,
43324
- input: state && isRecord3(state.input) ? state.input : null,
45376
+ input: state && isRecord4(state.input) ? state.input : null,
43325
45377
  output
43326
45378
  };
43327
45379
  }
@@ -43330,7 +45382,7 @@ function asToolPart(part) {
43330
45382
  name: typeof part.name === "string" ? part.name : "tool",
43331
45383
  callId: typeof part.id === "string" ? part.id : "",
43332
45384
  title: null,
43333
- input: isRecord3(part.input) ? part.input : null,
45385
+ input: isRecord4(part.input) ? part.input : null,
43334
45386
  output: null
43335
45387
  };
43336
45388
  }
@@ -43359,7 +45411,7 @@ function reasoningOf(part) {
43359
45411
  return null;
43360
45412
  }
43361
45413
  function renderPartPreview(part) {
43362
- if (!isRecord3(part))
45414
+ if (!isRecord4(part))
43363
45415
  return null;
43364
45416
  const text = textOf(part);
43365
45417
  if (text !== null) {
@@ -43383,7 +45435,7 @@ function renderPartPreview(part) {
43383
45435
  return ` • [${type}]`;
43384
45436
  }
43385
45437
  function renderPartFull(part) {
43386
- if (!isRecord3(part))
45438
+ if (!isRecord4(part))
43387
45439
  return null;
43388
45440
  const text = textOf(part);
43389
45441
  if (text !== null) {
@@ -48887,7 +50939,7 @@ function getMemoryVerifications(db, memoryIds) {
48887
50939
  }
48888
50940
  // ../plugin/src/features/magic-context/memory/verification-paths.ts
48889
50941
  import { execFile } from "node:child_process";
48890
- import { existsSync as existsSync11, realpathSync as realpathSync3, statSync as statSync7 } from "node:fs";
50942
+ import { existsSync as existsSync12, realpathSync as realpathSync3, statSync as statSync8 } from "node:fs";
48891
50943
  import path3 from "node:path";
48892
50944
  import { promisify } from "node:util";
48893
50945
  var execFileAsync = promisify(execFile);
@@ -48994,7 +51046,7 @@ function verificationFileExists(baseRoot, filePath) {
48994
51046
  return false;
48995
51047
  const root = path3.resolve(baseRoot);
48996
51048
  const candidate = path3.resolve(root, filePath);
48997
- return isWithin(root, candidate) && existsSync11(candidate);
51049
+ return isWithin(root, candidate) && existsSync12(candidate);
48998
51050
  }
48999
51051
  async function normalizeVerificationFiles(args) {
49000
51052
  const cwd = path3.resolve(args.cwd);
@@ -49027,9 +51079,9 @@ async function normalizeVerificationFiles(args) {
49027
51079
  warnings.push(`Skipped verification path "${value}" because it is the repo/project root.`);
49028
51080
  continue;
49029
51081
  }
49030
- if (existsSync11(candidate)) {
51082
+ if (existsSync12(candidate)) {
49031
51083
  try {
49032
- if (statSync7(candidate).isDirectory()) {
51084
+ if (statSync8(candidate).isDirectory()) {
49033
51085
  warnings.push(`Skipped verification path "${value}" because it is a directory.`);
49034
51086
  continue;
49035
51087
  }
@@ -49058,7 +51110,7 @@ async function normalizeVerificationFiles(args) {
49058
51110
  }
49059
51111
  normalized.push(tracked);
49060
51112
  } else {
49061
- if (!existsSync11(candidate)) {
51113
+ if (!existsSync12(candidate)) {
49062
51114
  warnings.push(`Skipped verification path "${value}" because it does not exist.`);
49063
51115
  continue;
49064
51116
  }
@@ -49548,13 +51600,13 @@ function createCtxMemoryTool(deps) {
49548
51600
  }
49549
51601
 
49550
51602
  // ../plugin/src/features/magic-context/smart-notes/condition-compiler.ts
49551
- import { existsSync as existsSync12 } from "node:fs";
51603
+ import { existsSync as existsSync13 } from "node:fs";
49552
51604
  import { isAbsolute as isAbsolute5 } from "node:path";
49553
51605
 
49554
51606
  // ../retina-local-fs/src/path-fence.ts
49555
51607
  import { lstat, readlink, realpath } from "node:fs/promises";
49556
51608
  import { homedir as homedir6 } from "node:os";
49557
- import { basename as basename3, dirname as dirname7, isAbsolute as isAbsolute4, join as join9, relative, resolve as resolve5, sep } from "node:path";
51609
+ import { basename as basename4, dirname as dirname8, isAbsolute as isAbsolute4, join as join10, relative, resolve as resolve5, sep } from "node:path";
49558
51610
 
49559
51611
  // ../retina-local-fs/src/errors.ts
49560
51612
  class ProviderError extends Error {
@@ -49569,7 +51621,7 @@ class ProviderError extends Error {
49569
51621
  // ../retina-local-fs/src/path-fence.ts
49570
51622
  async function resolveAndFenceProviderPath(configuredPath, options) {
49571
51623
  const { home, dataDirectory } = await resolveFenceRoots(options);
49572
- const expanded = configuredPath.startsWith("~/") ? join9(home, configuredPath.slice(2)) : configuredPath === "~" ? home : configuredPath;
51624
+ const expanded = configuredPath.startsWith("~/") ? join10(home, configuredPath.slice(2)) : configuredPath === "~" ? home : configuredPath;
49573
51625
  const absolute = isAbsolute4(expanded) ? resolve5(expanded) : resolve5(options.cwd ?? process.cwd(), expanded);
49574
51626
  const canonical = await canonicalPath(absolute, options.allowMissing);
49575
51627
  if (isFencedPath(canonical, home, dataDirectory)) {
@@ -49585,7 +51637,7 @@ async function resolveFenceRoots(options) {
49585
51637
  } catch (error51) {
49586
51638
  throw fsError(configuredHomePath, error51);
49587
51639
  }
49588
- const configuredDataDirectory = resolve5(options.dataDirectory ?? process.env.XDG_DATA_HOME ?? join9(home, ".local", "share"));
51640
+ const configuredDataDirectory = resolve5(options.dataDirectory ?? process.env.XDG_DATA_HOME ?? join10(home, ".local", "share"));
49589
51641
  const dataDirectory = await canonicalPath(configuredDataDirectory, true);
49590
51642
  return { home, dataDirectory };
49591
51643
  }
@@ -49603,22 +51655,22 @@ async function canonicalPath(path4, allowMissing) {
49603
51655
  const metadata = await lstat(candidate);
49604
51656
  if (metadata.isSymbolicLink()) {
49605
51657
  const target2 = await readlink(candidate);
49606
- const resolvedTarget = resolve5(dirname7(candidate), target2);
49607
- return canonicalPath(join9(resolvedTarget, ...suffix), true);
51658
+ const resolvedTarget = resolve5(dirname8(candidate), target2);
51659
+ return canonicalPath(join10(resolvedTarget, ...suffix), true);
49608
51660
  }
49609
51661
  } catch (candidateError) {
49610
51662
  if (!isMissingError(candidateError)) {
49611
51663
  throw fsError(path4, candidateError);
49612
51664
  }
49613
51665
  }
49614
- const parent = dirname7(candidate);
51666
+ const parent = dirname8(candidate);
49615
51667
  if (parent === candidate) {
49616
51668
  throw fsError(path4, error51);
49617
51669
  }
49618
- suffix.unshift(basename3(candidate));
51670
+ suffix.unshift(basename4(candidate));
49619
51671
  candidate = parent;
49620
51672
  try {
49621
- return join9(await realpath(candidate), ...suffix);
51673
+ return join10(await realpath(candidate), ...suffix);
49622
51674
  } catch (parentError) {
49623
51675
  if (!isMissingError(parentError)) {
49624
51676
  throw fsError(path4, parentError);
@@ -49627,13 +51679,13 @@ async function canonicalPath(path4, allowMissing) {
49627
51679
  }
49628
51680
  }
49629
51681
  }
49630
- function isFencedPath(canonicalPath2, homeDirectory, dataDirectory = process.env.XDG_DATA_HOME ?? join9(resolve5(homeDirectory), ".local", "share")) {
49631
- const cortexkitRoot = join9(resolve5(dataDirectory), "cortexkit");
51682
+ function isFencedPath(canonicalPath2, homeDirectory, dataDirectory = process.env.XDG_DATA_HOME ?? join10(resolve5(homeDirectory), ".local", "share")) {
51683
+ const cortexkitRoot = join10(resolve5(dataDirectory), "cortexkit");
49632
51684
  const relativeToCortexkit = relative(cortexkitRoot, canonicalPath2);
49633
51685
  const insideCortexkit = relativeToCortexkit !== "" && relativeToCortexkit !== ".." && !relativeToCortexkit.startsWith(`..${sep}`) && !isAbsolute4(relativeToCortexkit);
49634
51686
  const parts = insideCortexkit ? relativeToCortexkit.split(sep) : [];
49635
51687
  const pathParts = canonicalPath2.split(sep).filter(Boolean);
49636
- const name = basename3(canonicalPath2);
51688
+ const name = basename4(canonicalPath2);
49637
51689
  const catalogDirectoryCarveIn = pathParts.includes("catalog");
49638
51690
  const moduleBinCarveIn = parts.length >= 2 && parts[1] === "bin";
49639
51691
  const catalogJsonCarveIn = name.endsWith(".json") && name.includes("catalog");
@@ -49802,9 +51854,10 @@ async function compileSurfaceCondition(surfaceCondition, options) {
49802
51854
  const resolved = await resolveAndFenceProviderPath(path4, {
49803
51855
  allowMissing: true,
49804
51856
  homeDirectory: options.homeDirectory,
51857
+ dataDirectory: options.dataDirectory,
49805
51858
  cwd: options.projectPath
49806
51859
  });
49807
- return { path: resolved, exists: existsSync12(resolved) };
51860
+ return { path: resolved, exists: existsSync13(resolved) };
49808
51861
  });
49809
51862
  let predicates;
49810
51863
  try {
@@ -50036,7 +52089,7 @@ function singleLine(value) {
50036
52089
  }
50037
52090
 
50038
52091
  // ../plugin/src/features/magic-context/smart-notes/wake-plane.ts
50039
- import { join as join10 } from "node:path";
52092
+ import { join as join11 } from "node:path";
50040
52093
  var WAKE_PLANE_CAPABILITY = "wake.create";
50041
52094
  var WAKE_PLANE_STATUS_TTL_MS = 5 * 60 * 1000;
50042
52095
  var WAKE_PLANE_HANDSHAKE_TIMEOUT_MS = 2000;
@@ -50045,7 +52098,7 @@ var inFlightProbe = null;
50045
52098
  var catalogProbe = probeWakePlaneCatalog;
50046
52099
  var now = () => Date.now();
50047
52100
  function connectionFile() {
50048
- return join10(getDataDir(), "cortexkit", "run", "subc-connection.json");
52101
+ return join11(getDataDir(), "cortexkit", "run", "subc-connection.json");
50049
52102
  }
50050
52103
  async function probeWakePlaneCatalog() {
50051
52104
  const file2 = connectionFile();
@@ -52928,8 +54981,8 @@ class BoundedSessionMap {
52928
54981
 
52929
54982
  // ../plugin/src/features/magic-context/compaction-marker.ts
52930
54983
  import { createHash as createHash16 } from "node:crypto";
52931
- import { existsSync as existsSync13 } from "node:fs";
52932
- import { join as join11 } from "node:path";
54984
+ import { existsSync as existsSync14 } from "node:fs";
54985
+ import { join as join12 } from "node:path";
52933
54986
  var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
52934
54987
  var ID_PREFIX_HEX_LENGTH = 12;
52935
54988
  var ID_SUFFIX_LENGTH = 14;
@@ -52955,7 +55008,7 @@ function generatePartId(timestampMs, counter = 0n, identity = "") {
52955
55008
  return generateId("prt", timestampMs, counter, identity);
52956
55009
  }
52957
55010
  function getOpenCodeDbPath2() {
52958
- return join11(getDataDir(), "opencode", "opencode.db");
55011
+ return join12(getDataDir(), "opencode", "opencode.db");
52959
55012
  }
52960
55013
  var cachedWriteDb = null;
52961
55014
  var REQUIRED_MESSAGE_COLUMNS = ["id", "session_id", "time_created", "time_updated", "data"];
@@ -53000,7 +55053,7 @@ function getWritableOpenCodeDb() {
53000
55053
  closeQuietly(cachedWriteDb.db);
53001
55054
  } catch {}
53002
55055
  }
53003
- if (!existsSync13(dbPath)) {
55056
+ if (!existsSync14(dbPath)) {
53004
55057
  throw new Error(`OpenCode database not found at ${dbPath} (is OpenCode installed?)`);
53005
55058
  }
53006
55059
  const db = new Database(dbPath);
@@ -54141,4 +56194,4 @@ function registerMagicContextTools(pi, opts) {
54141
56194
  }
54142
56195
  }
54143
56196
 
54144
- 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 };
56197
+ 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, getChannel1NudgeState, setChannel1NudgeState, 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, shouldUseStickyChannel1Reminder, 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 };