import { execSync } from 'child_process'; import { randomBytes } from 'crypto'; import { confirm, input, password, select } from '@inquirer/prompts'; import ora from 'ora'; import { loadConfig, envGet, envSet, ensureEnvFile } from '../config.js'; import { runtimeCheck, composeCheck, composeBuild, composeUp, trustCaddyCert } from '../docker.js'; import { applyLlmProviderConfig, getConfiguredLlmProvider, getLlmProviderPreset, LLM_PROVIDER_PRESETS } from '../llm.js'; import { setupCloudflareTunnel, setupTailscaleTunnel } from '../remote.js'; import * as d from '../utils/display.js'; function generateKey(): string { return randomBytes(32).toString('hex'); } // The substrate container needs to bind-mount /var/run/docker.sock and have a group that // can read it. macOS has no docker group (uses 'staff' GID 20); podman rootless uses the // caller's GID; Linux looks up the real docker group. 999 is the debian-default fallback. function detectDockerGid(runtimeCmd: string): string { if (process.platform === 'darwin') return '20'; // Podman rootless doesn't need a docker group, but the Dockerfile still expects DOCKER_GID. // Fall back to the current user's GID when the docker group is absent. try { return execSync('getent group docker', { encoding: 'utf-8' }).split(':')[2] || '999'; } catch { if (runtimeCmd === 'podman') { try { return execSync('id -g', { encoding: 'utf-8' }).trim() || '999'; } catch { return '999'; } } return '999'; } } export async function setupCommand(opts: { envOnly?: boolean; hostname?: string; tunnel?: string; runtime?: string; }) { d.banner(); d.line(); const config = loadConfig(opts); d.header('Preflight'); d.label('Runtime', `${config.runtime.label} (${config.runtime.cmd})`); const runtime = runtimeCheck(config.runtime); if (!runtime.ok) { d.error(`${config.runtime.label} not found or not running`); if (config.runtime.cmd === 'docker') { d.command('https://docs.docker.com/get-docker/'); } else if (config.runtime.cmd === 'podman') { d.command('https://podman.io/docs/installation'); } d.info('Override with: aether-substrate init --runtime '); process.exit(1); } d.success(`${config.runtime.label} ${runtime.version}`); const compose = composeCheck(config.runtime); if (!compose.ok) { d.error(`${config.runtime.label} Compose not found`); if (config.runtime.cmd === 'podman') { d.info('Install Podman Compose: https://github.com/containers/podman-compose'); } else { d.info('Requires the Compose v2 plugin'); } process.exit(1); } d.success(`${config.runtime.label} Compose ${compose.version}`); const envExample = `${config.substrateDir}/.env.example`; d.header('Environment'); const created = ensureEnvFile(config.envFile, envExample); created ? d.success('Created .env from template') : d.info('Using existing .env'); const currentKey = envGet('SUBSTRATE_API_KEY', config.envFile); if (currentKey) { d.success(`API key set (${currentKey.length} chars)`); const regen = await confirm({ message: 'Generate a new API key?', default: false }); if (regen) { const key = generateKey(); envSet('SUBSTRATE_API_KEY', key, config.envFile); d.success(`New API key generated (${key.length} chars)`); d.warn('Update SUBSTRATE_API_KEY in your frontend .env.local to match'); } } else { const key = generateKey(); envSet('SUBSTRATE_API_KEY', key, config.envFile); d.success(`API key generated (${key.length} chars)`); } const gid = detectDockerGid(config.runtime.cmd); envSet('DOCKER_GID', gid, config.envFile); envSet('CONTAINER_RUNTIME', config.runtime.cmd, config.envFile); d.success(`DOCKER_GID=${gid}${process.platform === 'darwin' ? ' (macOS staff)' : ''}`); d.success(`CONTAINER_RUNTIME=${config.runtime.cmd}`); d.line(); d.header('Features'); let containers = await confirm({ message: 'Enable Docker container management?', default: true }); const workspace = await confirm({ message: 'Enable workspace container?', default: true }); if (workspace && !containers) { d.warn('Workspace requires container management. Enabling containers.'); containers = true; } envSet('SUBSTRATE_ENABLE_CONTAINERS', String(containers), config.envFile); envSet('SUBSTRATE_ENABLE_WORKSPACE', String(workspace), config.envFile); const terminal = await confirm({ message: 'Enable substrate host terminal WebSocket?', default: false }); envSet('SUBSTRATE_ENABLE_TERMINAL_WS', String(terminal), config.envFile); const embeddings = await confirm({ message: 'Enable embeddings (EmbeddingGemma vector search)?', default: false }); envSet('SUBSTRATE_ENABLE_EMBEDDINGS', String(embeddings), config.envFile); const llmEnabled = await confirm({ message: 'Enable LLM gateway?', default: envGet('SUBSTRATE_ENABLE_LLM', config.envFile) !== 'false' }); envSet('SUBSTRATE_ENABLE_LLM', String(llmEnabled), config.envFile); if (llmEnabled) { const currentLlm = getConfiguredLlmProvider(config.envFile); const providerId = await select({ message: 'Choose a default LLM provider', choices: LLM_PROVIDER_PRESETS.map((provider) => ({ name: provider.name, value: provider.id, description: `${provider.type === 'local' ? 'Local' : 'Hosted'} ยท ${provider.baseUrl}`, })), default: currentLlm.providerId || 'lmstudio', }); const preset = getLlmProviderPreset(providerId)!; const model = await input({ message: `${preset.name} default model`, default: currentLlm.providerId === providerId ? (currentLlm.model || preset.defaultModelPlaceholder) : preset.defaultModelPlaceholder, }); const baseUrl = await input({ message: `${preset.name} base URL`, default: currentLlm.providerId === providerId ? (currentLlm.baseUrl || preset.baseUrl) : preset.baseUrl, }); let apiKey: string | undefined; if (preset.apiKeyRequired) { const existingApiKey = envGet('LLM_API_KEY', config.envFile); const enteredApiKey = await password({ message: `${preset.name} API key${existingApiKey ? ' (leave blank to keep current)' : ''}`, mask: '*', }); apiKey = enteredApiKey || (existingApiKey ? undefined : ''); } applyLlmProviderConfig(config.envFile, { providerId: preset.id, model, baseUrl, apiKey, }); d.success(`${preset.name} configured for the LLM gateway`); } const currentOrigins = envGet('SUBSTRATE_ALLOWED_ORIGINS', config.envFile); const wantsOrigins = await confirm({ message: 'Add extra CORS origins?', default: Boolean(currentOrigins) }); if (wantsOrigins) { const origins = await input({ message: 'Origins (comma-separated)', default: currentOrigins || 'http://localhost:4305', }); if (origins) { envSet('SUBSTRATE_ALLOWED_ORIGINS', origins, config.envFile); d.success('CORS origins updated'); } } d.line(); d.success('Environment configuration complete'); if (opts.envOnly) { d.command('aether-substrate doctor'); d.line(); return; } d.header('Build & Start'); const noCache = await confirm({ message: 'Rebuild from scratch (no cache)?', default: false }); const buildSpinner = ora({ text: noCache ? 'Building (no cache)...' : 'Building...', indent: 2 }).start(); try { composeBuild(config, noCache); buildSpinner.succeed('Build complete'); } catch { buildSpinner.fail('Build failed'); process.exit(1); } const startSpinner = ora({ text: 'Starting containers...', indent: 2 }).start(); try { composeUp(config); startSpinner.succeed('Containers started'); } catch { startSpinner.fail('Failed to start containers'); process.exit(1); } const healthSpinner = ora({ text: 'Waiting for health check...', indent: 2 }).start(); for (let i = 0; i < 30; i++) { try { const res = await fetch(`${config.apiUrl}/health`, { signal: AbortSignal.timeout(2000) }); if (res.ok) { healthSpinner.succeed('Substrate is healthy'); break; } } catch { // Wait for API. } if (i === 29) { healthSpinner.warn('Health check timed out'); } await new Promise(r => setTimeout(r, 2000)); } if (process.platform === 'darwin') { const trust = await confirm({ message: 'Trust the local Caddy certificate?', default: true }); if (trust) { try { trustCaddyCert(config); d.success('Caddy root CA trusted'); } catch (error: any) { d.warn(`Could not trust Caddy cert: ${error.message}`); } } } let tunnelChoice = opts.tunnel; if (!tunnelChoice) { const wantsRemote = await confirm({ message: 'Configure remote access now?', default: true, }); if (wantsRemote) { tunnelChoice = await select({ message: 'Choose a tunnel workflow', choices: [ { name: 'Cloudflare Tunnel', value: 'cloudflare', description: 'Public HTTPS via Cloudflare' }, { name: 'Tailscale', value: 'tailscale', description: 'Private access with MagicDNS + serve' }, { name: 'Skip for now', value: 'none' }, ], }); } } if (tunnelChoice === 'cloudflare') { await setupCloudflareTunnel(config, { hostname: opts.hostname }); const startOverlay = await confirm({ message: 'Start the Cloudflare overlay now?', default: true, }); if (startOverlay) { composeUp(config, { cloudflare: true }); d.success('Cloudflare overlay started'); } } else if (tunnelChoice === 'tailscale') { await setupTailscaleTunnel({ serve: true }); } d.line(); d.success('Init complete'); d.info('Recommended follow-up'); d.command('aether-substrate doctor'); d.command('aether-substrate status'); d.line(); }