@cortexkit/magic-context 0.41.0 → 0.41.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +251 -57
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -14708,6 +14708,73 @@ function recordSwallowedWrite(error) {
14708
14708
  function ensureDir4(filePath) {
14709
14709
  fs.mkdirSync(path2.dirname(filePath), { recursive: true });
14710
14710
  }
14711
+ function isMissingFile(error) {
14712
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
14713
+ }
14714
+ function getCurrentLogSize(logFile) {
14715
+ if (activeLogFile === logFile && activeLogSize !== null && flushesSinceSizeCheck < SIZE_CHECK_INTERVAL_FLUSHES) {
14716
+ return activeLogSize;
14717
+ }
14718
+ try {
14719
+ const stat = fs.statSync(logFile);
14720
+ if (!stat.isFile()) {
14721
+ throw new Error(`Magic Context log path is not a regular file: ${logFile}`);
14722
+ }
14723
+ fs.chmodSync(logFile, 384);
14724
+ activeLogFile = logFile;
14725
+ activeLogSize = stat.size;
14726
+ flushesSinceSizeCheck = 0;
14727
+ return stat.size;
14728
+ } catch (error) {
14729
+ if (!isMissingFile(error))
14730
+ throw error;
14731
+ activeLogFile = logFile;
14732
+ activeLogSize = 0;
14733
+ flushesSinceSizeCheck = 0;
14734
+ return 0;
14735
+ }
14736
+ }
14737
+ function capLogData(data) {
14738
+ if (Buffer.byteLength(data) <= MAX_LOG_FILE_BYTES)
14739
+ return data;
14740
+ let bounded = Buffer.from(data).subarray(0, MAX_LOG_FILE_BYTES).toString("utf8");
14741
+ while (Buffer.byteLength(bounded) > MAX_LOG_FILE_BYTES) {
14742
+ bounded = bounded.slice(0, -1);
14743
+ }
14744
+ return bounded;
14745
+ }
14746
+ function writeBoundedPredecessor(logFile, predecessorPath, size) {
14747
+ const predecessorFd = fs.openSync(predecessorPath, "w", 384);
14748
+ try {
14749
+ fs.fchmodSync(predecessorFd, 384);
14750
+ const bytesToCopy = Math.min(size, MAX_LOG_FILE_BYTES);
14751
+ const sourceFd = fs.openSync(logFile, "r");
14752
+ try {
14753
+ const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, bytesToCopy));
14754
+ let remaining = bytesToCopy;
14755
+ let position = Math.max(0, size - bytesToCopy);
14756
+ while (remaining > 0) {
14757
+ const bytesRead = fs.readSync(sourceFd, chunk, 0, Math.min(chunk.length, remaining), position);
14758
+ if (bytesRead === 0)
14759
+ break;
14760
+ fs.writeSync(predecessorFd, chunk, 0, bytesRead);
14761
+ remaining -= bytesRead;
14762
+ position += bytesRead;
14763
+ }
14764
+ } finally {
14765
+ fs.closeSync(sourceFd);
14766
+ }
14767
+ } finally {
14768
+ fs.closeSync(predecessorFd);
14769
+ }
14770
+ }
14771
+ function rotateLogFile(logFile, size) {
14772
+ const predecessorPath = `${logFile}.1`;
14773
+ writeBoundedPredecessor(logFile, predecessorPath, size);
14774
+ fs.truncateSync(logFile, 0);
14775
+ activeLogSize = 0;
14776
+ flushesSinceSizeCheck = 0;
14777
+ }
14711
14778
  function flush() {
14712
14779
  if (flushTimer) {
14713
14780
  clearTimeout(flushTimer);
@@ -14715,13 +14782,26 @@ function flush() {
14715
14782
  }
14716
14783
  if (buffer.length === 0)
14717
14784
  return;
14718
- const data = buffer.join("");
14785
+ const bufferedData = buffer.join("");
14719
14786
  buffer = [];
14720
14787
  try {
14788
+ const data = capLogData(bufferedData);
14721
14789
  const logFile = getMagicContextLogPath();
14722
14790
  ensureDir4(logFile);
14723
- fs.appendFileSync(logFile, data);
14791
+ let currentSize = getCurrentLogSize(logFile);
14792
+ const dataSize = Buffer.byteLength(data);
14793
+ if (currentSize > 0 && currentSize + dataSize > MAX_LOG_FILE_BYTES) {
14794
+ rotateLogFile(logFile, currentSize);
14795
+ currentSize = 0;
14796
+ }
14797
+ fs.appendFileSync(logFile, data, { encoding: "utf8", mode: 384 });
14798
+ activeLogFile = logFile;
14799
+ activeLogSize = currentSize + dataSize;
14800
+ flushesSinceSizeCheck++;
14724
14801
  } catch (error) {
14802
+ activeLogFile = null;
14803
+ activeLogSize = null;
14804
+ flushesSinceSizeCheck = 0;
14725
14805
  recordSwallowedWrite(error);
14726
14806
  }
14727
14807
  }
@@ -14749,11 +14829,12 @@ ${data.stack}` : ""}`)}` : ` ${JSON.stringify(sanitizeConfigValue(data))}`;
14749
14829
  }
14750
14830
  } catch {}
14751
14831
  }
14752
- var isTestEnv = false, buffer, flushTimer = null, FLUSH_INTERVAL_MS = 500, BUFFER_SIZE_LIMIT = 50, swallowedWriteCount = 0, lastErrorMessage = null, lastErrorTime = null;
14832
+ var isTestEnv = false, buffer, flushTimer = null, FLUSH_INTERVAL_MS = 500, BUFFER_SIZE_LIMIT = 50, MAX_LOG_FILE_BYTES, SIZE_CHECK_INTERVAL_FLUSHES = 64, activeLogFile = null, activeLogSize = null, flushesSinceSizeCheck = 0, swallowedWriteCount = 0, lastErrorMessage = null, lastErrorTime = null;
14753
14833
  var init_logger = __esm(() => {
14754
14834
  init_data_path();
14755
14835
  init_redaction();
14756
14836
  buffer = [];
14837
+ MAX_LOG_FILE_BYTES = 32 * 1024 * 1024;
14757
14838
  if (!isTestEnv) {
14758
14839
  process.on("exit", flush);
14759
14840
  }
@@ -30132,6 +30213,7 @@ var init_magic_context = __esm(() => {
30132
30213
  query_input_type: exports_external.string().optional().describe("Optional input_type for query (search) embeddings on asymmetric models (e.g. NVIDIA NIM 'query'). When unset, query embeddings use embedding.input_type. Passage/stored content always uses embedding.input_type."),
30133
30214
  truncate: exports_external.string().optional().describe("Optional truncate mode sent in the embedding request body (e.g. NVIDIA NIM accepts 'NONE' | 'START' | 'END'). Omitted from the request when unset."),
30134
30215
  max_input_tokens: exports_external.number().int().positive().optional().describe("Optional maximum input tokens for chunk embeddings. Defaults conservatively to 512 when omitted."),
30216
+ local_runtime: exports_external.enum(["auto", "native", "wasm"]).default("auto").describe("Local provider only: ONNX runtime selection. 'auto' uses native under Node and uses WASM under Bun versions before 1.4.0, where Bun's NAPI teardown race can panic on quit; native is restored automatically on Bun 1.4.0+. Set 'native' only to prefer speed while accepting that pre-1.4.0 Bun crash risk, or 'wasm' to avoid loading the native addon."),
30135
30217
  local_dtype: exports_external.enum([
30136
30218
  "auto",
30137
30219
  "fp32",
@@ -30188,6 +30270,7 @@ var init_magic_context = __esm(() => {
30188
30270
  return {
30189
30271
  provider: "local",
30190
30272
  model: data.model?.trim() || DEFAULT_LOCAL_EMBEDDING_MODEL,
30273
+ local_runtime: data.local_runtime,
30191
30274
  ...data.max_input_tokens ? { max_input_tokens: data.max_input_tokens } : {},
30192
30275
  ...data.local_dtype ? { local_dtype: data.local_dtype } : {}
30193
30276
  };
@@ -30268,7 +30351,8 @@ var init_magic_context = __esm(() => {
30268
30351
  }).default({ enforce_private_permissions: true }).describe("Storage permission policy. The default keeps session content and memories owner-private. Disabling enforcement is for trusted shared-group storage managed externally; every group member able to read the storage can read all stored session content and memories."),
30269
30352
  embedding: EmbeddingConfigSchema.default({
30270
30353
  provider: "local",
30271
- model: DEFAULT_LOCAL_EMBEDDING_MODEL
30354
+ model: DEFAULT_LOCAL_EMBEDDING_MODEL,
30355
+ local_runtime: "auto"
30272
30356
  }).describe("Embedding provider configuration"),
30273
30357
  subc: exports_external.object({
30274
30358
  connection_file: exports_external.string().trim().min(1).transform(expandConfigPath).describe("Path to the owner-only subc connection file.")
@@ -32872,11 +32956,16 @@ function prepareMirrorPageStatements(db) {
32872
32956
  function mirrorIdentity(db, domain2, moduleProject, moduleRowId, statements) {
32873
32957
  return (statements?.identityByModule ?? db.prepare("SELECT context_row_id FROM mirror_identity WHERE domain = ? AND module_project = ? AND module_row_id = ?")).get(domain2, moduleProject, moduleRowId) ?? null;
32874
32958
  }
32875
- function rememberIdentity(db, domain2, moduleProject, moduleRowId, contextRowId, statements) {
32959
+ function rememberIdentity(db, domain2, moduleProject, moduleRowId, contextRowId, statements, replaceContextIdentity = domain2 === "notes") {
32876
32960
  const existing = mirrorIdentity(db, domain2, moduleProject, moduleRowId, statements);
32877
- if (existing)
32961
+ if (existing?.context_row_id === contextRowId)
32878
32962
  return;
32879
- if (domain2 === "notes") {
32963
+ if (existing) {
32964
+ if (!replaceContextIdentity)
32965
+ return;
32966
+ (statements?.deleteIdentity ?? db.prepare("DELETE FROM mirror_identity WHERE domain = ? AND module_project = ? AND module_row_id = ?")).run(domain2, moduleProject, moduleRowId);
32967
+ }
32968
+ if (replaceContextIdentity) {
32880
32969
  (statements?.deleteIdentityByContext ?? db.prepare("DELETE FROM mirror_identity WHERE domain = ? AND context_row_id = ?")).run(domain2, contextRowId);
32881
32970
  }
32882
32971
  (statements?.insertIdentity ?? db.prepare("INSERT OR IGNORE INTO mirror_identity(domain, module_project, module_row_id, context_row_id) VALUES (?, ?, ?, ?)")).run(domain2, moduleProject, moduleRowId, contextRowId);
@@ -32891,7 +32980,7 @@ function contextMemoryId(db, domain2, moduleProject, row, moduleRowId, statement
32891
32980
  if (sourceUuid && sourceUuid === localStoreUuid && sourceId >= 0) {
32892
32981
  const existing = (statements?.memoryIdByStoreId ?? db.prepare("SELECT id FROM memories WHERE id = ? AND project_path = ?")).get(sourceId, moduleProject);
32893
32982
  if (existing?.id !== undefined) {
32894
- rememberIdentity(db, domain2, moduleProject, moduleRowId, existing.id, statements);
32983
+ rememberIdentity(db, domain2, moduleProject, moduleRowId, existing.id, statements, true);
32895
32984
  return existing.id;
32896
32985
  }
32897
32986
  }
@@ -33120,6 +33209,24 @@ function applyMirrorPage(args) {
33120
33209
  if (page.domain === "memories" && resnapshotStatus !== "complete" && page.rows.some((feed) => feed.op === "tombstone")) {
33121
33210
  throw new Error("memory mirror resnapshot must complete before tombstones");
33122
33211
  }
33212
+ if (page.domain === "memories") {
33213
+ for (const feed of page.rows) {
33214
+ if (feed.domain !== "memories" || feed.op === "tombstone" || feed.feed_seq <= durableCursor) {
33215
+ continue;
33216
+ }
33217
+ const row = feed.full_row_snapshot;
33218
+ const moduleProject = rowString(row, "project_path");
33219
+ const sourceUuid = rowNullableString(row, "context_store_uuid");
33220
+ const sourceId = rowNumber(row, "context_row_id", -1);
33221
+ if (!moduleProject || !sourceUuid || sourceUuid !== statements.contextStoreUuid || sourceId < 0) {
33222
+ continue;
33223
+ }
33224
+ const existing = statements.memoryIdByStoreId.get(sourceId, moduleProject);
33225
+ if (existing?.id === undefined)
33226
+ continue;
33227
+ rememberIdentity(db, "memories", moduleProject, feed.module_row_id, existing.id, statements, true);
33228
+ }
33229
+ }
33123
33230
  const touchedProjects = new Set;
33124
33231
  for (const feed of page.rows) {
33125
33232
  if (feed.domain !== page.domain || feed.feed_seq <= nextCursor)
@@ -33314,7 +33421,7 @@ var init_context_authority = __esm(async () => {
33314
33421
  // ../plugin/src/features/magic-context/memory/project-identity.ts
33315
33422
  import { execFileSync as execFileSync3 } from "node:child_process";
33316
33423
  import { createHash as createHash2 } from "node:crypto";
33317
- import { existsSync as existsSync18, realpathSync as realpathSync2, statSync as statSync7 } from "node:fs";
33424
+ import { existsSync as existsSync18, realpathSync as realpathSync2, statSync as statSync8 } from "node:fs";
33318
33425
  import path3 from "node:path";
33319
33426
  function asError(error51) {
33320
33427
  return error51 instanceof Error ? error51 : undefined;
@@ -33359,7 +33466,7 @@ function directoryFallback(directory) {
33359
33466
  }
33360
33467
  function assertDirectoryUsable(canonicalDirectory, rawDirectory) {
33361
33468
  try {
33362
- const stat = statSync7(canonicalDirectory);
33469
+ const stat = statSync8(canonicalDirectory);
33363
33470
  if (!stat.isDirectory()) {
33364
33471
  throw new ProjectIdentityError("unknown", rawDirectory, `Project path is not a directory: ${canonicalDirectory}`);
33365
33472
  }
@@ -38656,14 +38763,14 @@ var init_tool_owner_backfill = __esm(() => {
38656
38763
 
38657
38764
  // ../plugin/src/features/magic-context/storage-db.ts
38658
38765
  import {
38659
- chmodSync as chmodSync2,
38766
+ chmodSync as chmodSync3,
38660
38767
  copyFileSync,
38661
38768
  cpSync,
38662
38769
  existsSync as existsSync19,
38663
38770
  mkdirSync as mkdirSync7,
38664
38771
  readdirSync as readdirSync2,
38665
38772
  readFileSync as readFileSync13,
38666
- statSync as statSync8,
38773
+ statSync as statSync9,
38667
38774
  unlinkSync as unlinkSync3
38668
38775
  } from "node:fs";
38669
38776
  import { basename as basename4, dirname as dirname11, join as join15, resolve as resolve6 } from "node:path";
@@ -40007,7 +40114,7 @@ var init_storage_db = __esm(async () => {
40007
40114
  defaultRpcDiscoveryFs = {
40008
40115
  readdirSync: (path4, options) => options?.withFileTypes ? readdirSync2(path4, { withFileTypes: true }) : readdirSync2(path4),
40009
40116
  readFileSync: (path4, encoding) => String(readFileSync13(path4, encoding)),
40010
- statSync: (path4) => ({ mtimeMs: statSync8(path4).mtimeMs }),
40117
+ statSync: (path4) => ({ mtimeMs: statSync9(path4).mtimeMs }),
40011
40118
  unlinkSync: (path4) => unlinkSync3(path4)
40012
40119
  };
40013
40120
  rpcDiscoveryFs = defaultRpcDiscoveryFs;
@@ -40647,15 +40754,15 @@ __export(exports_doctor_repair_db, {
40647
40754
  });
40648
40755
  import { spawnSync as spawnSync3 } from "node:child_process";
40649
40756
  import {
40650
- chmodSync as chmodSync3,
40651
- closeSync as closeSync3,
40757
+ chmodSync as chmodSync4,
40758
+ closeSync as closeSync4,
40652
40759
  constants as constants2,
40653
40760
  copyFileSync as copyFileSync2,
40654
40761
  existsSync as existsSync21,
40655
- openSync as openSync3,
40762
+ openSync as openSync4,
40656
40763
  renameSync as renameSync4,
40657
40764
  rmSync as rmSync2,
40658
- statSync as statSync9
40765
+ statSync as statSync10
40659
40766
  } from "node:fs";
40660
40767
  import { dirname as dirname12, join as join17 } from "node:path";
40661
40768
  function defaultInspectHolders(storageDir) {
@@ -40772,13 +40879,13 @@ function isRecoverCapabilityMissing(errorDetail) {
40772
40879
  function runRecoverShell(sqliteExecutable, sourcePath, recoveredPath, dumpPath) {
40773
40880
  let dumpWriteFd = null;
40774
40881
  try {
40775
- dumpWriteFd = openSync3(dumpPath, "wx", 384);
40882
+ dumpWriteFd = openSync4(dumpPath, "wx", 384);
40776
40883
  const recovered = spawnSync3(sqliteExecutable, [sourcePath, ".recover"], {
40777
40884
  stdio: ["ignore", dumpWriteFd, "pipe"],
40778
40885
  encoding: "utf8",
40779
40886
  windowsHide: true
40780
40887
  });
40781
- closeSync3(dumpWriteFd);
40888
+ closeSync4(dumpWriteFd);
40782
40889
  dumpWriteFd = null;
40783
40890
  if (recovered.error || recovered.status !== 0) {
40784
40891
  const errorDetail = sqliteError(recovered);
@@ -40790,7 +40897,7 @@ function runRecoverShell(sqliteExecutable, sourcePath, recoveredPath, dumpPath)
40790
40897
  unavailable: attempted && isRecoverCapabilityMissing(errorDetail)
40791
40898
  };
40792
40899
  }
40793
- const dumpReadFd = openSync3(dumpPath, "r");
40900
+ const dumpReadFd = openSync4(dumpPath, "r");
40794
40901
  try {
40795
40902
  const replayed = spawnSync3(sqliteExecutable, [recoveredPath], {
40796
40903
  stdio: [dumpReadFd, "ignore", "pipe"],
@@ -40806,7 +40913,7 @@ function runRecoverShell(sqliteExecutable, sourcePath, recoveredPath, dumpPath)
40806
40913
  };
40807
40914
  }
40808
40915
  } finally {
40809
- closeSync3(dumpReadFd);
40916
+ closeSync4(dumpReadFd);
40810
40917
  }
40811
40918
  return { ok: true };
40812
40919
  } catch (error51) {
@@ -40818,7 +40925,7 @@ function runRecoverShell(sqliteExecutable, sourcePath, recoveredPath, dumpPath)
40818
40925
  };
40819
40926
  } finally {
40820
40927
  if (dumpWriteFd !== null)
40821
- closeSync3(dumpWriteFd);
40928
+ closeSync4(dumpWriteFd);
40822
40929
  rmSync2(dumpPath, { force: true });
40823
40930
  }
40824
40931
  }
@@ -41039,8 +41146,8 @@ async function runRepairDb(options = {}) {
41039
41146
  return reportSafetyRefusal(prompts, dbPath, finalInspection, backup.basePath);
41040
41147
  }
41041
41148
  try {
41042
- const originalMode = statSync9(dbPath).mode & 511;
41043
- chmodSync3(recoveredPath, originalMode);
41149
+ const originalMode = statSync10(dbPath).mode & 511;
41150
+ chmodSync4(recoveredPath, originalMode);
41044
41151
  const originalAsidePath = uniqueBase(`${dbPath}.corrupt-original-${stamp}`);
41045
41152
  const moved = activateReplacement(dbPath, recoveredPath, originalAsidePath);
41046
41153
  reportSchemaTransition(prompts, salvageResult);
@@ -41087,8 +41194,8 @@ async function runRepairDb(options = {}) {
41087
41194
  return REPAIR_DB_EXIT.failed;
41088
41195
  }
41089
41196
  try {
41090
- const originalMode = statSync9(dbPath).mode & 511;
41091
- chmodSync3(freshPath, originalMode);
41197
+ const originalMode = statSync10(dbPath).mode & 511;
41198
+ chmodSync4(freshPath, originalMode);
41092
41199
  const originalAsidePath = uniqueBase(`${dbPath}.corrupt-original-${stamp}`);
41093
41200
  const moved = activateReplacement(dbPath, freshPath, originalAsidePath);
41094
41201
  reportSchemaTransition(prompts, fresh);
@@ -43686,12 +43793,12 @@ var DEFAULT_TIMEOUT_MS = 1e4, MAX_PREVIEW_CHARS = 240;
43686
43793
 
43687
43794
  // ../plugin/src/shared/tui-config.ts
43688
43795
  import {
43689
- chmodSync as chmodSync4,
43796
+ chmodSync as chmodSync5,
43690
43797
  existsSync as existsSync26,
43691
43798
  mkdirSync as mkdirSync10,
43692
43799
  readFileSync as readFileSync16,
43693
43800
  renameSync as renameSync6,
43694
- statSync as statSync10,
43801
+ statSync as statSync11,
43695
43802
  writeFileSync as writeFileSync7
43696
43803
  } from "node:fs";
43697
43804
  import { dirname as dirname15, join as join22 } from "node:path";
@@ -43727,8 +43834,8 @@ function writeTuiConfigAtomic(configPath, config2) {
43727
43834
  const tmpPath = `${configPath}.tmp`;
43728
43835
  writeFileSync7(tmpPath, body);
43729
43836
  try {
43730
- if (statSync10(configPath, { throwIfNoEntry: false })?.isFile()) {
43731
- chmodSync4(tmpPath, statSync10(configPath).mode & 511);
43837
+ if (statSync11(configPath, { throwIfNoEntry: false })?.isFile()) {
43838
+ chmodSync5(tmpPath, statSync11(configPath).mode & 511);
43732
43839
  }
43733
43840
  } catch {}
43734
43841
  renameSync6(tmpPath, configPath);
@@ -43800,7 +43907,7 @@ var init_tui_config = __esm(() => {
43800
43907
  });
43801
43908
 
43802
43909
  // src/lib/diagnostics-opencode.ts
43803
- import { existsSync as existsSync27, readdirSync as readdirSync3, readFileSync as readFileSync17, statSync as statSync11 } from "node:fs";
43910
+ import { existsSync as existsSync27, readdirSync as readdirSync3, readFileSync as readFileSync17, statSync as statSync12 } from "node:fs";
43804
43911
  import { createRequire as createRequire3 } from "node:module";
43805
43912
  import { homedir as homedir15 } from "node:os";
43806
43913
  import { join as join23 } from "node:path";
@@ -43838,7 +43945,7 @@ function getStorageResolution() {
43838
43945
  }
43839
43946
  function fileSize(path6) {
43840
43947
  try {
43841
- return existsSync27(path6) ? statSync11(path6).size : 0;
43948
+ return existsSync27(path6) ? statSync12(path6).size : 0;
43842
43949
  } catch {
43843
43950
  return 0;
43844
43951
  }
@@ -43915,7 +44022,7 @@ function listDumpsInDir(dir, limit) {
43915
44022
  return { count: 0, recent: [] };
43916
44023
  try {
43917
44024
  const entries = readdirSync3(dir).filter((name) => name.endsWith(".xml")).map((name) => {
43918
- const stat = statSync11(join23(dir, name));
44025
+ const stat = statSync12(join23(dir, name));
43919
44026
  return {
43920
44027
  name,
43921
44028
  mtime: stat.mtimeMs,
@@ -44169,7 +44276,7 @@ async function collectDiagnostics() {
44169
44276
  const storageDirPath = storageResolution.path;
44170
44277
  const contextDbPath = join23(storageDirPath, "context.db");
44171
44278
  const logPath = getMagicContextLogPath2("opencode");
44172
- const logFileSize = existsSync27(logPath) ? statSync11(logPath).size : 0;
44279
+ const logFileSize = existsSync27(logPath) ? statSync12(logPath).size : 0;
44173
44280
  let compactionEnabled = false;
44174
44281
  try {
44175
44282
  compactionEnabled = isCompactionEnabled(loadPluginConfig(process.cwd()));
@@ -44369,6 +44476,66 @@ var init_diagnostics_opencode = __esm(() => {
44369
44476
  import_comment_json10 = __toESM(require_src3(), 1);
44370
44477
  });
44371
44478
 
44479
+ // ../plugin/src/features/magic-context/memory/embedding-synapse.ts
44480
+ var SYNAPSE_CERTIFICATION_REFUSAL_REASONS, factoryClients;
44481
+ var init_embedding_synapse = __esm(() => {
44482
+ init_dist5();
44483
+ init_logger();
44484
+ SYNAPSE_CERTIFICATION_REFUSAL_REASONS = new Set([
44485
+ "not_certified",
44486
+ "probe_required",
44487
+ "migration_required"
44488
+ ]);
44489
+ factoryClients = new WeakMap;
44490
+ });
44491
+
44492
+ // ../plugin/src/features/magic-context/memory/normalize-hash.ts
44493
+ var init_normalize_hash = () => {};
44494
+
44495
+ // ../plugin/src/features/magic-context/memory/embedding-identity.ts
44496
+ var init_embedding_identity = __esm(() => {
44497
+ init_magic_context();
44498
+ init_embedding_synapse();
44499
+ init_normalize_hash();
44500
+ });
44501
+
44502
+ // ../plugin/src/features/magic-context/memory/embedding-local.ts
44503
+ function currentLocalEmbeddingHost() {
44504
+ const bun = globalThis.Bun;
44505
+ const bunVersion = typeof process !== "undefined" && typeof process.versions?.bun === "string" ? process.versions.bun : undefined;
44506
+ return {
44507
+ isElectron: typeof process !== "undefined" && Boolean(process.versions?.electron),
44508
+ isBun: Boolean(bun) || Boolean(bunVersion),
44509
+ bunVersion
44510
+ };
44511
+ }
44512
+ function bunHasNapiTeardownFix(version2) {
44513
+ const match = version2?.match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);
44514
+ if (!match || match[4])
44515
+ return false;
44516
+ const parsed = [Number(match[1]), Number(match[2]), Number(match[3])];
44517
+ return parsed.some((part) => !Number.isSafeInteger(part)) ? false : parsed[0] > BUN_NAPI_TEARDOWN_FIX_VERSION[0] || parsed[0] === BUN_NAPI_TEARDOWN_FIX_VERSION[0] && (parsed[1] > BUN_NAPI_TEARDOWN_FIX_VERSION[1] || parsed[1] === BUN_NAPI_TEARDOWN_FIX_VERSION[1] && parsed[2] >= BUN_NAPI_TEARDOWN_FIX_VERSION[2]);
44518
+ }
44519
+ function resolveLocalEmbeddingRuntime(preference = "auto", host = currentLocalEmbeddingHost()) {
44520
+ if (preference === "native" || preference === "wasm")
44521
+ return preference;
44522
+ if (host.isElectron)
44523
+ return "electron";
44524
+ if (host.isBun && !bunHasNapiTeardownFix(host.bunVersion))
44525
+ return "wasm";
44526
+ return "native";
44527
+ }
44528
+ var BUN_NAPI_TEARDOWN_FIX_VERSION, STALE_LOCK_MS, MAX_LOCK_WAIT_MS;
44529
+ var init_embedding_local = __esm(() => {
44530
+ init_magic_context();
44531
+ init_data_path();
44532
+ init_logger();
44533
+ init_embedding_identity();
44534
+ BUN_NAPI_TEARDOWN_FIX_VERSION = [1, 4, 0];
44535
+ STALE_LOCK_MS = 3 * 60000;
44536
+ MAX_LOCK_WAIT_MS = 5 * 60000;
44537
+ });
44538
+
44372
44539
  // src/lib/embedding-runtime.ts
44373
44540
  import { spawnSync as spawnSync6 } from "node:child_process";
44374
44541
  import { existsSync as existsSync28 } from "node:fs";
@@ -44477,9 +44644,12 @@ function describeNativeFailure(status) {
44477
44644
  return status.state === "package-missing" ? "package is not installed" : status.state === "binary-missing" ? "expected platform binding file is absent" : `binding failed to load: ${status.reason}`;
44478
44645
  }
44479
44646
  function isLocalEmbeddingRuntimeBroken(status) {
44480
- return status.state === "both-broken" || isNativeLocalEmbeddingRuntimeFailure(status);
44647
+ return status.state === "both-broken" || status.state === "wasm-broken" || isNativeLocalEmbeddingRuntimeFailure(status);
44481
44648
  }
44482
44649
  function formatLocalEmbeddingRuntimeDoctorWarning(status) {
44650
+ if (status.state === "wasm-broken") {
44651
+ return "Embedding provider: local — configured/selected onnxruntime-web (WASM) is unavailable — " + `${status.wasmReason}. Reinstall the plugin package or select embedding.local_runtime: native ` + "only on a host where its native runtime is safe.";
44652
+ }
44483
44653
  if (status.state !== "both-broken") {
44484
44654
  return "Embedding provider: local — onnxruntime-node native binding missing — " + `${describeNativeFailure(status)}; its postinstall likely failed. Embeddings will not work. ` + "Reinstall with network access to the npm registry and GitHub releases, " + "or switch `embedding.provider` to an HTTP endpoint (`openai-compatible`).";
44485
44655
  }
@@ -44519,11 +44689,19 @@ function withWasmFallback(native, probeWasm) {
44519
44689
  }
44520
44690
  return { state: "both-broken", nativeFailure: native, wasmReason: wasm.reason };
44521
44691
  }
44692
+ function formatLocalEmbeddingRuntimeWasmSelected(status) {
44693
+ return "Embedding provider: local — onnxruntime-web (WASM) selected by embedding.local_runtime/host at " + `${status.wasmPath}. The native addon was not probed or loaded. WASM inference is slower than native.`;
44694
+ }
44522
44695
  function probeWasmRuntimeAt(installRoot) {
44523
44696
  const requireFn = createRequire4(join24(installRoot, "package.json"));
44524
44697
  return probeWasmRuntimeFromRequire(requireFn);
44525
44698
  }
44526
- function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform, arch = process.arch) {
44699
+ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
44700
+ const selectedRuntime = resolveLocalEmbeddingRuntime(runtimePreference, host);
44701
+ if (selectedRuntime !== "native") {
44702
+ const wasm = probeWasmRuntimeAt(installRoot);
44703
+ return wasm.state === "ok" ? { state: "wasm-selected", wasmPath: wasm.wasmPath } : { state: "wasm-broken", wasmReason: wasm.reason };
44704
+ }
44527
44705
  const packageDir = join24(installRoot, "node_modules", "onnxruntime-node");
44528
44706
  let native;
44529
44707
  if (!existsSync28(join24(packageDir, "package.json"))) {
@@ -44542,7 +44720,7 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
44542
44720
  }
44543
44721
  return withWasmFallback(native, () => probeWasmRuntimeAt(installRoot));
44544
44722
  }
44545
- function checkLocalEmbeddingRuntime(installRoots, platform = process.platform, arch = process.arch) {
44723
+ function checkLocalEmbeddingRuntime(installRoots, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
44546
44724
  const existing = installRoots.filter((root) => existsSync28(root));
44547
44725
  if (existing.length === 0) {
44548
44726
  return {
@@ -44553,7 +44731,7 @@ function checkLocalEmbeddingRuntime(installRoots, platform = process.platform, a
44553
44731
  let firstFallback = null;
44554
44732
  let firstFailure = null;
44555
44733
  for (const root of existing) {
44556
- const status = checkLocalEmbeddingRuntimeAt(root, platform, arch);
44734
+ const status = checkLocalEmbeddingRuntimeAt(root, platform, arch, runtimePreference, host);
44557
44735
  if (status.state === "ok")
44558
44736
  return status;
44559
44737
  if (status.state === "wasm-fallback") {
@@ -44588,10 +44766,15 @@ function probeWasmRuntimeByResolution(pluginDir) {
44588
44766
  };
44589
44767
  }
44590
44768
  }
44591
- function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.platform, arch = process.arch) {
44769
+ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
44592
44770
  if (!existsSync28(join24(pluginDir, "package.json"))) {
44593
44771
  return { state: "unknown", reason: "plugin package dir not found" };
44594
44772
  }
44773
+ const selectedRuntime = resolveLocalEmbeddingRuntime(runtimePreference, host);
44774
+ if (selectedRuntime !== "native") {
44775
+ const wasm = probeWasmRuntimeByResolution(pluginDir);
44776
+ return wasm.state === "ok" ? { state: "wasm-selected", wasmPath: wasm.wasmPath } : { state: "wasm-broken", wasmReason: wasm.reason };
44777
+ }
44595
44778
  let onnxDir = null;
44596
44779
  let resolveError;
44597
44780
  try {
@@ -44632,6 +44815,7 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
44632
44815
  }
44633
44816
  var ONNX_LOAD_PROBE_TIMEOUT_MS = 1e4, ONNX_LOAD_PROBE_OUTPUT_LIMIT = 800, ONNX_LOAD_PROBE_PACKAGE_DIR_ENV = "MAGIC_CONTEXT_ONNX_RUNTIME_NODE_PACKAGE_DIR", ONNX_RUNTIME_NODE_LOAD_PROBE_SCRIPT, runOnnxRuntimeNodeLoadProbeChildForRuntime;
44634
44817
  var init_embedding_runtime = __esm(() => {
44818
+ init_embedding_local();
44635
44819
  ONNX_RUNTIME_NODE_LOAD_PROBE_SCRIPT = [
44636
44820
  'const { createRequire } = require("node:module");',
44637
44821
  'const { join } = require("node:path");',
@@ -45171,7 +45355,7 @@ import {
45171
45355
  constants as fsConstants,
45172
45356
  readFileSync as readFileSync19,
45173
45357
  renameSync as renameSync7,
45174
- statSync as statSync12,
45358
+ statSync as statSync13,
45175
45359
  writeFileSync as writeFileSync9
45176
45360
  } from "node:fs";
45177
45361
  import { dirname as dirname17, isAbsolute as isAbsolute5, join as join27, resolve as resolve8 } from "node:path";
@@ -45604,7 +45788,7 @@ var init_doctor_opencode_cache = __esm(() => {
45604
45788
 
45605
45789
  // src/commands/doctor-opencode.ts
45606
45790
  import { spawnSync as spawnSync7 } from "node:child_process";
45607
- import { existsSync as existsSync32, readFileSync as readFileSync22, statSync as statSync13 } from "node:fs";
45791
+ import { existsSync as existsSync32, readFileSync as readFileSync22, statSync as statSync14 } from "node:fs";
45608
45792
  import { createRequire as createRequire5 } from "node:module";
45609
45793
  import { homedir as homedir17 } from "node:os";
45610
45794
  import { join as join29 } from "node:path";
@@ -45826,8 +46010,12 @@ async function runIssueFlow2() {
45826
46010
  return 1;
45827
46011
  }
45828
46012
  }
45829
- function checkLocalEmbeddingRuntimeForDoctor() {
45830
- const runtime = checkLocalEmbeddingRuntime(getOpenCodePluginCacheRoots());
46013
+ function checkLocalEmbeddingRuntimeForDoctor(runtimePreference = "auto") {
46014
+ const runtime = checkLocalEmbeddingRuntime(getOpenCodePluginCacheRoots(), process.platform, process.arch, runtimePreference);
46015
+ if (runtime.state === "wasm-selected") {
46016
+ log2.info(formatLocalEmbeddingRuntimeWasmSelected(runtime));
46017
+ return { issues: 0 };
46018
+ }
45831
46019
  if (runtime.state === "wasm-fallback") {
45832
46020
  log2.warn(formatLocalEmbeddingRuntimeWasmFallback(runtime));
45833
46021
  return { issues: 0 };
@@ -45840,7 +46028,7 @@ function checkLocalEmbeddingRuntimeForDoctor() {
45840
46028
  log2.warn(`Local embedding runtime unverified: ${runtime.reason}`);
45841
46029
  return { issues: 0, unverified: true };
45842
46030
  }
45843
- log2.success("Embedding provider: local (native runtime OK; Xenova/all-MiniLM-L6-v2 bundled)");
46031
+ log2.success("Embedding provider: local (native runtime selected and OK; Xenova/all-MiniLM-L6-v2 bundled)");
45844
46032
  return { issues: 0 };
45845
46033
  }
45846
46034
  async function checkEmbeddingConfig(magicContextConfigPath) {
@@ -45875,7 +46063,8 @@ async function checkEmbeddingConfig(magicContextConfigPath) {
45875
46063
  return { issues: 0 };
45876
46064
  }
45877
46065
  if (provider === undefined || provider === "local") {
45878
- return checkLocalEmbeddingRuntimeForDoctor();
46066
+ const runtimePreference = embedding?.local_runtime === "native" || embedding?.local_runtime === "wasm" ? embedding.local_runtime : "auto";
46067
+ return checkLocalEmbeddingRuntimeForDoctor(runtimePreference);
45879
46068
  }
45880
46069
  if (provider !== "openai-compatible") {
45881
46070
  log2.warn(`Unknown embedding provider: ${String(provider)} (expected local | openai-compatible | off)`);
@@ -46493,7 +46682,7 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
46493
46682
  }
46494
46683
  const logPath = getMagicContextLogPath2("opencode");
46495
46684
  if (existsSync32(logPath)) {
46496
- const logStat = statSync13(logPath);
46685
+ const logStat = statSync14(logPath);
46497
46686
  const sizeKb = (logStat.size / 1024).toFixed(0);
46498
46687
  log2.info(`Log file: ${logPath} (${sizeKb} KB)`);
46499
46688
  } else {
@@ -46575,7 +46764,7 @@ var init_doctor_opencode = __esm(async () => {
46575
46764
  });
46576
46765
 
46577
46766
  // src/lib/diagnostics-pi.ts
46578
- import { existsSync as existsSync33, readdirSync as readdirSync5, readFileSync as readFileSync23, statSync as statSync14 } from "node:fs";
46767
+ import { existsSync as existsSync33, readdirSync as readdirSync5, readFileSync as readFileSync23, statSync as statSync15 } from "node:fs";
46579
46768
  import { createRequire as createRequire6 } from "node:module";
46580
46769
  import { join as join30 } from "node:path";
46581
46770
  function getSelfVersion3() {
@@ -46592,7 +46781,7 @@ function getSelfVersion3() {
46592
46781
  }
46593
46782
  function fileSize2(path6) {
46594
46783
  try {
46595
- return existsSync33(path6) ? statSync14(path6).size : 0;
46784
+ return existsSync33(path6) ? statSync15(path6).size : 0;
46596
46785
  } catch {
46597
46786
  return 0;
46598
46787
  }
@@ -46660,7 +46849,7 @@ function collectPiRecentSessions() {
46660
46849
  }
46661
46850
  for (const file2 of files) {
46662
46851
  try {
46663
- const mtime = statSync14(join30(slugDir, file2)).mtimeMs;
46852
+ const mtime = statSync15(join30(slugDir, file2)).mtimeMs;
46664
46853
  const sessionId = file2.replace(/\.jsonl$/, "");
46665
46854
  candidates.push({ sessionId, directory, mtime });
46666
46855
  } catch {}
@@ -46715,7 +46904,7 @@ function listDumpsInDir2(dir, limit) {
46715
46904
  return { count: 0, recent: [] };
46716
46905
  try {
46717
46906
  const entries = readdirSync5(dir).filter((name) => name.endsWith(".xml")).map((name) => {
46718
- const stat = statSync14(join30(dir, name));
46907
+ const stat = statSync15(join30(dir, name));
46719
46908
  return {
46720
46909
  name,
46721
46910
  mtime: stat.mtimeMs,
@@ -46790,7 +46979,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
46790
46979
  const storageDirPath = storageResolution.path;
46791
46980
  const dbPath = join30(storageDirPath, "context.db");
46792
46981
  const logPath = getMagicContextLogPath2("pi");
46793
- const logFileSize = existsSync33(logPath) ? statSync14(logPath).size : 0;
46982
+ const logFileSize = existsSync33(logPath) ? statSync15(logPath).size : 0;
46794
46983
  const otherPiExtensions = packages.filter((entry) => !isPiMagicContextPackageEntry(entry)).map(describePiPackageEntry);
46795
46984
  const recentSessions = collectPiRecentSessions();
46796
46985
  const historianDumps = collectPiHistorianDumps(recentSessions);
@@ -47010,7 +47199,7 @@ var init_logs_pi = __esm(() => {
47010
47199
 
47011
47200
  // src/commands/doctor-pi.ts
47012
47201
  import { execFileSync as execFileSync6, spawnSync as spawnSync8 } from "node:child_process";
47013
- import { existsSync as existsSync34, mkdirSync as mkdirSync11, readdirSync as readdirSync6, readFileSync as readFileSync25, rmSync as rmSync4, statSync as statSync15 } from "node:fs";
47202
+ import { existsSync as existsSync34, mkdirSync as mkdirSync11, readdirSync as readdirSync6, readFileSync as readFileSync25, rmSync as rmSync4, statSync as statSync16 } from "node:fs";
47014
47203
  import { createRequire as createRequire7 } from "node:module";
47015
47204
  import { homedir as homedir18 } from "node:os";
47016
47205
  import { dirname as dirname18, isAbsolute as isAbsolute6, join as join32 } from "node:path";
@@ -47251,7 +47440,7 @@ function findPiMagicContextCacheDirs(cwd, expectedVersion, force = false) {
47251
47440
  return;
47252
47441
  let stat;
47253
47442
  try {
47254
- stat = statSync15(path6);
47443
+ stat = statSync16(path6);
47255
47444
  } catch {
47256
47445
  return;
47257
47446
  }
@@ -47487,9 +47676,14 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
47487
47676
  let runtimeReported = false;
47488
47677
  let runtimeUnverifiedReason = "no installed plugin tree found to inspect";
47489
47678
  for (const pluginDir of piPluginDirCandidates(packages, options.cwd)) {
47490
- const runtime = checkLocalEmbeddingRuntimeByResolution(pluginDir);
47679
+ const runtime = checkLocalEmbeddingRuntimeByResolution(pluginDir, process.platform, process.arch, loadedConfig.config.embedding.provider === "local" ? loadedConfig.config.embedding.local_runtime : "auto", { isBun: false, isElectron: false });
47680
+ if (runtime.state === "wasm-selected") {
47681
+ add2(results, "info", formatLocalEmbeddingRuntimeWasmSelected(runtime));
47682
+ runtimeReported = true;
47683
+ break;
47684
+ }
47491
47685
  if (runtime.state === "ok") {
47492
- add2(results, "pass", `Embedding provider: ${loadedConfig.config.embedding.provider} (native runtime OK)`);
47686
+ add2(results, "pass", `Embedding provider: ${loadedConfig.config.embedding.provider} (native runtime selected and OK)`);
47493
47687
  runtimeReported = true;
47494
47688
  break;
47495
47689
  }
@@ -47507,7 +47701,7 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
47507
47701
  runtimeUnverifiedReason = runtime.reason;
47508
47702
  }
47509
47703
  if (!runtimeReported) {
47510
- add2(results, "warn", `Embedding provider ${loadedConfig.config.embedding.provider}: native runtime unverified (${runtimeUnverifiedReason})`);
47704
+ add2(results, "warn", `Embedding provider ${loadedConfig.config.embedding.provider}: selected runtime unverified (${runtimeUnverifiedReason})`);
47511
47705
  }
47512
47706
  }
47513
47707
  const piEntries = packages.filter(isPiMagicContextPackageEntry).map(describePiPackageEntry);
@@ -47534,7 +47728,7 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
47534
47728
  }
47535
47729
  const logPath = getMagicContextLogPath2("pi");
47536
47730
  if (existsSync34(logPath)) {
47537
- const stat = statSync15(logPath);
47731
+ const stat = statSync16(logPath);
47538
47732
  const sizeKb = (stat.size / 1024).toFixed(0);
47539
47733
  const lines = readFileSync25(logPath, "utf-8").split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
47540
47734
  add2(results, "info", `Log file: ${logPath} (${sizeKb} KB)`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/magic-context",
3
- "version": "0.41.0",
3
+ "version": "0.41.1",
4
4
  "description": "Unified CLI for Magic Context — setup, doctor, and migration across OpenCode, Pi, and OMP",
5
5
  "keywords": [
6
6
  "opencode",