@cortexkit/magic-context 0.49.24 → 0.49.26

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 +240 -25
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -25260,6 +25260,29 @@ function getOpenCodeV2ActiveGeneration(slot) {
25260
25260
  return;
25261
25261
  }
25262
25262
  }
25263
+ function openCodeV2SlotSpec(spec, platform = process.platform) {
25264
+ if (platform !== "win32")
25265
+ return spec;
25266
+ return Array.from(spec, (char) => '<>:"|?*'.includes(char) || char.charCodeAt(0) < 32 ? "_" : char).join("");
25267
+ }
25268
+ function getOpenCodePluginInstallRoots(hostGeneration, config, npmCacheDir = getOpenCodeV2NpmCacheDir(), platform = process.platform) {
25269
+ const configured = openCodeV2SlotSpec(readConfiguredOpenCodePluginSpec(config), platform);
25270
+ const v2 = listOpenCodeV2PluginCacheSlots(npmCacheDir).sort((a, b) => Number(b.spec === configured) - Number(a.spec === configured)).map((slot) => getOpenCodeV2ActiveGeneration(slot.slot)).filter((generation) => generation !== undefined);
25271
+ const v1 = getOpenCodePluginCacheRoots();
25272
+ return hostGeneration === "v2" ? [...v2, ...v1] : [...v1, ...v2];
25273
+ }
25274
+ function getOpenCodeLoadedPluginInstallRoots(hostGeneration, config, npmCacheDir = getOpenCodeV2NpmCacheDir(), platform = process.platform) {
25275
+ let loaded;
25276
+ if (hostGeneration === "v2") {
25277
+ const configured = openCodeV2SlotSpec(readConfiguredOpenCodePluginSpec(config), platform);
25278
+ const generation = getOpenCodeV2ActiveGeneration(getOpenCodeV2PluginCacheSlot(npmCacheDir, configured));
25279
+ loaded = generation === undefined ? [] : [generation];
25280
+ } else {
25281
+ loaded = getOpenCodePluginCacheRoots();
25282
+ }
25283
+ const others = getOpenCodePluginInstallRoots(hostGeneration, config, npmCacheDir, platform).filter((root) => !loaded.includes(root));
25284
+ return { loaded, others };
25285
+ }
25263
25286
  function readOpenCodeV2CachedPluginVersion(slot) {
25264
25287
  const generation = getOpenCodeV2ActiveGeneration(slot);
25265
25288
  if (!generation)
@@ -27266,6 +27289,9 @@ function readStoreStamp(db) {
27266
27289
  function sameStoreStamp(left, right) {
27267
27290
  return left !== null && right !== null && left.dataVersion === right.dataVersion && left.totalChanges === right.totalChanges && left.schemaVersion === right.schemaVersion;
27268
27291
  }
27292
+ function forgetRawSessionOrdinalWatermark(sessionId) {
27293
+ ordinalWatermarkEpochs.set(sessionId, (ordinalWatermarkEpochs.get(sessionId) ?? 0) + 1);
27294
+ }
27269
27295
  function compareOrdinalKeys(left, right) {
27270
27296
  if (left.timeCreated !== right.timeCreated)
27271
27297
  return left.timeCreated < right.timeCreated ? -1 : 1;
@@ -27283,12 +27309,31 @@ function countEligibleOrdinals(db, sessionId, after, through) {
27283
27309
  ordinalJsonRowsRead += visited;
27284
27310
  return typeof row?.eligible === "number" ? row.eligible : 0;
27285
27311
  }
27312
+ function forgetRawSessionSummaryRows(sessionId) {
27313
+ summaryCandidateEpochs.set(sessionId, (summaryCandidateEpochs.get(sessionId) ?? 0) + 1);
27314
+ writtenSummaryIds.delete(sessionId);
27315
+ forgetRawSessionOrdinalWatermark(sessionId);
27316
+ }
27286
27317
  function survivingAnchor(db, set) {
27287
27318
  if (set.anchors.length === 0)
27288
27319
  return null;
27289
27320
  const current = new Map(db.prepare(ANCHOR_CHECK_SQL).all(JSON.stringify(set.anchors.map((anchor) => anchor.rowid))).map((row) => [row.rid, row.id]));
27290
27321
  return set.anchors.find((anchor) => current.get(anchor.rowid) === anchor.id);
27291
27322
  }
27323
+ function hasLateCommitBehindCheckpoint(db, sessionId, scan) {
27324
+ const tail = scan.checkpoints?.at(-1);
27325
+ if (!tail || scan.maxRowid === undefined)
27326
+ return false;
27327
+ const row = db.prepare(`SELECT COUNT(*) AS count FROM message
27328
+ WHERE rowid > ? AND +session_id = ?
27329
+ AND (time_created, id) <= (?, ?)
27330
+ AND NOT (${EXCLUDED_ROW_SQL})`).get(scan.maxRowid, sessionId, tail.timeCreated, tail.id);
27331
+ return typeof row?.count === "number" && row.count > 0;
27332
+ }
27333
+ function discardRetainedOrdinalRanks(db, sessionId) {
27334
+ ordinalCheckpoints.get(db)?.delete(sessionId);
27335
+ ordinalSummarySeeds.get(db)?.delete(sessionId);
27336
+ }
27292
27337
  function currentOrdinalCheckpoints(db, sessionId) {
27293
27338
  const cached = ordinalCheckpoints.get(db)?.get(sessionId);
27294
27339
  if (!cached)
@@ -27318,10 +27363,16 @@ function extendOrdinalCheckpoints(db, sessionId, scan, limit) {
27318
27363
  scan.sessionRows = points.at(-1)?.storedCount ?? 0;
27319
27364
  }
27320
27365
  const tail = points.at(-1);
27321
- const rows = db.prepare(`SELECT id, time_created AS timeCreated, ${EXCLUDED_ROW_SQL} AS excluded FROM message
27366
+ const rows = db.prepare(`SELECT id, time_created AS timeCreated, rowid AS rowid, ${EXCLUDED_ROW_SQL} AS excluded FROM message
27322
27367
  WHERE session_id=?${tail ? " AND (time_created,id) > (?,?)" : ""}
27323
27368
  ORDER BY time_created,id${limit === undefined ? "" : ` LIMIT ${limit + 1}`}`).all(sessionId, ...tail ? [tail.timeCreated, tail.id] : []);
27324
27369
  ordinalJsonRowsRead += rows.length;
27370
+ if (hasLateCommitBehindCheckpoint(db, sessionId, scan)) {
27371
+ discardRetainedOrdinalRanks(db, sessionId);
27372
+ if (isMainThread)
27373
+ forgetRawSessionSummaryRows(sessionId);
27374
+ return false;
27375
+ }
27325
27376
  if (limit !== undefined && rows.length > limit)
27326
27377
  return false;
27327
27378
  let total = scan.total ?? 0;
@@ -27338,6 +27389,13 @@ function extendOrdinalCheckpoints(db, sessionId, scan, limit) {
27338
27389
  scan.checkpoints = points;
27339
27390
  scan.sessionRows += rows.length;
27340
27391
  scan.total = total;
27392
+ if (rows.length > 0) {
27393
+ let maxRowid = scan.maxRowid ?? -1;
27394
+ for (const row of rows)
27395
+ if (row.rowid > maxRowid)
27396
+ maxRowid = row.rowid;
27397
+ scan.maxRowid = maxRowid;
27398
+ }
27341
27399
  return true;
27342
27400
  }
27343
27401
  function rawOrdinalSummarySeed(db, sessionId) {
@@ -27390,8 +27448,7 @@ function boundedOrdinalPrefix(db, sessionId, through) {
27390
27448
  }
27391
27449
  function scanRawSessionSummaryRows(db, sessionId, previous) {
27392
27450
  return withReadSnapshot(db, () => {
27393
- if (previous?.checkpoints) {
27394
- extendOrdinalCheckpoints(db, sessionId, previous);
27451
+ if (previous?.checkpoints && extendOrdinalCheckpoints(db, sessionId, previous)) {
27395
27452
  return previous;
27396
27453
  }
27397
27454
  if (previous) {
@@ -27423,12 +27480,15 @@ function scanRawSessionSummaryRows(db, sessionId, previous) {
27423
27480
  }
27424
27481
  anchors.sort((left, right) => right.rowid - left.rowid);
27425
27482
  anchors.length = Math.min(anchors.length, SUMMARY_ANCHOR_LIMIT);
27426
- const keys = db.prepare(`SELECT id, time_created AS timeCreated, ${EXCLUDED_ROW_SQL} AS excluded FROM message WHERE session_id = ?
27483
+ const keys = db.prepare(`SELECT id, time_created AS timeCreated, rowid AS rowid, ${EXCLUDED_ROW_SQL} AS excluded FROM message WHERE session_id = ?
27427
27484
  ORDER BY time_created, id`).all(sessionId);
27428
27485
  const checkpoints = [];
27429
27486
  let total = 0;
27487
+ let maxRowid;
27430
27488
  for (let index = 0;index < keys.length; index++) {
27431
27489
  const key = keys[index];
27490
+ if (typeof key.rowid === "number")
27491
+ maxRowid = maxRowid === undefined ? key.rowid : Math.max(maxRowid, key.rowid);
27432
27492
  if (key.excluded !== 1)
27433
27493
  total++;
27434
27494
  if (index % 256 === 255 || index === keys.length - 1)
@@ -27439,7 +27499,7 @@ function scanRawSessionSummaryRows(db, sessionId, previous) {
27439
27499
  storedCount: index + 1
27440
27500
  });
27441
27501
  }
27442
- return { anchors, ids, sessionRows, checkpoints, total };
27502
+ return { anchors, ids, sessionRows, checkpoints, total, maxRowid };
27443
27503
  });
27444
27504
  }
27445
27505
  function getRawSessionSummaryEpoch(sessionId) {
@@ -33114,6 +33174,51 @@ var init_read_session_formatting = __esm(() => {
33114
33174
  PROMPT_TOKEN_COUNT_BYTES = 8 * 1024 * 1024;
33115
33175
  });
33116
33176
 
33177
+ // ../plugin/src/shared/bounded-session-map.ts
33178
+ class BoundedSessionMap {
33179
+ maxEntries;
33180
+ store = new Map;
33181
+ constructor(maxEntries) {
33182
+ if (!Number.isFinite(maxEntries) || maxEntries < 1) {
33183
+ throw new Error(`BoundedSessionMap: maxEntries must be >= 1, got ${maxEntries}`);
33184
+ }
33185
+ this.maxEntries = maxEntries;
33186
+ }
33187
+ get(sessionId) {
33188
+ const value = this.store.get(sessionId);
33189
+ if (value === undefined)
33190
+ return;
33191
+ this.store.delete(sessionId);
33192
+ this.store.set(sessionId, value);
33193
+ return value;
33194
+ }
33195
+ peek(sessionId) {
33196
+ return this.store.get(sessionId);
33197
+ }
33198
+ has(sessionId) {
33199
+ return this.store.has(sessionId);
33200
+ }
33201
+ set(sessionId, value) {
33202
+ if (this.store.has(sessionId)) {
33203
+ this.store.delete(sessionId);
33204
+ } else if (this.store.size >= this.maxEntries) {
33205
+ const oldest = this.store.keys().next().value;
33206
+ if (oldest !== undefined)
33207
+ this.store.delete(oldest);
33208
+ }
33209
+ this.store.set(sessionId, value);
33210
+ }
33211
+ delete(sessionId) {
33212
+ return this.store.delete(sessionId);
33213
+ }
33214
+ clear() {
33215
+ this.store.clear();
33216
+ }
33217
+ get size() {
33218
+ return this.store.size;
33219
+ }
33220
+ }
33221
+
33117
33222
  // ../plugin/src/shared/stable-json.ts
33118
33223
  function stableStringify(value, seen = new WeakSet) {
33119
33224
  const pieces = [];
@@ -33168,36 +33273,122 @@ function writeStable(value, seen, write) {
33168
33273
  }
33169
33274
 
33170
33275
  // ../plugin/src/features/magic-context/tool-definition-tokens.ts
33276
+ function agentKey(agentName) {
33277
+ return agentName && agentName.length > 0 ? agentName : "default";
33278
+ }
33171
33279
  function keyFor(providerID, modelID, agentName) {
33172
- const agent = agentName && agentName.length > 0 ? agentName : "default";
33173
- return `${providerID}/${modelID}/${agent}`;
33280
+ return `${providerID}/${modelID}/${agentKey(agentName)}`;
33281
+ }
33282
+ function routeFor(providerID, modelID, agentName) {
33283
+ const key = keyFor(providerID, modelID, agentName);
33284
+ let route = routes.get(key);
33285
+ if (!route) {
33286
+ route = {
33287
+ providerID,
33288
+ modelID,
33289
+ agentName: agentKey(agentName),
33290
+ tools: new Map,
33291
+ live: false,
33292
+ clock: 0,
33293
+ lastWallAt: Date.now(),
33294
+ oldestFireAt: Number.POSITIVE_INFINITY,
33295
+ retired: new Map,
33296
+ legacyRows: new Set
33297
+ };
33298
+ routes.set(key, route);
33299
+ }
33300
+ return { key, route };
33301
+ }
33302
+ function advanceClock(route) {
33303
+ const now = Date.now();
33304
+ const gap = Math.min(Math.max(now - route.lastWallAt, 0), MAX_ACTIVITY_GAP_MS);
33305
+ route.clock += gap;
33306
+ route.lastWallAt = Math.max(route.lastWallAt, now);
33307
+ return route.clock;
33308
+ }
33309
+ function readWindowedSince(db) {
33310
+ try {
33311
+ const row = db.prepare("SELECT value FROM schema_migrations_meta WHERE key = ?").get(WINDOWED_SINCE_KEY);
33312
+ if (!row)
33313
+ return;
33314
+ const value = Number(row.value);
33315
+ return Number.isFinite(value) ? value : undefined;
33316
+ } catch {
33317
+ return;
33318
+ }
33319
+ }
33320
+ function markWindowed() {
33321
+ if (windowedSince !== undefined || !persistenceDb)
33322
+ return;
33323
+ try {
33324
+ persistenceDb.prepare("INSERT OR IGNORE INTO schema_migrations_meta (key, value) VALUES (?, ?)").run(WINDOWED_SINCE_KEY, String(boundAt));
33325
+ windowedSince = readWindowedSince(persistenceDb);
33326
+ } catch {}
33174
33327
  }
33175
33328
  function setDatabase(db) {
33329
+ const rebound = persistenceDb !== null && persistenceDb !== db;
33176
33330
  persistenceDb = db;
33331
+ boundAt = Date.now();
33177
33332
  cachedInsertStmt = null;
33333
+ cachedDeleteStmt = null;
33334
+ if (rebound) {
33335
+ for (const route of routes.values()) {
33336
+ for (const slot of route.tools.values()) {
33337
+ slot.persisted = false;
33338
+ slot.writeFailedAt = undefined;
33339
+ }
33340
+ for (const retired of route.retired.values())
33341
+ retired.rowKept = false;
33342
+ route.legacyRows.clear();
33343
+ }
33344
+ }
33345
+ windowedSince = readWindowedSince(db);
33346
+ if (windowedSince !== undefined)
33347
+ return;
33348
+ try {
33349
+ if (!db.prepare("SELECT 1 FROM tool_definition_measurements LIMIT 1").get())
33350
+ markWindowed();
33351
+ } catch {}
33178
33352
  }
33179
33353
  function loadToolDefinitionMeasurements(db) {
33180
33354
  let rows = [];
33181
33355
  try {
33182
- rows = db.prepare("SELECT provider_id, model_id, agent_name, tool_id, token_count FROM tool_definition_measurements").all();
33356
+ rows = db.prepare("SELECT provider_id, model_id, agent_name, tool_id, token_count, recorded_at FROM tool_definition_measurements").all();
33183
33357
  } catch {
33184
33358
  return;
33185
33359
  }
33360
+ const since = readWindowedSince(db);
33361
+ const loadedAt = new Map;
33186
33362
  for (const row of rows) {
33187
- const key = keyFor(row.provider_id, row.model_id, row.agent_name);
33188
- let inner = measurements.get(key);
33189
- if (!inner) {
33190
- inner = new Map;
33191
- measurements.set(key, inner);
33192
- }
33193
- inner.set(row.tool_id, row.token_count);
33363
+ const { route } = routeFor(row.provider_id, row.model_id, row.agent_name);
33364
+ if (route.live)
33365
+ continue;
33366
+ let now = loadedAt.get(route);
33367
+ if (now === undefined) {
33368
+ now = advanceClock(route);
33369
+ loadedAt.set(route, now);
33370
+ }
33371
+ const legacy = since === undefined || !(Number(row.recorded_at) >= since);
33372
+ route.tools.set(row.tool_id, {
33373
+ tokens: row.token_count,
33374
+ fingerprint: undefined,
33375
+ lastFireAt: now,
33376
+ legacy,
33377
+ persisted: !legacy
33378
+ });
33379
+ route.oldestFireAt = Math.min(route.oldestFireAt, now);
33380
+ if (legacy)
33381
+ route.legacyRows.add(row.tool_id);
33382
+ else
33383
+ route.legacyRows.delete(row.tool_id);
33194
33384
  }
33195
33385
  }
33196
- var measurements, fingerprints, persistenceDb = null, cachedInsertStmt = null;
33386
+ var ACTIVITY_WINDOW_MS, MAX_ACTIVITY_GAP_MS = 60000, WINDOWED_SINCE_KEY = "tool_definition_measurements:windowed_since", routes, sessionFlights, persistenceDb = null, windowedSince, boundAt = 0, cachedInsertStmt = null, cachedDeleteStmt = null;
33197
33387
  var init_tool_definition_tokens = __esm(() => {
33198
33388
  init_read_session_formatting();
33199
- measurements = new Map;
33200
- fingerprints = new Map;
33389
+ ACTIVITY_WINDOW_MS = 10 * 60000;
33390
+ routes = new Map;
33391
+ sessionFlights = new BoundedSessionMap(1000);
33201
33392
  });
33202
33393
 
33203
33394
  // ../plugin/src/features/magic-context/tool-owner-backfill.ts
@@ -34927,6 +35118,7 @@ __export(exports_read_session_chunk, {
34927
35118
  readRawSessionMessages: () => readRawSessionMessages,
34928
35119
  readRawSessionSeedTail: () => readRawSessionSeedTail,
34929
35120
  readSessionChunk: () => readSessionChunk,
35121
+ resolveHistorianChunkStart: () => resolveHistorianChunkStart,
34930
35122
  resolveHostServedBoundaryId: () => resolveHostServedBoundaryId,
34931
35123
  setBoundedRawMessageProvider: () => setBoundedRawMessageProvider,
34932
35124
  setRawMessageProvider: () => setRawMessageProvider,
@@ -35399,6 +35591,20 @@ function readRawSessionMessageOrdinalById(sessionId, messageId) {
35399
35591
  return null;
35400
35592
  return withReadOnlySessionDb((db) => readRawSessionMessageOrdinalByIdFromDb(db, sessionId, messageId));
35401
35593
  }
35594
+ function resolveHistorianChunkStart(sessionId, newest) {
35595
+ if (!newest)
35596
+ return 1;
35597
+ const fallback = newest.endMessage + 1;
35598
+ if (hasRawMessageProvider(sessionId))
35599
+ return fallback;
35600
+ const endId = newest.endMessageId;
35601
+ if (typeof endId !== "string" || endId.length === 0)
35602
+ return fallback;
35603
+ const ordinal = readRawSessionMessageOrdinalById(sessionId, endId);
35604
+ if (typeof ordinal !== "number" || !Number.isFinite(ordinal) || ordinal < 1)
35605
+ return fallback;
35606
+ return ordinal + 1;
35607
+ }
35402
35608
  function readRawSessionMessageOrderPosition(sessionId, messageId) {
35403
35609
  const provider = sessionProviders.get(sessionId)?.provider;
35404
35610
  if (provider) {
@@ -52538,8 +52744,8 @@ async function runIssueFlow2(options = {}, deps = { collectDiagnostics }) {
52538
52744
  return 1;
52539
52745
  }
52540
52746
  }
52541
- function checkLocalEmbeddingRuntimeForDoctor(runtimePreference = "auto") {
52542
- const runtime = checkLocalEmbeddingRuntime(getOpenCodePluginCacheRoots(), process.platform, process.arch, runtimePreference);
52747
+ function checkLocalEmbeddingRuntimeForDoctor(installRoots, runtimePreference = "auto") {
52748
+ const runtime = checkLocalEmbeddingRuntime(installRoots, process.platform, process.arch, runtimePreference);
52543
52749
  if (runtime.state === "wasm-selected") {
52544
52750
  log3.warn(formatLocalEmbeddingRuntimeWasmSelected(runtime));
52545
52751
  return { issues: 0 };
@@ -52559,15 +52765,15 @@ function checkLocalEmbeddingRuntimeForDoctor(runtimePreference = "auto") {
52559
52765
  log3.success("Embedding provider: local (native runtime selected and OK; Xenova/all-MiniLM-L6-v2 bundled)");
52560
52766
  return { issues: 0 };
52561
52767
  }
52562
- async function checkEmbeddingConfig(magicContextConfigPath) {
52768
+ async function checkEmbeddingConfig(magicContextConfigPath, installRoots) {
52563
52769
  if (!existsSync49(magicContextConfigPath)) {
52564
- return checkLocalEmbeddingRuntimeForDoctor();
52770
+ return checkLocalEmbeddingRuntimeForDoctor(installRoots);
52565
52771
  }
52566
52772
  let rawText;
52567
52773
  try {
52568
52774
  const raw = loadRawConfigFile({ configPath: magicContextConfigPath, tier: "user" });
52569
52775
  if (!raw)
52570
- return checkLocalEmbeddingRuntimeForDoctor();
52776
+ return checkLocalEmbeddingRuntimeForDoctor(installRoots);
52571
52777
  rawText = raw.text;
52572
52778
  } catch {
52573
52779
  log3.warn("Could not read magic-context.jsonc for embedding check");
@@ -52592,7 +52798,7 @@ async function checkEmbeddingConfig(magicContextConfigPath) {
52592
52798
  }
52593
52799
  if (provider === undefined || provider === "local") {
52594
52800
  const runtimePreference = embedding?.local_runtime === "native" || embedding?.local_runtime === "wasm" ? embedding.local_runtime : "auto";
52595
- return checkLocalEmbeddingRuntimeForDoctor(runtimePreference);
52801
+ return checkLocalEmbeddingRuntimeForDoctor(installRoots, runtimePreference);
52596
52802
  }
52597
52803
  if (provider === "synapse") {
52598
52804
  const loaded = loadPluginConfig(process.cwd());
@@ -53271,7 +53477,16 @@ async function runDoctor2(options = {}) {
53271
53477
  }
53272
53478
  } catch {}
53273
53479
  }
53274
- const embeddingCheck = await checkEmbeddingConfig(paths.magicContextConfig);
53480
+ let embeddingHostConfig = null;
53481
+ try {
53482
+ if (paths.opencodeConfigFormat !== "none")
53483
+ embeddingHostConfig = import_comment_json11.parse(readFileSync32(paths.opencodeConfig, "utf-8"));
53484
+ } catch {}
53485
+ const embeddingInstalls = getOpenCodeLoadedPluginInstallRoots(hostGeneration, embeddingHostConfig);
53486
+ const unusedInstalls = embeddingInstalls.others.filter((root) => existsSync49(root));
53487
+ if (unusedInstalls.length > 0)
53488
+ log3.info(`Local embedding runtime: checked only the copy ${hostGeneration === "v2" ? "OpenCode 2" : "OpenCode 1"} loads; other installed copies (not loaded, not checked): ${unusedInstalls.join(", ")}`);
53489
+ const embeddingCheck = await checkEmbeddingConfig(paths.magicContextConfig, embeddingInstalls.loaded);
53275
53490
  issues += embeddingCheck.issues;
53276
53491
  if (embeddingCheck.issues > 0)
53277
53492
  failCount += embeddingCheck.issues;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/magic-context",
3
- "version": "0.49.24",
3
+ "version": "0.49.26",
4
4
  "description": "Unified CLI for Magic Context — setup, doctor, and migration across OpenCode, Pi, and OMP",
5
5
  "keywords": [
6
6
  "opencode",