Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

9.8 KB
Raw Blame
/**
 * `hood init` — the one-command onboarding wizard for the whole Robinhood
 * Chain trading stack: this CLI's wallet, hood-traders' bring-your-own-key
 * LLM strategist, and hood-alerts' Telegram bot + X (Twitter) auto-posting.
 *
 * hood-cli itself never runs a trading fleet or an alert bot — those are the
 * separate `hood-traders` and `hood-alerts` packages/processes. This wizard's
 * job is to collect the handful of choices and secrets those two packages
 * need and write them out as ready-to-use `.env` files, so getting the whole
 * stack running is "answer some questions, then `npx hood-traders` /
 * `npx hood-alerts`" instead of hand-editing two `.env.example` files.
 */
import { existsSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { Command } from 'commander'
import { loadConfig } from '../config.js'
import { setWallet } from './config.js'
import { canPrompt, confirm, promptLine, readPassword } from '../prompt.js'
import { printJson, printHuman, note } from '../output.js'
import { accent, bold, dim, green } from '../ui/ansi.js'
import { guardError } from '../errors.js'

const LLM_PROVIDERS = ['anthropic', 'openai', 'groq', 'openrouter'] as const
type LlmProvider = (typeof LLM_PROVIDERS)[number]

export interface InitAnswers {
  walletAddress?: string
  llmProvider?: LlmProvider
  llmApiKey?: string
  telegramToken?: string
  discordToken?: string
  discordAppId?: string
  xMode?: 'official' | 'xactions'
  xApiKey?: string
  xApiSecret?: string
  xAccessToken?: string
  xAccessSecret?: string
  xactionsUrl?: string
  xactionsToken?: string
}

/**
 * Render the `hood-traders` and `hood-alerts` `.env` file contents from
 * collected answers. Pure and side-effect-free so it's unit-testable without
 * a TTY — the wizard's IO (prompting, writing files) stays a thin shell
 * around this.
 */
export function buildEnvFiles(answers: InitAnswers): { traderEnv: string; alertsEnv: string } {
  const traderLines = [
    '# Generated by `hood init` — see hood-traders/.env.example for every option.',
    'HOOD_NETWORK=mainnet',
    'HOOD_TRADERS_LIVE=0   # flip to 1 (and set ROBINHOOD_CHAIN_PRIVATE_KEY) only when you are ready to trade real funds',
  ]
  if (answers.llmProvider && answers.llmApiKey) {
    traderLines.push('', '# llm-strategist', `HOOD_LLM_PROVIDER=${answers.llmProvider}`, `HOOD_LLM_API_KEY=${answers.llmApiKey}`)
  }

  const alertsLines = ['# Generated by `hood init` — see hood-alerts/.env.example for every option.']
  if (answers.telegramToken) {
    alertsLines.push('', '# Telegram', `HOOD_ALERTS_TELEGRAM_TOKEN=${answers.telegramToken}`)
  }
  if (answers.discordToken) {
    alertsLines.push('', '# Discord', `HOOD_ALERTS_DISCORD_TOKEN=${answers.discordToken}`, `HOOD_ALERTS_DISCORD_APP_ID=${answers.discordAppId ?? ''}`)
  }
  if (answers.xMode) {
    alertsLines.push('', '# X (Twitter)', `HOOD_ALERTS_X_MODE=${answers.xMode}`)
    if (answers.xMode === 'official') {
      alertsLines.push(
        `HOOD_ALERTS_X_API_KEY=${answers.xApiKey ?? ''}`,
        `HOOD_ALERTS_X_API_SECRET=${answers.xApiSecret ?? ''}`,
        `HOOD_ALERTS_X_ACCESS_TOKEN=${answers.xAccessToken ?? ''}`,
        `HOOD_ALERTS_X_ACCESS_SECRET=${answers.xAccessSecret ?? ''}`,
      )
    } else {
      alertsLines.push(`HOOD_ALERTS_XACTIONS_URL=${answers.xactionsUrl ?? ''}`, `HOOD_ALERTS_XACTIONS_TOKEN=${answers.xactionsToken ?? ''}`)
    }
  }

  return { traderEnv: traderLines.join('\n') + '\n', alertsEnv: alertsLines.join('\n') + '\n' }
}

export function initCommand(): Command {
  const cmd = new Command('init')
    .description('interactive setup wizard: wallet, LLM key (hood-traders), and Telegram/X (hood-alerts)')
    .option('--out <dir>', 'directory to write hood-traders.env / hood-alerts.env into', '.')
    .action(async (opts: { out: string }, _command, command) => {
      const json = !!command?.optsWithGlobals?.().json
      const assumeYes = !!command?.optsWithGlobals?.().yes
      await runInit(opts.out, json, assumeYes)
    })
  return cmd
}

async function runInit(outDir: string, json: boolean, assumeYes: boolean): Promise<void> {
  if (!canPrompt()) {
    throw guardError(
      'hood init needs an interactive terminal.',
      'Copy hood-traders/.env.example and hood-alerts/.env.example by hand instead, or re-run in a real TTY.',
    )
  }

  printHuman(`${accent('◈')} ${bold('hood init')} — set up the Robinhood Chain trading stack\n${dim('Every step below is optional; press Enter (or answer "n") to skip anything you don\'t need yet.')}\n`)

  const answers: InitAnswers = {}

  // ── 1. wallet ────────────────────────────────────────────────────────────
  const existing = loadConfig()
  if (existing.walletAddress) {
    note(`Wallet already configured: ${existing.walletAddress}`)
    answers.walletAddress = existing.walletAddress
  } else if (await confirm('Set up a local wallet now? (needed only for LIVE trading — skip to stay read-only/paper mode)')) {
    await setWallet(false, assumeYes)
    answers.walletAddress = loadConfig().walletAddress
  }

  // ── 2. llm-strategist (hood-traders) ────────────────────────────────────
  if (await confirm('Configure the llm-strategist for hood-traders? (bring your own key — Claude, OpenAI, Groq, or OpenRouter)')) {
    const providerAnswer = (
      await promptLine('Which provider — anthropic / openai / groq / openrouter?', undefined, 'anthropic')
    ).toLowerCase()
    if (!LLM_PROVIDERS.includes(providerAnswer as LlmProvider)) {
      throw guardError(`"${providerAnswer}" is not one of: ${LLM_PROVIDERS.join(', ')}.`)
    }
    answers.llmProvider = providerAnswer as LlmProvider
    answers.llmApiKey = await readPassword(`${answers.llmProvider} API key:`, 'HOOD_LLM_API_KEY')
  }

  // ── 3. hood-alerts: Telegram ─────────────────────────────────────────────
  if (await confirm('Set up the hood-alerts Telegram bot? (real-time launch/whale/premium feed)')) {
    note('Message @BotFather on Telegram, run /newbot, then paste the token below.')
    answers.telegramToken = await readPassword('Telegram bot token:', 'HOOD_ALERTS_TELEGRAM_TOKEN')
  }

  // ── 4. hood-alerts: Discord ──────────────────────────────────────────────
  if (await confirm('Set up the hood-alerts Discord bot too?')) {
    note('Create an app + bot at https://discord.com/developers/applications.')
    answers.discordToken = await readPassword('Discord bot token:', 'HOOD_ALERTS_DISCORD_TOKEN')
    answers.discordAppId = await promptLine('Discord application id:', 'HOOD_ALERTS_DISCORD_APP_ID')
  }

  // ── 5. hood-alerts: X (Twitter) ──────────────────────────────────────────
  if (await confirm('Set up X (Twitter) auto-posting for hood-alerts?')) {
    const mode = (await promptLine('Mode — "official" (X API v2, needs a paid developer tier) or "xactions" (free, self-hosted)?', undefined, 'official')).toLowerCase()
    if (mode !== 'official' && mode !== 'xactions') throw guardError('Mode must be "official" or "xactions".')
    answers.xMode = mode
    if (mode === 'official') {
      note('developer.x.com → your app → Keys and tokens. Needs read+write access token permissions.')
      answers.xApiKey = await readPassword('X API key (consumer key):', 'HOOD_ALERTS_X_API_KEY')
      answers.xApiSecret = await readPassword('X API secret (consumer secret):', 'HOOD_ALERTS_X_API_SECRET')
      answers.xAccessToken = await readPassword('X access token:', 'HOOD_ALERTS_X_ACCESS_TOKEN')
      answers.xAccessSecret = await readPassword('X access token secret:', 'HOOD_ALERTS_X_ACCESS_SECRET')
    } else {
      note('Point this at your own running xactions instance: https://github.com/nirholas/XActions')
      answers.xactionsUrl = await promptLine('xactions instance URL:', 'HOOD_ALERTS_XACTIONS_URL')
      answers.xactionsToken = await readPassword('xactions auth token:', 'HOOD_ALERTS_XACTIONS_TOKEN')
    }
  }

  // ── write ────────────────────────────────────────────────────────────────
  const { traderEnv, alertsEnv } = buildEnvFiles(answers)
  const traderPath = join(outDir, 'hood-traders.env')
  const alertsPath = join(outDir, 'hood-alerts.env')

  if (existsSync(traderPath) && !assumeYes && !(await confirm(`${traderPath} already exists. Overwrite it?`))) {
    throw guardError('hood init cancelled.')
  }
  if (existsSync(alertsPath) && !assumeYes && !(await confirm(`${alertsPath} already exists. Overwrite it?`))) {
    throw guardError('hood init cancelled.')
  }
  writeFileSync(traderPath, traderEnv, { mode: 0o600 })
  writeFileSync(alertsPath, alertsEnv, { mode: 0o600 })

  const summary = {
    ok: true,
    wallet: answers.walletAddress ?? null,
    llmProvider: answers.llmProvider ?? null,
    telegram: !!answers.telegramToken,
    discord: !!answers.discordToken,
    xMode: answers.xMode ?? null,
    traderEnv: traderPath,
    alertsEnv: alertsPath,
  }

  if (json) {
    printJson(summary)
    return
  }

  printHuman(
    `\n${green('✓')} Wrote ${bold(traderPath)} and ${bold(alertsPath)}\n\n` +
      `${dim('Next steps:')}\n` +
      `  ${dim('# run the trading fleet (paper mode by default — no funds move)')}\n` +
      `  cp ${traderPath} hood-traders/.env && cd hood-traders && npx hood-traders\n\n` +
      `  ${dim('# run the alert bot / real-time feed')}\n` +
      `  cp ${alertsPath} hood-alerts/.env && cd hood-alerts && npx hood-alerts\n`,
  )
}