From 01389ff8fc9eb9d41d8a230d890d1940416ea477 Mon Sep 17 00:00:00 2001 From: Koshkoshinsk Date: Sun, 19 Apr 2026 10:43:35 +0000 Subject: [PATCH 01/12] feat(new-setup): add onecli, auth, and cli-agent dispatcher steps Aggregates the loose OneCLI install, secret registration, and first-agent wiring commands from /setup into three new dispatcher steps. Adds --cli-only mode to init-first-agent so /new-setup can reach a working 2-way CLI chat with the bare minimum. - setup/onecli.ts: idempotent install + PATH + api-host + .env, polls /health - setup/auth.ts: --check verifies secret; --create --value registers it - setup/cli-agent.ts: wraps init-first-agent --cli-only - scripts/init-first-agent.ts: --cli-only mode; DM mode unchanged Co-Authored-By: Claude Opus 4.7 (1M context) --- scripts/init-first-agent.ts | 231 +++++++++++++++++++++++------------- setup/auth.ts | 186 +++++++++++++++++++++++++++++ setup/cli-agent.ts | 100 ++++++++++++++++ setup/index.ts | 3 + setup/onecli.ts | 194 ++++++++++++++++++++++++++++++ 5 files changed, 631 insertions(+), 83 deletions(-) create mode 100644 setup/auth.ts create mode 100644 setup/cli-agent.ts create mode 100644 setup/onecli.ts diff --git a/scripts/init-first-agent.ts b/scripts/init-first-agent.ts index efb3b6b..c40f07f 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 0000000..14e27b0 --- /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 0000000..e5a901d --- /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 e3b9dd7..526ea7d 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 0000000..7107371 --- /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', + }); +} From 6db81554bf7d3b42df3ddd3d533385fd24b02151 Mon Sep 17 00:00:00 2001 From: Koshkoshinsk Date: Sun, 19 Apr 2026 10:43:38 +0000 Subject: [PATCH 02/12] feat(new-setup): add probe step for dynamic context injection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Single upfront parallel scan the SKILL.md renders via `!`...`` so Claude sees system state before generating its first response. Each field maps to a routing decision (skip/run/ask) for a downstream step. Reports: OS, SHELL, DOCKER + IMAGE_PRESENT, ONECLI_STATUS + ONECLI_URL, ANTHROPIC_SECRET, SERVICE_STATUS, CLI_AGENT_WIRED, INFERRED_DISPLAY_NAME, TZ_STATUS + TZ_ENV + TZ_SYSTEM. Runs in ~200ms on a fully-set-up host. Not a replacement for per-step idempotency — each step keeps its own checks since probe is a snapshot and can go stale by execution time. Uses /api/health (OneCLI's actual endpoint). Anthropic secret check uses the CLI client so it works whenever onecli is installed, even if the direct HTTP health probe fails (different network paths). Co-Authored-By: Claude Opus 4.7 (1M context) --- setup/index.ts | 1 + setup/probe.ts | 308 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 309 insertions(+) create mode 100644 setup/probe.ts diff --git a/setup/index.ts b/setup/index.ts index 526ea7d..baa97e3 100644 --- a/setup/index.ts +++ b/setup/index.ts @@ -19,6 +19,7 @@ const STEPS: Record< onecli: () => import('./onecli.js'), auth: () => import('./auth.js'), 'cli-agent': () => import('./cli-agent.js'), + probe: () => import('./probe.js'), }; async function main(): Promise { diff --git a/setup/probe.ts b/setup/probe.ts new file mode 100644 index 0000000..14d0829 --- /dev/null +++ b/setup/probe.ts @@ -0,0 +1,308 @@ +/** + * Step: probe — Single upfront parallel scan for /new-setup's dynamic context + * injection. Rendered into the SKILL.md prompt via `!`pnpm exec tsx ... probe`` + * so Claude sees the current system state before generating its first response. + * + * This is a routing aid, NOT a replacement for per-step idempotency checks. + * Each existing step keeps its own checks; probe just tells the skill which + * steps to bother calling. + * + * Keep this step fast (<2s total). All probes swallow their own errors and + * report a neutral state rather than failing the whole scan. + */ +import { execFileSync, execSync } from 'child_process'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import Database from 'better-sqlite3'; + +import { DATA_DIR } from '../src/config.js'; +import { log } from '../src/log.js'; +import { isValidTimezone } from '../src/timezone.js'; +import { commandExists, getPlatform, isWSL } from './platform.js'; +import { emitStatus } from './status.js'; + +const LOCAL_BIN = path.join(os.homedir(), '.local', 'bin'); +const PROBE_TIMEOUT_MS = 2000; +const HEALTH_TIMEOUT_MS = 2000; +const AGENT_IMAGE = 'nanoclaw-agent:latest'; + +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 readEnvVar(name: string): string | null { + const envFile = path.join(process.cwd(), '.env'); + if (!fs.existsSync(envFile)) return null; + const content = fs.readFileSync(envFile, 'utf-8'); + const m = content.match(new RegExp(`^${name}=(.+)$`, 'm')); + if (!m) return null; + return m[1].trim().replace(/^["']|["']$/g, ''); +} + +function probeDocker(): { + status: 'running' | 'installed_not_running' | 'not_found'; + imagePresent: boolean; +} { + if (!commandExists('docker')) return { status: 'not_found', imagePresent: false }; + try { + execSync('docker info', { stdio: 'ignore', timeout: PROBE_TIMEOUT_MS }); + } catch { + return { status: 'installed_not_running', imagePresent: false }; + } + let imagePresent = false; + try { + execSync(`docker image inspect ${AGENT_IMAGE}`, { + stdio: 'ignore', + timeout: PROBE_TIMEOUT_MS, + }); + imagePresent = true; + } catch { + // image not built yet + } + return { status: 'running', imagePresent }; +} + +function probeOnecliUrl(): string | null { + const fromEnv = readEnvVar('ONECLI_URL'); + if (fromEnv) return fromEnv; + try { + const out = execFileSync('onecli', ['config', 'get', 'api-host'], { + encoding: 'utf-8', + env: childEnv(), + stdio: ['ignore', 'pipe', 'ignore'], + timeout: PROBE_TIMEOUT_MS, + }).trim(); + const parsed = JSON.parse(out) as { value?: unknown }; + if (typeof parsed.value === 'string' && parsed.value) return parsed.value; + } catch { + // onecli not installed or config not set + } + return null; +} + +async function probeOnecliStatus( + url: string | null, +): Promise<'healthy' | 'installed_not_healthy' | 'not_found'> { + const installed = + commandExists('onecli') || fs.existsSync(path.join(LOCAL_BIN, 'onecli')); + if (!installed) return 'not_found'; + if (!url) return 'installed_not_healthy'; + try { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), HEALTH_TIMEOUT_MS); + const res = await fetch(`${url}/api/health`, { signal: controller.signal }); + clearTimeout(timer); + return res.ok ? 'healthy' : 'installed_not_healthy'; + } catch { + return 'installed_not_healthy'; + } +} + +function probeAnthropicSecret(): boolean { + try { + const out = execFileSync('onecli', ['secrets', 'list'], { + encoding: 'utf-8', + env: childEnv(), + stdio: ['ignore', 'pipe', 'ignore'], + timeout: PROBE_TIMEOUT_MS, + }); + const parsed = JSON.parse(out) as { data?: Array<{ type: string }> }; + return !!parsed.data?.some((s) => s.type === 'anthropic'); + } catch { + return false; + } +} + +function probeServiceStatus(): 'running' | 'stopped' | 'not_configured' { + const platform = getPlatform(); + if (platform === 'macos') { + try { + const out = execSync('launchctl list', { + encoding: 'utf-8', + timeout: PROBE_TIMEOUT_MS, + }); + const line = out.split('\n').find((l) => l.includes('com.nanoclaw')); + if (!line) return 'not_configured'; + // Format: "PID STATUS LABEL" — PID is "-" when loaded but not running + const pid = line.trim().split(/\s+/)[0]; + return pid && pid !== '-' ? 'running' : 'stopped'; + } catch { + return 'not_configured'; + } + } + if (platform === 'linux') { + try { + execSync('systemctl --user is-active nanoclaw', { + stdio: 'ignore', + timeout: PROBE_TIMEOUT_MS, + }); + return 'running'; + } catch { + // Either stopped, not-configured, or is-active returned non-zero. + // Distinguish by checking if the unit file exists at all. + try { + execSync('systemctl --user cat nanoclaw', { + stdio: 'ignore', + timeout: PROBE_TIMEOUT_MS, + }); + return 'stopped'; + } catch { + return 'not_configured'; + } + } + } + return 'not_configured'; +} + +function probeCliAgentWired(): boolean { + const dbPath = path.join(DATA_DIR, 'v2.db'); + if (!fs.existsSync(dbPath)) return false; + let db: Database.Database | null = null; + try { + db = new Database(dbPath, { readonly: true }); + const row = db + .prepare( + `SELECT 1 FROM messaging_group_agents mga + JOIN messaging_groups mg ON mg.id = mga.messaging_group_id + WHERE mg.channel_type = 'cli' LIMIT 1`, + ) + .get(); + return !!row; + } catch { + // Tables may not exist yet + return false; + } finally { + db?.close(); + } +} + +function probeInferredDisplayName(): string { + const reject = (s: string | null | undefined): boolean => + !s || !s.trim() || s.trim().toLowerCase() === 'root'; + + // 1. git global user name + try { + const name = execFileSync('git', ['config', '--global', 'user.name'], { + encoding: 'utf-8', + timeout: 1000, + stdio: ['ignore', 'pipe', 'ignore'], + }).trim(); + if (!reject(name)) return name; + } catch { + // git missing or no config set + } + + const user = process.env.USER || os.userInfo().username; + const platform = getPlatform(); + + // 2. Platform full-name from directory services + if (platform === 'macos') { + try { + const fullName = execFileSync('id', ['-F', user], { + encoding: 'utf-8', + timeout: 1000, + stdio: ['ignore', 'pipe', 'ignore'], + }).trim(); + if (!reject(fullName)) return fullName; + } catch { + // id -F not supported + } + } else if (platform === 'linux') { + try { + const entry = execFileSync('getent', ['passwd', user], { + encoding: 'utf-8', + timeout: 1000, + stdio: ['ignore', 'pipe', 'ignore'], + }).trim(); + const gecos = entry.split(':')[4]; + if (gecos) { + const fullName = gecos.split(',')[0].trim(); + if (!reject(fullName)) return fullName; + } + } catch { + // getent missing + } + } + + // 3. $USER / whoami fallback + if (!reject(user)) return user; + return 'User'; +} + +function probeTimezone(): { + status: 'configured' | 'autodetected' | 'utc_suspicious' | 'needs_input'; + envTz: string; + systemTz: string; +} { + const envTz = readEnvVar('TZ'); + const systemTz = Intl.DateTimeFormat().resolvedOptions().timeZone || ''; + + let status: 'configured' | 'autodetected' | 'utc_suspicious' | 'needs_input'; + if (envTz && isValidTimezone(envTz)) { + status = 'configured'; + } else if (systemTz === 'UTC' || systemTz === 'Etc/UTC') { + status = 'utc_suspicious'; + } else if (systemTz && isValidTimezone(systemTz)) { + status = 'autodetected'; + } else { + status = 'needs_input'; + } + + return { + status, + envTz: envTz || 'none', + systemTz: systemTz || 'unknown', + }; +} + +export async function run(_args: string[]): Promise { + const started = Date.now(); + + // Resolve OS (with WSL distinguished) + const platform = getPlatform(); + const wsl = isWSL(); + const osLabel: 'macos' | 'linux' | 'wsl' | 'unknown' = + wsl ? 'wsl' : platform === 'macos' ? 'macos' : platform === 'linux' ? 'linux' : 'unknown'; + const shell = process.env.SHELL || 'unknown'; + + // Sync probes (child_process is blocking; parallelizing provides little gain + // and complicates error handling). + const docker = probeDocker(); + const oneCliUrl = probeOnecliUrl(); + const serviceStatus = probeServiceStatus(); + const cliAgentWired = probeCliAgentWired(); + const displayName = probeInferredDisplayName(); + const tz = probeTimezone(); + + // Async: health check is the only non-blocking probe. + const onecliStatus = await probeOnecliStatus(oneCliUrl); + + // Secret check uses the CLI client and works whenever onecli is installed, + // even if our direct HTTP health probe failed (different network paths). + const anthropicSecret = onecliStatus !== 'not_found' ? probeAnthropicSecret() : false; + + const elapsedMs = Date.now() - started; + log.info('probe complete', { elapsedMs }); + + emitStatus('PROBE', { + OS: osLabel, + SHELL: shell, + DOCKER: docker.status, + IMAGE_PRESENT: docker.imagePresent, + ONECLI_STATUS: onecliStatus, + ONECLI_URL: oneCliUrl || 'none', + ANTHROPIC_SECRET: anthropicSecret, + SERVICE_STATUS: serviceStatus, + CLI_AGENT_WIRED: cliAgentWired, + INFERRED_DISPLAY_NAME: displayName, + TZ_STATUS: tz.status, + TZ_ENV: tz.envTz, + TZ_SYSTEM: tz.systemTz, + ELAPSED_MS: elapsedMs, + STATUS: 'success', + }); +} From f6ddd20636a395c1947ab9d6bc3d76b3bef44119 Mon Sep 17 00:00:00 2001 From: Koshkoshinsk Date: Sun, 19 Apr 2026 10:43:41 +0000 Subject: [PATCH 03/12] feat(new-setup): add skill definition MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Shortest path from zero to a working two-way agent chat via the CLI channel. Renders `!`pnpm exec tsx setup/index.ts --step probe`` at the top for dynamic context injection — Claude sees current system state before generating its first response and routes each subsequent step (skip/ask/run) off the probe snapshot. Pre-approves the Bash patterns it needs via `allowed-tools` so setup runs without per-step prompts. Lives alongside /setup for now; will replace it once proven. Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/skills/new-setup/SKILL.md | 116 ++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 .claude/skills/new-setup/SKILL.md diff --git a/.claude/skills/new-setup/SKILL.md b/.claude/skills/new-setup/SKILL.md new file mode 100644 index 0000000..4ea6ece --- /dev/null +++ b/.claude/skills/new-setup/SKILL.md @@ -0,0 +1,116 @@ +--- +name: new-setup +description: Shortest path from zero to a working two-way agent chat, for any user regardless of technical background — ends at a running NanoClaw instance with at least one CLI-reachable agent. +allowed-tools: Bash(bash setup.sh) Bash(pnpm exec tsx setup/index.ts *) Bash(pnpm run chat *) Bash(brew install *) Bash(curl -fsSL https://get.docker.com | sh) Bash(sudo usermod -aG docker *) Bash(open -a Docker) Bash(sudo systemctl start docker) +--- + +# NanoClaw bare-minimum setup + +Purpose of this skill is to take any user — technical or not — from zero to a two-way chat with an agent in the fewest steps possible. Done means a running NanoClaw instance with at least one agent reachable via the CLI channel. + +Only run the steps strictly required for the NanoClaw process to start and respond to the user end-to-end. Everything else is deferred to post-setup skills. + +For each step, print a one-liner to the user explaining what it does and why it's needed. Keep the tone friendly and lightly informative — context, not jargon. + +Each step is invoked as `pnpm exec tsx setup/index.ts --step ` and emits a structured status block Claude parses to decide what to do next. + +Start with a probe: a single parallel scan that snapshots every prerequisite and dependency. The rest of the flow reads this snapshot to decide what to run, skip, or ask about — no per-step re-checking. + +## Current state + +!`pnpm exec tsx setup/index.ts --step probe` + +## Flow + +Parse the probe block above. For each step below, consult the named probe fields and skip, ask, or run accordingly. Before running any step, say the quoted one-liner to the user. + +### 1. Node bootstrap + +Always runs — probe can't report on this since it lives below the Node layer. + +> *"Now I'm installing Node and your project's dependencies, so the rest of setup has what it needs to run."* + +Run `bash setup.sh`. Parse the status block. + +- `NODE_OK=false` → Offer to install Node 22 (macOS: `brew install node@22`; Linux: `curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - && sudo apt-get install -y nodejs`). Re-run. +- `DEPS_OK=false` or `NATIVE_OK=false` → Read `logs/setup.log`, fix, re-run. + +> **Loose command:** `bash setup.sh`. Justification: pre-Node bootstrap. Can't call the Node-based dispatcher before Node and `pnpm install` are in place. + +### 2. Docker + +Check probe results and skip if `DOCKER=running` AND `IMAGE_PRESENT=true`. + +**Runtime:** +- `DOCKER=not_found` → + > *"Now I'm installing Docker so your agents can work safely in a contained environment."* + - macOS: `brew install --cask docker && open -a Docker` + - Linux: `curl -fsSL https://get.docker.com | sh && sudo usermod -aG docker $USER` (tell user they may need to log out/in for group membership) +- `DOCKER=installed_not_running` → + > *"Starting Docker up so the agent containers can come online."* + - macOS: `open -a Docker` + - Linux: `sudo systemctl start docker` + +Wait ~15s after either, then proceed. + +> **Loose commands:** Docker install/start. Justification: platform-specific package-manager invocations. Wrapping them in a `--step` would just move the same branching into TypeScript with no added value. + +**Image (run if `IMAGE_PRESENT=false`):** + +> *"Next I'm building the agent container image — takes a few minutes the first time, but it's a one-off."* + +`pnpm exec tsx setup/index.ts --step container -- --runtime docker` + +### 3. OneCLI + +Check probe results and skip if `ONECLI_STATUS=healthy`. + +> *"Now I'm installing OneCLI — a local vault that keeps your API keys safe and hands them to your agents only when they need them."* + +`pnpm exec tsx setup/index.ts --step onecli` + +### 4. Anthropic credential + +Check probe results and skip if `ANTHROPIC_SECRET=true`. + +> *"Your agent needs an Anthropic credential to talk to Claude. Let's get that set up."* + +Use `AskUserQuestion`: +1. **Claude subscription (Pro/Max)** — "Run `claude setup-token` in another terminal. It prints a token; paste it back here when ready." +2. **Anthropic API key** — "Get one from https://console.anthropic.com/settings/keys." + +Wait for the token. When received, run: + +`pnpm exec tsx setup/index.ts --step auth -- --create --value ` + +### 5. Service + +Check probe results and skip if `SERVICE_STATUS=running`. + +> *"Starting the NanoClaw background service so it can relay messages between you and your agent."* + +`pnpm exec tsx setup/index.ts --step service` + +### 6. First CLI agent + +Check probe results and skip if `CLI_AGENT_WIRED=true`. + +> *"Now I'm creating your first agent and hooking it up to the terminal so you can start chatting."* + +Ask: *"What should I call you?"* Default: the value of `INFERRED_DISPLAY_NAME` from probe. + +`pnpm exec tsx setup/index.ts --step cli-agent -- --display-name ""` + +### 7. First chat + +> *"You're all set — send your first message to your agent:"* + +`pnpm run chat hi` + +The agent should reply within ~60s (first container spin-up is slowest). If no reply, tail `logs/nanoclaw.log`. + +> **Loose command:** `pnpm run chat hi`. Justification: this is the command the user will keep using after setup. Hiding it behind a `--step` would force them to memorize a second way to do the same thing. + +## If anything fails + +Any step that reports `STATUS: failed` in its status block: read `logs/setup.log`, diagnose, fix the underlying cause, re-run the same `--step`. Don't bypass errors to keep moving. From b3e8b2e047c96a36b8436e64894259d979aff9cd Mon Sep 17 00:00:00 2001 From: Koshkoshinsk Date: Sun, 19 Apr 2026 11:03:49 +0000 Subject: [PATCH 04/12] fix(new-setup): run probe before pnpm is installed Port probe to zero-dep plain ESM (setup/probe.mjs) so /new-setup can inject dynamic context on a fresh machine where pnpm/node_modules don't yet exist. Skill falls back to a STATUS: unavailable block if Node itself isn't on PATH, and the flow treats that as "run every step from 1" (each step is idempotent). Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/skills/new-setup/SKILL.md | 8 +- setup/index.ts | 1 - setup/{probe.ts => probe.mjs} | 193 ++++++++++++++++++------------ 3 files changed, 122 insertions(+), 80 deletions(-) rename setup/{probe.ts => probe.mjs} (62%) diff --git a/.claude/skills/new-setup/SKILL.md b/.claude/skills/new-setup/SKILL.md index 4ea6ece..3643b92 100644 --- a/.claude/skills/new-setup/SKILL.md +++ b/.claude/skills/new-setup/SKILL.md @@ -1,7 +1,7 @@ --- name: new-setup description: Shortest path from zero to a working two-way agent chat, for any user regardless of technical background — ends at a running NanoClaw instance with at least one CLI-reachable agent. -allowed-tools: Bash(bash setup.sh) Bash(pnpm exec tsx setup/index.ts *) Bash(pnpm run chat *) Bash(brew install *) Bash(curl -fsSL https://get.docker.com | sh) Bash(sudo usermod -aG docker *) Bash(open -a Docker) Bash(sudo systemctl start docker) +allowed-tools: Bash(bash setup.sh) Bash(node setup/probe.mjs) Bash(pnpm exec tsx setup/index.ts *) Bash(pnpm run chat *) Bash(brew install *) Bash(curl -fsSL https://get.docker.com | sh) Bash(sudo usermod -aG docker *) Bash(open -a Docker) Bash(sudo systemctl start docker) --- # NanoClaw bare-minimum setup @@ -14,16 +14,18 @@ For each step, print a one-liner to the user explaining what it does and why it' Each step is invoked as `pnpm exec tsx setup/index.ts --step ` and emits a structured status block Claude parses to decide what to do next. -Start with a probe: a single parallel scan that snapshots every prerequisite and dependency. The rest of the flow reads this snapshot to decide what to run, skip, or ask about — no per-step re-checking. +Start with a probe: a single parallel scan that snapshots every prerequisite and dependency. The rest of the flow reads this snapshot to decide what to run, skip, or ask about — no per-step re-checking. The probe is plain ESM JS (`setup/probe.mjs`) with no external deps so it can run before step 1 has installed `pnpm`/`node_modules`. ## Current state -!`pnpm exec tsx setup/index.ts --step probe` +!`command -v node >/dev/null 2>&1 && node setup/probe.mjs || printf '=== NANOCLAW SETUP: PROBE ===\nSTATUS: unavailable\nREASON: node_not_installed\n=== END ===\n'` ## Flow Parse the probe block above. For each step below, consult the named probe fields and skip, ask, or run accordingly. Before running any step, say the quoted one-liner to the user. +If the probe reports `STATUS: unavailable` (Node isn't installed yet), ignore all `skip if …` probe conditions and run every step from 1 onward — each step has its own idempotency check, so re-running is safe. + ### 1. Node bootstrap Always runs — probe can't report on this since it lives below the Node layer. diff --git a/setup/index.ts b/setup/index.ts index baa97e3..526ea7d 100644 --- a/setup/index.ts +++ b/setup/index.ts @@ -19,7 +19,6 @@ const STEPS: Record< onecli: () => import('./onecli.js'), auth: () => import('./auth.js'), 'cli-agent': () => import('./cli-agent.js'), - probe: () => import('./probe.js'), }; async function main(): Promise { diff --git a/setup/probe.ts b/setup/probe.mjs similarity index 62% rename from setup/probe.ts rename to setup/probe.mjs index 14d0829..a28f759 100644 --- a/setup/probe.ts +++ b/setup/probe.mjs @@ -1,40 +1,82 @@ +#!/usr/bin/env node /** - * Step: probe — Single upfront parallel scan for /new-setup's dynamic context - * injection. Rendered into the SKILL.md prompt via `!`pnpm exec tsx ... probe`` - * so Claude sees the current system state before generating its first response. + * Setup step: probe — Single upfront parallel scan for /new-setup's dynamic + * context injection. Rendered into the SKILL.md prompt via + * `!node setup/probe.mjs` so Claude sees the current system state before + * generating its first response. * * This is a routing aid, NOT a replacement for per-step idempotency checks. - * Each existing step keeps its own checks; probe just tells the skill which - * steps to bother calling. + * Each step keeps its own checks; probe tells the skill which steps to skip. * - * Keep this step fast (<2s total). All probes swallow their own errors and - * report a neutral state rather than failing the whole scan. + * Plain ESM JS (zero deps) by design: this runs BEFORE setup.sh has installed + * pnpm and node_modules, so it can only use Node built-ins. `better-sqlite3` + * is dynamic-imported so the probe degrades gracefully on fresh installs. + * + * Keep fast (<2s total). All probes swallow their own errors and report a + * neutral state rather than failing the whole scan. */ -import { execFileSync, execSync } from 'child_process'; -import fs from 'fs'; -import os from 'os'; -import path from 'path'; - -import Database from 'better-sqlite3'; - -import { DATA_DIR } from '../src/config.js'; -import { log } from '../src/log.js'; -import { isValidTimezone } from '../src/timezone.js'; -import { commandExists, getPlatform, isWSL } from './platform.js'; -import { emitStatus } from './status.js'; +import { execFileSync, execSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; const LOCAL_BIN = path.join(os.homedir(), '.local', 'bin'); const PROBE_TIMEOUT_MS = 2000; const HEALTH_TIMEOUT_MS = 2000; const AGENT_IMAGE = 'nanoclaw-agent:latest'; +const DATA_DIR = path.resolve(process.cwd(), 'data'); -function childEnv(): NodeJS.ProcessEnv { +function childEnv() { const parts = [LOCAL_BIN]; if (process.env.PATH) parts.push(process.env.PATH); return { ...process.env, PATH: parts.join(path.delimiter) }; } -function readEnvVar(name: string): string | null { +function getPlatform() { + const p = os.platform(); + if (p === 'darwin') return 'macos'; + if (p === 'linux') return 'linux'; + return 'unknown'; +} + +function isWSL() { + if (os.platform() !== 'linux') return false; + try { + const release = fs.readFileSync('/proc/version', 'utf-8').toLowerCase(); + return release.includes('microsoft') || release.includes('wsl'); + } catch { + return false; + } +} + +function commandExists(name) { + try { + execSync(`command -v ${name}`, { stdio: 'ignore' }); + return true; + } catch { + return false; + } +} + +function isValidTimezone(tz) { + try { + new Intl.DateTimeFormat(undefined, { timeZone: tz }); + return true; + } catch { + return false; + } +} + +function emitStatus(step, fields) { + const lines = [`=== NANOCLAW SETUP: ${step} ===`]; + for (const [k, v] of Object.entries(fields)) { + lines.push(`${k}: ${v}`); + } + lines.push('=== END ==='); + console.log(lines.join('\n')); +} + +function readEnvVar(name) { const envFile = path.join(process.cwd(), '.env'); if (!fs.existsSync(envFile)) return null; const content = fs.readFileSync(envFile, 'utf-8'); @@ -43,10 +85,7 @@ function readEnvVar(name: string): string | null { return m[1].trim().replace(/^["']|["']$/g, ''); } -function probeDocker(): { - status: 'running' | 'installed_not_running' | 'not_found'; - imagePresent: boolean; -} { +function probeDocker() { if (!commandExists('docker')) return { status: 'not_found', imagePresent: false }; try { execSync('docker info', { stdio: 'ignore', timeout: PROBE_TIMEOUT_MS }); @@ -66,7 +105,7 @@ function probeDocker(): { return { status: 'running', imagePresent }; } -function probeOnecliUrl(): string | null { +function probeOnecliUrl() { const fromEnv = readEnvVar('ONECLI_URL'); if (fromEnv) return fromEnv; try { @@ -76,7 +115,7 @@ function probeOnecliUrl(): string | null { stdio: ['ignore', 'pipe', 'ignore'], timeout: PROBE_TIMEOUT_MS, }).trim(); - const parsed = JSON.parse(out) as { value?: unknown }; + const parsed = JSON.parse(out); if (typeof parsed.value === 'string' && parsed.value) return parsed.value; } catch { // onecli not installed or config not set @@ -84,9 +123,7 @@ function probeOnecliUrl(): string | null { return null; } -async function probeOnecliStatus( - url: string | null, -): Promise<'healthy' | 'installed_not_healthy' | 'not_found'> { +async function probeOnecliStatus(url) { const installed = commandExists('onecli') || fs.existsSync(path.join(LOCAL_BIN, 'onecli')); if (!installed) return 'not_found'; @@ -102,7 +139,7 @@ async function probeOnecliStatus( } } -function probeAnthropicSecret(): boolean { +function probeAnthropicSecret() { try { const out = execFileSync('onecli', ['secrets', 'list'], { encoding: 'utf-8', @@ -110,14 +147,14 @@ function probeAnthropicSecret(): boolean { stdio: ['ignore', 'pipe', 'ignore'], timeout: PROBE_TIMEOUT_MS, }); - const parsed = JSON.parse(out) as { data?: Array<{ type: string }> }; - return !!parsed.data?.some((s) => s.type === 'anthropic'); + const parsed = JSON.parse(out); + return !!(parsed.data && parsed.data.some((s) => s.type === 'anthropic')); } catch { return false; } } -function probeServiceStatus(): 'running' | 'stopped' | 'not_configured' { +function probeServiceStatus() { const platform = getPlatform(); if (platform === 'macos') { try { @@ -127,7 +164,6 @@ function probeServiceStatus(): 'running' | 'stopped' | 'not_configured' { }); const line = out.split('\n').find((l) => l.includes('com.nanoclaw')); if (!line) return 'not_configured'; - // Format: "PID STATUS LABEL" — PID is "-" when loaded but not running const pid = line.trim().split(/\s+/)[0]; return pid && pid !== '-' ? 'running' : 'stopped'; } catch { @@ -142,8 +178,6 @@ function probeServiceStatus(): 'running' | 'stopped' | 'not_configured' { }); return 'running'; } catch { - // Either stopped, not-configured, or is-active returned non-zero. - // Distinguish by checking if the unit file exists at all. try { execSync('systemctl --user cat nanoclaw', { stdio: 'ignore', @@ -158,33 +192,36 @@ function probeServiceStatus(): 'running' | 'stopped' | 'not_configured' { return 'not_configured'; } -function probeCliAgentWired(): boolean { +async function probeCliAgentWired() { const dbPath = path.join(DATA_DIR, 'v2.db'); if (!fs.existsSync(dbPath)) return false; - let db: Database.Database | null = null; + // Dynamic-import so probe still runs before `pnpm install` has built the + // native module. On truly fresh installs `data/v2.db` can't exist anyway, + // so the short-circuit above handles that path. try { - db = new Database(dbPath, { readonly: true }); - const row = db - .prepare( - `SELECT 1 FROM messaging_group_agents mga - JOIN messaging_groups mg ON mg.id = mga.messaging_group_id - WHERE mg.channel_type = 'cli' LIMIT 1`, - ) - .get(); - return !!row; + const mod = await import('better-sqlite3'); + const Database = mod.default ?? mod; + const db = new Database(dbPath, { readonly: true }); + try { + const row = db + .prepare( + `SELECT 1 FROM messaging_group_agents mga + JOIN messaging_groups mg ON mg.id = mga.messaging_group_id + WHERE mg.channel_type = 'cli' LIMIT 1`, + ) + .get(); + return !!row; + } finally { + db.close(); + } } catch { - // Tables may not exist yet return false; - } finally { - db?.close(); } } -function probeInferredDisplayName(): string { - const reject = (s: string | null | undefined): boolean => - !s || !s.trim() || s.trim().toLowerCase() === 'root'; +function probeInferredDisplayName() { + const reject = (s) => !s || !s.trim() || s.trim().toLowerCase() === 'root'; - // 1. git global user name try { const name = execFileSync('git', ['config', '--global', 'user.name'], { encoding: 'utf-8', @@ -199,7 +236,6 @@ function probeInferredDisplayName(): string { const user = process.env.USER || os.userInfo().username; const platform = getPlatform(); - // 2. Platform full-name from directory services if (platform === 'macos') { try { const fullName = execFileSync('id', ['-F', user], { @@ -228,20 +264,15 @@ function probeInferredDisplayName(): string { } } - // 3. $USER / whoami fallback if (!reject(user)) return user; return 'User'; } -function probeTimezone(): { - status: 'configured' | 'autodetected' | 'utc_suspicious' | 'needs_input'; - envTz: string; - systemTz: string; -} { +function probeTimezone() { const envTz = readEnvVar('TZ'); const systemTz = Intl.DateTimeFormat().resolvedOptions().timeZone || ''; - let status: 'configured' | 'autodetected' | 'utc_suspicious' | 'needs_input'; + let status; if (envTz && isValidTimezone(envTz)) { status = 'configured'; } else if (systemTz === 'UTC' || systemTz === 'Etc/UTC') { @@ -259,34 +290,35 @@ function probeTimezone(): { }; } -export async function run(_args: string[]): Promise { +export async function run() { const started = Date.now(); - // Resolve OS (with WSL distinguished) const platform = getPlatform(); const wsl = isWSL(); - const osLabel: 'macos' | 'linux' | 'wsl' | 'unknown' = - wsl ? 'wsl' : platform === 'macos' ? 'macos' : platform === 'linux' ? 'linux' : 'unknown'; + const osLabel = wsl + ? 'wsl' + : platform === 'macos' + ? 'macos' + : platform === 'linux' + ? 'linux' + : 'unknown'; const shell = process.env.SHELL || 'unknown'; - // Sync probes (child_process is blocking; parallelizing provides little gain - // and complicates error handling). const docker = probeDocker(); const oneCliUrl = probeOnecliUrl(); const serviceStatus = probeServiceStatus(); - const cliAgentWired = probeCliAgentWired(); const displayName = probeInferredDisplayName(); const tz = probeTimezone(); - // Async: health check is the only non-blocking probe. - const onecliStatus = await probeOnecliStatus(oneCliUrl); + const [onecliStatus, cliAgentWired] = await Promise.all([ + probeOnecliStatus(oneCliUrl), + probeCliAgentWired(), + ]); - // Secret check uses the CLI client and works whenever onecli is installed, - // even if our direct HTTP health probe failed (different network paths). - const anthropicSecret = onecliStatus !== 'not_found' ? probeAnthropicSecret() : false; + const anthropicSecret = + onecliStatus !== 'not_found' ? probeAnthropicSecret() : false; const elapsedMs = Date.now() - started; - log.info('probe complete', { elapsedMs }); emitStatus('PROBE', { OS: osLabel, @@ -306,3 +338,12 @@ export async function run(_args: string[]): Promise { STATUS: 'success', }); } + +const invokedDirectly = + import.meta.url === `file://${path.resolve(process.argv[1] ?? '')}`; +if (invokedDirectly) { + run().catch((err) => { + console.error(err); + process.exit(1); + }); +} From 77624d785453e38ea4b4baab61691041d2b1f402 Mon Sep 17 00:00:00 2001 From: Koshkoshinsk Date: Sun, 19 Apr 2026 11:05:54 +0000 Subject: [PATCH 05/12] fix(new-setup): wrap probe in shell script for single-command permission check The chained `&& / ||` inline command tripped Claude Code's per-operation permission check. Move the Node-missing fallback into setup/probe.sh so the skill's `!` block is a single `bash setup/probe.sh` call. Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/skills/new-setup/SKILL.md | 4 ++-- setup/probe.sh | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) create mode 100755 setup/probe.sh diff --git a/.claude/skills/new-setup/SKILL.md b/.claude/skills/new-setup/SKILL.md index 3643b92..4c2a1fe 100644 --- a/.claude/skills/new-setup/SKILL.md +++ b/.claude/skills/new-setup/SKILL.md @@ -1,7 +1,7 @@ --- name: new-setup description: Shortest path from zero to a working two-way agent chat, for any user regardless of technical background — ends at a running NanoClaw instance with at least one CLI-reachable agent. -allowed-tools: Bash(bash setup.sh) Bash(node setup/probe.mjs) Bash(pnpm exec tsx setup/index.ts *) Bash(pnpm run chat *) Bash(brew install *) Bash(curl -fsSL https://get.docker.com | sh) Bash(sudo usermod -aG docker *) Bash(open -a Docker) Bash(sudo systemctl start docker) +allowed-tools: Bash(bash setup.sh) Bash(bash setup/probe.sh) Bash(pnpm exec tsx setup/index.ts *) Bash(pnpm run chat *) Bash(brew install *) Bash(curl -fsSL https://get.docker.com | sh) Bash(sudo usermod -aG docker *) Bash(open -a Docker) Bash(sudo systemctl start docker) --- # NanoClaw bare-minimum setup @@ -18,7 +18,7 @@ Start with a probe: a single parallel scan that snapshots every prerequisite and ## Current state -!`command -v node >/dev/null 2>&1 && node setup/probe.mjs || printf '=== NANOCLAW SETUP: PROBE ===\nSTATUS: unavailable\nREASON: node_not_installed\n=== END ===\n'` +!`bash setup/probe.sh` ## Flow diff --git a/setup/probe.sh b/setup/probe.sh new file mode 100755 index 0000000..8be2948 --- /dev/null +++ b/setup/probe.sh @@ -0,0 +1,19 @@ +#!/bin/bash +# Wrapper for setup/probe.mjs so /new-setup's inline `!` block is a single +# shell command (permission-check friendly). When Node isn't installed yet, +# emit an "unavailable" status block so the skill's flow knows to skip the +# probe's skip-if conditions and run every step from 1. +set -u + +PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +if command -v node >/dev/null 2>&1; then + exec node "$PROJECT_ROOT/setup/probe.mjs" "$@" +fi + +cat <<'EOF' +=== NANOCLAW SETUP: PROBE === +STATUS: unavailable +REASON: node_not_installed +=== END === +EOF From 77fec6c7c33cf69adbdac6b1081e625e2901657e Mon Sep 17 00:00:00 2001 From: Koshkoshinsk Date: Sun, 19 Apr 2026 11:37:03 +0000 Subject: [PATCH 06/12] fix(new-setup): avoid double-bootstrap and corepack EACCES on system Node MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two fixes to the fresh-install path: 1. setup.sh: when `corepack enable` runs as a non-root user against a system-wide Node install (apt-installed to /usr/bin), it fails EACCES trying to symlink /usr/bin/pnpm, leaving pnpm off PATH. Retry with sudo when pnpm is still missing — gated to Linux/WSL so macOS Homebrew prefixes aren't polluted with root-owned shims. 2. SKILL.md step 1: if the probe reports STATUS: unavailable (Node not installed), install Node BEFORE invoking `bash setup.sh`. The old flow ran setup.sh first as a diagnostic, which always failed fast, installed Node, then re-ran — two bootstraps for no reason. Combined: fresh Linux box now goes Node install -> single setup.sh run. Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/skills/new-setup/SKILL.md | 13 +++++++++---- setup.sh | 13 ++++++++++++- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/.claude/skills/new-setup/SKILL.md b/.claude/skills/new-setup/SKILL.md index 4c2a1fe..2a92b58 100644 --- a/.claude/skills/new-setup/SKILL.md +++ b/.claude/skills/new-setup/SKILL.md @@ -28,13 +28,18 @@ If the probe reports `STATUS: unavailable` (Node isn't installed yet), ignore al ### 1. Node bootstrap -Always runs — probe can't report on this since it lives below the Node layer. - > *"Now I'm installing Node and your project's dependencies, so the rest of setup has what it needs to run."* -Run `bash setup.sh`. Parse the status block. +If the probe reported `STATUS: unavailable` (Node isn't installed yet), install Node 22 **before** running `bash setup.sh` — otherwise the first bootstrap run is guaranteed to fail and you'll pay for it twice: -- `NODE_OK=false` → Offer to install Node 22 (macOS: `brew install node@22`; Linux: `curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - && sudo apt-get install -y nodejs`). Re-run. +- macOS: `brew install node@22` +- Linux / WSL: `curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - && sudo apt-get install -y nodejs` + +Then run `bash setup.sh`. If the probe reported any other status, run `bash setup.sh` directly — it's idempotent and verifies host deps + native modules. + +Parse the status block: + +- `NODE_OK=false` → Node install didn't take effect (PATH issue, keg-only formula, etc.). Investigate `logs/setup.log`, resolve, re-run. - `DEPS_OK=false` or `NATIVE_OK=false` → Read `logs/setup.log`, fix, re-run. > **Loose command:** `bash setup.sh`. Justification: pre-Node bootstrap. Can't call the Node-based dispatcher before Node and `pnpm install` are in place. diff --git a/setup.sh b/setup.sh index fb69d0a..af2c5e5 100755 --- a/setup.sh +++ b/setup.sh @@ -72,10 +72,21 @@ install_deps() { cd "$PROJECT_ROOT" - # Enable corepack for pnpm + # Enable corepack so `pnpm` shim lands on PATH. log "Enabling corepack" corepack enable >> "$LOG_FILE" 2>&1 || true + # On Linux/WSL with system-wide Node (e.g. apt-installed to /usr/bin), + # corepack needs root to symlink /usr/bin/pnpm. Retry with sudo when pnpm + # isn't on PATH. macOS Homebrew installs land in a user-writable prefix, + # and a sudo retry there would create root-owned shims inside /opt/homebrew + # that later break brew — so the retry is Linux-only. + if ! command -v pnpm >/dev/null 2>&1 && [ "$PLATFORM" = "linux" ] \ + && command -v sudo >/dev/null 2>&1; then + log "pnpm not on PATH after corepack enable — retrying with sudo" + sudo corepack enable >> "$LOG_FILE" 2>&1 || true + fi + log "Running pnpm install --frozen-lockfile" if pnpm install --frozen-lockfile >> "$LOG_FILE" 2>&1; then DEPS_OK="true" From f553c8126cd296bf1e83420318f2d780040bb464 Mon Sep 17 00:00:00 2001 From: Koshkoshinsk Date: Sun, 19 Apr 2026 11:50:00 +0000 Subject: [PATCH 07/12] refactor(new-setup): add step-4 join barrier and drop scripted one-liners MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two flow fixes: 1. Add "Ordering and parallelism" section making explicit that step 4 (auth) must block until step 3 (OneCLI) is complete — auth writes the secret into the vault, so firing an AskUserQuestion while OneCLI is still installing asks the user for a credential the system can't store. Step 2 (container build) is safe to run past step 4, joined before step 6 (first CLI agent). 2. Drop the per-step quoted one-liners. They duplicated Claude's own natural narration ("While those build, let's get your credential set up." → immediately echoed by the scripted "Your agent needs an Anthropic credential..."). Each step now has a short description instead; Claude narrates in its own voice. Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/skills/new-setup/SKILL.md | 38 +++++++++++++++++-------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/.claude/skills/new-setup/SKILL.md b/.claude/skills/new-setup/SKILL.md index 2a92b58..ba62242 100644 --- a/.claude/skills/new-setup/SKILL.md +++ b/.claude/skills/new-setup/SKILL.md @@ -10,7 +10,7 @@ Purpose of this skill is to take any user — technical or not — from zero to Only run the steps strictly required for the NanoClaw process to start and respond to the user end-to-end. Everything else is deferred to post-setup skills. -For each step, print a one-liner to the user explaining what it does and why it's needed. Keep the tone friendly and lightly informative — context, not jargon. +Before each step, narrate to the user in your own words what's about to happen — one short, friendly sentence, no jargon. Don't read a scripted line; use the step context below to speak naturally. Each step is invoked as `pnpm exec tsx setup/index.ts --step ` and emits a structured status block Claude parses to decide what to do next. @@ -22,13 +22,21 @@ Start with a probe: a single parallel scan that snapshots every prerequisite and ## Flow -Parse the probe block above. For each step below, consult the named probe fields and skip, ask, or run accordingly. Before running any step, say the quoted one-liner to the user. +Parse the probe block above. For each step below, consult the named probe fields and skip, ask, or run accordingly. If the probe reports `STATUS: unavailable` (Node isn't installed yet), ignore all `skip if …` probe conditions and run every step from 1 onward — each step has its own idempotency check, so re-running is safe. -### 1. Node bootstrap +## Ordering and parallelism -> *"Now I'm installing Node and your project's dependencies, so the rest of setup has what it needs to run."* +Run steps sequentially by default: invoke the step, wait for its status block, act on the result, move to the next. + +One permitted parallelism: + +- **Step 2 (container image build) and step 3 (OneCLI install)** are independent — they may start together in the background. +- **Step 4 (auth) must NOT start until step 3 has completed.** Auth writes the secret into the OneCLI vault; if OneCLI isn't installed and healthy yet, the user gets asked for a credential the system can't store. Do not open an `AskUserQuestion` for step 4 while OneCLI is still installing. +- Step 2's image build may continue running past step 4 — the image isn't consumed until step 6 (first CLI agent). Join before step 6. + +### 1. Node bootstrap If the probe reported `STATUS: unavailable` (Node isn't installed yet), install Node 22 **before** running `bash setup.sh` — otherwise the first bootstrap run is guaranteed to fail and you'll pay for it twice: @@ -49,12 +57,10 @@ Parse the status block: Check probe results and skip if `DOCKER=running` AND `IMAGE_PRESENT=true`. **Runtime:** -- `DOCKER=not_found` → - > *"Now I'm installing Docker so your agents can work safely in a contained environment."* +- `DOCKER=not_found` → Docker itself is missing — install it so agent containers have an isolated place to run. - macOS: `brew install --cask docker && open -a Docker` - Linux: `curl -fsSL https://get.docker.com | sh && sudo usermod -aG docker $USER` (tell user they may need to log out/in for group membership) -- `DOCKER=installed_not_running` → - > *"Starting Docker up so the agent containers can come online."* +- `DOCKER=installed_not_running` → Docker is installed but the daemon is down — start it. - macOS: `open -a Docker` - Linux: `sudo systemctl start docker` @@ -62,9 +68,7 @@ Wait ~15s after either, then proceed. > **Loose commands:** Docker install/start. Justification: platform-specific package-manager invocations. Wrapping them in a `--step` would just move the same branching into TypeScript with no added value. -**Image (run if `IMAGE_PRESENT=false`):** - -> *"Next I'm building the agent container image — takes a few minutes the first time, but it's a one-off."* +**Image (run if `IMAGE_PRESENT=false`):** build the agent container image — takes a few minutes the first time, one-off cost. `pnpm exec tsx setup/index.ts --step container -- --runtime docker` @@ -72,7 +76,7 @@ Wait ~15s after either, then proceed. Check probe results and skip if `ONECLI_STATUS=healthy`. -> *"Now I'm installing OneCLI — a local vault that keeps your API keys safe and hands them to your agents only when they need them."* +OneCLI is the local vault that holds API keys and only releases them to agents when they need them. `pnpm exec tsx setup/index.ts --step onecli` @@ -80,7 +84,7 @@ Check probe results and skip if `ONECLI_STATUS=healthy`. Check probe results and skip if `ANTHROPIC_SECRET=true`. -> *"Your agent needs an Anthropic credential to talk to Claude. Let's get that set up."* +The agent needs an Anthropic credential to talk to Claude. Two sources: Use `AskUserQuestion`: 1. **Claude subscription (Pro/Max)** — "Run `claude setup-token` in another terminal. It prints a token; paste it back here when ready." @@ -94,7 +98,7 @@ Wait for the token. When received, run: Check probe results and skip if `SERVICE_STATUS=running`. -> *"Starting the NanoClaw background service so it can relay messages between you and your agent."* +Start the NanoClaw background service — it relays messages between the user and the agent. `pnpm exec tsx setup/index.ts --step service` @@ -102,15 +106,15 @@ Check probe results and skip if `SERVICE_STATUS=running`. Check probe results and skip if `CLI_AGENT_WIRED=true`. -> *"Now I'm creating your first agent and hooking it up to the terminal so you can start chatting."* +If step 2's container build is still running in the background, join it here before proceeding — the agent needs the image. -Ask: *"What should I call you?"* Default: the value of `INFERRED_DISPLAY_NAME` from probe. +Create the first agent and wire it to the CLI channel. Ask the user "What should I call you?" first — default the offered value to `INFERRED_DISPLAY_NAME` from the probe. `pnpm exec tsx setup/index.ts --step cli-agent -- --display-name ""` ### 7. First chat -> *"You're all set — send your first message to your agent:"* +Everything's ready — send the first message to the agent. `pnpm run chat hi` From 0992979c5a02089a64b2a31098153f40b3c16ab8 Mon Sep 17 00:00:00 2001 From: Koshkoshinsk Date: Sun, 19 Apr 2026 12:01:05 +0000 Subject: [PATCH 08/12] feat(new-setup): probe host-deps and skip bootstrap when already installed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Probe now emits HOST_DEPS (ok|missing) based on whether node_modules/better-sqlite3/build/Release/better_sqlite3.node exists — the canonical proof that `pnpm install` ran and the native build step succeeded. Step 1 (Node bootstrap) skips when HOST_DEPS=ok instead of always re-running setup.sh. Probe now genuinely routes step 1 the same way it routes every other step. Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/skills/new-setup/SKILL.md | 6 ++++-- setup/probe.mjs | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/.claude/skills/new-setup/SKILL.md b/.claude/skills/new-setup/SKILL.md index ba62242..f08fd16 100644 --- a/.claude/skills/new-setup/SKILL.md +++ b/.claude/skills/new-setup/SKILL.md @@ -38,12 +38,14 @@ One permitted parallelism: ### 1. Node bootstrap -If the probe reported `STATUS: unavailable` (Node isn't installed yet), install Node 22 **before** running `bash setup.sh` — otherwise the first bootstrap run is guaranteed to fail and you'll pay for it twice: +Check probe results and skip if `HOST_DEPS=ok` — Node, pnpm, `node_modules`, and `better-sqlite3`'s native binding are already in place. + +If the probe reported `STATUS: unavailable` (Node isn't installed yet — probe itself couldn't run), install Node 22 **before** running `bash setup.sh`, otherwise the first bootstrap run is guaranteed to fail: - macOS: `brew install node@22` - Linux / WSL: `curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - && sudo apt-get install -y nodejs` -Then run `bash setup.sh`. If the probe reported any other status, run `bash setup.sh` directly — it's idempotent and verifies host deps + native modules. +Then run `bash setup.sh`. If the probe succeeded but `HOST_DEPS=missing`, run `bash setup.sh` directly — Node is there, deps aren't. Parse the status block: diff --git a/setup/probe.mjs b/setup/probe.mjs index a28f759..5aea0d4 100644 --- a/setup/probe.mjs +++ b/setup/probe.mjs @@ -268,6 +268,22 @@ function probeInferredDisplayName() { return 'User'; } +function probeHostDeps() { + const nodeModules = path.resolve(process.cwd(), 'node_modules'); + if (!fs.existsSync(nodeModules)) return 'missing'; + // better-sqlite3's compiled native binding is the canonical proof that + // `pnpm install` ran AND the native build step succeeded. Cheaper than + // actually loading the module, and unambiguous on success. + const nativeBinding = path.join( + nodeModules, + 'better-sqlite3', + 'build', + 'Release', + 'better_sqlite3.node', + ); + return fs.existsSync(nativeBinding) ? 'ok' : 'missing'; +} + function probeTimezone() { const envTz = readEnvVar('TZ'); const systemTz = Intl.DateTimeFormat().resolvedOptions().timeZone || ''; @@ -309,6 +325,7 @@ export async function run() { const serviceStatus = probeServiceStatus(); const displayName = probeInferredDisplayName(); const tz = probeTimezone(); + const hostDeps = probeHostDeps(); const [onecliStatus, cliAgentWired] = await Promise.all([ probeOnecliStatus(oneCliUrl), @@ -323,6 +340,7 @@ export async function run() { emitStatus('PROBE', { OS: osLabel, SHELL: shell, + HOST_DEPS: hostDeps, DOCKER: docker.status, IMAGE_PRESENT: docker.imagePresent, ONECLI_STATUS: onecliStatus, From 5542107b9e9496a189ffd0ce2530d3b615b7e27f Mon Sep 17 00:00:00 2001 From: Koshkoshinsk Date: Sun, 19 Apr 2026 12:10:21 +0000 Subject: [PATCH 09/12] fix(new-setup): align onecli health path and rework auth flow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit onecli step: - Poll /api/health (was /health) so the step's health check matches the probe's. On hosted OneCLI (app.onecli.sh) the old path returned non-ok, flagging the gateway as "degraded" even though install succeeded. - Drop the "try `onecli start`" hint — no such subcommand exists and it sent the skill off chasing fabricated commands. A failed health poll is demoted to a soft warning; the auth step surfaces a real outage via `onecli secrets list`. SKILL.md step 4: rewrite to match the /setup skill's pattern — the user generates the token themselves, picks dashboard or CLI to register it with OneCLI, and the skill verifies via `auth --check`. Tokens no longer travel through chat. Co-Authored-By: Koshkoshinsk Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/skills/new-setup/SKILL.md | 24 ++++++++++++++++++------ setup/onecli.ts | 14 +++++++++++--- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/.claude/skills/new-setup/SKILL.md b/.claude/skills/new-setup/SKILL.md index f08fd16..a671fb0 100644 --- a/.claude/skills/new-setup/SKILL.md +++ b/.claude/skills/new-setup/SKILL.md @@ -86,15 +86,27 @@ OneCLI is the local vault that holds API keys and only releases them to agents w Check probe results and skip if `ANTHROPIC_SECRET=true`. -The agent needs an Anthropic credential to talk to Claude. Two sources: +The credential never travels through chat — the user generates it, registers it with OneCLI themselves, and the skill verifies. -Use `AskUserQuestion`: -1. **Claude subscription (Pro/Max)** — "Run `claude setup-token` in another terminal. It prints a token; paste it back here when ready." -2. **Anthropic API key** — "Get one from https://console.anthropic.com/settings/keys." +**4a. Pick the source.** `AskUserQuestion`: -Wait for the token. When received, run: +1. **Claude subscription (Pro/Max)** — "Generate a token via `claude setup-token` in another terminal." +2. **Anthropic API key** — "Use a pay-per-use key from console.anthropic.com/settings/keys." -`pnpm exec tsx setup/index.ts --step auth -- --create --value ` +**4b. Wait for the user to obtain the credential.** For subscription, have them run `claude setup-token` in another terminal. For API key, point them to the console URL above. Either way, they keep the token — just confirm when they have it. + +**4c. Pick the registration path.** `AskUserQuestion` — substitute `${ONECLI_URL}` from the probe (or `.env`): + +1. **Dashboard** — "Open ${ONECLI_URL} in a browser; add a secret of type `anthropic`, value = the token, host-pattern `api.anthropic.com`." +2. **CLI** — "Run in another terminal: `onecli secrets create --name Anthropic --type anthropic --value YOUR_TOKEN --host-pattern api.anthropic.com`" + +Wait for the user's confirmation. If their reply happens to include a token (starts with `sk-ant-`), register it for them: `pnpm exec tsx setup/index.ts --step auth -- --create --value `. + +**4d. Verify.** + +`pnpm exec tsx setup/index.ts --step auth -- --check` + +If `ANTHROPIC_OK=false`, the secret isn't there yet — ask them to retry, then re-check. ### 5. Service diff --git a/setup/onecli.ts b/setup/onecli.ts index 7107371..ddb68c6 100644 --- a/setup/onecli.ts +++ b/setup/onecli.ts @@ -106,10 +106,11 @@ function installOnecli(): { stdout: string; ok: boolean } { } async function pollHealth(url: string, timeoutMs: number): Promise { + // `/api/health` matches the path probe.mjs uses — keep them aligned. const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { try { - const res = await fetch(`${url}/health`); + const res = await fetch(`${url}/api/health`); if (res.ok) return true; } catch { // not ready yet @@ -185,10 +186,17 @@ export async function run(_args: string[]): Promise { INSTALLED: true, ONECLI_URL: url, HEALTHY: healthy, - STATUS: healthy ? 'success' : 'degraded', + // Install succeeded regardless — a failed health poll often just means + // the endpoint is auth-gated or the gateway hasn't finished warming up. + // The next step (auth) will surface a genuinely broken gateway via + // `onecli secrets list`, so don't trigger rescue attempts from here. + STATUS: 'success', ...(healthy ? {} - : { HINT: 'Gateway did not respond to /health within 15s. Try `onecli start`.' }), + : { + 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', }); } From 96d765611230e7f4026126c0a92fa3dd4090fa16 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Sun, 19 Apr 2026 12:40:53 +0000 Subject: [PATCH 10/12] refactor(new-setup): rewrite probe in pure bash, drop unavailable fallback The probe now returns a real snapshot from second zero, so every step consults real probe fields instead of falling back to "run every step blindly" when Node isn't installed. Also drops the redundant CLI_AGENT_WIRED field (it gated the last step on its own end-state) and scopes timezone out of the probe (timezone is not part of /new-setup). Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/skills/new-setup/SKILL.md | 12 +- setup/onecli.ts | 2 +- setup/probe.mjs | 367 ------------------------------ setup/probe.sh | 247 +++++++++++++++++++- 4 files changed, 243 insertions(+), 385 deletions(-) delete mode 100644 setup/probe.mjs diff --git a/.claude/skills/new-setup/SKILL.md b/.claude/skills/new-setup/SKILL.md index a671fb0..6b95695 100644 --- a/.claude/skills/new-setup/SKILL.md +++ b/.claude/skills/new-setup/SKILL.md @@ -14,7 +14,7 @@ Before each step, narrate to the user in your own words what's about to happen Each step is invoked as `pnpm exec tsx setup/index.ts --step ` and emits a structured status block Claude parses to decide what to do next. -Start with a probe: a single parallel scan that snapshots every prerequisite and dependency. The rest of the flow reads this snapshot to decide what to run, skip, or ask about — no per-step re-checking. The probe is plain ESM JS (`setup/probe.mjs`) with no external deps so it can run before step 1 has installed `pnpm`/`node_modules`. +Start with a probe: a single upfront scan that snapshots every prerequisite and dependency. The rest of the flow reads this snapshot to decide what to run, skip, or ask about — no per-step re-checking. The probe is pure bash (`setup/probe.sh`) with no external deps so it runs correctly before Node has been installed. ## Current state @@ -22,9 +22,7 @@ Start with a probe: a single parallel scan that snapshots every prerequisite and ## Flow -Parse the probe block above. For each step below, consult the named probe fields and skip, ask, or run accordingly. - -If the probe reports `STATUS: unavailable` (Node isn't installed yet), ignore all `skip if …` probe conditions and run every step from 1 onward — each step has its own idempotency check, so re-running is safe. +Parse the probe block above. For each step below, consult the named probe fields and skip, ask, or run accordingly. The probe always returns a real snapshot — there is no "node not installed" fallback; `HOST_DEPS=missing` is how you know Node/pnpm haven't been bootstrapped yet. ## Ordering and parallelism @@ -40,12 +38,12 @@ One permitted parallelism: Check probe results and skip if `HOST_DEPS=ok` — Node, pnpm, `node_modules`, and `better-sqlite3`'s native binding are already in place. -If the probe reported `STATUS: unavailable` (Node isn't installed yet — probe itself couldn't run), install Node 22 **before** running `bash setup.sh`, otherwise the first bootstrap run is guaranteed to fail: +If `HOST_DEPS=missing` and `node --version` fails (Node isn't installed at all), install Node 22 **before** running `bash setup.sh`, otherwise the first bootstrap run is guaranteed to fail: - macOS: `brew install node@22` - Linux / WSL: `curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - && sudo apt-get install -y nodejs` -Then run `bash setup.sh`. If the probe succeeded but `HOST_DEPS=missing`, run `bash setup.sh` directly — Node is there, deps aren't. +Then run `bash setup.sh`. If Node is already present and only `HOST_DEPS=missing`, run `bash setup.sh` directly — deps just haven't been installed yet. Parse the status block: @@ -118,8 +116,6 @@ Start the NanoClaw background service — it relays messages between the user an ### 6. First CLI agent -Check probe results and skip if `CLI_AGENT_WIRED=true`. - If step 2's container build is still running in the background, join it here before proceeding — the agent needs the image. Create the first agent and wire it to the CLI channel. Ask the user "What should I call you?" first — default the offered value to `INFERRED_DISPLAY_NAME` from the probe. diff --git a/setup/onecli.ts b/setup/onecli.ts index ddb68c6..226d302 100644 --- a/setup/onecli.ts +++ b/setup/onecli.ts @@ -106,7 +106,7 @@ function installOnecli(): { stdout: string; ok: boolean } { } async function pollHealth(url: string, timeoutMs: number): Promise { - // `/api/health` matches the path probe.mjs uses — keep them aligned. + // `/api/health` matches the path probe.sh uses — keep them aligned. const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { try { diff --git a/setup/probe.mjs b/setup/probe.mjs deleted file mode 100644 index 5aea0d4..0000000 --- a/setup/probe.mjs +++ /dev/null @@ -1,367 +0,0 @@ -#!/usr/bin/env node -/** - * Setup step: probe — Single upfront parallel scan for /new-setup's dynamic - * context injection. Rendered into the SKILL.md prompt via - * `!node setup/probe.mjs` so Claude sees the current system state before - * generating its first response. - * - * This is a routing aid, NOT a replacement for per-step idempotency checks. - * Each step keeps its own checks; probe tells the skill which steps to skip. - * - * Plain ESM JS (zero deps) by design: this runs BEFORE setup.sh has installed - * pnpm and node_modules, so it can only use Node built-ins. `better-sqlite3` - * is dynamic-imported so the probe degrades gracefully on fresh installs. - * - * Keep fast (<2s total). All probes swallow their own errors and report a - * neutral state rather than failing the whole scan. - */ -import { execFileSync, execSync } from 'node:child_process'; -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; - -const LOCAL_BIN = path.join(os.homedir(), '.local', 'bin'); -const PROBE_TIMEOUT_MS = 2000; -const HEALTH_TIMEOUT_MS = 2000; -const AGENT_IMAGE = 'nanoclaw-agent:latest'; -const DATA_DIR = path.resolve(process.cwd(), 'data'); - -function childEnv() { - const parts = [LOCAL_BIN]; - if (process.env.PATH) parts.push(process.env.PATH); - return { ...process.env, PATH: parts.join(path.delimiter) }; -} - -function getPlatform() { - const p = os.platform(); - if (p === 'darwin') return 'macos'; - if (p === 'linux') return 'linux'; - return 'unknown'; -} - -function isWSL() { - if (os.platform() !== 'linux') return false; - try { - const release = fs.readFileSync('/proc/version', 'utf-8').toLowerCase(); - return release.includes('microsoft') || release.includes('wsl'); - } catch { - return false; - } -} - -function commandExists(name) { - try { - execSync(`command -v ${name}`, { stdio: 'ignore' }); - return true; - } catch { - return false; - } -} - -function isValidTimezone(tz) { - try { - new Intl.DateTimeFormat(undefined, { timeZone: tz }); - return true; - } catch { - return false; - } -} - -function emitStatus(step, fields) { - const lines = [`=== NANOCLAW SETUP: ${step} ===`]; - for (const [k, v] of Object.entries(fields)) { - lines.push(`${k}: ${v}`); - } - lines.push('=== END ==='); - console.log(lines.join('\n')); -} - -function readEnvVar(name) { - const envFile = path.join(process.cwd(), '.env'); - if (!fs.existsSync(envFile)) return null; - const content = fs.readFileSync(envFile, 'utf-8'); - const m = content.match(new RegExp(`^${name}=(.+)$`, 'm')); - if (!m) return null; - return m[1].trim().replace(/^["']|["']$/g, ''); -} - -function probeDocker() { - if (!commandExists('docker')) return { status: 'not_found', imagePresent: false }; - try { - execSync('docker info', { stdio: 'ignore', timeout: PROBE_TIMEOUT_MS }); - } catch { - return { status: 'installed_not_running', imagePresent: false }; - } - let imagePresent = false; - try { - execSync(`docker image inspect ${AGENT_IMAGE}`, { - stdio: 'ignore', - timeout: PROBE_TIMEOUT_MS, - }); - imagePresent = true; - } catch { - // image not built yet - } - return { status: 'running', imagePresent }; -} - -function probeOnecliUrl() { - const fromEnv = readEnvVar('ONECLI_URL'); - if (fromEnv) return fromEnv; - try { - const out = execFileSync('onecli', ['config', 'get', 'api-host'], { - encoding: 'utf-8', - env: childEnv(), - stdio: ['ignore', 'pipe', 'ignore'], - timeout: PROBE_TIMEOUT_MS, - }).trim(); - const parsed = JSON.parse(out); - if (typeof parsed.value === 'string' && parsed.value) return parsed.value; - } catch { - // onecli not installed or config not set - } - return null; -} - -async function probeOnecliStatus(url) { - const installed = - commandExists('onecli') || fs.existsSync(path.join(LOCAL_BIN, 'onecli')); - if (!installed) return 'not_found'; - if (!url) return 'installed_not_healthy'; - try { - const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(), HEALTH_TIMEOUT_MS); - const res = await fetch(`${url}/api/health`, { signal: controller.signal }); - clearTimeout(timer); - return res.ok ? 'healthy' : 'installed_not_healthy'; - } catch { - return 'installed_not_healthy'; - } -} - -function probeAnthropicSecret() { - try { - const out = execFileSync('onecli', ['secrets', 'list'], { - encoding: 'utf-8', - env: childEnv(), - stdio: ['ignore', 'pipe', 'ignore'], - timeout: PROBE_TIMEOUT_MS, - }); - const parsed = JSON.parse(out); - return !!(parsed.data && parsed.data.some((s) => s.type === 'anthropic')); - } catch { - return false; - } -} - -function probeServiceStatus() { - const platform = getPlatform(); - if (platform === 'macos') { - try { - const out = execSync('launchctl list', { - encoding: 'utf-8', - timeout: PROBE_TIMEOUT_MS, - }); - const line = out.split('\n').find((l) => l.includes('com.nanoclaw')); - if (!line) return 'not_configured'; - const pid = line.trim().split(/\s+/)[0]; - return pid && pid !== '-' ? 'running' : 'stopped'; - } catch { - return 'not_configured'; - } - } - if (platform === 'linux') { - try { - execSync('systemctl --user is-active nanoclaw', { - stdio: 'ignore', - timeout: PROBE_TIMEOUT_MS, - }); - return 'running'; - } catch { - try { - execSync('systemctl --user cat nanoclaw', { - stdio: 'ignore', - timeout: PROBE_TIMEOUT_MS, - }); - return 'stopped'; - } catch { - return 'not_configured'; - } - } - } - return 'not_configured'; -} - -async function probeCliAgentWired() { - const dbPath = path.join(DATA_DIR, 'v2.db'); - if (!fs.existsSync(dbPath)) return false; - // Dynamic-import so probe still runs before `pnpm install` has built the - // native module. On truly fresh installs `data/v2.db` can't exist anyway, - // so the short-circuit above handles that path. - try { - const mod = await import('better-sqlite3'); - const Database = mod.default ?? mod; - const db = new Database(dbPath, { readonly: true }); - try { - const row = db - .prepare( - `SELECT 1 FROM messaging_group_agents mga - JOIN messaging_groups mg ON mg.id = mga.messaging_group_id - WHERE mg.channel_type = 'cli' LIMIT 1`, - ) - .get(); - return !!row; - } finally { - db.close(); - } - } catch { - return false; - } -} - -function probeInferredDisplayName() { - const reject = (s) => !s || !s.trim() || s.trim().toLowerCase() === 'root'; - - try { - const name = execFileSync('git', ['config', '--global', 'user.name'], { - encoding: 'utf-8', - timeout: 1000, - stdio: ['ignore', 'pipe', 'ignore'], - }).trim(); - if (!reject(name)) return name; - } catch { - // git missing or no config set - } - - const user = process.env.USER || os.userInfo().username; - const platform = getPlatform(); - - if (platform === 'macos') { - try { - const fullName = execFileSync('id', ['-F', user], { - encoding: 'utf-8', - timeout: 1000, - stdio: ['ignore', 'pipe', 'ignore'], - }).trim(); - if (!reject(fullName)) return fullName; - } catch { - // id -F not supported - } - } else if (platform === 'linux') { - try { - const entry = execFileSync('getent', ['passwd', user], { - encoding: 'utf-8', - timeout: 1000, - stdio: ['ignore', 'pipe', 'ignore'], - }).trim(); - const gecos = entry.split(':')[4]; - if (gecos) { - const fullName = gecos.split(',')[0].trim(); - if (!reject(fullName)) return fullName; - } - } catch { - // getent missing - } - } - - if (!reject(user)) return user; - return 'User'; -} - -function probeHostDeps() { - const nodeModules = path.resolve(process.cwd(), 'node_modules'); - if (!fs.existsSync(nodeModules)) return 'missing'; - // better-sqlite3's compiled native binding is the canonical proof that - // `pnpm install` ran AND the native build step succeeded. Cheaper than - // actually loading the module, and unambiguous on success. - const nativeBinding = path.join( - nodeModules, - 'better-sqlite3', - 'build', - 'Release', - 'better_sqlite3.node', - ); - return fs.existsSync(nativeBinding) ? 'ok' : 'missing'; -} - -function probeTimezone() { - const envTz = readEnvVar('TZ'); - const systemTz = Intl.DateTimeFormat().resolvedOptions().timeZone || ''; - - let status; - if (envTz && isValidTimezone(envTz)) { - status = 'configured'; - } else if (systemTz === 'UTC' || systemTz === 'Etc/UTC') { - status = 'utc_suspicious'; - } else if (systemTz && isValidTimezone(systemTz)) { - status = 'autodetected'; - } else { - status = 'needs_input'; - } - - return { - status, - envTz: envTz || 'none', - systemTz: systemTz || 'unknown', - }; -} - -export async function run() { - const started = Date.now(); - - const platform = getPlatform(); - const wsl = isWSL(); - const osLabel = wsl - ? 'wsl' - : platform === 'macos' - ? 'macos' - : platform === 'linux' - ? 'linux' - : 'unknown'; - const shell = process.env.SHELL || 'unknown'; - - const docker = probeDocker(); - const oneCliUrl = probeOnecliUrl(); - const serviceStatus = probeServiceStatus(); - const displayName = probeInferredDisplayName(); - const tz = probeTimezone(); - const hostDeps = probeHostDeps(); - - const [onecliStatus, cliAgentWired] = await Promise.all([ - probeOnecliStatus(oneCliUrl), - probeCliAgentWired(), - ]); - - const anthropicSecret = - onecliStatus !== 'not_found' ? probeAnthropicSecret() : false; - - const elapsedMs = Date.now() - started; - - emitStatus('PROBE', { - OS: osLabel, - SHELL: shell, - HOST_DEPS: hostDeps, - DOCKER: docker.status, - IMAGE_PRESENT: docker.imagePresent, - ONECLI_STATUS: onecliStatus, - ONECLI_URL: oneCliUrl || 'none', - ANTHROPIC_SECRET: anthropicSecret, - SERVICE_STATUS: serviceStatus, - CLI_AGENT_WIRED: cliAgentWired, - INFERRED_DISPLAY_NAME: displayName, - TZ_STATUS: tz.status, - TZ_ENV: tz.envTz, - TZ_SYSTEM: tz.systemTz, - ELAPSED_MS: elapsedMs, - STATUS: 'success', - }); -} - -const invokedDirectly = - import.meta.url === `file://${path.resolve(process.argv[1] ?? '')}`; -if (invokedDirectly) { - run().catch((err) => { - console.error(err); - process.exit(1); - }); -} diff --git a/setup/probe.sh b/setup/probe.sh index 8be2948..6f40fff 100755 --- a/setup/probe.sh +++ b/setup/probe.sh @@ -1,19 +1,248 @@ #!/bin/bash -# Wrapper for setup/probe.mjs so /new-setup's inline `!` block is a single -# shell command (permission-check friendly). When Node isn't installed yet, -# emit an "unavailable" status block so the skill's flow knows to skip the -# probe's skip-if conditions and run every step from 1. +# Setup step: probe — single upfront parallel-ish scan that snapshots every +# prerequisite and dependency for /new-setup's dynamic context injection. +# Rendered into the SKILL.md prompt via `!bash setup/probe.sh` so Claude sees +# the current system state before generating its first response. +# +# Pure bash by design: this runs BEFORE setup.sh has installed Node, pnpm, and +# node_modules, so it cannot rely on any Node-based tooling. Every field below +# is computed from POSIX utilities + grep/awk/curl. +# +# This is a routing aid, NOT a replacement for per-step idempotency checks. +# Each step keeps its own checks; probe tells the skill which steps to skip. +# +# Keep fast (<2s total). All probes swallow their own errors and report a +# neutral state rather than failing the whole scan. set -u +START_S=$(date +%s) + PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +LOCAL_BIN="$HOME/.local/bin" +AGENT_IMAGE="nanoclaw-agent:latest" -if command -v node >/dev/null 2>&1; then - exec node "$PROJECT_ROOT/setup/probe.mjs" "$@" +export PATH="$LOCAL_BIN:$PATH" + +command_exists() { command -v "$1" >/dev/null 2>&1; } + +# Best-effort 2s timeout; falls back to no timeout on macOS if `timeout` isn't +# installed (the probed commands are all expected to return fast anyway). +with_timeout() { + if command_exists timeout; then timeout 2 "$@" + elif command_exists gtimeout; then gtimeout 2 "$@" + else "$@" + fi +} + +trim() { + local s="$1" + s="${s#"${s%%[![:space:]]*}"}" + s="${s%"${s##*[![:space:]]}"}" + printf '%s' "$s" +} + +read_env_var() { + local name="$1" + local envfile="$PROJECT_ROOT/.env" + [[ -f "$envfile" ]] || return 0 + local line + line=$(grep -E "^${name}=" "$envfile" 2>/dev/null | head -n1) || return 0 + [[ -z "$line" ]] && return 0 + local val="${line#*=}" + val="${val%\"}"; val="${val#\"}" + val="${val%\'}"; val="${val#\'}" + trim "$val" +} + +probe_os() { + case "$(uname -s 2>/dev/null)" in + Darwin) echo "macos" ;; + Linux) + if [[ -r /proc/version ]] && grep -qEi "microsoft|wsl" /proc/version; then + echo "wsl" + else + echo "linux" + fi + ;; + *) echo "unknown" ;; + esac +} + +probe_host_deps() { + local node_modules="$PROJECT_ROOT/node_modules" + local native="$node_modules/better-sqlite3/build/Release/better_sqlite3.node" + # `better-sqlite3`'s compiled native binding is the canonical proof that + # `pnpm install` ran AND the native build step succeeded. + if [[ -d "$node_modules" && -f "$native" ]]; then + echo "ok" + else + echo "missing" + fi +} + +# Sets DOCKER_STATUS and IMAGE_PRESENT as globals. +probe_docker() { + DOCKER_STATUS="not_found" + IMAGE_PRESENT="false" + command_exists docker || return 0 + if ! with_timeout docker info >/dev/null 2>&1; then + DOCKER_STATUS="installed_not_running" + return 0 + fi + DOCKER_STATUS="running" + if with_timeout docker image inspect "$AGENT_IMAGE" >/dev/null 2>&1; then + IMAGE_PRESENT="true" + fi +} + +probe_onecli_url() { + local url + url=$(read_env_var ONECLI_URL) + if [[ -n "$url" ]]; then + printf '%s' "$url" + return + fi + command_exists onecli || return 0 + local out + out=$(with_timeout onecli config get api-host 2>/dev/null) || return 0 + # Minimal JSON extract: {"value":"http..."} — avoid hard dep on jq + if [[ "$out" =~ \"value\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]]; then + printf '%s' "${BASH_REMATCH[1]}" + fi +} + +probe_onecli_status() { + local url="$1" + if ! command_exists onecli && [[ ! -x "$LOCAL_BIN/onecli" ]]; then + echo "not_found"; return + fi + if [[ -z "$url" ]]; then + echo "installed_not_healthy"; return + fi + if command_exists curl \ + && curl -fsS --max-time 2 "${url}/api/health" >/dev/null 2>&1; then + echo "healthy" + else + echo "installed_not_healthy" + fi +} + +probe_anthropic_secret() { + command_exists onecli || { echo "false"; return; } + local out + out=$(with_timeout onecli secrets list 2>/dev/null) || { echo "false"; return; } + if echo "$out" | grep -Eq '"type"[[:space:]]*:[[:space:]]*"anthropic"'; then + echo "true" + else + echo "false" + fi +} + +probe_service_status() { + local platform="$1" + case "$platform" in + macos) + command_exists launchctl || { echo "not_configured"; return; } + local line + line=$(with_timeout launchctl list 2>/dev/null | grep "com.nanoclaw") || { + echo "not_configured"; return; } + local pid + pid=$(echo "$line" | awk '{print $1}') + if [[ -n "$pid" && "$pid" != "-" ]]; then + echo "running" + else + echo "stopped" + fi + ;; + linux|wsl) + command_exists systemctl || { echo "not_configured"; return; } + if with_timeout systemctl --user is-active nanoclaw >/dev/null 2>&1; then + echo "running" + elif with_timeout systemctl --user cat nanoclaw >/dev/null 2>&1; then + echo "stopped" + else + echo "not_configured" + fi + ;; + *) + echo "not_configured" + ;; + esac +} + +probe_display_name() { + local platform="$1" + local reject_re='^(|root)$' + local name + + if command_exists git; then + name=$(trim "$(git config --global user.name 2>/dev/null)") + if [[ -n "$name" && ! "$name" =~ $reject_re ]]; then + printf '%s' "$name"; return + fi + fi + + local user="${USER:-$(id -un 2>/dev/null)}" + + case "$platform" in + macos) + if command_exists id; then + name=$(trim "$(id -F "$user" 2>/dev/null)") + if [[ -n "$name" && ! "$name" =~ $reject_re ]]; then + printf '%s' "$name"; return + fi + fi + ;; + linux|wsl) + if command_exists getent; then + local entry gecos + entry=$(getent passwd "$user" 2>/dev/null) + gecos=$(echo "$entry" | awk -F: '{print $5}') + name=$(trim "$(echo "$gecos" | awk -F, '{print $1}')") + if [[ -n "$name" && ! "$name" =~ $reject_re ]]; then + printf '%s' "$name"; return + fi + fi + ;; + esac + + if [[ -n "$user" && ! "$user" =~ $reject_re ]]; then + printf '%s' "$user" + else + printf 'User' + fi +} + +OS=$(probe_os) +SHELL_NAME="${SHELL:-unknown}" +HOST_DEPS=$(probe_host_deps) +probe_docker +ONECLI_URL_VAL=$(probe_onecli_url) +ONECLI_STATUS=$(probe_onecli_status "$ONECLI_URL_VAL") +if [[ "$ONECLI_STATUS" == "not_found" ]]; then + ANTHROPIC_SECRET="false" +else + ANTHROPIC_SECRET=$(probe_anthropic_secret) fi +SERVICE_STATUS=$(probe_service_status "$OS") +DISPLAY_NAME=$(probe_display_name "$OS") -cat <<'EOF' +END_S=$(date +%s) +ELAPSED_MS=$(( (END_S - START_S) * 1000 )) + +cat < Date: Sun, 19 Apr 2026 12:46:34 +0000 Subject: [PATCH 11/12] docs(add-github): document bot account, userName, sender policy, and wiring Update SKILL.md with tested setup: dedicated bot account prerequisite, GITHUB_BOT_USERNAME env var for @-mention detection, private vs public repo sender policy guidance, member registration for strict mode, per-thread session mode, and wiring example. Co-Authored-By: Claude Opus 4.6 (1M context) --- .claude/skills/add-github/SKILL.md | 86 ++++++++++++++++++++++++------ 1 file changed, 70 insertions(+), 16 deletions(-) diff --git a/.claude/skills/add-github/SKILL.md b/.claude/skills/add-github/SKILL.md index e60e562..78366f3 100644 --- a/.claude/skills/add-github/SKILL.md +++ b/.claude/skills/add-github/SKILL.md @@ -7,6 +7,10 @@ description: Add GitHub channel integration via Chat SDK. PR and issue comment t Adds GitHub support via the Chat SDK bridge. The agent participates in PR and issue comment threads. +## Prerequisites + +You need a **dedicated GitHub bot account** (not your personal account). The adapter uses this account to post replies and filters out its own messages to avoid loops. Create a free GitHub account for your bot (e.g. `my-org-bot`), then invite it as a collaborator with write access to the repos you want monitored. + ## Install NanoClaw doesn't ship channels in trunk. This skill copies the GitHub adapter in from the `channels` branch. @@ -55,40 +59,90 @@ pnpm run build ## Credentials -> 1. Go to [GitHub Settings > Developer Settings > Personal Access Tokens](https://github.com/settings/tokens) -> 2. Create a **Fine-grained token** with: -> - Repository access: select the repos you want the bot to monitor -> - Permissions: **Pull requests** (Read & Write), **Issues** (Read & Write) -> 3. Copy the token -> 4. Set up a webhook on your repo(s): -> - Go to **Settings** > **Webhooks** > **Add webhook** -> - Payload URL: `https://your-domain/webhook/github` -> - Content type: `application/json` -> - Secret: generate a random string -> - Events: select **Issue comments**, **Pull request review comments** +### 1. Create a Personal Access Token for the bot account -### Configure environment +Log in as your **bot account**, then: + +1. Go to [Settings > Developer Settings > Personal Access Tokens](https://github.com/settings/tokens) +2. Create a **Fine-grained token** with: + - Repository access: select the repos you want the bot to monitor + - Permissions: **Pull requests** (Read & Write), **Issues** (Read & Write) +3. Copy the token + +### 2. Set up a webhook on each repo + +On each repo (logged in as the repo owner/admin): + +1. Go to **Settings** > **Webhooks** > **Add webhook** +2. Payload URL: `https://your-domain/webhook/github` (the shared webhook server, default port 3000) +3. Content type: `application/json` +4. Secret: generate a random string (e.g. `openssl rand -hex 20`) +5. Events: select **Issue comments** and **Pull request review comments** + +### 3. Configure environment Add to `.env`: ```bash GITHUB_TOKEN=github_pat_... GITHUB_WEBHOOK_SECRET=your-webhook-secret +GITHUB_BOT_USERNAME=your-bot-username ``` +`GITHUB_BOT_USERNAME` must match the bot account's GitHub username exactly. This is used for @-mention detection — the agent responds when someone writes `@your-bot-username` in a PR or issue comment. + Sync to container: `mkdir -p data/env && cp .env data/env/env` +## Wiring + +Ask the user: **Is this a private or public repo?** + +- **Private repo** — use `unknown_sender_policy: 'public'`. Only collaborators can comment anyway, so it's safe to let all comments through. +- **Public repo** — use `unknown_sender_policy: 'strict'`. Only registered members can trigger the agent, preventing strangers from consuming agent resources. Add trusted collaborators as members (see below). + +Run `/manage-channels` to wire the GitHub channel to an agent group, or insert manually: + +```sql +-- Create messaging group (one per repo) +INSERT INTO messaging_groups (id, channel_type, platform_id, name, is_group, unknown_sender_policy, created_at) +VALUES ('mg-github-myrepo', 'github', 'github:owner/repo', 'owner/repo', 1, '', datetime('now')); + +-- Wire to agent group +INSERT INTO messaging_group_agents (id, messaging_group_id, agent_group_id, trigger_rules, response_scope, session_mode, priority, created_at) +VALUES ('mga-github-myrepo', 'mg-github-myrepo', '', '', 'all', 'per-thread', 10, datetime('now')); +``` + +Replace `` with `public` or `strict` based on the user's choice above. + +### Adding members (for strict mode) + +When using `strict`, add each GitHub user who should be able to trigger the agent: + +```sql +-- Add user (kind = 'github', id = 'github:') +INSERT OR IGNORE INTO users (id, kind, display_name, created_at) +VALUES ('github:', 'github', '', datetime('now')); + +-- Grant membership to the agent group +INSERT OR IGNORE INTO agent_group_members (user_id, agent_group_id) +VALUES ('github:', ''); +``` + +To find a GitHub user's numeric ID: `gh api users/ --jq .id` + +Use `per-thread` session mode so each PR/issue gets its own agent session. + ## Next Steps If you're in the middle of `/setup`, return to the setup flow now. -Otherwise, run `/manage-channels` to wire this channel to an agent group. +Otherwise, restart the service (`systemctl --user restart nanoclaw` or `launchctl kickstart -k gui/$(id -u)/com.nanoclaw`) to pick up the new channel. ## Channel Info - **type**: `github` - **terminology**: GitHub has "repositories" containing "pull requests" and "issues." Each PR or issue comment thread is a separate conversation. -- **how-to-find-id**: The platform ID is `owner/repo` (e.g. `acme/backend`). Each PR/issue becomes its own thread automatically. +- **how-to-find-id**: The platform ID is `github:owner/repo` (e.g. `github:acme/backend`). Each PR/issue becomes its own thread automatically. - **supports-threads**: yes (PR and issue comment threads are native conversations) -- **typical-use**: Webhook/notification — the agent receives PR and issue events and responds in comment threads -- **default-isolation**: Typically shares a session with a chat channel (e.g. Slack) so the agent can summarize PRs and respond to reviews in the same context. Use a separate agent group if the repo contains sensitive code that other channels shouldn't access. +- **typical-use**: Webhook-driven — the agent receives PR and issue comment events and responds in comment threads when @-mentioned. After the first mention, the thread is subscribed and the agent responds to all follow-up comments. +- **default-isolation**: Use `per-thread` session mode. Each PR or issue gets its own isolated agent session. Typically wire to a dedicated agent group if the repo contains sensitive code. From 0d09c6ea212be54886cb97cd8d2c76ea311a8a28 Mon Sep 17 00:00:00 2001 From: Gabi Simons Date: Sun, 19 Apr 2026 15:45:02 +0000 Subject: [PATCH 12/12] docs(add-linear): OAuth app auth, bridge patch, team routing, wiring Rewrite SKILL.md with tested setup: OAuth app with client credentials (recommended), bridge catchAll patch for platforms without @-mention, LINEAR_TEAM_KEY for team-based routing, webhook setup with delay note, private vs public sender policy, and wiring example. Co-Authored-By: Claude Opus 4.6 (1M context) --- .claude/skills/add-linear/SKILL.md | 115 ++++++++++++++++++++++++----- 1 file changed, 96 insertions(+), 19 deletions(-) diff --git a/.claude/skills/add-linear/SKILL.md b/.claude/skills/add-linear/SKILL.md index f3650b6..dc657af 100644 --- a/.claude/skills/add-linear/SKILL.md +++ b/.claude/skills/add-linear/SKILL.md @@ -5,11 +5,24 @@ description: Add Linear channel integration via Chat SDK. Issue comment threads # Add Linear Channel -Adds Linear support via the Chat SDK bridge. The agent participates in issue comment threads. +Adds Linear support via the Chat SDK bridge. The agent participates in issue comment threads. Every comment on a Linear issue triggers the agent — no @-mention needed. + +## Prerequisites + +**Recommended:** Create a Linear **OAuth application** so the agent posts as an app identity, not as you. This prevents the adapter from filtering your own comments as self-messages. + +1. Go to [Linear Settings > API > OAuth Applications](https://linear.app/settings/api/applications/new) +2. Create an app (e.g. "NanoClaw Bot") + - Developer URL: your repo URL (e.g. `https://github.com/your-org/nanoclaw`) + - Callback URL: `http://localhost` +3. After creating, click the app and enable **Client credentials** under grant types +4. Copy the **Client ID** and **Client Secret** + +**Alternative:** Use a Personal API Key (`LINEAR_API_KEY`) for simpler setup. The agent will post as you, and your own comments will be filtered (other team members' comments still work). ## Install -NanoClaw doesn't ship channels in trunk. This skill copies the Linear adapter in from the `channels` branch. +NanoClaw doesn't ship channels in trunk. This skill copies the Linear adapter in from the `channels` branch and patches the Chat SDK bridge to support catch-all message forwarding (Linear OAuth apps can't be @-mentioned). ### Pre-flight (idempotent) @@ -18,6 +31,7 @@ Skip to **Credentials** if all of these are already in place: - `src/channels/linear.ts` exists - `src/channels/index.ts` contains `import './linear.js';` - `@chat-adapter/linear` is listed in `package.json` dependencies +- `src/channels/chat-sdk-bridge.ts` contains `catchAll` Otherwise continue. Every step below is safe to re-run. @@ -41,13 +55,42 @@ Append to `src/channels/index.ts` (skip if the line is already present): import './linear.js'; ``` -### 4. Install the adapter package (pinned) +### 4. Patch the Chat SDK bridge for catch-all message forwarding + +Linear OAuth apps can't be @-mentioned, so the bridge's `onNewMention` handler never fires. Add `catchAll` support to `src/channels/chat-sdk-bridge.ts`: + +**4a.** Add `catchAll?: boolean` to the `ChatSdkBridgeConfig` interface: + +```typescript + /** + * Forward ALL messages in unsubscribed threads, not just @-mentions. + * Use for platforms where the bot identity can't be @-mentioned (e.g. + * Linear OAuth apps). The thread is auto-subscribed on first message. + */ + catchAll?: boolean; +``` + +**4b.** Add this handler block right after the `chat.onNewMention(...)` block (before the DMs block): + +```typescript + // Catch-all for platforms where @-mention isn't possible (e.g. Linear + // OAuth apps). Forward every unsubscribed message and auto-subscribe. + if (config.catchAll) { + chat.onNewMessage(/.*/, async (thread, message) => { + const channelId = adapter.channelIdFromThreadId(thread.id); + await setupConfig.onInbound(channelId, thread.id, await messageToInbound(message)); + await thread.subscribe(); + }); + } +``` + +### 5. Install the adapter package (pinned) ```bash pnpm install @chat-adapter/linear@4.26.0 ``` -### 5. Build +### 6. Build ```bash pnpm run build @@ -55,37 +98,71 @@ pnpm run build ## Credentials -> 1. Go to [Linear Settings > API Keys](https://linear.app/settings/account/security/api-keys/new) -> 2. Create a **Personal API Key** (or use an OAuth application for team-wide access) -> 3. Copy the API key -> 4. Set up a webhook: -> - Go to **Settings** > **API** > **Webhooks** > **New webhook** -> - URL: `https://your-domain/webhook/linear` -> - Select events: **Comment** (created, updated) -> - Copy the signing secret +### 1. Set up a webhook -### Configure environment +1. Go to **Linear Settings** > **API** > **Webhooks** > **New webhook** +2. Label: `NanoClaw` +3. URL: `https://your-domain/webhook/linear` (the shared webhook server, default port 3000) +4. Team: select the team you want to monitor +5. Events: check **Comment** +6. Save — copy the **signing secret** + +Note: Linear webhook delivery may be delayed 1-5 minutes for new webhooks. This is normal. + +### 2. Configure environment Add to `.env`: ```bash -LINEAR_API_KEY=lin_api_... -LINEAR_WEBHOOK_SECRET=your-webhook-secret +# OAuth app (recommended) +LINEAR_CLIENT_ID=your-client-id +LINEAR_CLIENT_SECRET=your-client-secret + +# OR Personal API key (simpler, but agent posts as you) +# LINEAR_API_KEY=lin_api_... + +LINEAR_WEBHOOK_SECRET=your-webhook-signing-secret +LINEAR_BOT_USERNAME=NanoClaw Bot +LINEAR_TEAM_KEY=ENG ``` +- `LINEAR_BOT_USERNAME`: display name for the bot (used for self-message detection when using a Personal API Key) +- `LINEAR_TEAM_KEY`: the Linear team key (e.g. `ENG`, `NAN`). Find it in Linear under Settings > Teams. All issues in this team route to one messaging group. + Sync to container: `mkdir -p data/env && cp .env data/env/env` +## Wiring + +Ask the user: **Is this a private or public Linear workspace?** + +- **Private workspace** — use `unknown_sender_policy: 'public'`. Only workspace members can comment. +- **Public workspace** — use `unknown_sender_policy: 'strict'` and add trusted members (see GitHub skill for member registration example). + +Run `/manage-channels` to wire the Linear channel to an agent group, or insert manually: + +```sql +-- Create messaging group (one per team) +INSERT INTO messaging_groups (id, channel_type, platform_id, name, is_group, unknown_sender_policy, created_at) +VALUES ('mg-linear-eng', 'linear', 'linear:ENG', 'Engineering', 1, 'public', datetime('now')); + +-- Wire to agent group +INSERT INTO messaging_group_agents (id, messaging_group_id, agent_group_id, trigger_rules, response_scope, session_mode, priority, created_at) +VALUES ('mga-linear-eng', 'mg-linear-eng', '', '', 'all', 'per-thread', 10, datetime('now')); +``` + +The `platform_id` must be `linear:` matching the `LINEAR_TEAM_KEY` env var. Use `per-thread` session mode so each issue comment thread gets its own agent session. + ## Next Steps If you're in the middle of `/setup`, return to the setup flow now. -Otherwise, run `/manage-channels` to wire this channel to an agent group. +Otherwise, restart the service (`systemctl --user restart nanoclaw` or `launchctl kickstart -k gui/$(id -u)/com.nanoclaw`) to pick up the new channel. ## Channel Info - **type**: `linear` - **terminology**: Linear has "teams" containing "issues." Each issue's comment thread is a separate conversation. -- **how-to-find-id**: The platform ID is your team key (e.g. `ENG`). Find it in Linear under Settings > Teams. Each issue becomes its own thread automatically. +- **how-to-find-id**: The platform ID is `linear:` (e.g. `linear:ENG`). Find your team key in Linear under Settings > Teams. Each issue becomes its own thread automatically. - **supports-threads**: yes (issue comment threads are native conversations) -- **typical-use**: Webhook/notification — the agent receives issue comment events and responds in threads -- **default-isolation**: Typically shares a session with a chat channel (e.g. Slack) so the agent can discuss issues in the same context as team chat. Use a separate agent group if the Linear team tracks sensitive work. +- **typical-use**: Webhook-driven — the agent receives all issue comment events and responds automatically. No @-mention needed (Linear OAuth apps can't be @-mentioned). +- **default-isolation**: Use `per-thread` session mode. Each issue comment thread gets its own isolated agent session.