Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

8.6 KB
Raw Blame
/**
 * Runtime detection of the Mercury ink patch set.
 *
 * Since ADR-017 ink is VENDORED: `vendor/ink` (stock 8.0.0 + the hunks in
 * scripts/apply-ink-patch.cjs, regenerated by scripts/vendor-ink.cjs) is
 * bundled into dist by tsup and aliased in vitest. The vendored build stamps
 * `globalThis.__mercuryInkPatch = { vendored: true, hunks }` and every hunk
 * sets a runtime global, so it is judged WITHOUT reading files — the stock
 * ink that may still sit in node_modules is irrelevant and never inspected.
 *
 * The file-based path below remains for a non-vendored ink (a dev running
 * source against node_modules); it is reported as source `node_modules`.
 *
 * On stock ink the TUI's `<Static itemKey>` prop is silently ignored: the
 * transcript stops rendering new messages once the bounded window starts
 * sliding (~100 messages), and the Yoga free-node hygiene is missing (WASM
 * "memory access out of bounds" crashes). The patch is applied by
 * postinstall, which npm users never see fail — so the TUI checks for the
 * patch markers at boot and says so loudly instead of degrading silently.
 *
 * Markers, in order of trust:
 *   1. `globalThis.__mercuryFrameGate` — set by patched ink.js at module
 *      eval. Works for bundled/standalone binaries too (no file reads).
 *   2. `components/Static.js` contains `itemKey` + `setCommitTick`.
 *   3. `reconciler.js` contains `clearYogaRefs`.
 * File-based markers are only consulted when the file could be read, so a
 * standalone binary (no node_modules on disk) is judged by the gate alone.
 */
// Side-effect import: evaluating ink (vendored in every build) installs the
// runtime markers this module reads.
import 'ink';
import { readFileSync, existsSync } from 'node:fs';
import { createRequire } from 'node:module';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

export type InkPatchSource = 'vendored' | 'node_modules';

export interface InkPatchStatus {
  /** True when every observable marker is present. */
  patched: boolean;
  /** Where the running ink came from: the bundled vendor/ink build, or an
   * ink resolved from node_modules (patched in place or stock). */
  source: InkPatchSource;
  /** Human-readable names of the missing markers (empty when patched). */
  missing: string[];
  /** Directory of the ink build that was inspected, when resolvable. */
  inkBuildDir?: string;
}

export interface InkPatchProbe {
  /** `globalThis.__mercuryFrameGate` (object when patched ink.js loaded). */
  frameGate?: unknown;
  /** `globalThis.__mercuryInkPatch` manifest ({ vendored, hunks }). */
  manifest?: unknown;
  /** `globalThis.__mercuryInkYogaHygiene` (true when patched reconciler.js loaded). */
  yogaHygiene?: unknown;
  /** `globalThis.__mercuryCursorAnchor` (object when the cursor hunk loaded). */
  cursorAnchor?: unknown;
  /** Contents of ink/build/components/Static.js; null/undefined = unreadable. */
  staticSource?: string | null;
  /** Contents of ink/build/reconciler.js; null/undefined = unreadable. */
  reconcilerSource?: string | null;
}

export const INK_PATCH_MARKERS = {
  frameGate: 'freeze gate (ink.js)',
  staticItemKey: 'Static.itemKey dedup (components/Static.js)',
  yogaHygiene: 'Yoga free-node hygiene (reconciler.js)',
  cursor: 'hardware cursor positioning (ink.js)',
} as const;

interface InkPatchManifest { vendored: boolean; hunks: string[] }

function asManifest(value: unknown): InkPatchManifest | null {
  if (!value || typeof value !== 'object') return null;
  const m = value as Partial<InkPatchManifest>;
  if (typeof m.vendored !== 'boolean' || !Array.isArray(m.hunks)) return null;
  return { vendored: m.vendored, hunks: m.hunks };
}

/** Pure evaluation of a probe — unit-testable without touching node_modules. */
export function evaluateInkPatch(probe: InkPatchProbe): InkPatchStatus {
  const missing: string[] = [];
  const manifest = asManifest(probe.manifest);
  if (manifest?.vendored) {
    // Vendored build: every hunk is observable through runtime globals.
    // Yoga hygiene is upstream since ink 8 (freeYogaSubtree), so the
    // vendored build no longer carries or reports it.
    if (!probe.frameGate || typeof probe.frameGate !== 'object') missing.push(INK_PATCH_MARKERS.frameGate);
    if (!manifest.hunks.includes('static-item-key')) missing.push(INK_PATCH_MARKERS.staticItemKey);
    if (!probe.cursorAnchor || typeof probe.cursorAnchor !== 'object') missing.push(INK_PATCH_MARKERS.cursor);
    return { patched: missing.length === 0, missing, source: 'vendored' };
  }
  if (!probe.frameGate || typeof probe.frameGate !== 'object') {
    missing.push(INK_PATCH_MARKERS.frameGate);
  }
  if (typeof probe.staticSource === 'string'
    && !(probe.staticSource.includes('itemKey') && probe.staticSource.includes('setCommitTick'))) {
    missing.push(INK_PATCH_MARKERS.staticItemKey);
  }
  if (typeof probe.reconcilerSource === 'string' && !probe.reconcilerSource.includes('clearYogaRefs')) {
    missing.push(INK_PATCH_MARKERS.yogaHygiene);
  }
  return { patched: missing.length === 0, missing, source: 'node_modules' };
}

/** Best-effort read of the ink build files Node would load from here. */
export function readInkSources(): Pick<InkPatchProbe, 'staticSource' | 'reconcilerSource'> & { inkBuildDir?: string } {
  try {
    const req = createRequire(import.meta.url);
    const inkBuildDir = dirname(req.resolve('ink'));
    const read = (p: string): string | null => {
      try { return readFileSync(p, 'utf8'); } catch { return null; }
    };
    return {
      inkBuildDir,
      staticSource: read(join(inkBuildDir, 'components', 'Static.js')),
      reconcilerSource: read(join(inkBuildDir, 'reconciler.js')),
    };
  } catch {
    return { staticSource: null, reconcilerSource: null };
  }
}

let cached: InkPatchStatus | null = null;

/**
 * Detect whether the running ink is patched. Cached per process; the result
 * is also mirrored to `globalThis.__mercuryInkPatchMissing` so any surface
 * (doctor, status) can report it without importing this module.
 */
export function detectInkPatch(force = false): InkPatchStatus {
  if (cached && !force) return cached;
  const g = globalThis as any;
  const vendored = asManifest(g.__mercuryInkPatch)?.vendored === true;
  // A vendored build never consults node_modules: whatever ink is installed
  // there is not the one rendering.
  const sources = vendored ? { staticSource: null, reconcilerSource: null, inkBuildDir: undefined } : readInkSources();
  const status = evaluateInkPatch({
    frameGate: g.__mercuryFrameGate,
    manifest: g.__mercuryInkPatch,
    yogaHygiene: g.__mercuryInkYogaHygiene,
    cursorAnchor: g.__mercuryCursorAnchor,
    staticSource: sources.staticSource,
    reconcilerSource: sources.reconcilerSource,
  });
  cached = { ...status, inkBuildDir: sources.inkBuildDir };
  (globalThis as any).__mercuryInkPatchMissing = !cached.patched;
  return cached;
}

/** Locate the shipped applier: walk up from this module (dist/ or src/ui/). */
export function findInkPatchScript(startDir: string = dirname(fileURLToPath(import.meta.url))): string | null {
  let dir = startDir;
  for (let i = 0; i < 5; i++) {
    const candidate = join(dir, 'scripts', 'apply-ink-patch.cjs');
    if (existsSync(candidate)) return candidate;
    const parent = resolve(dir, '..');
    if (parent === dir) break;
    dir = parent;
  }
  return null;
}

/** One-line description for `mercury doctor`. */
export function describeInkPatch(status: InkPatchStatus): string {
  if (!status.patched) return `MISSING (${status.missing.join('; ')})`;
  return status.source === 'vendored' ? 'vendored (patched ink 8.0.0 bundled)' : 'applied (node_modules)';
}

/** The one command a user should run to fix an unpatched install. Every
 * release bundles the patched ink, so outside a source checkout the fix is
 * a reinstall; in a checkout, regenerate vendor/ink and rebuild. */
export function inkPatchFixCommand(scriptPath: string | null = findInkPatchScript()): string {
  if (scriptPath) return `node "${scriptPath.replace(/apply-ink-patch\.cjs$/, 'vendor-ink.cjs')}" && npm run build`;
  return 'npm install -g @cosmicstack/mercury-agent --force   (every release bundles the patched ink)';
}

/** One-paragraph warning for the TUI transcript / doctor. */
export function inkPatchWarning(status: InkPatchStatus, fixCommand: string = inkPatchFixCommand()): string {
  return `⚠ Ink patch not applied (missing: ${status.missing.join('; ')}). `
    + 'On stock ink the transcript silently stops rendering new messages after ~100 and long sessions can crash '
    + '(Yoga WASM). The TUI keeps running, but to fix it run: '
    + `\`${fixCommand}\` and restart Mercury. If the script is missing, reinstall Mercury.`;
}