@cortexkit/pi-magic-context 0.21.1 → 0.21.2

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 +104 -134
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -8163,10 +8163,10 @@ var require_stringify = __commonJS((exports, module) => {
8163
8163
  replacer = null;
8164
8164
  indent = EMPTY;
8165
8165
  };
8166
- 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)), gap) : two ? two.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(two, gap)), gap) : EMPTY;
8166
+ 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)), gap) : two ? two.trimRight() + repeat_line_breaks(Math.max(1, count_trailing_line_breaks(two, gap)), gap) : EMPTY;
8167
8167
  var join_content = (inside, value, gap) => {
8168
8168
  const comment = process_comments(value, PREFIX_BEFORE, gap + indent, true);
8169
- return join8(comment, inside, gap);
8169
+ return join9(comment, inside, gap);
8170
8170
  };
8171
8171
  var stringify_string = (holder, key, value) => {
8172
8172
  const raw = get_raw_string_literal(holder, key);
@@ -8188,13 +8188,13 @@ var require_stringify = __commonJS((exports, module) => {
8188
8188
  if (i !== 0) {
8189
8189
  inside += COMMA;
8190
8190
  }
8191
- const before = join8(after_comma, process_comments(value, BEFORE(i), deeper_gap), deeper_gap);
8191
+ const before = join9(after_comma, process_comments(value, BEFORE(i), deeper_gap), deeper_gap);
8192
8192
  inside += before || LF + deeper_gap;
8193
8193
  inside += stringify(i, value, deeper_gap) || STR_NULL;
8194
8194
  inside += process_comments(value, AFTER_VALUE(i), deeper_gap);
8195
8195
  after_comma = process_comments(value, AFTER(i), deeper_gap);
8196
8196
  }
8197
- inside += join8(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
8197
+ inside += join9(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
8198
8198
  return BRACKET_OPEN + join_content(inside, value, gap) + BRACKET_CLOSE;
8199
8199
  };
8200
8200
  var object_stringify = (value, gap) => {
@@ -8215,13 +8215,13 @@ var require_stringify = __commonJS((exports, module) => {
8215
8215
  inside += COMMA;
8216
8216
  }
8217
8217
  first = false;
8218
- const before = join8(after_comma, process_comments(value, BEFORE(key), deeper_gap), deeper_gap);
8218
+ const before = join9(after_comma, process_comments(value, BEFORE(key), deeper_gap), deeper_gap);
8219
8219
  inside += before || LF + deeper_gap;
8220
8220
  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);
8221
8221
  after_comma = process_comments(value, AFTER(key), deeper_gap);
8222
8222
  };
8223
8223
  keys.forEach(iteratee);
8224
- inside += join8(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
8224
+ inside += join9(after_comma, process_comments(value, PREFIX_AFTER, deeper_gap), deeper_gap);
8225
8225
  return CURLY_BRACKET_OPEN + join_content(inside, value, gap) + CURLY_BRACKET_CLOSE;
8226
8226
  };
8227
8227
  function stringify(key, holder, gap) {
@@ -8342,8 +8342,8 @@ var init_rpc_notifications = __esm(() => {
8342
8342
  });
8343
8343
 
8344
8344
  // src/index.ts
8345
- import { createRequire as createRequire3 } from "node:module";
8346
- import { join as join18 } from "node:path";
8345
+ import { createRequire as createRequire4 } from "node:module";
8346
+ import { join as join19 } from "node:path";
8347
8347
 
8348
8348
  // ../plugin/src/features/magic-context/memory/project-identity.ts
8349
8349
  import { execSync } from "node:child_process";
@@ -145216,9 +145216,22 @@ init_logger();
145216
145216
  // src/subagent-runner.ts
145217
145217
  import * as childProcess from "node:child_process";
145218
145218
  import { existsSync as existsSync6 } from "node:fs";
145219
- import { dirname as dirname3, resolve as resolvePath } from "node:path";
145219
+ import { createRequire as createRequire3 } from "node:module";
145220
+ import { dirname as dirname3, join as join8, resolve as resolvePath } from "node:path";
145220
145221
  import { createInterface } from "node:readline";
145221
145222
  import { fileURLToPath } from "node:url";
145223
+ function resolveBundledPiCli() {
145224
+ try {
145225
+ const require_ = createRequire3(import.meta.url);
145226
+ const pkgJson = require_.resolve("@earendil-works/pi-coding-agent/package.json");
145227
+ const cliPath = join8(dirname3(pkgJson), "dist/cli.js");
145228
+ if (existsSync6(cliPath))
145229
+ return cliPath;
145230
+ return null;
145231
+ } catch {
145232
+ return null;
145233
+ }
145234
+ }
145222
145235
  function resolveSubagentEntryPath() {
145223
145236
  try {
145224
145237
  const here = dirname3(fileURLToPath(import.meta.url));
@@ -145242,7 +145255,16 @@ class PiSubagentRunner {
145242
145255
  piBinary;
145243
145256
  spawnImpl;
145244
145257
  constructor(options = {}) {
145245
- this.piBinary = options.piBinary ?? "pi";
145258
+ if (options.piBinary) {
145259
+ this.piBinary = options.piBinary;
145260
+ } else {
145261
+ const bundled = resolveBundledPiCli();
145262
+ if (bundled) {
145263
+ this.piBinary = bundled;
145264
+ } else {
145265
+ this.piBinary = "pi";
145266
+ }
145267
+ }
145246
145268
  this.spawnImpl = options.spawnImpl ?? childProcess.spawn;
145247
145269
  }
145248
145270
  async run(options) {
@@ -145853,7 +145875,7 @@ function clearStaleEntries(db, maxAgeMs) {
145853
145875
  init_logger();
145854
145876
  // ../plugin/src/features/magic-context/dreamer/runner.ts
145855
145877
  import { existsSync as existsSync8 } from "node:fs";
145856
- import { join as join10 } from "node:path";
145878
+ import { join as join11 } from "node:path";
145857
145879
 
145858
145880
  // ../plugin/src/shared/index.ts
145859
145881
  init_logger();
@@ -146148,14 +146170,14 @@ await init_sqlite();
146148
146170
 
146149
146171
  // ../plugin/src/features/magic-context/key-files/identify-key-files.ts
146150
146172
  import { readFileSync as readFileSync4 } from "node:fs";
146151
- import { join as join9 } from "node:path";
146173
+ import { join as join10 } from "node:path";
146152
146174
  init_logger();
146153
146175
 
146154
146176
  // ../plugin/src/features/magic-context/key-files/aft-availability.ts
146155
146177
  var import_comment_json = __toESM(require_src2(), 1);
146156
146178
  import { existsSync as existsSync7, readFileSync as readFileSync3 } from "node:fs";
146157
146179
  import { homedir as homedir3 } from "node:os";
146158
- import { join as join8 } from "node:path";
146180
+ import { join as join9 } from "node:path";
146159
146181
  var overrideAvailability = null;
146160
146182
  function parseConfig(path5) {
146161
146183
  if (!existsSync7(path5))
@@ -146182,10 +146204,10 @@ function hasAftAtKeys(value, keys) {
146182
146204
  function getAftAvailability() {
146183
146205
  const home = process.env.HOME || homedir3();
146184
146206
  const opencodePaths = [
146185
- join8(home, ".config", "opencode", "opencode.jsonc"),
146186
- join8(home, ".config", "opencode", "opencode.json")
146207
+ join9(home, ".config", "opencode", "opencode.jsonc"),
146208
+ join9(home, ".config", "opencode", "opencode.json")
146187
146209
  ];
146188
- const piPaths = [join8(home, ".pi", "agent", "settings.json")];
146210
+ const piPaths = [join9(home, ".pi", "agent", "settings.json")];
146189
146211
  const checkedPaths = [...opencodePaths, ...piPaths];
146190
146212
  let opencode = false;
146191
146213
  for (const path5 of opencodePaths) {
@@ -146572,7 +146594,7 @@ async function runKeyFilesLlm(args) {
146572
146594
  });
146573
146595
  const messagesResponse = await args.client.session.messages({
146574
146596
  path: { id: agentSessionId },
146575
- query: { directory: args.projectPath }
146597
+ query: { directory: args.projectPath, limit: 50 }
146576
146598
  });
146577
146599
  const messages = normalizeSDKResponse(messagesResponse, [], {
146578
146600
  preferResponseOnMissingData: true
@@ -146609,7 +146631,7 @@ async function runKeyFilesTask(args) {
146609
146631
  if (row.staleReason !== null || row.generationConfigHash !== configHash)
146610
146632
  return false;
146611
146633
  try {
146612
- return sha256(readFileSync4(join9(projectPath, row.path))) === row.contentHash;
146634
+ return sha256(readFileSync4(join10(projectPath, row.path))) === row.contentHash;
146613
146635
  } catch {
146614
146636
  return false;
146615
146637
  }
@@ -147680,7 +147702,7 @@ If no promotions are warranted, return empty arrays. Always consume reviewed can
147680
147702
  });
147681
147703
  const messagesResponse = await args.client.session.messages({
147682
147704
  path: { id: agentSessionId },
147683
- query: { directory: args.sessionDirectory }
147705
+ query: { directory: args.sessionDirectory, limit: 50 }
147684
147706
  });
147685
147707
  const messages = normalizeSDKResponse(messagesResponse, [], {
147686
147708
  preferResponseOnMissingData: true
@@ -147806,7 +147828,7 @@ function logWithStackHead(message, stackHead) {
147806
147828
  log(message, stackHead ? { stackHead } : undefined);
147807
147829
  }
147808
147830
  function getOpenCodeDbPath2() {
147809
- return join10(getDataDir(), "opencode", "opencode.db");
147831
+ return join11(getDataDir(), "opencode", "opencode.db");
147810
147832
  }
147811
147833
  function openOpenCodeDb() {
147812
147834
  const dbPath = getOpenCodeDbPath2();
@@ -147941,8 +147963,8 @@ async function runDream(args) {
147941
147963
  try {
147942
147964
  const docsDir = args.sessionDirectory ?? args.projectIdentity;
147943
147965
  const existingDocs = taskName === "maintain-docs" ? {
147944
- architecture: existsSync8(join10(docsDir, "ARCHITECTURE.md")),
147945
- structure: existsSync8(join10(docsDir, "STRUCTURE.md"))
147966
+ architecture: existsSync8(join11(docsDir, "ARCHITECTURE.md")),
147967
+ structure: existsSync8(join11(docsDir, "STRUCTURE.md"))
147946
147968
  } : undefined;
147947
147969
  const userMemories = taskName === "archive-stale" ? getActiveUserMemories(args.db).map((um) => ({
147948
147970
  id: um.id,
@@ -147986,7 +148008,7 @@ async function runDream(args) {
147986
148008
  }
147987
148009
  const messagesResponse = await args.client.session.messages({
147988
148010
  path: { id: agentSessionId },
147989
- query: { directory: args.sessionDirectory ?? args.projectIdentity }
148011
+ query: { directory: args.sessionDirectory ?? args.projectIdentity, limit: 50 }
147990
148012
  });
147991
148013
  const messages = normalizeSDKResponse(messagesResponse, [], {
147992
148014
  preferResponseOnMissingData: true
@@ -148309,7 +148331,7 @@ Only include notes whose conditions you could definitively evaluate. Skip notes
148309
148331
  });
148310
148332
  const messagesResponse = await args.client.session.messages({
148311
148333
  path: { id: agentSessionId },
148312
- query: { directory: args.sessionDirectory ?? args.projectIdentity }
148334
+ query: { directory: args.sessionDirectory ?? args.projectIdentity, limit: 50 }
148313
148335
  });
148314
148336
  const messages = normalizeSDKResponse(messagesResponse, [], {
148315
148337
  preferResponseOnMissingData: true
@@ -163130,7 +163152,7 @@ function getEmbeddingProviderIdentity(config2) {
163130
163152
  // ../plugin/src/features/magic-context/memory/embedding-local.ts
163131
163153
  import { mkdirSync as mkdirSync4 } from "node:fs";
163132
163154
  import { open, stat, unlink, writeFile } from "node:fs/promises";
163133
- import { dirname as dirname4, join as join11 } from "node:path";
163155
+ import { dirname as dirname4, join as join12 } from "node:path";
163134
163156
  import { pathToFileURL } from "node:url";
163135
163157
  init_data_path();
163136
163158
  init_logger();
@@ -163197,7 +163219,7 @@ async function injectWasmOrtForElectron() {
163197
163219
  const { createRequire: createRequireFn } = await import("node:module");
163198
163220
  const requireFn = createRequireFn(import.meta.url);
163199
163221
  const pkgPath = requireFn.resolve("onnxruntime-web/package.json");
163200
- const distDir = join11(dirname4(pkgPath), "dist");
163222
+ const distDir = join12(dirname4(pkgPath), "dist");
163201
163223
  const wasmPathsPrefix = `${pathToFileURL(distDir).href}/`;
163202
163224
  if (ortWeb.env?.wasm) {
163203
163225
  ortWeb.env.wasm.wasmPaths = wasmPathsPrefix;
@@ -163308,7 +163330,7 @@ class LocalEmbeddingProvider {
163308
163330
  if (LogLevel && "ERROR" in LogLevel) {
163309
163331
  env.logLevel = LogLevel.ERROR;
163310
163332
  }
163311
- const modelCacheDir = join11(getMagicContextStorageDir(), "models");
163333
+ const modelCacheDir = join12(getMagicContextStorageDir(), "models");
163312
163334
  try {
163313
163335
  mkdirSync4(modelCacheDir, { recursive: true });
163314
163336
  env.cacheDir = modelCacheDir;
@@ -163316,7 +163338,7 @@ class LocalEmbeddingProvider {
163316
163338
  log("[magic-context] could not create model cache dir, using library default");
163317
163339
  }
163318
163340
  const createPipeline = transformersModule.pipeline;
163319
- const lockPath = join11(modelCacheDir, ".load.lock");
163341
+ const lockPath = join12(modelCacheDir, ".load.lock");
163320
163342
  const releaseLock = await acquireModelLoadLock(lockPath);
163321
163343
  const stopHeartbeat = startLockHeartbeat(lockPath);
163322
163344
  try {
@@ -164670,7 +164692,7 @@ function handleUntrustedLoad(db, projectIdentity, directory, detailed) {
164670
164692
  // src/config/index.ts
164671
164693
  import { existsSync as existsSync10, readFileSync as readFileSync6 } from "node:fs";
164672
164694
  import { homedir as homedir5 } from "node:os";
164673
- import { join as join12 } from "node:path";
164695
+ import { join as join13 } from "node:path";
164674
164696
 
164675
164697
  // ../plugin/src/config/variable.ts
164676
164698
  import { existsSync as existsSync9, readFileSync as readFileSync5 } from "node:fs";
@@ -164738,12 +164760,12 @@ function substituteConfigVariables(input) {
164738
164760
  var import_comment_json2 = __toESM(require_src2(), 1);
164739
164761
  var CONFIG_FILE_NAME = "magic-context";
164740
164762
  function getProjectConfigPaths(cwd) {
164741
- const basePath = join12(cwd, ".pi", CONFIG_FILE_NAME);
164763
+ const basePath = join13(cwd, ".pi", CONFIG_FILE_NAME);
164742
164764
  return [`${basePath}.jsonc`, `${basePath}.json`];
164743
164765
  }
164744
164766
  function getUserConfigPaths() {
164745
164767
  const home = process.env.HOME ?? homedir5();
164746
- const basePath = join12(home, ".pi", "agent", CONFIG_FILE_NAME);
164768
+ const basePath = join13(home, ".pi", "agent", CONFIG_FILE_NAME);
164747
164769
  return [`${basePath}.jsonc`, `${basePath}.json`];
164748
164770
  }
164749
164771
  function resolveFirstExisting(paths) {
@@ -169243,7 +169265,7 @@ function getReducedRecompTokenBudget(currentBudget) {
169243
169265
  // ../plugin/src/hooks/magic-context/historian-state-file.ts
169244
169266
  init_data_path();
169245
169267
  import { mkdirSync as mkdirSync5, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
169246
- import { join as join13 } from "node:path";
169268
+ import { join as join14 } from "node:path";
169247
169269
  var HISTORIAN_STATE_INLINE_THRESHOLD = 30000;
169248
169270
  function maybeWriteHistorianStateFile(sessionId, existingState, directory) {
169249
169271
  if (existingState.length <= HISTORIAN_STATE_INLINE_THRESHOLD)
@@ -169251,7 +169273,7 @@ function maybeWriteHistorianStateFile(sessionId, existingState, directory) {
169251
169273
  try {
169252
169274
  const dir = getProjectMagicContextHistorianDir(directory);
169253
169275
  mkdirSync5(dir, { recursive: true });
169254
- const path5 = join13(dir, `state-${sessionId}-${Date.now()}.xml`);
169276
+ const path5 = join14(dir, `state-${sessionId}-${Date.now()}.xml`);
169255
169277
  writeFileSync2(path5, existingState, "utf8");
169256
169278
  return path5;
169257
169279
  } catch {
@@ -170211,7 +170233,7 @@ function stripPiDroppedPlaceholderMessages(args) {
170211
170233
  // src/system-prompt.ts
170212
170234
  import { createHash as createHash8 } from "node:crypto";
170213
170235
  import { existsSync as existsSync11, readFileSync as readFileSync8 } from "node:fs";
170214
- import { join as join15 } from "node:path";
170236
+ import { join as join16 } from "node:path";
170215
170237
 
170216
170238
  // ../plugin/src/agents/magic-context-prompt.ts
170217
170239
  function getToolHistoryGuidance(dropToolStructure) {
@@ -170302,7 +170324,7 @@ Prefer many small targeted operations over one large blanket operation. Compress
170302
170324
 
170303
170325
  // ../plugin/src/hooks/magic-context/key-files-block.ts
170304
170326
  import { readFileSync as readFileSync7, realpathSync as realpathSync3 } from "node:fs";
170305
- import { join as join14, sep as sep2 } from "node:path";
170327
+ import { join as join15, sep as sep2 } from "node:path";
170306
170328
  init_logger();
170307
170329
  var cachedKeyFilesBySession = new Map;
170308
170330
  var staleUpdates = new Map;
@@ -170355,7 +170377,7 @@ function buildKeyFilesBlock(db, projectPath, config2 = { enabled: true, tokenBud
170355
170377
  let nextStale = null;
170356
170378
  let observed = false;
170357
170379
  try {
170358
- const absPath = join14(projectPath, row.path);
170380
+ const absPath = join15(projectPath, row.path);
170359
170381
  const real = realpathSync3(absPath);
170360
170382
  if (!isUnderProject(projectPath, real)) {
170361
170383
  nextStale = "missing";
@@ -170438,7 +170460,7 @@ var DOC_FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
170438
170460
  function readProjectDocs(directory) {
170439
170461
  const sections = [];
170440
170462
  for (const filename of DOC_FILES) {
170441
- const filePath = join15(directory, filename);
170463
+ const filePath = join16(directory, filename);
170442
170464
  try {
170443
170465
  if (existsSync11(filePath)) {
170444
170466
  const content = readFileSync8(filePath, "utf-8").trim();
@@ -171329,104 +171351,52 @@ function resolveSessionId2(ctx) {
171329
171351
  return;
171330
171352
  }
171331
171353
  }
171332
- function collectMessageEntryIds(ctx, expectedLength, sessionId, strict = false) {
171354
+ function collectMessageEntryIdsByRef(ctx, messages, sessionId) {
171333
171355
  const sm = ctx.sessionManager;
171334
171356
  if (typeof sm?.getBranch !== "function")
171335
- return;
171357
+ return null;
171336
171358
  let entries;
171337
171359
  try {
171338
171360
  entries = sm.getBranch.call(sm);
171339
- } catch {
171340
- return;
171361
+ } catch (error51) {
171362
+ sessionLog(sessionId ?? "pi", `collectMessageEntryIdsByRef getBranch failed: ${error51 instanceof Error ? error51.message : String(error51)}`);
171363
+ return null;
171341
171364
  }
171342
171365
  if (!Array.isArray(entries))
171343
- return;
171344
- let compactionIndex = -1;
171345
- let firstKeptEntryId;
171346
- for (let i = entries.length - 1;i >= 0; i--) {
171347
- const e = entries[i];
171348
- if (e && typeof e === "object" && e.type === "compaction") {
171349
- compactionIndex = i;
171350
- if (typeof e.firstKeptEntryId === "string") {
171351
- firstKeptEntryId = e.firstKeptEntryId;
171352
- }
171353
- break;
171354
- }
171355
- }
171356
- const ids = [];
171357
- const isEmitEligible = (entry) => {
171366
+ return null;
171367
+ const entryIdByMsgRef = new Map;
171368
+ for (const entry of entries) {
171358
171369
  if (!entry || typeof entry !== "object")
171359
- return false;
171360
- const t = entry.type;
171361
- const id = entry.id;
171362
- if (typeof id !== "string")
171363
- return false;
171364
- if (t === "message")
171365
- return true;
171366
- if (t === "custom_message")
171367
- return true;
171368
- if (t === "branch_summary") {
171369
- const summary = entry.summary;
171370
- return typeof summary === "string" && summary.length > 0;
171371
- }
171372
- return false;
171373
- };
171374
- if (compactionIndex >= 0) {
171375
- ids.push(undefined);
171376
- if (firstKeptEntryId !== undefined) {
171377
- let foundFirstKept = false;
171378
- for (let i = 0;i < compactionIndex; i++) {
171379
- const entry = entries[i];
171380
- const entryId = entry?.id;
171381
- if (typeof entryId === "string" && entryId === firstKeptEntryId) {
171382
- foundFirstKept = true;
171383
- }
171384
- if (!foundFirstKept)
171385
- continue;
171386
- if (isEmitEligible(entry)) {
171387
- ids.push(entry.id);
171388
- }
171389
- }
171390
- }
171391
- for (let i = compactionIndex + 1;i < entries.length; i++) {
171392
- const entry = entries[i];
171393
- if (isEmitEligible(entry)) {
171394
- ids.push(entry.id);
171395
- }
171396
- }
171397
- } else {
171398
- for (const entry of entries) {
171399
- if (isEmitEligible(entry)) {
171400
- ids.push(entry.id);
171401
- }
171402
- }
171370
+ continue;
171371
+ const e = entry;
171372
+ if (e.type !== "message")
171373
+ continue;
171374
+ if (typeof e.id !== "string")
171375
+ continue;
171376
+ if (!e.message || typeof e.message !== "object")
171377
+ continue;
171378
+ entryIdByMsgRef.set(e.message, e.id);
171403
171379
  }
171404
- if (ids.length !== expectedLength) {
171405
- const sm2 = sm;
171406
- const totalEntries = entries.length;
171407
- log(`[magic-context][pi]${sessionId ? `[${sessionId}]` : ""} collectMessageEntryIds length mismatch: ` + `expected=${expectedLength} got=${ids.length} (compactionIndex=${compactionIndex} ` + `firstKeptEntryId=${firstKeptEntryId ?? "<none>"} totalBranchEntries=${totalEntries})` + ` — best-effort mapping returned; boundary trim may not match exactly`);
171408
- if (strict)
171409
- return;
171410
- const _unused = sm2;
171411
- if (ids.length < expectedLength) {
171412
- const padded = [];
171413
- for (let i = 0;i < expectedLength - ids.length; i++) {
171414
- padded.push(undefined);
171415
- }
171416
- padded.push(...ids);
171417
- return padded;
171380
+ const result = new Array(messages.length);
171381
+ let resolved = 0;
171382
+ for (let i = 0;i < messages.length; i++) {
171383
+ const msg = messages[i];
171384
+ if (!msg || typeof msg !== "object") {
171385
+ result[i] = undefined;
171386
+ continue;
171387
+ }
171388
+ const id = entryIdByMsgRef.get(msg);
171389
+ if (typeof id === "string") {
171390
+ result[i] = id;
171391
+ resolved += 1;
171392
+ } else {
171393
+ result[i] = undefined;
171418
171394
  }
171419
- return ids.slice(ids.length - expectedLength);
171420
171395
  }
171421
- return ids;
171422
- }
171423
- function collectMessageEntryIdsStrict(ctx, expectedLength, sessionId) {
171424
- try {
171425
- return collectMessageEntryIds(ctx, expectedLength, sessionId, true) ?? null;
171426
- } catch (error51) {
171427
- sessionLog(sessionId ?? "pi", `collectMessageEntryIdsStrict failed: ${error51 instanceof Error ? error51.message : String(error51)}`);
171428
- return null;
171396
+ if (resolved < messages.length) {
171397
+ log(`[magic-context][pi]${sessionId ? `[${sessionId}]` : ""} ` + `collectMessageEntryIdsByRef: resolved=${resolved}/${messages.length} ` + `(branchEntries=${entries.length}, messageEntries=${entryIdByMsgRef.size}) — ` + `unmapped slots fall through to synthesized ids; boundary lookup still works ` + `for any compartment whose start/end message is among the resolved set`);
171429
171398
  }
171399
+ return result;
171430
171400
  }
171431
171401
  function registerPiContextHandler(pi, options) {
171432
171402
  const tagger = createTagger();
@@ -171467,7 +171437,7 @@ function registerPiContextHandler(pi, options) {
171467
171437
  const unregisterRaw = setRawMessageProvider(sessionId, rawMessageProvider);
171468
171438
  rawMessageProviderUnregistersBySession.set(sessionId, unregisterRaw);
171469
171439
  scheduleReconciliation(options.db, sessionId, readRawSessionMessages);
171470
- const strictEntryIds = collectMessageEntryIdsStrict(ctx, event.messages.length, sessionId);
171440
+ const strictEntryIds = collectMessageEntryIdsByRef(ctx, event.messages, sessionId);
171471
171441
  const tLastUser = performance.now();
171472
171442
  const latestUser = findLatestUserMessageIdPi(event.messages, buildPiMessageIdByIndex(event.messages, strictEntryIds));
171473
171443
  logTransformTiming(sessionId, "findLastUserMessageId", tLastUser);
@@ -171600,7 +171570,7 @@ function registerPiContextHandler(pi, options) {
171600
171570
  const isCacheBusting = historyRefreshSessions.has(sessionId);
171601
171571
  sessionLog(sessionId, `transform: usage=${usagePercentage.toFixed(1)}% (${usageInputTokens} tokens, limit=${usageContextLimit ?? "?"}) decision=${schedulerDecision}${forceMaterialization ? " force=true" : ""}${isEmergency ? " EMERGENCY=true" : ""}${isCacheBusting ? " busting=true" : ""}`);
171602
171572
  logTransformTiming(sessionId, "emergencyRecoveryBlock", tEmergencyRecovery);
171603
- const entryIds = collectMessageEntryIds(ctx, event.messages.length, sessionId);
171573
+ const entryIds = collectMessageEntryIdsByRef(ctx, event.messages, sessionId) ?? undefined;
171604
171574
  const result = await runPipeline({
171605
171575
  db: options.db,
171606
171576
  tagger,
@@ -172468,7 +172438,7 @@ init_logger();
172468
172438
  init_data_path();
172469
172439
  init_logger();
172470
172440
  await init_sqlite();
172471
- import { join as join16 } from "node:path";
172441
+ import { join as join17 } from "node:path";
172472
172442
  var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
172473
172443
  function randomBase62(length) {
172474
172444
  const chars = [];
@@ -172489,7 +172459,7 @@ function generatePartId(timestampMs, counter = 0n) {
172489
172459
  return generateId("prt", timestampMs, counter);
172490
172460
  }
172491
172461
  function getOpenCodeDbPath3() {
172492
- return join16(getDataDir(), "opencode", "opencode.db");
172462
+ return join17(getDataDir(), "opencode", "opencode.db");
172493
172463
  }
172494
172464
  var cachedWriteDb = null;
172495
172465
  var REQUIRED_MESSAGE_COLUMNS = ["id", "session_id", "time_created", "time_updated", "data"];
@@ -173009,7 +172979,7 @@ async function runCompressorPass2(args) {
173009
172979
  });
173010
172980
  const messagesResponse = await client.session.messages({
173011
172981
  path: { id: agentSessionId },
173012
- query: { directory }
172982
+ query: { directory, limit: 50 }
173013
172983
  });
173014
172984
  const messages = normalizeSDKResponse(messagesResponse, [], {
173015
172985
  preferResponseOnMissingData: true
@@ -173047,7 +173017,7 @@ async function runCompressorPass2(args) {
173047
173017
 
173048
173018
  // ../plugin/src/hooks/magic-context/compartment-runner-historian.ts
173049
173019
  import { mkdirSync as mkdirSync6, unlinkSync as unlinkSync2, writeFileSync as writeFileSync3 } from "node:fs";
173050
- import { join as join17 } from "node:path";
173020
+ import { join as join18 } from "node:path";
173051
173021
  init_data_path();
173052
173022
  function historianResponseDumpDir(directory) {
173053
173023
  return getProjectMagicContextHistorianDir(directory);
@@ -173194,7 +173164,7 @@ async function runHistorianPrompt(args) {
173194
173164
  }
173195
173165
  const messagesResponse = await client.session.messages({
173196
173166
  path: { id: agentSessionId },
173197
- query: { directory: sessionDirectory }
173167
+ query: { directory: sessionDirectory, limit: 50 }
173198
173168
  });
173199
173169
  const messages = normalizeSDKResponse(messagesResponse, [], {
173200
173170
  preferResponseOnMissingData: true
@@ -173301,7 +173271,7 @@ function dumpHistorianResponse(sessionId, directory, label, text) {
173301
173271
  mkdirSync6(dumpDir, { recursive: true });
173302
173272
  const safeSessionId = sanitizeDumpName(sessionId);
173303
173273
  const safeLabel = sanitizeDumpName(label);
173304
- const dumpPath = join17(dumpDir, `${safeSessionId}-${safeLabel}-${Date.now()}.xml`);
173274
+ const dumpPath = join18(dumpDir, `${safeSessionId}-${safeLabel}-${Date.now()}.xml`);
173305
173275
  writeFileSync3(dumpPath, text, "utf8");
173306
173276
  sessionLog(sessionId, "compartment agent: historian response dumped", {
173307
173277
  label,
@@ -174507,7 +174477,7 @@ import {
174507
174477
  // package.json
174508
174478
  var package_default = {
174509
174479
  name: "@cortexkit/pi-magic-context",
174510
- version: "0.21.1",
174480
+ version: "0.21.2",
174511
174481
  type: "module",
174512
174482
  description: "Pi coding agent extension for Magic Context — cross-session memory and context management",
174513
174483
  main: "dist/index.js",
@@ -180210,7 +180180,7 @@ async function persistPiPressureFromMessageEnd(args) {
180210
180180
  }
180211
180181
  var PLUGIN_VERSION = (() => {
180212
180182
  try {
180213
- const req = createRequire3(import.meta.url);
180183
+ const req = createRequire4(import.meta.url);
180214
180184
  return req("../package.json").version;
180215
180185
  } catch {
180216
180186
  return "0.0.0";
@@ -180288,7 +180258,7 @@ function resolveDreamerFromConfig(config2) {
180288
180258
  }
180289
180259
  async function src_default2(pi) {
180290
180260
  const storageDir = getMagicContextStorageDir();
180291
- const dbPath = join18(storageDir, "context.db");
180261
+ const dbPath = join19(storageDir, "context.db");
180292
180262
  let db;
180293
180263
  try {
180294
180264
  db = openDatabase();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.21.1",
3
+ "version": "0.21.2",
4
4
  "type": "module",
5
5
  "description": "Pi coding agent extension for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",