@cortexkit/pi-magic-context 0.49.76 → 0.49.78

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.
@@ -138,10 +138,10 @@ async function serveV2ArchiveReads2(port, openConnections) {
138
138
  ] = await Promise.all([
139
139
  import("./sqlite-v89bj0yy.js"),
140
140
  import("./store-reader-mmfw2h48.js"),
141
- import("./store-grcwn6hs.js"),
141
+ import("./store-e9ve3qzt.js"),
142
142
  import("./read-session-chunk-ygwyfvtr.js"),
143
143
  import("./render-gbeyky54.js"),
144
- import("./search-archive-33p4gebn.js"),
144
+ import("./search-archive-hrp4sa2w.js"),
145
145
  import("./expand-attachments-8sxeyj26.js")
146
146
  ]);
147
147
  const pool = new V2StoreReaderPool;
@@ -7662,6 +7662,80 @@ async function reportSubagentStartupError(error) {
7662
7662
  });
7663
7663
  }
7664
7664
 
7665
+ // src/pi-tui-compat.ts
7666
+ import { realpathSync as realpathSync3 } from "node:fs";
7667
+ import { createRequire } from "node:module";
7668
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
7669
+ function legacyExports(tui) {
7670
+ if (typeof tui?.Box === "function" && typeof tui.Text === "function" && typeof tui.matchesKey === "function" && typeof tui.truncateToWidth === "function" && typeof tui.visibleWidth === "function") {
7671
+ return tui;
7672
+ }
7673
+ }
7674
+ async function loadOmpRowsTui() {
7675
+ try {
7676
+ const width = await import("@oh-my-pi/pi-tui/text/width");
7677
+ const keys = await import("@oh-my-pi/pi-tui/driver/input/keys");
7678
+ if (width.visibleWidth && width.truncate && keys.decodeKey) {
7679
+ return {
7680
+ visibleWidth: width.visibleWidth,
7681
+ truncate: width.truncate,
7682
+ decodeKey: keys.decodeKey
7683
+ };
7684
+ }
7685
+ } catch {}
7686
+ }
7687
+ async function loadDisplayTui() {
7688
+ const piPeer = "@earendil-works/pi-tui";
7689
+ if ((await resolvePiHarnessDetection()).kind === "omp") {
7690
+ const tui = await import("@oh-my-pi/pi-tui").catch(() => {
7691
+ return;
7692
+ });
7693
+ const legacy = legacyExports(tui);
7694
+ if (legacy)
7695
+ return { legacy };
7696
+ if (typeof tui?.createSurface === "function") {
7697
+ return { rows: await loadOmpRowsTui() };
7698
+ }
7699
+ } else if (process.argv[1]) {
7700
+ try {
7701
+ const hostRequire = createRequire(realpathSync3(process.argv[1]));
7702
+ const peerUrl = pathToFileURL2(hostRequire.resolve(piPeer));
7703
+ const tui = legacyExports(await import(peerUrl.href));
7704
+ if (tui)
7705
+ return { legacy: tui };
7706
+ } catch {}
7707
+ }
7708
+ return { legacy: legacyExports(await import(piPeer).catch(() => {
7709
+ return;
7710
+ })) };
7711
+ }
7712
+ var { legacy, rows } = await loadDisplayTui();
7713
+ var legacyTui = legacy;
7714
+ var hasOmpRowsTui = rows !== undefined;
7715
+ var canRenderPiRows = legacyTui !== undefined || hasOmpRowsTui;
7716
+ function piTerminalRows(host) {
7717
+ return "size" in host ? host.size().rows : host.terminal.rows;
7718
+ }
7719
+ function piOverlayOptions(width) {
7720
+ return {
7721
+ overlay: true,
7722
+ ...legacyTui && { overlayOptions: { anchor: "center", width } }
7723
+ };
7724
+ }
7725
+ function matchesKey(...args) {
7726
+ if (legacyTui)
7727
+ return legacyTui.matchesKey(...args);
7728
+ const [data, key] = args;
7729
+ const event = rows?.decodeKey(data, { kitty: false, backspaceIsCtrl: false });
7730
+ return event?.id === (key === "return" ? "enter" : key);
7731
+ }
7732
+ function truncateToWidth(...args) {
7733
+ return legacyTui?.truncateToWidth(...args) ?? rows?.truncate(...args) ?? args[0];
7734
+ }
7735
+ function visibleWidth(text) {
7736
+ return legacyTui?.visibleWidth(text) ?? rows?.visibleWidth(text) ?? text.length;
7737
+ }
7738
+
7665
7739
  // src/pi-ordinal-alignment.ts
7666
7740
  var ALIGNED = { kind: "aligned", offset: 0 };
7667
7741
  var resolvedByEntries = new WeakMap;
@@ -10371,9 +10445,6 @@ function throwReturnedToolErrors(tool) {
10371
10445
  }
10372
10446
 
10373
10447
  // src/tools/todo-view-pi.ts
10374
- import {
10375
- truncateToWidth
10376
- } from "@earendil-works/pi-tui";
10377
10448
  var TODO_TOOL_NAME = "todowrite";
10378
10449
  var TODOS_COMMAND_NAME = "todos";
10379
10450
  var WIDGET_KEY = "magic-context-todos";
@@ -10664,7 +10735,7 @@ class TodoOverlay {
10664
10735
  }
10665
10736
  }
10666
10737
  update(sessionId = this.sessionId) {
10667
- if (!this.uiCtx || !this.sessionId || sessionId !== this.sessionId)
10738
+ if (!canRenderPiRows || !this.uiCtx || !this.sessionId || sessionId !== this.sessionId)
10668
10739
  return;
10669
10740
  const todos = getTodoSnapshot(this.sessionId).todos;
10670
10741
  this.pruneCompletedDisplayState(todos);
@@ -10680,12 +10751,16 @@ class TodoOverlay {
10680
10751
  if (!this.widgetRegistered) {
10681
10752
  this.uiCtx.setWidget(WIDGET_KEY, (tui, theme) => {
10682
10753
  this.tui = tui;
10754
+ const clearRegistration = () => {
10755
+ if (this.tui !== tui)
10756
+ return;
10757
+ this.widgetRegistered = false;
10758
+ this.tui = undefined;
10759
+ };
10683
10760
  return {
10684
10761
  render: (width) => this.renderWidget(theme, width),
10685
- invalidate: () => {
10686
- this.widgetRegistered = false;
10687
- this.tui = undefined;
10688
- }
10762
+ invalidate: clearRegistration,
10763
+ dispose: clearRegistration
10689
10764
  };
10690
10765
  }, { placement: "aboveEditor" });
10691
10766
  this.widgetRegistered = true;
@@ -10872,11 +10947,9 @@ function createTodowriteTool() {
10872
10947
  }
10873
10948
  };
10874
10949
  },
10875
- renderCall(args, theme, context) {
10876
- return renderTodowriteCall(args, theme, context);
10877
- },
10878
- renderResult(result, _opts, theme, context) {
10879
- return renderTodowriteResult(result, theme, context);
10950
+ ...canRenderPiRows && {
10951
+ renderCall: (args, theme, context) => renderTodowriteCall(args, theme, hasOmpRowsTui ? undefined : context),
10952
+ renderResult: (result, _opts, theme, context) => renderTodowriteResult(result, theme, hasOmpRowsTui ? undefined : context)
10880
10953
  }
10881
10954
  };
10882
10955
  }
@@ -10969,4 +11042,4 @@ function registerMagicContextTools(pi, opts) {
10969
11042
  }
10970
11043
  }
10971
11044
 
10972
- export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, isCommitRetentionPaused, copyCommitRetentionRecovery, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, OPENCODE_OUTPUT_CAP, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, formatWindowSource, isSaneLimit, resolveOutputReserve, getSdkWindowGeometry, getSdkContextLimit, getSdkOutputLimit, getSdkInputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, resolvePiRealStableId, isPiContentFallbackId, isPiIndexFallbackId, piContentFallbackIds, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findRestartModelSeedFromBranch, iterateEntriesToRawMessageRange, iterateAsyncEntriesToRawMessageRange, convertEntriesToRawMessages, convertPiAssistantEntryById, convertEntriesToRawMessagePage, countPiRawMessages, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getSkippedDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, requestToolsFingerprint, classifyRequestToolsChange, requestToolSchemaDigest, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, withCachedM0MemoryIds, readCachedM0MemoryIds, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, TEMPORAL_MARKER_REPLAY_PATTERN, temporalMarkerPrefix, renderUserProfileContent, clearInjectionCache, getVisibleMemoryIds, orderHistorianMemories, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, resolveWorkspaceRenderContext, sourceNamesForMemories, readM0ProjectMemories, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, resetPrefixTrimFallbackState, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, neutralizeOmpMentions, restoreOmpMentions, resolvePiHarnessDetection, resolvePiHarnessKind, readSubagentStartupError, reportSubagentStartupError, inheritPiOrdinalAlignment, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
11045
+ export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, isCommitRetentionPaused, copyCommitRetentionRecovery, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, OPENCODE_OUTPUT_CAP, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, formatWindowSource, isSaneLimit, resolveOutputReserve, getSdkWindowGeometry, getSdkContextLimit, getSdkOutputLimit, getSdkInputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, resolvePiRealStableId, isPiContentFallbackId, isPiIndexFallbackId, piContentFallbackIds, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findRestartModelSeedFromBranch, iterateEntriesToRawMessageRange, iterateAsyncEntriesToRawMessageRange, convertEntriesToRawMessages, convertPiAssistantEntryById, convertEntriesToRawMessagePage, countPiRawMessages, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getSkippedDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, requestToolsFingerprint, classifyRequestToolsChange, requestToolSchemaDigest, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, withCachedM0MemoryIds, readCachedM0MemoryIds, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, TEMPORAL_MARKER_REPLAY_PATTERN, temporalMarkerPrefix, renderUserProfileContent, clearInjectionCache, getVisibleMemoryIds, orderHistorianMemories, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, resolveWorkspaceRenderContext, sourceNamesForMemories, readM0ProjectMemories, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, resetPrefixTrimFallbackState, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, neutralizeOmpMentions, restoreOmpMentions, resolvePiHarnessDetection, resolvePiHarnessKind, readSubagentStartupError, reportSubagentStartupError, legacyTui, canRenderPiRows, piTerminalRows, piOverlayOptions, matchesKey, truncateToWidth, visibleWidth, inheritPiOrdinalAlignment, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
package/dist/index.js CHANGED
@@ -145,6 +145,13 @@ import {
145
145
  resolvePiHarnessDetection,
146
146
  resolvePiHarnessKind,
147
147
  readSubagentStartupError,
148
+ legacyTui,
149
+ canRenderPiRows,
150
+ piTerminalRows,
151
+ piOverlayOptions,
152
+ matchesKey,
153
+ truncateToWidth,
154
+ visibleWidth,
148
155
  inheritPiOrdinalAlignment,
149
156
  resolvePiOrdinalAlignment,
150
157
  piRawOrdinalOffsetSource,
@@ -158,7 +165,7 @@ import {
158
165
  registerTodoStateLifecycle,
159
166
  syncCtxMemoryToolEnabled,
160
167
  registerMagicContextTools
161
- } from "./index-vpby27d0.js";
168
+ } from "./index-6bjc4pam.js";
162
169
  import"./index-4knyh1kt.js";
163
170
  import {
164
171
  canonicalModelIdentity,
@@ -858,7 +865,7 @@ import {
858
865
  } from "./index-wmkkxwvf.js";
859
866
  import"./index-71rg8j43.js";
860
867
  import"./index-8d2z6503.js";
861
- import"./index-0x61mf6t.js";
868
+ import"./index-077gbj21.js";
862
869
  import"./index-cyzsn2hb.js";
863
870
  import {
864
871
  __toESM
@@ -3611,7 +3618,7 @@ function startHostStallProfilerSwitch() {
3611
3618
  // package.json
3612
3619
  var package_default = {
3613
3620
  name: "@cortexkit/pi-magic-context",
3614
- version: "0.49.76",
3621
+ version: "0.49.78",
3615
3622
  type: "module",
3616
3623
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3617
3624
  main: "dist/index.js",
@@ -3640,7 +3647,7 @@ var package_default = {
3640
3647
  ],
3641
3648
  "//": "The build intentionally bundles typebox (no --external typebox) and keeps it a regular dependency. OMP's extension loader rewrites every bare `typebox` import to its own omptype-based shim, whose schemas are callable objects rather than JSON Schema; they fail structuredClone during tool registration, so an external typebox import stops Magic Context loading on OMP. src/typebox-bundling.test.ts guards this.",
3642
3649
  scripts: {
3643
- build: "bun ../../scripts/check-bun.mjs && tsc -p ../retina-local-fs/tsconfig.build.json && bun ../../scripts/clean-dist-chunks.mjs dist index.js subagent-entry.js historian-calibration-extension.js embedding-worker-process.js raw-ordinal-warmup-worker.js tag-snapshot-worker-pi.js transformers-web.js transformers-node-wasm.js && bun build ../plugin/src/features/magic-context/memory/transformers-web-entry.ts --outfile dist/transformers-web.js --target browser --format esm --external onnxruntime-web && bun ../plugin/scripts/build-transformers-node-wasm.ts dist && bun build src/index.ts src/tag-snapshot-worker-pi.ts src/subagent-entry.ts src/historian-calibration-extension.ts ../plugin/src/features/magic-context/memory/embedding-worker.ts ../plugin/src/features/magic-context/memory/embedding-worker-process.ts ../plugin/src/features/magic-context/migration-worker.ts ../plugin/src/hooks/magic-context/auto-search-worker.ts ../plugin/src/hooks/magic-context/raw-ordinal-warmup-worker.ts ../plugin/src/features/magic-context/compaction-marker-candidates-worker.ts ../plugin/src/features/magic-context/chunk-embedding-write-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --format esm --splitting --external @earendil-works/pi-coding-agent --external @oh-my-pi/pi-coding-agent --external @earendil-works/pi-tui --external @earendil-works/pi-ai --external onnxruntime-node --external onnxruntime-web --external sharp --external bun:ffi --external node:sqlite",
3650
+ build: "bun ../../scripts/check-bun.mjs && tsc -p ../retina-local-fs/tsconfig.build.json && bun ../../scripts/clean-dist-chunks.mjs dist index.js subagent-entry.js historian-calibration-extension.js embedding-worker-process.js raw-ordinal-warmup-worker.js tag-snapshot-worker-pi.js transformers-web.js transformers-node-wasm.js && bun build ../plugin/src/features/magic-context/memory/transformers-web-entry.ts --outfile dist/transformers-web.js --target browser --format esm --external onnxruntime-web && bun ../plugin/scripts/build-transformers-node-wasm.ts dist && bun build src/index.ts src/tag-snapshot-worker-pi.ts src/subagent-entry.ts src/historian-calibration-extension.ts ../plugin/src/features/magic-context/memory/embedding-worker.ts ../plugin/src/features/magic-context/memory/embedding-worker-process.ts ../plugin/src/features/magic-context/migration-worker.ts ../plugin/src/hooks/magic-context/auto-search-worker.ts ../plugin/src/hooks/magic-context/raw-ordinal-warmup-worker.ts ../plugin/src/features/magic-context/compaction-marker-candidates-worker.ts ../plugin/src/features/magic-context/chunk-embedding-write-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --format esm --splitting --external @earendil-works/pi-coding-agent --external @oh-my-pi/pi-coding-agent --external @earendil-works/pi-tui --external @oh-my-pi/pi-tui --external '@oh-my-pi/pi-tui/*' --external @earendil-works/pi-ai --external onnxruntime-node --external onnxruntime-web --external sharp --external bun:ffi --external node:sqlite",
3644
3651
  "build:e2e-argv": `bun ../../scripts/clean-dist-chunks.mjs ../../tests/docker/.generated subagent-runner-e2e.mjs && bun build src/subagent-runner.ts --outdir ../../tests/docker/.generated --entry-naming 'subagent-runner-e2e.mjs' --splitting --target node --format esm --external node:sqlite && node --input-type=module -e 'const { __test } = await import("../../tests/docker/.generated/subagent-runner-e2e.mjs"); if (typeof __test.buildArgs !== "function" || typeof __test.resolvePiInvocation !== "function") throw new Error("argv renderer exports missing"); console.log("Node argv renderer: 2 exports loaded")'`,
3645
3652
  typecheck: "tsc -p ../retina-local-fs/tsconfig.build.json && tsc --noEmit",
3646
3653
  test: "bun ../../scripts/check-bun.mjs && bun install --frozen-lockfile && MC_SLOW_TESTS=0 BUN_JSC_useOMGJIT=0 bun test --parallel=4 --timeout 30000",
@@ -22181,10 +22188,11 @@ function buildArgs(options, opts) {
22181
22188
  args.push("--extension", historianCalibrationEntryPath);
22182
22189
  }
22183
22190
  const strictTools = STRICT_TOOL_ALLOWLIST.get(options.agent);
22191
+ const emptyToolFlag = ompTarget ? "--tools=" : "--no-tools";
22184
22192
  let activeToolNames = [];
22185
22193
  if (strictTools === undefined) {
22186
- sessionLog2(options.accountingSessionId ?? "pi-subagent", `Pi subagent agent "${options.agent}" has no strict tool allow-list; forcing --no-tools`);
22187
- args.push("--no-tools");
22194
+ sessionLog2(options.accountingSessionId ?? "pi-subagent", `Pi subagent agent "${options.agent}" has no strict tool allow-list; forcing an empty tool list`);
22195
+ args.push(emptyToolFlag);
22188
22196
  } else {
22189
22197
  const resolution = resolveHostToolAllowlistDetails(strictTools, ompTarget, ompTarget ? opts?.hostToolNames : undefined);
22190
22198
  const hostTools = resolution.tools;
@@ -22202,7 +22210,7 @@ function buildArgs(options, opts) {
22202
22210
  if (hostTools.length > 0) {
22203
22211
  args.push("--tools", hostTools.join(","));
22204
22212
  } else {
22205
- args.push("--no-tools");
22213
+ args.push(emptyToolFlag);
22206
22214
  }
22207
22215
  }
22208
22216
  if (ompTarget) {
@@ -23527,7 +23535,6 @@ function makeMessage(role, parts) {
23527
23535
  }
23528
23536
 
23529
23537
  // src/commands/pi-command-utils.ts
23530
- import { Box, matchesKey, Text } from "@earendil-works/pi-tui";
23531
23538
  var CTX_STATUS_CUSTOM_TYPE = "ctx-status";
23532
23539
  var statusLifecycleSignals = new WeakMap;
23533
23540
  function registerCtxStatusLifecycleSignal(pi, signal) {
@@ -23549,11 +23556,13 @@ function resolveSessionId(ctx) {
23549
23556
  }
23550
23557
  }
23551
23558
  async function showCtxStatusDialog(ctx, content) {
23559
+ if (!canRenderPiRows)
23560
+ return false;
23552
23561
  let factoryInvoked = false;
23553
23562
  await ctx.ui.custom((_tui, theme, _keybindings, done) => {
23554
23563
  factoryInvoked = true;
23555
23564
  return new CtxStatusDialog(content, theme, done);
23556
- }, { overlay: true, overlayOptions: { anchor: "center", width: 92 } });
23565
+ }, piOverlayOptions(92));
23557
23566
  return factoryInvoked;
23558
23567
  }
23559
23568
 
@@ -23597,13 +23606,13 @@ function statusTitleColor(level) {
23597
23606
  }
23598
23607
  var renderCtxStatusEntry = (entry, _options, theme) => {
23599
23608
  const data = entry?.data;
23600
- if (!data || typeof data !== "object" || typeof data.title !== "string" || typeof data.text !== "string") {
23609
+ if (!legacyTui || !data || typeof data !== "object" || typeof data.title !== "string" || typeof data.text !== "string") {
23601
23610
  return;
23602
23611
  }
23603
23612
  const title = theme.bold(theme.fg(statusTitleColor(data.level), `[${data.title}]`));
23604
23613
  const body = theme.fg("customMessageText", data.text);
23605
- const box = new Box(1, 0, (text) => theme.bg("customMessageBg", text));
23606
- box.addChild(new Text(`${title}
23614
+ const box = new legacyTui.Box(1, 0, (text) => theme.bg("customMessageBg", text));
23615
+ box.addChild(new legacyTui.Text(`${title}
23607
23616
  ${body}`));
23608
23617
  return box;
23609
23618
  };
@@ -37700,9 +37709,6 @@ function resolvePiUsableContextLimit(args) {
37700
37709
  return resolvePiWindowGeometry(args)?.usableSoft;
37701
37710
  }
37702
37711
 
37703
- // src/pi-context-refusal.ts
37704
- import { Text as Text2 } from "@earendil-works/pi-tui";
37705
-
37706
37712
  // src/omp-diagnostic-context.ts
37707
37713
  function isOmpDumpContextStack(stack) {
37708
37714
  if (!stack)
@@ -44719,7 +44725,10 @@ function registerPiGuardedContext(pi, handler, options = {}) {
44719
44725
  return operation?.refused ? piRefusedPayload(operation.refusalMessage ?? RETRY_MESSAGE) : undefined;
44720
44726
  });
44721
44727
  }
44722
- pi.registerEntryRenderer?.(ENTRY_TYPE, (entry) => new Text2(entry.data?.message ?? RETRY_MESSAGE, 0, 0));
44728
+ if (legacyTui) {
44729
+ const { Text } = legacyTui;
44730
+ pi.registerEntryRenderer?.(ENTRY_TYPE, (entry) => new Text(entry.data?.message ?? RETRY_MESSAGE, 0, 0));
44731
+ }
44723
44732
  pi.on("context", async (event, ctx) => {
44724
44733
  if (fenceEnabled && isOmpDumpContext())
44725
44734
  return { messages: event.messages };
@@ -55132,13 +55141,6 @@ function inferLevel(text) {
55132
55141
  return "info";
55133
55142
  }
55134
55143
 
55135
- // src/dialogs/status-dialog.ts
55136
- import {
55137
- matchesKey as matchesKey2,
55138
- truncateToWidth,
55139
- visibleWidth
55140
- } from "@earendil-works/pi-tui";
55141
-
55142
55144
  // ../plugin/src/features/magic-context/memory/memory-diagnostics.ts
55143
55145
  function emptyMemoryImportanceHistogram() {
55144
55146
  return {
@@ -56183,6 +56185,10 @@ async function showStatusDialog(pi, ctx, deps) {
56183
56185
  const sessionId = resolveSessionId(ctx);
56184
56186
  if (!sessionId)
56185
56187
  throw new Error("No active Pi session is available.");
56188
+ if (!canRenderPiRows) {
56189
+ ctx.ui.notify(formatPiStatusSummary(buildPiStatusDetail(pi, ctx, deps, sessionId)), "info");
56190
+ return;
56191
+ }
56186
56192
  await ctx.ui.custom((tui, theme, _keybindings, done) => new StatusDialogComponent({
56187
56193
  pi,
56188
56194
  ctx,
@@ -56191,10 +56197,7 @@ async function showStatusDialog(pi, ctx, deps) {
56191
56197
  theme,
56192
56198
  tui,
56193
56199
  done
56194
- }), {
56195
- overlay: true,
56196
- overlayOptions: { anchor: "center", width: 78 }
56197
- });
56200
+ }), piOverlayOptions(78));
56198
56201
  }
56199
56202
  var openStatusDialogs = new Set;
56200
56203
  function stopStatusDialogRefresh() {
@@ -56228,22 +56231,22 @@ class StatusDialogComponent {
56228
56231
  handleInput(data) {
56229
56232
  if (this.closed)
56230
56233
  return;
56231
- if (matchesKey2(data, "escape") || matchesKey2(data, "ctrl+c") || matchesKey2(data, "return")) {
56234
+ if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c") || matchesKey(data, "return")) {
56232
56235
  this.close();
56233
56236
  return;
56234
56237
  }
56235
56238
  let offset = this.scrollOffset;
56236
- if (matchesKey2(data, "up"))
56239
+ if (matchesKey(data, "up"))
56237
56240
  offset -= 1;
56238
- else if (matchesKey2(data, "down"))
56241
+ else if (matchesKey(data, "down"))
56239
56242
  offset += 1;
56240
- else if (matchesKey2(data, "pageUp"))
56243
+ else if (matchesKey(data, "pageUp"))
56241
56244
  offset -= this.viewportHeight;
56242
- else if (matchesKey2(data, "pageDown"))
56245
+ else if (matchesKey(data, "pageDown"))
56243
56246
  offset += this.viewportHeight;
56244
- else if (matchesKey2(data, "home"))
56247
+ else if (matchesKey(data, "home"))
56245
56248
  offset = 0;
56246
- else if (matchesKey2(data, "end"))
56249
+ else if (matchesKey(data, "end"))
56247
56250
  offset = this.maxScrollOffset;
56248
56251
  else
56249
56252
  return;
@@ -56261,7 +56264,7 @@ class StatusDialogComponent {
56261
56264
  const frameWidth = BORDER_COLUMNS + PADDING_COLUMNS;
56262
56265
  const innerWidth = Math.max(1, width - frameWidth);
56263
56266
  const inner = renderPiStatusOverlay(this.detail, this.props.theme, innerWidth);
56264
- const rows = Math.max(0, this.props.tui.terminal.rows);
56267
+ const rows = Math.max(0, piTerminalRows(this.props.tui));
56265
56268
  const header = inner.slice(0, 1);
56266
56269
  const footer = inner.slice(-1);
56267
56270
  const body = inner.slice(header.length, inner.length - footer.length);
@@ -19,7 +19,7 @@ serveWorkerJobs(async (input, port) => {
19
19
  await main();
20
20
  async function main() {
21
21
  if (input.v2ArchiveReader) {
22
- const { serveV2ArchiveReads } = await import("./v2-archive-reader-5cydt27v.js");
22
+ const { serveV2ArchiveReads } = await import("./v2-archive-reader-w897mvf5.js");
23
23
  await serveV2ArchiveReads(port, openConnections);
24
24
  return;
25
25
  }
@@ -51,7 +51,7 @@ serveWorkerJobs(async (input, port) => {
51
51
  await runMessageFtsRowidMapBackfill(db);
52
52
  reply = { kind: "fts-rowid-backfill" };
53
53
  } else if (input.searchArchive) {
54
- const { renderSearchArchive } = await import("./search-archive-33p4gebn.js");
54
+ const { renderSearchArchive } = await import("./search-archive-hrp4sa2w.js");
55
55
  const { readRawSessionMessageIdOrdinalsForRangeFromDb } = await import("./read-session-raw-0tytrjye.js");
56
56
  const archive = input.searchArchive;
57
57
  let raw;
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  renderSearchArchive2
3
3
  } from "./index-cyzsn2hb.js";
4
- import"./index-0x61mf6t.js";
4
+ import"./index-077gbj21.js";
5
5
  import"./index-8d2z6503.js";
6
6
  import"./index-apff8dej.js";
7
7
  import"./index-6gwasf0v.js";
@@ -18,7 +18,80 @@ function isStorageNoticeText(text) {
18
18
  return typeof text === "string" && text.startsWith(STORAGE_NOTICE_PREFIX);
19
19
  }
20
20
 
21
+ // ../plugin/src/v2/fold/host-media.ts
22
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
23
+ function isClassInstance(value) {
24
+ if (!isRecord(value))
25
+ return false;
26
+ const prototype = Object.getPrototypeOf(value);
27
+ return prototype !== Object.prototype && prototype !== null;
28
+ }
29
+ var rememberedAssetClass;
30
+ var rememberedAssetSchema;
31
+ var assetSchemaByClass = new WeakMap;
32
+ function decodeThroughHostSchema(encoded) {
33
+ const source = encoded.source;
34
+ const assetSchema = rememberedAssetSchema;
35
+ if (!assetSchema)
36
+ return "no host message schema with a media member seen";
37
+ const encoding = assetSchema.ast?.encoding;
38
+ const decode = Array.isArray(encoding) ? encoding[0]?.transformation?.decode : undefined;
39
+ const getter = decode;
40
+ let asset;
41
+ if (getter?._tag === "Transform") {
42
+ if (typeof getter.transform !== "function")
43
+ return "host media schema has no decode transformation";
44
+ asset = getter.transform(encoded);
45
+ } else {
46
+ if (getter?._tag !== undefined)
47
+ return `host media schema has unsupported decode transformation: ${String(getter._tag)}`;
48
+ const run = getter?.run;
49
+ if (typeof run !== "function")
50
+ return "host media schema has no decode transformation";
51
+ const result = run.call(decode, { _tag: "Some", value: encoded }, {});
52
+ const option = result?._tag === "Success" ? result.value : undefined;
53
+ asset = option?._tag === "Some" ? option.value : undefined;
54
+ }
55
+ if (!isClassInstance(asset) || asset.source !== source)
56
+ return "host media schema decode did not return an asset";
57
+ return asset;
58
+ }
59
+ function hostMediaAsset(data, mediaType) {
60
+ return hostMediaFromEncoded({ source: { type: "base64", data, mediaType } });
61
+ }
62
+ function hostMediaFromEncoded(value) {
63
+ if (!isRecord(value.source))
64
+ return "missing Media.Asset source";
65
+ const encoded = structuredClone(value);
66
+ if (encoded.source.type === "bytes") {
67
+ if (typeof encoded.source.data !== "string")
68
+ return "bytes media has no JSON codec payload";
69
+ encoded.source.data = new Uint8Array(Buffer.from(encoded.source.data, "base64"));
70
+ }
71
+ if (!["bytes", "base64", "url", "ref"].includes(String(encoded.source.type)))
72
+ return "unknown Media.Asset source";
73
+ let first = "no Media.Asset seen in this process";
74
+ if (rememberedAssetClass) {
75
+ try {
76
+ return new rememberedAssetClass(encoded);
77
+ } catch (error) {
78
+ first = `remembered asset class threw: ${String(error)}`;
79
+ }
80
+ }
81
+ let second;
82
+ try {
83
+ const decoded = decodeThroughHostSchema(encoded);
84
+ if (typeof decoded !== "string")
85
+ return decoded;
86
+ second = decoded;
87
+ } catch (error) {
88
+ second = `host media schema decode threw: ${String(error)}`;
89
+ }
90
+ return `${first}; ${second}`;
91
+ }
92
+
21
93
  // ../plugin/src/v2/fold/restore.ts
94
+ var HOST_RESTORE_MEDIA = { asset: hostMediaAsset, unavailable: () => {} };
22
95
  function unavailableAttachmentNote(name, mediaType) {
23
96
  return `[Attachment ${name ? `"${name}" ` : ""}(${mediaType}) is not available in this restored history]`;
24
97
  }
@@ -69,17 +142,6 @@ ${[
69
142
  return [];
70
143
  const metadata = file.description === undefined ? undefined : { description: file.description };
71
144
  const located = location ? [{ type: "text", text: `Attached file: ${location}` }] : [];
72
- if (!media)
73
- return [
74
- ...located,
75
- {
76
- type: "media",
77
- mediaType: file.mime,
78
- data: file.data,
79
- filename: file.name,
80
- metadata
81
- }
82
- ];
83
145
  const asset = media.asset(file.data, file.mime);
84
146
  if (typeof asset === "string") {
85
147
  media.unavailable({ rowID, name: file.name, mediaType: file.mime, reason: asset });
@@ -91,7 +153,7 @@ ${[
91
153
  return [...located, { type: "media", media: asset, filename: file.name, metadata }];
92
154
  });
93
155
  }
94
- function restoreRow(row, model, media) {
156
+ function restoreRow(row, model, media = HOST_RESTORE_MEDIA) {
95
157
  const data = row.data;
96
158
  const make = (role, content, metadata = data.metadata) => ({
97
159
  id: row.id,
@@ -251,8 +313,12 @@ function toolStateContent(state) {
251
313
  var rawMessageTypes = new Set(RAW_MESSAGE_TYPES2);
252
314
  var isRawRow = (row) => rawMessageTypes.has(row.type);
253
315
  var NO_MODEL = { providerID: "", id: "" };
316
+ var NO_MEDIA = {
317
+ asset: () => "rendered only to read message ids",
318
+ unavailable: () => {}
319
+ };
254
320
  function hostServesRowById(row) {
255
- return isRawRow(row) && restoreRow(row, NO_MODEL).some((message) => message.id === row.id);
321
+ return isRawRow(row) && restoreRow(row, NO_MODEL, NO_MEDIA).some((message) => message.id === row.id);
256
322
  }
257
323
  function projectRawMessages(rows, ordinalFor) {
258
324
  return rows.filter(isRawRow).map((row, index) => {
@@ -34,7 +34,7 @@ import {
34
34
  resolvePiHarnessKind,
35
35
  reportSubagentStartupError,
36
36
  registerMagicContextTools
37
- } from "./index-vpby27d0.js";
37
+ } from "./index-6bjc4pam.js";
38
38
  import"./index-vcegxfwg.js";
39
39
  import"./index-5rcjs14a.js";
40
40
  import"./index-cxczethe.js";
@@ -52,7 +52,7 @@ import"./index-6x556c2q.js";
52
52
  import"./index-nvh6d3bz.js";
53
53
  import"./index-k7a8x7ba.js";
54
54
  import"./index-8d2z6503.js";
55
- import"./index-0x61mf6t.js";
55
+ import"./index-077gbj21.js";
56
56
  import"./index-cyzsn2hb.js";
57
57
  import"./index-gczr1m66.js";
58
58
  import"./index-29nw7n1r.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readV2ArchiveOffThread2,
3
3
  serveV2ArchiveReads2
4
- } from "./index-0x61mf6t.js";
4
+ } from "./index-077gbj21.js";
5
5
  import"./index-8sqebjzk.js";
6
6
  import"./index-2qtx0q6h.js";
7
7
  import"./index-x2n261wp.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.49.76",
3
+ "version": "0.49.78",
4
4
  "type": "module",
5
5
  "description": "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",
@@ -29,7 +29,7 @@
29
29
  ],
30
30
  "//": "The build intentionally bundles typebox (no --external typebox) and keeps it a regular dependency. OMP's extension loader rewrites every bare `typebox` import to its own omptype-based shim, whose schemas are callable objects rather than JSON Schema; they fail structuredClone during tool registration, so an external typebox import stops Magic Context loading on OMP. src/typebox-bundling.test.ts guards this.",
31
31
  "scripts": {
32
- "build": "bun ../../scripts/check-bun.mjs && tsc -p ../retina-local-fs/tsconfig.build.json && bun ../../scripts/clean-dist-chunks.mjs dist index.js subagent-entry.js historian-calibration-extension.js embedding-worker-process.js raw-ordinal-warmup-worker.js tag-snapshot-worker-pi.js transformers-web.js transformers-node-wasm.js && bun build ../plugin/src/features/magic-context/memory/transformers-web-entry.ts --outfile dist/transformers-web.js --target browser --format esm --external onnxruntime-web && bun ../plugin/scripts/build-transformers-node-wasm.ts dist && bun build src/index.ts src/tag-snapshot-worker-pi.ts src/subagent-entry.ts src/historian-calibration-extension.ts ../plugin/src/features/magic-context/memory/embedding-worker.ts ../plugin/src/features/magic-context/memory/embedding-worker-process.ts ../plugin/src/features/magic-context/migration-worker.ts ../plugin/src/hooks/magic-context/auto-search-worker.ts ../plugin/src/hooks/magic-context/raw-ordinal-warmup-worker.ts ../plugin/src/features/magic-context/compaction-marker-candidates-worker.ts ../plugin/src/features/magic-context/chunk-embedding-write-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --format esm --splitting --external @earendil-works/pi-coding-agent --external @oh-my-pi/pi-coding-agent --external @earendil-works/pi-tui --external @earendil-works/pi-ai --external onnxruntime-node --external onnxruntime-web --external sharp --external bun:ffi --external node:sqlite",
32
+ "build": "bun ../../scripts/check-bun.mjs && tsc -p ../retina-local-fs/tsconfig.build.json && bun ../../scripts/clean-dist-chunks.mjs dist index.js subagent-entry.js historian-calibration-extension.js embedding-worker-process.js raw-ordinal-warmup-worker.js tag-snapshot-worker-pi.js transformers-web.js transformers-node-wasm.js && bun build ../plugin/src/features/magic-context/memory/transformers-web-entry.ts --outfile dist/transformers-web.js --target browser --format esm --external onnxruntime-web && bun ../plugin/scripts/build-transformers-node-wasm.ts dist && bun build src/index.ts src/tag-snapshot-worker-pi.ts src/subagent-entry.ts src/historian-calibration-extension.ts ../plugin/src/features/magic-context/memory/embedding-worker.ts ../plugin/src/features/magic-context/memory/embedding-worker-process.ts ../plugin/src/features/magic-context/migration-worker.ts ../plugin/src/hooks/magic-context/auto-search-worker.ts ../plugin/src/hooks/magic-context/raw-ordinal-warmup-worker.ts ../plugin/src/features/magic-context/compaction-marker-candidates-worker.ts ../plugin/src/features/magic-context/chunk-embedding-write-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --format esm --splitting --external @earendil-works/pi-coding-agent --external @oh-my-pi/pi-coding-agent --external @earendil-works/pi-tui --external @oh-my-pi/pi-tui --external '@oh-my-pi/pi-tui/*' --external @earendil-works/pi-ai --external onnxruntime-node --external onnxruntime-web --external sharp --external bun:ffi --external node:sqlite",
33
33
  "build:e2e-argv": "bun ../../scripts/clean-dist-chunks.mjs ../../tests/docker/.generated subagent-runner-e2e.mjs && bun build src/subagent-runner.ts --outdir ../../tests/docker/.generated --entry-naming 'subagent-runner-e2e.mjs' --splitting --target node --format esm --external node:sqlite && node --input-type=module -e 'const { __test } = await import(\"../../tests/docker/.generated/subagent-runner-e2e.mjs\"); if (typeof __test.buildArgs !== \"function\" || typeof __test.resolvePiInvocation !== \"function\") throw new Error(\"argv renderer exports missing\"); console.log(\"Node argv renderer: 2 exports loaded\")'",
34
34
  "typecheck": "tsc -p ../retina-local-fs/tsconfig.build.json && tsc --noEmit",
35
35
  "test": "bun ../../scripts/check-bun.mjs && bun install --frozen-lockfile && MC_SLOW_TESTS=0 BUN_JSC_useOMGJIT=0 bun test --parallel=4 --timeout 30000",