@cortexkit/pi-magic-context 0.30.4 → 0.30.5

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.
package/dist/index.js CHANGED
@@ -156667,8 +156667,9 @@ init_logger();
156667
156667
 
156668
156668
  // src/subagent-runner.ts
156669
156669
  import * as childProcess from "node:child_process";
156670
- import { existsSync as existsSync7 } from "node:fs";
156670
+ import { existsSync as existsSync7, mkdtempSync as mkdtempSync2, rmSync as rmSync2, writeFileSync as writeFileSync5 } from "node:fs";
156671
156671
  import { createRequire as createRequire2 } from "node:module";
156672
+ import { tmpdir as tmpdir2 } from "node:os";
156672
156673
  import { basename as basename2, dirname as dirname4, join as join8, resolve as resolvePath } from "node:path";
156673
156674
  import { createInterface } from "node:readline";
156674
156675
  import { fileURLToPath } from "node:url";
@@ -156889,9 +156890,11 @@ class PiSubagentRunner {
156889
156890
  harness = "pi";
156890
156891
  invocation;
156891
156892
  spawnImpl;
156893
+ platform;
156892
156894
  constructor(options = {}) {
156893
156895
  this.invocation = options.piBinary ? { command: options.piBinary, prefixArgs: [] } : resolvePiInvocation();
156894
156896
  this.spawnImpl = options.spawnImpl ?? childProcess.spawn;
156897
+ this.platform = options.platform ?? process.platform;
156895
156898
  }
156896
156899
  async run(options) {
156897
156900
  const models = [options.model, ...options.fallbackModels ?? []].filter((model) => typeof model === "string" && model.length > 0);
@@ -156950,10 +156953,47 @@ class PiSubagentRunner {
156950
156953
  }
156951
156954
  return result;
156952
156955
  }
156956
+ const failBeforeSpawn = (reason, error) => {
156957
+ const result = {
156958
+ ok: false,
156959
+ reason,
156960
+ error,
156961
+ durationMs: Date.now() - startTime
156962
+ };
156963
+ try {
156964
+ recordAccounting(result);
156965
+ } catch (err) {
156966
+ sessionLog(options.accountingSessionId ?? "subagent", `subagent accounting failed (continuing): ${err instanceof Error ? err.message : String(err)}`);
156967
+ }
156968
+ return result;
156969
+ };
156953
156970
  const promptBytes = Buffer.byteLength(options.userMessage, "utf8");
156954
- const deliverViaStdin = promptBytes > PROMPT_ARGV_MAX_BYTES;
156971
+ const deliverViaStdin = promptBytes > PROMPT_ARGV_MAX_BYTES || this.platform === "win32";
156972
+ let systemPromptTempDir;
156973
+ let systemPromptPath;
156974
+ const cleanupSystemPromptFile = () => {
156975
+ if (!systemPromptTempDir)
156976
+ return;
156977
+ const tempDir = systemPromptTempDir;
156978
+ systemPromptTempDir = undefined;
156979
+ systemPromptPath = undefined;
156980
+ try {
156981
+ rmSync2(tempDir, { recursive: true, force: true });
156982
+ } catch {}
156983
+ };
156984
+ if (options.systemPrompt.length > 0) {
156985
+ try {
156986
+ systemPromptTempDir = mkdtempSync2(join8(tmpdir2(), "mc-pi-prompt-"));
156987
+ systemPromptPath = join8(systemPromptTempDir, "system-prompt.txt");
156988
+ writeFileSync5(systemPromptPath, options.systemPrompt, "utf8");
156989
+ } catch (error) {
156990
+ cleanupSystemPromptFile();
156991
+ return failBeforeSpawn("spawn_failed", `failed to prepare pi system prompt file: ${error instanceof Error ? error.message : String(error)}`);
156992
+ }
156993
+ }
156955
156994
  const args = buildArgs(options, {
156956
- omitPositionalMessage: deliverViaStdin
156995
+ omitPositionalMessage: deliverViaStdin,
156996
+ systemPromptPath
156957
156997
  });
156958
156998
  return new Promise((resolve) => {
156959
156999
  let accountingMessages = [];
@@ -156962,6 +157002,7 @@ class PiSubagentRunner {
156962
157002
  if (settled)
156963
157003
  return;
156964
157004
  settled = true;
157005
+ cleanupSystemPromptFile();
156965
157006
  try {
156966
157007
  recordAccounting(result, accountingMessages);
156967
157008
  } catch (err) {
@@ -156987,6 +157028,7 @@ class PiSubagentRunner {
156987
157028
  stdio: [deliverViaStdin ? "pipe" : "ignore", "pipe", "pipe"]
156988
157029
  });
156989
157030
  } catch (error) {
157031
+ cleanupSystemPromptFile();
156990
157032
  settle({
156991
157033
  ok: false,
156992
157034
  reason: "spawn_failed",
@@ -157280,7 +157322,8 @@ function buildArgs(options, opts) {
157280
157322
  "json",
157281
157323
  "--no-session",
157282
157324
  "--no-skills",
157283
- "--no-prompt-templates"
157325
+ "--no-prompt-templates",
157326
+ "--no-context-files"
157284
157327
  ];
157285
157328
  const shouldLoadSubagentExtension = SUBAGENT_ENTRY_PATH && (SEARCH_ONLY_SUBAGENT_TOOL_AGENTS.has(options.agent) || DREAMER_ACTION_AGENTS.has(options.agent));
157286
157329
  if (shouldLoadSubagentExtension) {
@@ -157300,8 +157343,8 @@ function buildArgs(options, opts) {
157300
157343
  args.push("--no-tools");
157301
157344
  }
157302
157345
  }
157303
- if (options.systemPrompt && options.systemPrompt.length > 0) {
157304
- args.push("--system-prompt", options.systemPrompt);
157346
+ if (opts?.systemPromptPath) {
157347
+ args.push("--system-prompt", opts.systemPromptPath);
157305
157348
  }
157306
157349
  if (typeof options.model === "string" && options.model.length > 0) {
157307
157350
  args.push("--model", resolveModelRefForPi(options.model));
@@ -172538,7 +172581,7 @@ var DreamTasksSchema = exports_external.object({
172538
172581
  }).describe("Per-task scheduling + model config. Each task has its own cron schedule and may override the dreamer-level model.");
172539
172582
  var DreamerConfigSchema = AgentOverrideConfigSchema.merge(exports_external.object({
172540
172583
  tasks: DreamTasksSchema.default(() => DreamTasksSchema.parse({})),
172541
- inject_docs: exports_external.boolean().default(true).describe("Inject ARCHITECTURE.md and STRUCTURE.md into system prompt"),
172584
+ inject_docs: exports_external.boolean().default(true).describe("Inject ARCHITECTURE.md and STRUCTURE.md into the m[0] `<project-docs>` block (default true)"),
172542
172585
  thinking_level: PiThinkingLevelSchema.describe("Pi only: default thinking level for dreamer subagent invocations. See historian.thinking_level.")
172543
172586
  }));
172544
172587
  var SidekickConfigSchema = AgentOverrideConfigSchema.extend({
@@ -179044,7 +179087,7 @@ Output exactly JSON: {"met": false}`;
179044
179087
 
179045
179088
  // ../plugin/src/features/magic-context/dreamer/maintain-docs-protected-enforcement.ts
179046
179089
  init_logger();
179047
- import { existsSync as existsSync10, readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "node:fs";
179090
+ import { existsSync as existsSync10, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "node:fs";
179048
179091
  import { join as join11 } from "node:path";
179049
179092
 
179050
179093
  // ../plugin/src/features/magic-context/dreamer/protected-regions.ts
@@ -179164,7 +179207,7 @@ function enforceMaintainDocsProtectedRegions(args) {
179164
179207
  if (!violated) {
179165
179208
  continue;
179166
179209
  }
179167
- writeFileSync5(path9, text, "utf8");
179210
+ writeFileSync6(path9, text, "utf8");
179168
179211
  log(`[dreamer] maintain-docs altered a protected region in ${fileName} — restored from pre-task snapshot`);
179169
179212
  } catch (error51) {
179170
179213
  log(`[dreamer] maintain-docs protected-region enforcement failed for ${fileName}: ${error51}`);
@@ -189868,6 +189911,13 @@ function safeGetActiveUserMemoriesPi(db) {
189868
189911
  throw error51;
189869
189912
  }
189870
189913
  }
189914
+ var EMPTY_PI_PROJECT_DOCS = {
189915
+ renderedBlock: "",
189916
+ canonicalHash: ""
189917
+ };
189918
+ function readProjectDocsForPiM0(state) {
189919
+ return state.injectDocs !== false ? readProjectDocsCanonical(state.projectDirectory) : EMPTY_PI_PROJECT_DOCS;
189920
+ }
189871
189921
  function memoryProjectPath(state) {
189872
189922
  return state.memoryEnabled === false ? undefined : state.projectIdentity;
189873
189923
  }
@@ -189994,7 +190044,7 @@ function readCurrentMarkersFromCompartments(db, state, compartments, projectDocs
189994
190044
  projectMemoryEpoch: projectState?.projectMemoryEpoch ?? 0,
189995
190045
  workspaceFingerprint: workspace.isWorkspaced ? computeWorkspaceEpochFingerprint(db, workspace.identities) : null,
189996
190046
  projectUserProfileVersion: globalState?.projectUserProfileVersion ?? 0,
189997
- projectDocsHash: projectDocsHash ?? readProjectDocsCanonical(state.projectDirectory).canonicalHash,
190047
+ projectDocsHash: projectDocsHash ?? readProjectDocsForPiM0(state).canonicalHash,
189998
190048
  sessionFactsVersion: getSessionFactsVersion(db, state.sessionId),
189999
190049
  materializedAt: Date.now(),
190000
190050
  upgradeState: `${PI_M0_UPGRADE_STATE}:${compartments.some((c) => c.legacy === 1) ? "legacy" : "ready"}`,
@@ -190055,7 +190105,7 @@ ${memories.map((memory) => `- ${escapeXmlContent(memory.content)}`).join(`
190055
190105
  `)}
190056
190106
  </${wrapper}>`;
190057
190107
  }
190058
- function renderM0Pi(state, db, projectDocs = readProjectDocsCanonical(state.projectDirectory).renderedBlock, decayPressureMultiplier = 1, memoriesOverride, compartmentsOverride, userProfileOverride, workspaceOverride) {
190108
+ function renderM0Pi(state, db, projectDocs = readProjectDocsForPiM0(state).renderedBlock, decayPressureMultiplier = 1, memoriesOverride, compartmentsOverride, userProfileOverride, workspaceOverride) {
190059
190109
  const memPath = memoryProjectPath(state);
190060
190110
  const workspace = workspaceOverride ?? resolveWorkspaceRenderContextPi(state, db);
190061
190111
  const allMemories = memoriesOverride ?? (memPath ? workspace.isWorkspaced ? getMemoriesByProjects(db, workspace.expandedIdentities, ["active", "permanent"], Date.now(), workspace.ownIdentities, workspace.shareCategories) : getMemoriesByProject(db, memPath, ["active", "permanent"]) : []);
@@ -190123,7 +190173,7 @@ class PiMaterializeContentionError extends Error {
190123
190173
  this.name = "PiMaterializeContentionError";
190124
190174
  }
190125
190175
  }
190126
- function readFrozenM0InputsPi(state, db, docs = readProjectDocsCanonical(state.projectDirectory), memoryCutoff) {
190176
+ function readFrozenM0InputsPi(state, db, docs = readProjectDocsForPiM0(state), memoryCutoff) {
190127
190177
  const memPath = memoryProjectPath(state);
190128
190178
  const read = db.transaction(() => {
190129
190179
  const workspace = resolveWorkspaceRenderContextPi(state, db);
@@ -190154,7 +190204,7 @@ function readFrozenM0InputsPi(state, db, docs = readProjectDocsCanonical(state.p
190154
190204
  return read();
190155
190205
  }
190156
190206
  function renderFreshM0PiNonPersisted(state, db) {
190157
- const docs = readProjectDocsCanonical(state.projectDirectory);
190207
+ const docs = readProjectDocsForPiM0(state);
190158
190208
  const cachedMaterializedAt = getOrCreateSessionMeta(db, state.sessionId).cachedM0MaterializedAt ?? 0;
190159
190209
  const frozen = readFrozenM0InputsPi(state, db, docs, cachedMaterializedAt);
190160
190210
  frozen.markers.materializedAt = cachedMaterializedAt;
@@ -190174,7 +190224,7 @@ function renderFreshM0PiNonPersisted(state, db) {
190174
190224
  };
190175
190225
  }
190176
190226
  function materializeM0Pi(state, db) {
190177
- const docs = readProjectDocsCanonical(state.projectDirectory);
190227
+ const docs = readProjectDocsForPiM0(state);
190178
190228
  const foldMaterializedAt = Date.now();
190179
190229
  const frozen = readFrozenM0InputsPi(state, db, docs, foldMaterializedAt);
190180
190230
  const snapshotMarkers = frozen.markers;
@@ -190192,7 +190242,7 @@ function materializeM0Pi(state, db) {
190192
190242
  attempts += 1;
190193
190243
  }
190194
190244
  const m0Bytes = Buffer.from(m0, "utf8");
190195
- const phase3ProjectDocsHash = readProjectDocsCanonical(state.projectDirectory).canonicalHash;
190245
+ const phase3ProjectDocsHash = readProjectDocsForPiM0(state).canonicalHash;
190196
190246
  try {
190197
190247
  db.exec("BEGIN IMMEDIATE");
190198
190248
  } catch (error51) {
@@ -197323,6 +197373,7 @@ async function runPipeline(args) {
197323
197373
  projectIdentity: args.projectIdentity,
197324
197374
  projectDirectory: args.projectDirectory,
197325
197375
  memoryEnabled: args.injection.memoryEnabled,
197376
+ injectDocs: args.injection.injectDocs,
197326
197377
  injectionBudgetTokens: args.injection.injectionBudgetTokens,
197327
197378
  historyBudgetTokens: args.injection.historyBudgetTokens,
197328
197379
  hardSignals: piHardSignals
@@ -197634,7 +197685,7 @@ ${result}`;
197634
197685
  init_logger();
197635
197686
 
197636
197687
  // ../plugin/src/hooks/magic-context/historian-state-file.ts
197637
- import { mkdirSync as mkdirSync8, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6 } from "node:fs";
197688
+ import { mkdirSync as mkdirSync8, unlinkSync as unlinkSync2, writeFileSync as writeFileSync7 } from "node:fs";
197638
197689
  init_data_path();
197639
197690
  function cleanupHistorianStateFile(path11) {
197640
197691
  if (!path11)
@@ -197727,7 +197778,7 @@ function updateCompactionMarkerAfterPublication(db, sessionId, lastCompartmentEn
197727
197778
  }
197728
197779
 
197729
197780
  // ../plugin/src/hooks/magic-context/compartment-runner-historian.ts
197730
- import { mkdirSync as mkdirSync9, unlinkSync as unlinkSync3, writeFileSync as writeFileSync7 } from "node:fs";
197781
+ import { mkdirSync as mkdirSync9, unlinkSync as unlinkSync3, writeFileSync as writeFileSync8 } from "node:fs";
197731
197782
  import { join as join12 } from "node:path";
197732
197783
 
197733
197784
  // ../plugin/src/agents/historian.ts
@@ -198047,7 +198098,7 @@ function dumpHistorianResponse(sessionId, directory, label, text) {
198047
198098
  const safeSessionId = sanitizeDumpName(sessionId);
198048
198099
  const safeLabel = sanitizeDumpName(label);
198049
198100
  const dumpPath = join12(dumpDir, `${safeSessionId}-${safeLabel}-${Date.now()}.xml`);
198050
- writeFileSync7(dumpPath, text, "utf8");
198101
+ writeFileSync8(dumpPath, text, "utf8");
198051
198102
  sessionLog(sessionId, "compartment agent: historian response dumped", {
198052
198103
  label,
198053
198104
  dumpPath
@@ -200012,7 +200063,7 @@ function formatThresholdPercent(value) {
200012
200063
  // package.json
200013
200064
  var package_default = {
200014
200065
  name: "@cortexkit/pi-magic-context",
200015
- version: "0.30.4",
200066
+ version: "0.30.5",
200016
200067
  type: "module",
200017
200068
  description: "Pi coding agent extension for Magic Context — cross-session memory and context management",
200018
200069
  main: "dist/index.js",
@@ -206458,6 +206509,7 @@ async function src_default2(pi) {
206458
206509
  },
206459
206510
  injection: {
206460
206511
  memoryEnabled: cfg.memory.enabled,
206512
+ injectDocs: cfg.dreamer?.inject_docs !== false,
206461
206513
  injectionBudgetTokens: cfg.memory.injection_budget_tokens,
206462
206514
  temporalAwareness: cfg.temporal_awareness === true
206463
206515
  },
@@ -206686,13 +206738,11 @@ async function src_default2(pi) {
206686
206738
  }
206687
206739
  const isCacheBusting = sessionId ? hasSystemPromptRefresh(sessionId) : true;
206688
206740
  const effectiveDreamerRunnable = switchedProject ? isDreamerRunnable(effectiveConfig) : isDreamerRunnable(config2);
206689
- const injectDocs = switchedProject ? effectiveDreamerRunnable && (effectiveConfig.dreamer?.inject_docs ?? true) : isDreamerRunnable(config2) && (config2.dreamer?.inject_docs ?? true);
206690
206741
  const block = buildMagicContextBlock({
206691
206742
  db,
206692
206743
  cwd: currentProject.projectDir,
206693
206744
  sessionId,
206694
206745
  memoryEnabled: effectiveConfig.memory.enabled,
206695
- injectDocs,
206696
206746
  includeGuidance: true,
206697
206747
  protectedTags: effectiveConfig.protected_tags,
206698
206748
  ctxReduceEnabled: effectiveConfig.ctx_reduce_enabled,
@@ -159656,7 +159656,7 @@ var DreamTasksSchema = exports_external.object({
159656
159656
  }).describe("Per-task scheduling + model config. Each task has its own cron schedule and may override the dreamer-level model.");
159657
159657
  var DreamerConfigSchema = AgentOverrideConfigSchema.merge(exports_external.object({
159658
159658
  tasks: DreamTasksSchema.default(() => DreamTasksSchema.parse({})),
159659
- inject_docs: exports_external.boolean().default(true).describe("Inject ARCHITECTURE.md and STRUCTURE.md into system prompt"),
159659
+ inject_docs: exports_external.boolean().default(true).describe("Inject ARCHITECTURE.md and STRUCTURE.md into the m[0] `<project-docs>` block (default true)"),
159660
159660
  thinking_level: PiThinkingLevelSchema.describe("Pi only: default thinking level for dreamer subagent invocations. See historian.thinking_level.")
159661
159661
  }));
159662
159662
  var SidekickConfigSchema = AgentOverrideConfigSchema.extend({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.30.4",
3
+ "version": "0.30.5",
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",