diff --git a/scripts/init-first-agent.ts b/scripts/init-first-agent.ts index efb3b6bdb..c40f07f93 100644 --- a/scripts/init-first-agent.ts +++ b/scripts/init-first-agent.ts @@ -1,15 +1,26 @@ /** - * Init the first (or Nth) NanoClaw v2 agent for a DM channel. + * Init the first (or Nth) NanoClaw v2 agent. + * + * Two modes: + * + * 1. **DM channel mode** (default): wires a real DM channel (discord, telegram, + * etc.) + the CLI channel to the same agent, stages a welcome into the DM + * session so the agent greets the operator over that channel. + * + * 2. **CLI-only mode** (`--cli-only`): wires only the CLI channel. Used by + * `/new-setup` to get to a working 2-way CLI chat with the bare minimum. + * Owner grant uses a synthetic `cli:local` user so admin-gated flows work. * * Creates/reuses: user, owner grant (if none), agent group + filesystem, - * DM messaging group, wiring, session. Stages a system welcome message so - * the host sweep wakes the container and the agent DMs the operator via + * messaging group(s), wiring, session. Stages a system welcome message so + * the host sweep wakes the container and the agent sends the greeting via * the normal delivery path. * * Runs alongside the service (WAL-mode sqlite) — does NOT initialize * channel adapters, so there's no Gateway conflict. * * Usage: + * # DM mode * pnpm exec tsx scripts/init-first-agent.ts \ * --channel discord \ * --user-id discord:1470183333427675709 \ @@ -18,6 +29,12 @@ * [--agent-name "Andy"] \ * [--welcome "System instruction: ..."] * + * # CLI-only mode + * pnpm exec tsx scripts/init-first-agent.ts --cli-only \ + * --display-name "Gavriel" \ + * [--agent-name "Andy"] \ + * [--welcome "System instruction: ..."] + * * For direct-addressable channels (telegram, whatsapp, etc.), --platform-id * is typically the same as the handle in --user-id, with the channel prefix. */ @@ -38,9 +55,10 @@ import { grantRole, hasAnyOwner } from '../src/modules/permissions/db/user-roles import { upsertUser } from '../src/modules/permissions/db/users.js'; import { initGroupFilesystem } from '../src/group-init.js'; import { resolveSession, writeSessionMessage } from '../src/session-manager.js'; -import type { AgentGroup } from '../src/types.js'; +import type { AgentGroup, MessagingGroup } from '../src/types.js'; interface Args { + cliOnly: boolean; channel: string; userId: string; platformId: string; @@ -52,12 +70,19 @@ interface Args { const DEFAULT_WELCOME = 'System instruction: run /welcome to introduce yourself to the user on this new channel.'; +const CLI_CHANNEL = 'cli'; +const CLI_PLATFORM_ID = 'local'; +const CLI_SYNTHETIC_USER_ID = `${CLI_CHANNEL}:${CLI_PLATFORM_ID}`; + function parseArgs(argv: string[]): Args { - const out: Partial = {}; + const out: Partial = { cliOnly: false }; for (let i = 0; i < argv.length; i++) { const key = argv[i]; const val = argv[i + 1]; switch (key) { + case '--cli-only': + out.cliOnly = true; + break; case '--channel': out.channel = (val ?? '').toLowerCase(); i++; @@ -85,7 +110,26 @@ function parseArgs(argv: string[]): Args { } } - const required: (keyof Args)[] = ['channel', 'userId', 'platformId', 'displayName']; + if (!out.displayName) { + console.error('Missing required arg: --display-name'); + console.error('See scripts/init-first-agent.ts header for usage.'); + process.exit(2); + } + + if (out.cliOnly) { + // CLI-only: channel/user/platform default to the synthetic local CLI identity. + return { + cliOnly: true, + channel: CLI_CHANNEL, + userId: CLI_SYNTHETIC_USER_ID, + platformId: CLI_PLATFORM_ID, + displayName: out.displayName, + agentName: out.agentName?.trim() || out.displayName, + welcome: out.welcome?.trim() || DEFAULT_WELCOME, + }; + } + + const required: (keyof Args)[] = ['channel', 'userId', 'platformId']; const missing = required.filter((k) => !out[k]); if (missing.length) { console.error(`Missing required args: ${missing.map((k) => `--${k.replace(/([A-Z])/g, '-$1').toLowerCase()}`).join(', ')}`); @@ -94,11 +138,12 @@ function parseArgs(argv: string[]): Args { } return { + cliOnly: false, channel: out.channel!, userId: out.userId!, platformId: out.platformId!, - displayName: out.displayName!, - agentName: out.agentName?.trim() || out.displayName!, + displayName: out.displayName, + agentName: out.agentName?.trim() || out.displayName, welcome: out.welcome?.trim() || DEFAULT_WELCOME, }; } @@ -115,6 +160,48 @@ function generateId(prefix: string): string { return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; } +function ensureCliMessagingGroup(now: string): MessagingGroup { + let cliMg = getMessagingGroupByPlatform(CLI_CHANNEL, CLI_PLATFORM_ID); + if (cliMg) return cliMg; + + cliMg = { + id: generateId('mg'), + channel_type: CLI_CHANNEL, + platform_id: CLI_PLATFORM_ID, + name: 'Local CLI', + is_group: 0, + unknown_sender_policy: 'public', + created_at: now, + }; + createMessagingGroup(cliMg); + console.log(`Created CLI messaging group: ${cliMg.id}`); + return cliMg; +} + +function wireIfMissing( + mg: MessagingGroup, + ag: AgentGroup, + now: string, + label: string, +): void { + const existing = getMessagingGroupAgentByPair(mg.id, ag.id); + if (existing) { + console.log(`Wiring already exists: ${existing.id} (${label})`); + return; + } + createMessagingGroupAgent({ + id: generateId('mga'), + messaging_group_id: mg.id, + agent_group_id: ag.id, + trigger_rules: null, + response_scope: 'all', + session_mode: 'shared', + priority: 0, + created_at: now, + }); + console.log(`Wired ${label}: ${mg.id} -> ${ag.id}`); +} + async function main(): Promise { const args = parseArgs(process.argv.slice(2)); @@ -123,7 +210,8 @@ async function main(): Promise { const now = new Date().toISOString(); - // 1. User + (conditional) owner grant + // 1. User + (conditional) owner grant. + // In cli-only mode, the synthetic `cli:local` user becomes the first owner. const userId = namespacedUserId(args.channel, args.userId); upsertUser({ id: userId, @@ -145,7 +233,9 @@ async function main(): Promise { } // 2. Agent group + filesystem - const folder = `dm-with-${normalizeName(args.displayName)}`; + const folder = args.cliOnly + ? `cli-with-${normalizeName(args.displayName)}` + : `dm-with-${normalizeName(args.displayName)}`; let ag: AgentGroup | undefined = getAgentGroupByFolder(folder); if (!ag) { const agId = generateId('ag'); @@ -168,54 +258,54 @@ async function main(): Promise { 'When you receive a system welcome prompt, introduce yourself briefly and invite them to chat. Keep replies concise.', }); - // 3. DM messaging group - const platformId = namespacedPlatformId(args.channel, args.platformId); - let mg = getMessagingGroupByPlatform(args.channel, platformId); - if (!mg) { - const mgId = generateId('mg'); - createMessagingGroup({ - id: mgId, - channel_type: args.channel, - platform_id: platformId, - name: args.displayName, - is_group: 0, - unknown_sender_policy: 'strict', - created_at: now, - }); - mg = getMessagingGroupByPlatform(args.channel, platformId)!; - console.log(`Created messaging group: ${mg.id} (${platformId})`); + // 3. Primary messaging group + wiring + welcome session. + // In DM mode: the DM messaging group is primary, CLI is wired as a bonus. + // In cli-only mode: the CLI messaging group is primary; no DM group. + const cliMg = ensureCliMessagingGroup(now); + + let primaryMg: MessagingGroup; + if (args.cliOnly) { + primaryMg = cliMg; } else { - console.log(`Reusing messaging group: ${mg.id} (${platformId})`); + const platformId = namespacedPlatformId(args.channel, args.platformId); + let dmMg = getMessagingGroupByPlatform(args.channel, platformId); + if (!dmMg) { + const mgId = generateId('mg'); + createMessagingGroup({ + id: mgId, + channel_type: args.channel, + platform_id: platformId, + name: args.displayName, + is_group: 0, + unknown_sender_policy: 'strict', + created_at: now, + }); + dmMg = getMessagingGroupByPlatform(args.channel, platformId)!; + console.log(`Created messaging group: ${dmMg.id} (${platformId})`); + } else { + console.log(`Reusing messaging group: ${dmMg.id} (${platformId})`); + } + primaryMg = dmMg; } - // 4. Wire (auto-creates the companion agent_destinations row) - const existingMga = getMessagingGroupAgentByPair(mg.id, ag.id); - if (!existingMga) { - createMessagingGroupAgent({ - id: generateId('mga'), - messaging_group_id: mg.id, - agent_group_id: ag.id, - trigger_rules: null, - response_scope: 'all', - session_mode: 'shared', - priority: 0, - created_at: now, - }); - console.log(`Wired ${mg.id} -> ${ag.id}`); - } else { - console.log(`Wiring already exists: ${existingMga.id}`); + // Wire primary (DM or CLI), auto-creates companion agent_destinations row. + wireIfMissing(primaryMg, ag, now, args.cliOnly ? 'cli' : 'dm'); + + // In DM mode also wire CLI so `pnpm run chat` works immediately. + if (!args.cliOnly) { + wireIfMissing(cliMg, ag, now, 'cli-bonus'); } - // 5. Session + staged welcome message - const { session, created } = resolveSession(ag.id, mg.id, null, 'shared'); + // 4. Session + staged welcome (on the primary messaging group) + const { session, created } = resolveSession(ag.id, primaryMg.id, null, 'shared'); console.log(`${created ? 'Created' : 'Reusing'} session: ${session.id}`); writeSessionMessage(ag.id, session.id, { id: generateId('sys-welcome'), kind: 'chat', timestamp: now, - platformId: mg.platform_id, - channelType: args.channel, + platformId: primaryMg.platform_id, + channelType: primaryMg.channel_type, threadId: null, content: JSON.stringify({ text: args.welcome, @@ -224,48 +314,23 @@ async function main(): Promise { }), }); - // 6. Wire the CLI channel to the same agent so the user can `pnpm run chat` - // immediately. CLI ships with main and is always available — separate - // messaging_group from the DM channel, so the two don't share a session. - const CLI_PLATFORM_ID = 'local'; - let cliMg = getMessagingGroupByPlatform('cli', CLI_PLATFORM_ID); - if (!cliMg) { - cliMg = { - id: generateId('mg'), - channel_type: 'cli', - platform_id: CLI_PLATFORM_ID, - name: 'Local CLI', - is_group: 0, - unknown_sender_policy: 'public', - created_at: now, - }; - createMessagingGroup(cliMg); - console.log(`Created CLI messaging group: ${cliMg.id}`); - } - const existingCliMga = getMessagingGroupAgentByPair(cliMg.id, ag.id); - if (!existingCliMga) { - createMessagingGroupAgent({ - id: generateId('mga'), - messaging_group_id: cliMg.id, - agent_group_id: ag.id, - trigger_rules: null, - response_scope: 'all', - session_mode: 'shared', - priority: 0, - created_at: now, - }); - console.log(`Wired cli/${CLI_PLATFORM_ID} -> ${ag.id}`); - } - console.log(''); console.log('Init complete.'); console.log(` owner: ${userId}${promotedToOwner ? ' (promoted on first owner)' : ''}`); console.log(` agent: ${ag.name} [${ag.id}] @ groups/${folder}`); - console.log(` channel: ${args.channel} ${platformId}`); + if (args.cliOnly) { + console.log(` channel: cli/${CLI_PLATFORM_ID}`); + } else { + console.log(` channel: ${args.channel} ${primaryMg.platform_id}`); + console.log(` cli: cli/${CLI_PLATFORM_ID} wired — try \`pnpm run chat hi\``); + } console.log(` session: ${session.id}`); - console.log(` cli: cli/${CLI_PLATFORM_ID} wired — try \`pnpm run chat hi\``); console.log(''); - console.log('Host sweep (<=60s) will wake the container and the agent will send the welcome DM.'); + console.log( + args.cliOnly + ? 'Host sweep (<=60s) will wake the container. Try `pnpm run chat hi`.' + : 'Host sweep (<=60s) will wake the container and the agent will send the welcome DM.', + ); } main().catch((err) => { diff --git a/setup/auth.ts b/setup/auth.ts new file mode 100644 index 000000000..14e27b042 --- /dev/null +++ b/setup/auth.ts @@ -0,0 +1,186 @@ +/** + * Step: auth — Verify or register an Anthropic credential in OneCLI. + * + * Modes: + * --check (default) Verify an Anthropic secret exists. + * --create --value Create an Anthropic secret. Errors if one + * already exists unless --force is passed. + * + * The actual user-facing prompt (subscription vs API key, paste the token) + * stays in the /new-setup SKILL.md. This step is just the machine side: + * it calls `onecli secrets list` / `onecli secrets create` and emits a + * structured status block. The token value is never logged. + */ +import { execFileSync } from 'child_process'; +import os from 'os'; +import path from 'path'; + +import { log } from '../src/log.js'; +import { emitStatus } from './status.js'; + +const LOCAL_BIN = path.join(os.homedir(), '.local', 'bin'); + +interface Args { + mode: 'check' | 'create'; + value?: string; + force: boolean; +} + +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 parseArgs(args: string[]): Args { + let mode: 'check' | 'create' = 'check'; + let value: string | undefined; + let force = false; + + for (let i = 0; i < args.length; i++) { + const key = args[i]; + const val = args[i + 1]; + switch (key) { + case '--check': + mode = 'check'; + break; + case '--create': + mode = 'create'; + break; + case '--value': + value = val; + i++; + break; + case '--force': + force = true; + break; + } + } + + if (mode === 'create' && !value) { + emitStatus('AUTH', { + STATUS: 'failed', + ERROR: 'missing_value_for_create', + LOG: 'logs/setup.log', + }); + process.exit(2); + } + + return { mode, value, force }; +} + +interface OnecliSecret { + id: string; + name: string; + type: string; + hostPattern: string | null; +} + +function listSecrets(): OnecliSecret[] { + const out = execFileSync('onecli', ['secrets', 'list'], { + encoding: 'utf-8', + env: childEnv(), + stdio: ['ignore', 'pipe', 'ignore'], + }); + const parsed = JSON.parse(out) as { data?: unknown }; + return Array.isArray(parsed.data) ? (parsed.data as OnecliSecret[]) : []; +} + +function findAnthropicSecret(secrets: OnecliSecret[]): OnecliSecret | undefined { + return secrets.find((s) => s.type === 'anthropic'); +} + +function createAnthropicSecret(value: string): void { + // `value` is a credential — do not log it, do not echo, do not pass through a shell. + execFileSync( + 'onecli', + [ + 'secrets', + 'create', + '--name', + 'Anthropic', + '--type', + 'anthropic', + '--value', + value, + '--host-pattern', + 'api.anthropic.com', + ], + { + env: childEnv(), + stdio: ['ignore', 'ignore', 'pipe'], + }, + ); +} + +export async function run(args: string[]): Promise { + const { mode, value, force } = parseArgs(args); + + let secrets: OnecliSecret[]; + try { + secrets = listSecrets(); + } catch (err) { + log.error('onecli secrets list failed', { err }); + emitStatus('AUTH', { + STATUS: 'failed', + ERROR: 'onecli_list_failed', + HINT: 'Is OneCLI running? Run `/new-setup` from the onecli step.', + LOG: 'logs/setup.log', + }); + process.exit(1); + } + + const existing = findAnthropicSecret(secrets); + + if (mode === 'check') { + emitStatus('AUTH', { + SECRET_PRESENT: !!existing, + ANTHROPIC_OK: !!existing, + STATUS: existing ? 'success' : 'missing', + ...(existing ? { SECRET_NAME: existing.name, SECRET_ID: existing.id } : {}), + LOG: 'logs/setup.log', + }); + return; + } + + // mode === 'create' + if (existing && !force) { + emitStatus('AUTH', { + SECRET_PRESENT: true, + STATUS: 'skipped', + REASON: 'anthropic_secret_already_exists', + SECRET_NAME: existing.name, + SECRET_ID: existing.id, + HINT: 'Re-run with --force to replace, or delete the existing secret first.', + LOG: 'logs/setup.log', + }); + return; + } + + try { + createAnthropicSecret(value!); + } catch (err) { + const e = err as { stderr?: string | Buffer; status?: number }; + const stderr = typeof e.stderr === 'string' ? e.stderr : e.stderr?.toString('utf-8') ?? ''; + log.error('onecli secrets create failed', { status: e.status, stderr }); + emitStatus('AUTH', { + STATUS: 'failed', + ERROR: 'onecli_create_failed', + EXIT_CODE: e.status ?? -1, + LOG: 'logs/setup.log', + }); + process.exit(1); + } + + // Re-verify + const updated = findAnthropicSecret(listSecrets()); + + emitStatus('AUTH', { + SECRET_PRESENT: !!updated, + ANTHROPIC_OK: !!updated, + CREATED: true, + STATUS: updated ? 'success' : 'failed', + ...(updated ? { SECRET_NAME: updated.name, SECRET_ID: updated.id } : {}), + LOG: 'logs/setup.log', + }); +} diff --git a/setup/cli-agent.ts b/setup/cli-agent.ts new file mode 100644 index 000000000..e5a901dda --- /dev/null +++ b/setup/cli-agent.ts @@ -0,0 +1,100 @@ +/** + * Step: cli-agent — Create the first agent wired to the CLI channel. + * + * Thin wrapper around `scripts/init-first-agent.ts --cli-only`. Emits a + * status block so /new-setup SKILL.md can parse the result without having + * to read the script's plain stdout. + * + * Args: + * --display-name (required) operator's display name + * --agent-name (optional) agent persona name, defaults to display-name + * --welcome (optional) system welcome instruction + */ +import { execFileSync } from 'child_process'; +import path from 'path'; + +import { log } from '../src/log.js'; +import { emitStatus } from './status.js'; + +function parseArgs(args: string[]): { + displayName: string; + agentName?: string; + welcome?: string; +} { + let displayName: string | undefined; + let agentName: string | undefined; + let welcome: string | undefined; + + for (let i = 0; i < args.length; i++) { + const key = args[i]; + const val = args[i + 1]; + switch (key) { + case '--display-name': + displayName = val; + i++; + break; + case '--agent-name': + agentName = val; + i++; + break; + case '--welcome': + welcome = val; + i++; + break; + } + } + + if (!displayName) { + emitStatus('CLI_AGENT', { + STATUS: 'failed', + ERROR: 'missing_display_name', + LOG: 'logs/setup.log', + }); + process.exit(2); + } + + return { displayName, agentName, welcome }; +} + +export async function run(args: string[]): Promise { + const { displayName, agentName, welcome } = parseArgs(args); + + const projectRoot = process.cwd(); + const script = path.join(projectRoot, 'scripts', 'init-first-agent.ts'); + + const scriptArgs = ['exec', 'tsx', script, '--cli-only', '--display-name', displayName]; + if (agentName) scriptArgs.push('--agent-name', agentName); + if (welcome) scriptArgs.push('--welcome', welcome); + + log.info('Invoking init-first-agent in cli-only mode', { displayName, agentName }); + + try { + execFileSync('pnpm', scriptArgs, { + cwd: projectRoot, + stdio: ['ignore', 'pipe', 'pipe'], + encoding: 'utf-8', + }); + } catch (err) { + const e = err as { stdout?: string; stderr?: string; status?: number }; + log.error('init-first-agent failed', { + status: e.status, + stdout: e.stdout, + stderr: e.stderr, + }); + emitStatus('CLI_AGENT', { + STATUS: 'failed', + ERROR: 'init_script_failed', + EXIT_CODE: e.status ?? -1, + LOG: 'logs/setup.log', + }); + process.exit(1); + } + + emitStatus('CLI_AGENT', { + DISPLAY_NAME: displayName, + AGENT_NAME: agentName || displayName, + CHANNEL: 'cli/local', + STATUS: 'success', + LOG: 'logs/setup.log', + }); +} diff --git a/setup/index.ts b/setup/index.ts index e3b9dd7bb..526ea7d63 100644 --- a/setup/index.ts +++ b/setup/index.ts @@ -16,6 +16,9 @@ const STEPS: Record< mounts: () => import('./mounts.js'), service: () => import('./service.js'), verify: () => import('./verify.js'), + onecli: () => import('./onecli.js'), + auth: () => import('./auth.js'), + 'cli-agent': () => import('./cli-agent.js'), }; async function main(): Promise { diff --git a/setup/onecli.ts b/setup/onecli.ts new file mode 100644 index 000000000..710737151 --- /dev/null +++ b/setup/onecli.ts @@ -0,0 +1,194 @@ +/** + * Step: onecli — Install + configure the OneCLI gateway and CLI. + * + * Aggregates what the old /setup + /init-onecli skills ran as loose shell + * commands. Idempotent: skips install if `onecli` already works, and safely + * re-applies PATH, api-host, and .env updates. + * + * Emits ONECLI_URL so /new-setup SKILL.md can forward it downstream (e.g. as + * ${ONECLI_URL} in status messages). Polls /health to give downstream steps + * (auth, service) a ready gateway. + */ +import { execFileSync, execSync } from 'child_process'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { log } from '../src/log.js'; +import { emitStatus } from './status.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; + } +} + +function getApiHost(): string | null { + try { + const out = execFileSync('onecli', ['config', 'get', 'api-host'], { + encoding: 'utf-8', + env: childEnv(), + stdio: ['ignore', 'pipe', 'ignore'], + }).trim(); + const parsed = JSON.parse(out) as { value?: unknown }; + return typeof parsed.value === 'string' && parsed.value ? parsed.value : null; + } 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 }); + } + } +} + +function writeEnvOnecliUrl(url: string): void { + const envFile = path.join(process.cwd(), '.env'); + let content = fs.existsSync(envFile) ? fs.readFileSync(envFile, 'utf-8') : ''; + if (/^ONECLI_URL=/m.test(content)) { + content = content.replace(/^ONECLI_URL=.*$/m, `ONECLI_URL=${url}`); + } else { + content = content.trimEnd() + (content ? '\n' : '') + `ONECLI_URL=${url}\n`; + } + fs.writeFileSync(envFile, content); +} + +function installOnecli(): { stdout: string; ok: boolean } { + // OneCLI's own install script handles gateway + CLI + PATH. + // We run the two canonical installers in sequence and capture stdout so + // we can extract the printed URL as a fallback to `onecli config get`. + let stdout = ''; + try { + stdout += execSync('curl -fsSL onecli.sh/install | sh', { + encoding: 'utf-8', + stdio: ['ignore', 'pipe', 'pipe'], + }); + stdout += execSync('curl -fsSL onecli.sh/cli/install | sh', { + encoding: 'utf-8', + stdio: ['ignore', 'pipe', 'pipe'], + }); + return { stdout, ok: true }; + } catch (err) { + const e = err as { stdout?: string; stderr?: string }; + log.error('OneCLI install failed', { stderr: e.stderr }); + return { stdout: stdout + (e.stdout ?? '') + (e.stderr ?? ''), ok: false }; + } +} + +async function pollHealth(url: string, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { + const res = await fetch(`${url}/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 { + ensureShellProfilePath(); + + let installOutput = ''; + let present = !!onecliVersion(); + if (!present) { + log.info('Installing OneCLI gateway and CLI'); + const res = installOnecli(); + installOutput = res.stdout; + if (!res.ok) { + emitStatus('ONECLI', { + INSTALLED: false, + STATUS: 'failed', + ERROR: 'install_failed', + LOG: 'logs/setup.log', + }); + process.exit(1); + } + present = !!onecliVersion(); + if (!present) { + 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); + } + } + + let url = getApiHost(); + if (!url && installOutput) { + url = extractUrlFromOutput(installOutput); + if (url) { + try { + execFileSync('onecli', ['config', 'set', 'api-host', url], { + stdio: 'ignore', + env: childEnv(), + }); + } catch (err) { + log.warn('onecli config set api-host failed', { err }); + } + } + } + + if (!url) { + emitStatus('ONECLI', { + INSTALLED: true, + STATUS: 'failed', + ERROR: 'could_not_resolve_api_host', + HINT: 'Run `onecli config get api-host` to inspect the gateway URL.', + LOG: 'logs/setup.log', + }); + process.exit(1); + } + + writeEnvOnecliUrl(url); + log.info('Wrote ONECLI_URL to .env', { url }); + + const healthy = await pollHealth(url, 15000); + + emitStatus('ONECLI', { + INSTALLED: true, + ONECLI_URL: url, + HEALTHY: healthy, + STATUS: healthy ? 'success' : 'degraded', + ...(healthy + ? {} + : { HINT: 'Gateway did not respond to /health within 15s. Try `onecli start`.' }), + LOG: 'logs/setup.log', + }); +}