Skip to content

nanocoai/nanoclaw / .claude/skills/add-onecli

add-onecli

Flagged

Install or refresh OneCLI as NanoClaw's gateway provider. Use when setup selects OneCLI, an existing OneCLI-backed install is migrated to the gateway seam, or its runtime, approval bridge, setup, and agent guidance must be restored from the in-tree package.

FileKindSize
REMOVE.mdmarkdown576 B
SKILL.mdskill md10.4 KB
apply-fixtures.jsonconfig1.9 KB
gateway.jsonconfig123 B
payload/docs/onecli-upgrades.mdmarkdown28.0 KB
payload/src/gateway-providers/onecli-chatgpt-stub.test.tsscript4.9 KB
payload/src/gateway-providers/onecli-chatgpt-stub.tsscript3.9 KB
payload/src/gateway-providers/onecli-files.test.tsscript4.4 KB
payload/src/gateway-providers/onecli-files.tsscript4.2 KB
payload/src/gateway-providers/onecli-install.test.tsscript1.1 KB
payload/src/gateway-providers/onecli-provider-credentials.test.tsscript7.6 KB
payload/src/gateway-providers/onecli-provider-credentials.tsscript9.6 KB
payload/src/gateway-providers/onecli.test.tsscript44.6 KB
payload/src/gateway-providers/onecli.tsscript18.2 KB
references/chatgpt-oauth-refresh.mdmarkdown1.1 KB
scripts/auth.test.tsscript10.1 KB
scripts/auth.tsscript7.5 KB
scripts/check-grants-gateway.shexecutablescript3.5 KB
scripts/credential-store.test.tsscript6.4 KB
scripts/credential-store.tsscript2.9 KB
scripts/detect.tsscript873 B
scripts/dial-key-check.shexecutablescript11.1 KB
scripts/install-claude.shexecutablescript1.6 KB
scripts/no-proxy.test.tsscript1.6 KB
scripts/post-upgrade-check.shexecutablescript2.7 KB
scripts/postgres-check.tsscript222 B
scripts/postgres-password.test.tsscript29.2 KB
scripts/postgres-password.tsscript20.2 KB
scripts/pre-upgrade-check.shexecutablescript2.9 KB
scripts/provider-credentials.test.tsscript21.9 KB
scripts/provider-credentials.tsscript12.7 KB
scripts/proxy-check.tsscript213 B
scripts/readiness.test.tsscript1.1 KB
scripts/register-claude-token.shexecutablescript4.0 KB
scripts/remote-proxy.test.tsscript10.9 KB
scripts/remote-proxy.tsscript4.2 KB
scripts/secret-input.test.tsscript10.4 KB
scripts/secret-input.tsscript4.9 KB
scripts/setup.tsscript23.1 KB
versions.jsonconfig84 B

scripts/setup.ts

View on GitHub
/**
 * Step: onecli — Install + configure the OneCLI gateway and CLI.
 *
 * Two modes:
 *   (default) run the OneCLI installer, configure api-host, write .env.
 *   --reuse   skip the installer; reuse the onecli instance already running
 *             on the host. Required for users who have other apps bound to
 *             an existing gateway, since re-running the installer rebinds
 *             the listener and breaks those consumers.
 *
 * Emits ONECLI_URL and polls /health so downstream steps (auth, service)
 * get a ready gateway.
 */
import { execFileSync, execSync } from 'child_process';
import fs from 'fs';
import net from 'net';
import os from 'os';
import path from 'path';
import { fileURLToPath, pathToFileURL } from 'url';

import { log } from '../../../../src/log.js';
import { emitStatus } from '../../../../setup/status.js';
import { REFUSED_HINT, rotateDefaultPassword, seedPassword } from './postgres-password.js';
import { login } from './secret-input.js';

const LOCAL_BIN = path.join(os.homedir(), '.local', 'bin');

function childEnv(): NodeJS.ProcessEnv {
  const parts = [LOCAL_BIN];
  if (process.env.PATH) parts.push(process.env.PATH);
  return { ...process.env, PATH: parts.join(path.delimiter) };
}

function onecliVersion(): string | null {
  try {
    return execFileSync('onecli', ['version'], {
      encoding: 'utf-8',
      env: childEnv(),
      stdio: ['ignore', 'pipe', 'ignore'],
    }).trim();
  } catch {
    return null;
  }
}

/**
 * Ask the installed onecli CLI for its configured api-host. Returns null if
 * onecli isn't on PATH, errors, or has no api-host configured.
 *
 * Tolerates both JSON output (onecli 1.3+) and older raw-text output.
 */
export function getOnecliApiHost(): string | null {
  try {
    const out = execFileSync('onecli', ['config', 'get', 'api-host'], {
      encoding: 'utf-8',
      env: childEnv(),
      stdio: ['ignore', 'pipe', 'ignore'],
    }).trim();
    try {
      const parsed = JSON.parse(out) as { data?: unknown; value?: unknown };
      const val = parsed.data ?? parsed.value;
      if (typeof val === 'string' && val.trim()) return val.trim();
    } catch {
      // not JSON — fall through to URL extraction
    }
    return extractUrlFromOutput(out);
  } catch {
    return null;
  }
}

function extractUrlFromOutput(output: string): string | null {
  const match = output.match(/https?:\/\/[\w.\-]+(?::\d+)?/);
  return match ? match[0] : null;
}

function ensureShellProfilePath(): void {
  const home = os.homedir();
  const line = 'export PATH="$HOME/.local/bin:$PATH"';
  for (const profile of [path.join(home, '.bashrc'), path.join(home, '.zshrc')]) {
    try {
      const content = fs.existsSync(profile) ? fs.readFileSync(profile, 'utf-8') : '';
      if (!content.includes('.local/bin')) {
        fs.appendFileSync(profile, `\n${line}\n`);
        log.info('Added ~/.local/bin to PATH in shell profile', { profile });
      }
    } catch (err) {
      log.warn('Could not update shell profile', { profile, err });
    }
  }
}

export function withEnvVar(content: string, name: string, value: string): string {
  const re = new RegExp(`^${name}=.*$`, 'm');
  if (re.test(content)) {
    return content.replace(re, `${name}=${value}`);
  }
  return content.trimEnd() + (content ? '\n' : '') + `${name}=${value}\n`;
}

function writeEnvVar(name: string, value: string, envFile = path.join(process.cwd(), '.env')): void {
  const content = fs.existsSync(envFile) ? fs.readFileSync(envFile, 'utf-8') : '';
  fs.writeFileSync(envFile, withEnvVar(content, name, value));
}

/**
 * True for hosts reachable without an outbound proxy: loopback, docker bridge
 * and RFC 1918 ranges, link-local, CGNAT (tailnets), single-label names and
 * .local names. IP ranges only match IPv4 literals, not hostnames.
 */
export function isLocalHost(host: string): boolean {
  if (net.isIPv4(host)) {
    return /^(127\.|10\.|192\.168\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)/.test(
      host,
    );
  }
  return (
    host === 'localhost' ||
    host === 'host.docker.internal' ||
    host === '::1' ||
    host.endsWith('.local') ||
    (!host.includes('.') && !host.includes(':'))
  );
}

/**
 * Adds the gateway host to NO_PROXY in .env content when it is local or
 * private, so a host behind an outbound proxy still reaches a gateway bound
 * to the docker bridge. A remote gateway keeps going through the proxy.
 */
export function withGatewayNoProxy(content: string, gatewayUrl: string): string {
  let host: string;
  try {
    host = new URL(gatewayUrl).hostname.replace(/^\[|\]$/g, '');
  } catch {
    return content;
  }
  if (!host || !isLocalHost(host)) return content;
  const rawCurrent = content.match(/^NO_PROXY=(.*)$/m)?.[1]?.trim() ?? '';
  const current = /^(['"])(.*)\1$/.exec(rawCurrent)?.[2] ?? rawCurrent;
  const entries = current
    .split(',')
    .map((entry) => entry.trim())
    .filter(Boolean);
  if (entries.includes(host)) return content;
  return withEnvVar(content, 'NO_PROXY', [...entries, host].join(','));
}

function writeEnvOnecliUrl(url: string): void {
  writeEnvVar('ONECLI_URL', url);
  const envFile = path.join(process.cwd(), '.env');
  const content = fs.readFileSync(envFile, 'utf-8');
  const next = withGatewayNoProxy(content, url);
  if (next !== content) fs.writeFileSync(envFile, next);
}

// The SANCTIONED gateway version: fresh installs pin to it. Upgrading an
// existing gateway is NOT done here — the gateway is a separate out-of-band
// component, and the migrator is the user's coding agent following
// docs/onecli-upgrades.md during /update-nanoclaw. The pin lives in
// versions.json ("onecli-gateway") so that flow can diff it across updates and
// route the agent to the doc; bump it there deliberately on a new release.
const pins = JSON.parse(
  fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'versions.json'), 'utf8'),
) as Record<string, string>;
const ONECLI_GATEWAY_VERSION = pins['onecli-gateway'];
// The CLI binary follows the same convention: installed at its pin
// ("onecli-cli" in versions.json), never at whatever "latest" means today.
const ONECLI_CLI_VERSION = pins['onecli-cli'];
const ONECLI_CLI_REPO = 'onecli/onecli-cli';

// Remove containers in the "onecli" compose project whose service name isn't
// in the v2 set. Pre-v2 OneCLI used service "app" (container onecli-app-1);
// v2 uses "onecli". Compose flags the old container as an orphan but won't
// stop it without --remove-orphans, leaving port 10254 bound and crashing
// the new bring-up. Filed upstream; this is the downstream workaround.
function removeLegacyOnecliContainers(): string {
  const out: string[] = [];
  let list = '';
  try {
    list = execSync(
      `docker ps -a --filter "label=com.docker.compose.project=onecli" --format '{{.Names}}|{{.Label "com.docker.compose.service"}}'`,
      { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] },
    ).trim();
  } catch {
    return '';
  }
  if (!list) return '';
  const v2Services = new Set(['onecli', 'postgres']);
  for (const line of list.split('\n')) {
    const [name, service] = line.split('|');
    if (!name || !service || v2Services.has(service)) continue;
    out.push(`Removing legacy OneCLI container: ${name} (service=${service})`);
    try {
      execSync(`docker rm -f ${JSON.stringify(name)}`, {
        stdio: ['ignore', 'pipe', 'pipe'],
      });
    } catch (err) {
      out.push(`  rm failed (continuing): ${(err as Error).message}`);
    }
  }
  return out.join('\n');
}

export function withLinuxHostGateway(compose: string, platform = process.platform): string {
  if (platform !== 'linux' || compose.includes('host.docker.internal:host-gateway')) {
    return compose;
  }
  const marker = '    container_name: onecli\n';
  if (!compose.includes(marker)) {
    throw new Error('OneCLI compose file has no onecli service marker');
  }
  return compose.replace(marker, `${marker}    extra_hosts:\n      - "host.docker.internal:host-gateway"\n`);
}

function ensureLocalGatewayHostAccess(): void {
  if (process.platform !== 'linux') return;
  const composeFile = path.join(os.homedir(), '.onecli', 'docker-compose.yml');
  const current = fs.readFileSync(composeFile, 'utf8');
  const next = withLinuxHostGateway(current);
  if (next === current) return;
  fs.writeFileSync(composeFile, next);
  execFileSync('docker', ['compose', '-f', composeFile, 'up', '-d', 'onecli'], {
    cwd: path.dirname(composeFile),
    stdio: 'ignore',
  });
}

function installOnecli(): { stdout: string; ok: boolean } {
  let stdout = '';

  const cleanup = removeLegacyOnecliContainers();
  if (cleanup) stdout += cleanup + '\n';
  // The installer and the compose calls below must use the password in ~/.onecli/.env; an exported one wins in compose.
  delete process.env.POSTGRES_PASSWORD;
  try {
    if (seedPassword()) log.info('Generated a OneCLI database password in ~/.onecli/.env');
  } catch (err) {
    log.error('Could not write the OneCLI database password', { err });
    return { stdout, ok: false };
  }

  // Gateway install (docker-compose based, no rate-limit concerns).
  // Pipe into the system shell by absolute path. `sh` resolved through PATH can
  // be a foreign shell (exe.dev images ship /exe.dev/bin/sh first on PATH; its
  // builtin lsof always exits 0, so the installer's port probe reports every
  // port as busy and the install fails with "Port 5432 is already in use").
  // The script runs in a shell, so fetch it over HTTPS only: a scheme-less URL
  // makes curl use plain HTTP, and --proto-redir blocks a redirect downgrade.
  const gw = runInstall(
    `export ONECLI_VERSION=${ONECLI_GATEWAY_VERSION} && curl --proto '=https' --proto-redir '=https' -fsSL https://onecli.sh/install | /bin/sh`,
  );
  stdout += gw.stdout;
  if (!gw.ok) {
    log.error('OneCLI gateway install failed', { stderr: gw.stderr });
    return { stdout: stdout + (gw.stderr ?? ''), ok: false };
  }
  try {
    const gatewayUrl = extractUrlFromOutput(gw.stdout);
    if (!gatewayUrl) throw new Error('OneCLI installer did not report its URL');
    const onecliEnv = path.join(os.homedir(), '.onecli', '.env');
    writeEnvVar('ONECLI_VERSION', ONECLI_GATEWAY_VERSION, onecliEnv);
    writeEnvVar('ONECLI_BIND_HOST', new URL(gatewayUrl).hostname, onecliEnv);
    ensureLocalGatewayHostAccess();
  } catch (err) {
    log.error('OneCLI gateway host mapping failed', { err });
    return { stdout, ok: false };
  }

  const cli = installOnecliCliDirect();
  stdout += cli.stdout;
  if (!cli.ok) {
    log.error('OneCLI CLI install failed');
    return { stdout, ok: false };
  }
  return { stdout, ok: true };
}

/**
 * Moves a local OneCLI database off the compose default password. A refusal
 * changed nothing and comes back as a hint; a failure fails the step.
 */
function securePostgres(): { restarted?: boolean; hint?: string; error?: string } {
  try {
    const result = rotateDefaultPassword();
    if (result.status === 'rotated') {
      log.info('Moved the OneCLI database to its own password');
      return { restarted: true };
    }
    if (result.status === 'stopped') {
      return {
        hint: "OneCLI's database is stopped, so its password was not checked. Start OneCLI and run setup again.",
      };
    }
    if (result.status !== 'refused') return {};
    log.warn('OneCLI database still uses the compose default password', { reason: result.detail });
    return { hint: `OneCLI's database still uses the default password: ${result.detail}. ${REFUSED_HINT}` };
  } catch (err) {
    log.error('OneCLI database password change failed', { err });
    return { error: (err as Error).message };
  }
}

function postgresFailed(error: string): never {
  emitStatus('ONECLI', {
    INSTALLED: true,
    STATUS: 'failed',
    ERROR: 'postgres_password_failed',
    HINT: error,
    LOG: 'logs/setup.log',
  });
  process.exit(1);
}

function runInstall(cmd: string): {
  stdout: string;
  stderr?: string;
  ok: boolean;
} {
  try {
    const stdout = execSync(cmd, {
      encoding: 'utf-8',
      stdio: ['ignore', 'pipe', 'pipe'],
    });
    return { stdout, ok: true };
  } catch (err) {
    const e = err as { stdout?: string; stderr?: string };
    return { stdout: e.stdout ?? '', stderr: e.stderr, ok: false };
  }
}

/**
 * Install the OneCLI CLI at the sanctioned pin by downloading the release
 * archive straight from GitHub. Deliberately no "latest" resolution — the
 * upstream installer script always chases the newest release, which would
 * drift from the pin. PATH setup is not lost by skipping it:
 * ensureShellProfilePath() in run() covers it.
 */
function installOnecliCliDirect(): { stdout: string; ok: boolean } {
  const lines: string[] = [];
  const append = (s: string): void => {
    lines.push(s);
  };

  const osName = process.platform === 'darwin' ? 'darwin' : process.platform === 'linux' ? 'linux' : null;
  if (!osName) {
    append(`Unsupported platform: ${process.platform}`);
    return { stdout: lines.join('\n'), ok: false };
  }
  const arch = process.arch === 'x64' ? 'amd64' : process.arch === 'arm64' ? 'arm64' : null;
  if (!arch) {
    append(`Unsupported arch: ${process.arch}`);
    return { stdout: lines.join('\n'), ok: false };
  }

  const version = ONECLI_CLI_VERSION;
  const archive = `onecli_${version}_${osName}_${arch}.tar.gz`;
  const url = `https://github.com/${ONECLI_CLI_REPO}/releases/download/v${version}/${archive}`;
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'onecli-'));
  const archivePath = path.join(tmpDir, archive);

  try {
    append(`Downloading ${url}`);
    execSync(`curl -fsSL -o ${JSON.stringify(archivePath)} ${JSON.stringify(url)}`, {
      stdio: ['ignore', 'pipe', 'pipe'],
    });
    execSync(`tar -xzf ${JSON.stringify(archivePath)} -C ${JSON.stringify(tmpDir)}`, {
      stdio: ['ignore', 'pipe', 'pipe'],
    });

    let installDir = '/usr/local/bin';
    try {
      fs.accessSync(installDir, fs.constants.W_OK);
    } catch {
      installDir = LOCAL_BIN;
      fs.mkdirSync(installDir, { recursive: true });
    }
    const binSrc = path.join(tmpDir, 'onecli');
    const binDest = path.join(installDir, 'onecli');
    fs.copyFileSync(binSrc, binDest);
    fs.chmodSync(binDest, 0o755);
    append(`onecli ${version} installed to ${binDest}.`);
    return { stdout: lines.join('\n'), ok: true };
  } catch (err) {
    const e = err as { stdout?: string; stderr?: string; message?: string };
    append(`Direct install failed: ${e.stderr ?? e.message ?? String(err)}`);
    return { stdout: lines.join('\n'), ok: false };
  } finally {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  }
}

/**
 * /v1 API compatibility check. @onecli-sh/sdk 2.x requires the server's /v1
 * API; servers older than the cutover answer 404 on every SDK call (permanent,
 * but presents as transient per-spawn failures). This is detect-only — setup
 * does not migrate the gateway. The upgrade is an out-of-band action on a
 * separate component that the agent runs via docs/onecli-upgrades.md during
 * /update-nanoclaw, so this step only surfaces the condition and points there.
 */
export async function verifyGatewayV1(
  url: string,
  fetchImpl: typeof fetch = fetch,
): Promise<'ok' | 'incompatible' | 'unreachable'> {
  try {
    const res = await fetchImpl(`${url}/v1/health`, {
      signal: AbortSignal.timeout(5000),
    });
    return res.ok ? 'ok' : 'incompatible';
  } catch {
    return 'unreachable';
  }
}

/**
 * Detect-and-warn helper: returns a status HINT (and logs) when the gateway is
 * pre-/v1, else null. Never fails the step or auto-upgrades — the agent owns
 * the upgrade via docs/onecli-upgrades.md.
 */
function gatewayV1Hint(result: 'ok' | 'incompatible' | 'unreachable'): string | null {
  if (result !== 'incompatible') return null;
  log.warn('OneCLI gateway lacks the /v1 API @onecli-sh/sdk 2.x requires', {
    pin: ONECLI_GATEWAY_VERSION,
  });
  return 'OneCLI gateway lacks the /v1 API @onecli-sh/sdk 2.x requires — upgrade it: docs/onecli-upgrades.md';
}

export function gatewayReadinessError(result: 'ok' | 'incompatible' | 'unreachable'): string | null {
  if (result === 'ok') return null;
  return result === 'incompatible'
    ? 'OneCLI gateway lacks the /v1 API required by the installed SDK'
    : 'OneCLI gateway /v1 API is unreachable';
}

export async function pollHealth(url: string, timeoutMs: number): Promise<boolean> {
  // `/api/health` matches the path probe.sh uses — keep them aligned.
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    try {
      const res = await fetch(`${url}/api/health`);
      if (res.ok) return true;
    } catch {
      // not ready yet
    }
    await new Promise((resolve) => setTimeout(resolve, 1000));
  }
  return false;
}

export async function run(args: string[]): Promise<void> {
  const requestedRemote = process.env.NANOCLAW_ONECLI_API_HOST?.trim();
  if (requestedRemote && !args.includes('--remote-url')) args = [...args, '--remote-url', requestedRemote];
  const reuse = args.includes('--reuse') || (!requestedRemote && !!onecliVersion() && !!getOnecliApiHost());
  const remoteUrlIdx = args.indexOf('--remote-url');
  const remoteUrl = remoteUrlIdx !== -1 ? args[remoteUrlIdx + 1] : null;
  ensureShellProfilePath();

  if (remoteUrl) {
    // Remote-mode: install only the CLI, point it at the remote gateway, and
    // record the URL in .env. No local gateway is started.
    log.info('Installing OneCLI CLI for remote gateway', { remoteUrl });
    const res = installOnecliCliDirect();
    if (!res.ok || !onecliVersion()) {
      emitStatus('ONECLI', {
        INSTALLED: false,
        STATUS: 'failed',
        ERROR: 'cli_install_failed',
        HINT: 'CLI binary install failed. Make sure curl is installed and ~/.local/bin is writable.',
        LOG: 'logs/setup.log',
      });
      process.exit(1);
    }
    try {
      execFileSync('onecli', ['config', 'set', 'api-host', remoteUrl], {
        stdio: 'ignore',
        env: childEnv(),
      });
    } catch (err) {
      log.warn('onecli config set api-host failed', { err });
    }
    writeEnvOnecliUrl(remoteUrl);
    log.info('Wrote ONECLI_URL to .env', { url: remoteUrl });
    const remoteToken = process.env.NANOCLAW_ONECLI_API_TOKEN?.trim();
    if (remoteToken) {
      // Two auth surfaces: `onecli auth login` persists the key for CLI
      // calls during setup itself (e.g. detecting an existing Anthropic
      // secret via `onecli secrets list`), and ONECLI_API_KEY in .env is
      // read by the runtime SDK at request time. Both are needed.
      try {
        login(remoteToken, childEnv());
      } catch (err) {
        log.warn('onecli auth login failed', { err });
      }
      writeEnvVar('ONECLI_API_KEY', remoteToken);
      log.info('Wrote ONECLI_API_KEY to .env');
    }
    const healthy = await pollHealth(remoteUrl, 5000);
    const v1Status = await verifyGatewayV1(remoteUrl);
    const v1Hint = gatewayV1Hint(v1Status);
    const readinessError = gatewayReadinessError(v1Status);
    emitStatus('ONECLI', {
      INSTALLED: true,
      REMOTE: true,
      ONECLI_URL: remoteUrl,
      HEALTHY: healthy,
      STATUS: readinessError ? 'failed' : 'success',
      ...(readinessError ? { ERROR: 'gateway_not_ready', HINT: readinessError } : {}),
      ...(v1Hint ? { GATEWAY_HINT: v1Hint } : {}),
      LOG: 'logs/setup.log',
    });
    if (readinessError) throw new Error(readinessError);
    return;
  }

  if (reuse) {
    // Reuse-mode: don't reinstall or rebind the running gateway. Verify it
    // exists, read its api-host, write ONECLI_URL to .env, and move a local
    // database off the default password (a one-time restart).
    const version = onecliVersion();
    if (!version) {
      emitStatus('ONECLI', {
        INSTALLED: false,
        STATUS: 'failed',
        ERROR: 'onecli_not_found_for_reuse',
        HINT: 'onecli not on PATH. Re-run setup and choose "install fresh".',
        LOG: 'logs/setup.log',
      });
      process.exit(1);
    }
    const url = getOnecliApiHost();
    if (!url) {
      emitStatus('ONECLI', {
        INSTALLED: true,
        STATUS: 'failed',
        ERROR: 'onecli_api_host_not_configured',
        HINT: 'Existing onecli has no api-host set. Run `onecli config set api-host <url>` or re-run setup with install-fresh.',
        LOG: 'logs/setup.log',
      });
      process.exit(1);
    }
    writeEnvOnecliUrl(url);
    log.info('Reusing existing OneCLI', { url });
    const pg = securePostgres();
    if (pg.error) postgresFailed(pg.error);
    const healthy = await pollHealth(url, pg.restarted ? 60000 : 5000);
    const v1Status = await verifyGatewayV1(url);
    const v1Hint = gatewayV1Hint(v1Status);
    const readinessError = gatewayReadinessError(v1Status);
    emitStatus('ONECLI', {
      INSTALLED: true,
      REUSED: true,
      ONECLI_URL: url,
      HEALTHY: healthy,
      STATUS: readinessError ? 'failed' : 'success',
      ...(readinessError ? { ERROR: 'gateway_not_ready', HINT: readinessError } : {}),
      ...(v1Hint ? { GATEWAY_HINT: v1Hint } : {}),
      ...(pg.hint ? { POSTGRES_HINT: pg.hint } : {}),
      LOG: 'logs/setup.log',
    });
    if (readinessError) throw new Error(readinessError);
    return;
  }

  log.info('Installing OneCLI gateway and CLI');
  const res = installOnecli();
  if (!res.ok) {
    emitStatus('ONECLI', {
      INSTALLED: false,
      STATUS: 'failed',
      ERROR: 'install_failed',
      LOG: 'logs/setup.log',
    });
    process.exit(1);
  }
  if (!onecliVersion()) {
    emitStatus('ONECLI', {
      INSTALLED: false,
      STATUS: 'failed',
      ERROR: 'onecli_not_on_path_after_install',
      HINT: 'Open a new shell or run `export PATH="$HOME/.local/bin:$PATH"` and retry.',
      LOG: 'logs/setup.log',
    });
    process.exit(1);
  }

  const pg = securePostgres();
  if (pg.error) postgresFailed(pg.error);

  const url = extractUrlFromOutput(res.stdout);
  if (!url) {
    emitStatus('ONECLI', {
      INSTALLED: true,
      STATUS: 'failed',
      ERROR: 'could_not_resolve_api_host',
      HINT: 'Inspect logs/setup.log for the install output.',
      LOG: 'logs/setup.log',
    });
    process.exit(1);
  }

  try {
    execFileSync('onecli', ['config', 'set', 'api-host', url], {
      stdio: 'ignore',
      env: childEnv(),
    });
  } catch (err) {
    log.warn('onecli config set api-host failed', { err });
  }

  writeEnvOnecliUrl(url);
  log.info('Wrote ONECLI_URL to .env', { url });

  const healthy = await pollHealth(url, pg.restarted ? 60000 : 15000);
  const v1Status = await verifyGatewayV1(url);
  const v1Hint = gatewayV1Hint(v1Status);
  const readinessError = gatewayReadinessError(v1Status);

  emitStatus('ONECLI', {
    INSTALLED: true,
    ONECLI_URL: url,
    HEALTHY: healthy,
    STATUS: readinessError ? 'failed' : 'success',
    ...(readinessError ? { ERROR: 'gateway_not_ready', HINT: readinessError } : {}),
    ...(v1Hint ? { GATEWAY_HINT: v1Hint } : {}),
    ...(pg.hint ? { POSTGRES_HINT: pg.hint } : {}),
    ...(healthy
      ? {}
      : {
          HEALTH_HINT:
            'Health poll returned non-ok within 15s — likely auth-gated. Proceed to the auth step; it will surface a real outage.',
        }),
    LOG: 'logs/setup.log',
  });
  if (readinessError) throw new Error(readinessError);
}

if (
  process.argv[1] &&
  fs.existsSync(process.argv[1]) &&
  import.meta.url === pathToFileURL(fs.realpathSync(process.argv[1])).href
) {
  void run(process.argv.slice(2));
}
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall