Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

8.7 KB
Raw Blame
import { basename, dirname } from 'node:path';
import {
  currentCliCommandName,
  formatRelativeAge,
  LOCAL_DIR,
  OK_DIR,
  RELATIVE_TIME_UNKNOWN,
} from '@inkeep/open-knowledge-core';
import { lockAdvertisesUi } from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import pc from 'picocolors';
import {
  discoverLockDirs,
  extractOkBinaryPath,
  type ProcessUsage,
  processCommand,
  processUsage,
} from '../utils/process-scan.ts';
import { inspectLock, type LockState } from './lock-state.ts';

interface PsEntry {
  directory: string | null;
  server: {
    port: number | null;
    status: Exclude<LockState['status'], 'missing' | 'corrupt' | 'read-error'>;
    pid: number;
    startedAt: string | null;
    usage: ProcessUsage | null;
  };
  ui: {
    port: number;
    status: LockState['status'];
    pid: number;
    startedAt: string;
    usage: ProcessUsage | null;
  } | null;
  hostname: string | null;
  lockPath: string;
  binary: string | null;
  command: string | null;
  isDesktop: boolean;
}

export function isDesktopCommand(command: string | null): boolean {
  if (command == null) return false;
  return (
    command.includes('--type=utility') &&
    command.includes('--utility-sub-type=node.mojom.NodeService')
  );
}

export function startedCell(isoString: string | null, now = Date.now()): string {
  if (isoString === null) return '—';
  const age = formatRelativeAge(isoString, now);
  return age === RELATIVE_TIME_UNKNOWN ? '—' : age;
}

function projectDirectoryForLockDir(lockDir: string): string | null {
  const parent = dirname(lockDir);
  if (basename(lockDir) === LOCAL_DIR && basename(parent) === OK_DIR) return dirname(parent);
  if (basename(lockDir) === OK_DIR) return parent;
  return null;
}

function buildEntry(
  lockDir: string,
  serverState: LockState,
  command: string | null,
  serverUsage: ProcessUsage | null,
): PsEntry | null {
  if (
    serverState.status === 'missing' ||
    serverState.status === 'corrupt' ||
    serverState.status === 'read-error'
  ) {
    return null;
  }

  if (serverState.status === 'unverified-owner') {
    return {
      directory: projectDirectoryForLockDir(lockDir),
      server: {
        port: null,
        status: serverState.status,
        pid: serverState.pid,
        startedAt: null,
        usage: null,
      },
      ui: null,
      hostname: null,
      lockPath: serverState.lockPath,
      binary: null,
      command: null,
      isDesktop: false,
    };
  }
  const serverLock = serverState.lock;

  const ui: PsEntry['ui'] =
    serverState.status === 'alive' && lockAdvertisesUi(serverLock)
      ? {
          port: serverLock.port,
          status: serverState.status,
          pid: serverLock.pid,
          startedAt: serverLock.startedAt,
          usage: serverUsage,
        }
      : null;

  return {
    directory: serverLock.worktreeRoot,
    server: {
      port: serverLock.port,
      status: serverState.status,
      pid: serverLock.pid,
      startedAt: serverLock.startedAt,
      usage: serverUsage,
    },
    ui,
    hostname: serverLock.hostname,
    lockPath: serverState.lockPath,
    binary: command == null ? null : extractOkBinaryPath(command),
    command,
    isDesktop: isDesktopCommand(command),
  };
}

type DisplayStatus = 'running' | 'desktop' | 'foreign' | 'stale' | 'unverified';

function displayStatus(entry: PsEntry): DisplayStatus {
  const serverStatus = entry.server.status;
  switch (serverStatus) {
    case 'unverified-owner':
      return 'unverified';
    case 'alive':
      return entry.isDesktop ? 'desktop' : 'running';
    case 'foreign-host':
      return entry.isDesktop ? 'desktop' : 'foreign';
    case 'dead-pid':
    case 'reused-pid':
      return 'stale';
    default: {
      const exhaustive: never = serverStatus;
      return exhaustive;
    }
  }
}

const DEFAULT_VISIBLE: ReadonlySet<DisplayStatus> = new Set([
  'running',
  'desktop',
  'foreign',
  'unverified',
]);

function colorStatus(label: DisplayStatus): string {
  switch (label) {
    case 'running':
      return pc.green(label);
    case 'desktop':
      return pc.blue(label);
    case 'foreign':
      return pc.cyan(label);
    case 'unverified':
    case 'stale':
      return pc.yellow(label);
  }
}

function formatUsage(usage: ProcessUsage | null): string {
  if (usage == null) return '—';
  return `${usage.cpuPercent.toFixed(1)}% / ${usage.memPercent.toFixed(1)}%`;
}

function formatCombinedUsage(entry: PsEntry): string {
  return `${formatUsage(entry.server.usage)} | ${formatUsage(entry.ui?.usage ?? null)}`;
}

function formatPorts(entry: PsEntry): string {
  const serverPort =
    entry.server.port === null
      ? '—'
      : entry.server.port === 0
        ? '(starting)'
        : String(entry.server.port);
  const uiPort = entry.ui == null ? '—' : String(entry.ui.port);
  return `${serverPort} / ${uiPort}`;
}

export function renderTable(entries: PsEntry[]): string {
  if (entries.length === 0) {
    return 'No open-knowledge servers found.';
  }

  const headers = [
    'DIRECTORY',
    'PORTS (API/UI)',
    'CPU/MEM (API | UI)',
    'STATUS',
    'PID',
    'STARTED',
    'BINARY',
  ];
  const rows = entries.map((e) => {
    return [
      e.directory ?? '—',
      formatPorts(e),
      formatCombinedUsage(e),
      displayStatus(e),
      String(e.server.pid),
      startedCell(e.server.startedAt),
      e.binary ?? '—',
    ];
  });

  const colCount = headers.length;
  const widths: number[] = headers.map((h) => h.length);
  for (const row of rows) {
    for (let i = 0; i < colCount; i++) {
      widths[i] = Math.max(widths[i] ?? 0, (row[i] ?? '').length);
    }
  }

  const headerLine = headers
    .map((h, i) => h.padEnd(widths[i] ?? 0))
    .join('  ')
    .trimEnd();

  const dataLines = entries.map((entry, rowIdx) => {
    const row = rows[rowIdx] ?? [];
    const cols: string[] = [];
    for (let i = 0; i < colCount; i++) {
      let cell = (row[i] ?? '').padEnd(widths[i] ?? 0);
      if (i === 3) {
        const rawCell = row[i] ?? '';
        const colored = colorStatus(displayStatus(entry));
        const padding = ' '.repeat(Math.max(0, (widths[i] ?? 0) - rawCell.length));
        cell = colored + padding;
      }
      cols.push(cell);
    }
    return cols.join('  ').trimEnd();
  });

  const hint = pc.dim(`To stop a server: ${currentCliCommandName()} stop <port|pid|directory|all>`);
  return [headerLine, ...dataLines, '', hint].join('\n');
}

interface RunPsDeps {
  discover?: () => Promise<string[]>;
  inspect?: (lockDir: string) => LockState;
  resolveCommand?: (pid: number) => string | null;
  resolveUsage?: (pid: number) => ProcessUsage | null;
  json?: boolean;
  all?: boolean;
  log?: (msg: string) => void;
}

export async function runPs(deps: RunPsDeps = {}): Promise<void> {
  const discover = deps.discover ?? discoverLockDirs;
  const inspect = deps.inspect ?? ((dir) => inspectLock(dir, 'server'));
  const log = deps.log ?? ((msg) => console.log(msg));
  const resolveCommand = deps.resolveCommand ?? processCommand;
  const resolveUsage = deps.resolveUsage ?? processUsage;

  const lockDirs = await discover();

  const entries: PsEntry[] = [];
  for (const lockDir of lockDirs) {
    const serverState = inspect(lockDir);
    const command =
      serverState.status === 'missing' ||
      serverState.status === 'corrupt' ||
      serverState.status === 'read-error' ||
      serverState.status === 'unverified-owner' ||
      serverState.status === 'reused-pid'
        ? null
        : resolveCommand(serverState.lock.pid);
    const serverUsage =
      serverState.status === 'missing' ||
      serverState.status === 'corrupt' ||
      serverState.status === 'read-error' ||
      serverState.status === 'unverified-owner' ||
      serverState.status === 'reused-pid'
        ? null
        : resolveUsage(serverState.lock.pid);
    const entry = buildEntry(lockDir, serverState, command, serverUsage);
    if (entry != null) {
      entries.push(entry);
    }
  }

  if (deps.json) {
    const enriched = entries.map((e) => ({ ...e, displayStatus: displayStatus(e) }));
    log(JSON.stringify(enriched, null, 2));
    return;
  }

  const filtered = deps.all
    ? entries
    : entries.filter((e) => DEFAULT_VISIBLE.has(displayStatus(e)));

  log(renderTable(filtered));
}

export function psCommand(): Command {
  return new Command('ps')
    .description('List all running open-knowledge servers')
    .argument('[modifier]', '"all" to include stale entries')
    .option('--all', 'Include stale entries (foreign and unverified entries already show)')
    .option('--json', 'Emit structured JSON (always includes all statuses)')
    .action(async (modifier: string | undefined, opts: { all?: boolean; json?: boolean }) => {
      const all = opts.all === true || modifier === 'all';
      await runPs({ all, json: opts.json === true });
    });
}