Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

8.2 KB
Raw Blame
// F1 foundation: spawn wrapper that hides child windows on Windows by default. See src/shared/spawn.ts.test.ts for invariant.
import {
  spawn,
  spawnSync,
  type SpawnOptions,
  type ChildProcess,
  type SpawnSyncOptionsWithStringEncoding,
} from 'node:child_process';
import { existsSync } from 'node:fs';
import { dirname, extname, join, win32 } from 'node:path';

export type SpawnHiddenOptions = SpawnOptions;

export function spawnHidden(
  command: string,
  args?: readonly string[],
  options?: SpawnOptions
): ChildProcess {
  // windowsHide MUST win over caller options: it is what keeps a background
  // daemon child from flashing a console. `detached: true` is safe with it —
  // on win32 the child gets no console window and outlives the launcher (see
  // ProcessManager.spawnDetachedWorkerDaemon, #5240).
  return spawn(command, args ?? [], { ...options, windowsHide: true });
}

export const WINDOWS_CMD_EXTENSIONS = new Set(['.cmd', '.bat']);
export const WINDOWS_NATIVE_EXTENSIONS = new Set(['.exe', '.com']);
export const WINDOWS_COMMAND_EXTENSIONS = new Set([
  ...WINDOWS_NATIVE_EXTENSIONS,
  ...WINDOWS_CMD_EXTENSIONS,
]);

export interface SpawnSyncInvocation {
  command: string;
  args: string[];
  options: SpawnSyncOptionsWithStringEncoding;
}

export function quoteWindowsCmdArgument(value: string): string {
  return `"${value.replace(/"/g, '""')}"`;
}

/** True when `command` is a natively-spawnable Windows binary (.exe/.com), not a .cmd/.bat shim. */
export function isWindowsNativeExecutable(command: string): boolean {
  return WINDOWS_NATIVE_EXTENSIONS.has(extname(command).toLowerCase());
}

/**
 * Absolute path of where.exe. Spawning the bare name lets Windows run a
 * `where.exe` from the current directory (often the user's project, for hooks)
 * before PATH, which would execute untrusted code.
 */
export function windowsWhereExecutablePath(env: NodeJS.ProcessEnv = process.env): string {
  const systemRoot = env.SystemRoot || env.SYSTEMROOT || env.windir || env.WINDIR || 'C:\\Windows';
  return join(systemRoot, 'System32', 'where.exe');
}

/**
 * True when `candidatePath` sits directly inside `cwd`. On Windows, where.exe
 * searches the current directory BEFORE PATH, so a `bun.exe` / `codex.exe` /
 * `dsh.exe` planted in the project a hook runs from would outrank the real
 * install and execute untrusted code.
 *
 * The comparison is flavor-aware and separator-insensitive: a Windows-style
 * `C:\tools\bun.exe` is parsed with win32 rules even on a POSIX test host
 * (POSIX dirname would otherwise treat the whole string as a basename and
 * resolve() would fold it into cwd, which is the bug this filter exists to
 * prevent). Case-folded: NTFS is case-insensitive. Injectable `cwd` for tests.
 */
export function isCurrentDirectoryCandidate(candidatePath: string, cwd: string = process.cwd()): boolean {
  const looksWindows = /^[a-zA-Z]:[\\/]|\\\\/.test(candidatePath);
  const dir = looksWindows ? win32.dirname(candidatePath) : dirname(candidatePath);
  const normalize = (p: string) => p.replace(/[\\/]+/g, '/').replace(/\/+$/, '').toLowerCase();
  return normalize(dir) === normalize(cwd);
}

/** Every PATH hit for `command`, in `where` order (PATH order). */
export function lookupWindowsCommandCandidates(command: string, cwd: string = process.cwd()): string[] {
  if (process.platform !== 'win32') return [];
  try {
    const result = spawnSync(windowsWhereExecutablePath(), [command], {
      encoding: 'utf-8',
      stdio: ['ignore', 'pipe', 'ignore'],
      windowsHide: true,
    });
    if (result.status !== 0 || !result.stdout.trim()) return [];
    return result.stdout
      .split(/\r?\n/)
      .map(line => line.trim())
      .filter(Boolean)
      // where.exe reports the current directory first, and hooks run with the
      // user's project as cwd: a planted `bun.exe`/`codex.exe`/`dsh.exe` there
      // would otherwise be returned to a caller that spawns it verbatim.
      .filter(line => !isCurrentDirectoryCandidate(line, cwd))
      // where.exe writes the console's active code page (cp949 on ko-KR) while
      // the `encoding: 'utf-8'` above decodes the bytes as UTF-8, so a
      // non-ASCII profile folder name arrives as U+FFFD and the path does not
      // exist (#4694, #3865). Callers spawn these paths; a nonexistent one can
      // only fail with ENOENT, so drop it here.
      .filter(line => existsSync(line));
  } catch {
    // where exits non-zero when absent and can throw if PATH is malformed.
    return [];
  }
}

type VoltaWhichRunner = (
  command: string,
  args: readonly string[],
  options: SpawnSyncOptionsWithStringEncoding,
) => { status: number | null; stdout: string };

const VOLTA_SHIM_RESOLUTION_TIMEOUT_MS = 5_000;

const runVoltaWhich: VoltaWhichRunner = (command, args, options) =>
  spawnSync(command, args, options);

export function selectWindowsCommandCandidate(
  candidates: string[],
  resolveShim?: (shimPath: string) => string | null,
): string | null {
  const native = candidates.find(isWindowsNativeExecutable);
  if (native) return native;

  const shim = candidates.find(candidate =>
    WINDOWS_CMD_EXTENSIONS.has(extname(candidate).toLowerCase()));
  if (shim && resolveShim) {
    const resolved = resolveShim(shim);
    if (resolved && isWindowsNativeExecutable(resolved)) {
      return resolved;
    }
  }

  return shim
    ?? candidates.find(candidate => WINDOWS_COMMAND_EXTENSIONS.has(extname(candidate).toLowerCase()))
    ?? candidates[0]
    ?? null;
}

export function resolveVoltaShim(
  command: string,
  shimPath: string,
  run: VoltaWhichRunner = runVoltaWhich,
): string | null {
  if (!/[\\/]volta[\\/]bin[\\/]/i.test(shimPath)) return null;
  try {
    const result = run(join(dirname(shimPath), 'volta.exe'), ['which', command], {
      encoding: 'utf-8',
      stdio: ['ignore', 'pipe', 'ignore'],
      timeout: VOLTA_SHIM_RESOLUTION_TIMEOUT_MS,
      windowsHide: true,
    });
    if (result.status !== 0 || !result.stdout.trim()) return null;
    return result.stdout.split(/\r?\n/).map(line => line.trim()).find(Boolean) ?? null;
  } catch {
    return null;
  }
}

export function lookupWindowsCommand(command: string): string | null {
  return selectWindowsCommandCandidate(
    lookupWindowsCommandCandidates(command),
    shimPath => resolveVoltaShim(command, shimPath),
  );
}

export interface CommandInvocation {
  command: string;
  args: string[];
  /** Set for a .cmd/.bat shim run through cmd.exe: Node must pass the payload unescaped. */
  windowsVerbatimArguments: boolean;
}

/**
 * How to start `command` with `args` (spawn or spawnSync). Node cannot start a
 * .cmd/.bat shim directly on Windows, so one runs through cmd.exe.
 */
export function commandInvocation(
  command: string,
  args: readonly string[],
  platform: NodeJS.Platform = process.platform,
): CommandInvocation {
  if (platform === 'win32' && WINDOWS_CMD_EXTENSIONS.has(extname(command).toLowerCase())) {
    const commandLine = [command, ...args].map(quoteWindowsCmdArgument).join(' ');
    return {
      command: process.env.ComSpec ?? 'cmd.exe',
      // Wrap the per-arg-quoted command line in ONE outer quote pair: `cmd /s /c`
      // strips the outermost quotes and leaves the inner per-arg quoting intact,
      // so a shim path (or any arg) containing spaces survives. Pairs with
      // windowsVerbatimArguments, which stops Node re-escaping this payload
      // (without it the leading `"` becomes `\"` and cmd.exe rejects the command).
      args: ['/d', '/s', '/c', `"${commandLine}"`],
      windowsVerbatimArguments: true,
    };
  }
  return { command, args: [...args], windowsVerbatimArguments: false };
}

export function buildSpawnSyncInvocation(
  command: string,
  args: readonly string[],
  options: SpawnSyncOptionsWithStringEncoding,
  platform: NodeJS.Platform = process.platform,
): SpawnSyncInvocation {
  const invocationOptions: SpawnSyncOptionsWithStringEncoding = {
    ...options,
    // Force hide on Windows last so callers cannot override it off (#3521).
    ...(platform === 'win32' ? { windowsHide: true } : {}),
  };
  const invocation = commandInvocation(command, args, platform);
  return {
    command: invocation.command,
    args: invocation.args,
    options: invocation.windowsVerbatimArguments ? { ...invocationOptions, windowsVerbatimArguments: true } : invocationOptions,
  };
}