diff --git a/CHANGELOG.md b/CHANGELOG.md index a161df7fa..9564c12e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ - CLI: add ASCII banner header to wizard entry points. - CLI: add `configure`, `doctor`, and `update` wizards for ongoing setup, health checks, and modernization. - CLI: add Signal CLI auto-install from GitHub releases in the wizard and persist wizard run metadata in config. +- CLI: add remote gateway client config (gateway.remote.*) with Bonjour-assisted discovery. - Skills: allow `bun` as a node manager for skill installs. - Tests: add a Docker-based onboarding E2E harness. diff --git a/docs/configuration.md b/docs/configuration.md index 35f2ae95a..de59536c3 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -524,6 +524,22 @@ Auth and Tailscale: - `gateway.tailscale.mode: "funnel"` exposes the dashboard publicly; requires auth. - `gateway.tailscale.resetOnExit` resets Serve/Funnel config on shutdown. +Remote client defaults (CLI): +- `gateway.remote.url` sets the default Gateway WebSocket URL for CLI calls when `gateway.mode = "remote"`. +- `gateway.remote.token` supplies the token for remote calls (leave unset for no auth). + +```json5 +{ + gateway: { + mode: "remote", + remote: { + url: "ws://gateway.tailnet:18789", + token: "your-token" + } + } +} +``` + ### `hooks` (Gateway webhooks) Enable a simple HTTP webhook surface on the Gateway HTTP server. diff --git a/docs/remote.md b/docs/remote.md index aafb89a2c..394c3e4dc 100644 --- a/docs/remote.md +++ b/docs/remote.md @@ -27,6 +27,24 @@ With the tunnel up: - `clawdis health` and `clawdis status --deep` now reach the remote gateway via `ws://127.0.0.1:18789`. - `clawdis gateway {status,health,send,agent,call}` can also target the forwarded URL via `--url` when needed. +## CLI remote defaults + +You can persist a remote target so CLI commands use it by default: + +```json5 +{ + gateway: { + mode: "remote", + remote: { + url: "ws://127.0.0.1:18789", + token: "your-token" + } + } +} +``` + +When the gateway is loopback-only, keep the URL at `ws://127.0.0.1:18789` and open the SSH tunnel first. + ## Chat UI over SSH WebChat no longer uses a separate HTTP port. The SwiftUI chat UI connects directly to the Gateway WebSocket. diff --git a/docs/wizard.md b/docs/wizard.md index eab869976..f8abee157 100644 --- a/docs/wizard.md +++ b/docs/wizard.md @@ -10,7 +10,7 @@ read_when: Goal: interactive wizards for first-run onboarding **and** ongoing reconfiguration. Uses `@clack/prompts` for arrow-key selection and step UX. -Scope: **Local gateway only**. Remote mode is **info-only** (no config writes). +Scope: local gateway setup plus **remote gateway client config** (no remote-side installs). ## Entry points @@ -47,7 +47,7 @@ Reset uses `trash` (never `rm`). 1) **Mode** - Local (full wizard) - - Remote (info-only; no config writes) + - Remote (configure client connection only) 2) **Model/Auth (local only)** - Anthropic OAuth (recommended) @@ -91,15 +91,13 @@ Reset uses `trash` (never `rm`). - Summary + next steps - Reminder: iOS/Android/macOS node apps add canvas/camera/screen/system features. -## Remote mode (info-only) +## Remote mode (client config) -- Explain where gateway runs. -- Show required steps on gateway host: - - `clawdis setup` - - `clawdis gateway-daemon ...` - - OAuth file: `~/.clawdis/credentials/oauth.json` - - Workspace: `~/clawd` -- No local config changes. +- Optional Bonjour discovery (macOS: `dns-sd`, Linux: `avahi-browse`) +- Save `gateway.remote.url` (+ optional `gateway.remote.token`) +- Token optional; omit for no-auth gateways +- Provide SSH tunnel hint when the gateway is loopback-only +- No remote installs or daemon changes from this machine ## Config writes @@ -111,6 +109,7 @@ Wizard writes: - `skills.entries..env` / `.apiKey` (if set in skills step) - `telegram.botToken`, `discord.token`, `signal.*` (if set in providers step) - `wizard.lastRunAt`, `wizard.lastRunVersion`, `wizard.lastRunCommit`, `wizard.lastRunCommand`, `wizard.lastRunMode` + - `gateway.remote.url`, `gateway.remote.token` (remote mode) WhatsApp login writes credentials to `~/.clawdis/credentials/creds.json`. diff --git a/src/cli/canvas-cli.ts b/src/cli/canvas-cli.ts index fb8dc176a..49d9582b9 100644 --- a/src/cli/canvas-cli.ts +++ b/src/cli/canvas-cli.ts @@ -67,7 +67,10 @@ type A2UIVersion = "v0.8" | "v0.9"; const canvasCallOpts = (cmd: Command) => cmd - .option("--url ", "Gateway WebSocket URL", "ws://127.0.0.1:18789") + .option( + "--url ", + "Gateway WebSocket URL (defaults to gateway.remote.url when configured)", + ) .option("--token ", "Gateway token (if required)") .option("--timeout ", "Timeout in ms", "10000") .option("--json", "Output JSON", false); diff --git a/src/cli/gateway-cli.ts b/src/cli/gateway-cli.ts index 220761289..7d68b7998 100644 --- a/src/cli/gateway-cli.ts +++ b/src/cli/gateway-cli.ts @@ -105,7 +105,10 @@ async function runGatewayLoop(params: { const gatewayCallOpts = (cmd: Command) => cmd - .option("--url ", "Gateway WebSocket URL", "ws://127.0.0.1:18789") + .option( + "--url ", + "Gateway WebSocket URL (defaults to gateway.remote.url when configured)", + ) .option("--token ", "Gateway token (if required)") .option("--password ", "Gateway password (password auth)") .option("--timeout ", "Timeout in ms", "10000") diff --git a/src/cli/gateway-rpc.ts b/src/cli/gateway-rpc.ts index 293b97b6c..2d729d606 100644 --- a/src/cli/gateway-rpc.ts +++ b/src/cli/gateway-rpc.ts @@ -10,7 +10,10 @@ export type GatewayRpcOpts = { export function addGatewayClientOptions(cmd: Command) { return cmd - .option("--url ", "Gateway WebSocket URL", "ws://127.0.0.1:18789") + .option( + "--url ", + "Gateway WebSocket URL (defaults to gateway.remote.url when configured)", + ) .option("--token ", "Gateway token (if required)") .option("--timeout ", "Timeout in ms", "10000") .option("--expect-final", "Wait for final response (agent)", false); diff --git a/src/cli/nodes-cli.ts b/src/cli/nodes-cli.ts index 18f3bc804..26c2d3bb4 100644 --- a/src/cli/nodes-cli.ts +++ b/src/cli/nodes-cli.ts @@ -94,7 +94,10 @@ type PairingList = { const nodesCallOpts = (cmd: Command, defaults?: { timeoutMs?: number }) => cmd - .option("--url ", "Gateway WebSocket URL", "ws://127.0.0.1:18789") + .option( + "--url ", + "Gateway WebSocket URL (defaults to gateway.remote.url when configured)", + ) .option("--token ", "Gateway token (if required)") .option( "--timeout ", diff --git a/src/cli/program.ts b/src/cli/program.ts index c81098ccb..11a41010c 100644 --- a/src/cli/program.ts +++ b/src/cli/program.ts @@ -112,6 +112,8 @@ export function buildProgram() { .option("--wizard", "Run the interactive onboarding wizard", false) .option("--non-interactive", "Run the wizard without prompts", false) .option("--mode ", "Wizard mode: local|remote") + .option("--remote-url ", "Remote Gateway WebSocket URL") + .option("--remote-token ", "Remote Gateway token (optional)") .action(async (opts) => { try { if (opts.wizard) { @@ -120,6 +122,8 @@ export function buildProgram() { workspace: opts.workspace as string | undefined, nonInteractive: Boolean(opts.nonInteractive), mode: opts.mode as "local" | "remote" | undefined, + remoteUrl: opts.remoteUrl as string | undefined, + remoteToken: opts.remoteToken as string | undefined, }, defaultRuntime, ); @@ -150,6 +154,8 @@ export function buildProgram() { .option("--gateway-auth ", "Gateway auth: off|token|password") .option("--gateway-token ", "Gateway token (token auth)") .option("--gateway-password ", "Gateway password (password auth)") + .option("--remote-url ", "Remote Gateway WebSocket URL") + .option("--remote-token ", "Remote Gateway token (optional)") .option("--tailscale ", "Tailscale: off|serve|funnel") .option("--tailscale-reset-on-exit", "Reset tailscale serve/funnel on exit") .option("--install-daemon", "Install gateway daemon") @@ -188,6 +194,8 @@ export function buildProgram() { | undefined, gatewayToken: opts.gatewayToken as string | undefined, gatewayPassword: opts.gatewayPassword as string | undefined, + remoteUrl: opts.remoteUrl as string | undefined, + remoteToken: opts.remoteToken as string | undefined, tailscale: opts.tailscale as "off" | "serve" | "funnel" | undefined, tailscaleResetOnExit: Boolean(opts.tailscaleResetOnExit), installDaemon: Boolean(opts.installDaemon), diff --git a/src/commands/configure.ts b/src/commands/configure.ts index 649a46db7..63855f539 100644 --- a/src/commands/configure.ts +++ b/src/commands/configure.ts @@ -41,6 +41,7 @@ import { summarizeExistingConfig, } from "./onboard-helpers.js"; import { setupProviders } from "./onboard-providers.js"; +import { promptRemoteGatewayConfig } from "./onboard-remote.js"; import { setupSkills } from "./onboard-skills.js"; type WizardSection = @@ -387,17 +388,14 @@ export async function runConfigureWizard( ) as "local" | "remote"; if (mode === "remote") { - note( - [ - "Run on the gateway host:", - "- clawdis setup", - "- clawdis gateway-daemon --port 18789", - "- OAuth creds: ~/.clawdis/credentials/oauth.json", - "- Workspace: ~/clawd", - ].join("\n"), - "Remote setup", - ); - outro("Done. Local config unchanged."); + let remoteConfig = await promptRemoteGatewayConfig(baseConfig, runtime); + remoteConfig = applyWizardMetadata(remoteConfig, { + command: opts.command, + mode, + }); + await writeConfigFile(remoteConfig); + runtime.log(`Updated ${CONFIG_PATH_CLAWDIS}`); + outro("Remote gateway configured."); return; } diff --git a/src/commands/onboard-helpers.ts b/src/commands/onboard-helpers.ts index 825ae0d85..9ebb94855 100644 --- a/src/commands/onboard-helpers.ts +++ b/src/commands/onboard-helpers.ts @@ -32,6 +32,9 @@ export function summarizeExistingConfig(config: ClawdisConfig): string { if (config.agent?.model) rows.push(`model: ${config.agent.model}`); if (config.gateway?.mode) rows.push(`gateway.mode: ${config.gateway.mode}`); if (config.gateway?.bind) rows.push(`gateway.bind: ${config.gateway.bind}`); + if (config.gateway?.remote?.url) { + rows.push(`gateway.remote.url: ${config.gateway.remote.url}`); + } if (config.skills?.install?.nodeManager) { rows.push(`skills.nodeManager: ${config.skills.install.nodeManager}`); } diff --git a/src/commands/onboard-interactive.ts b/src/commands/onboard-interactive.ts index 720efcbca..fcb3bab41 100644 --- a/src/commands/onboard-interactive.ts +++ b/src/commands/onboard-interactive.ts @@ -41,6 +41,7 @@ import { summarizeExistingConfig, } from "./onboard-helpers.js"; import { setupProviders } from "./onboard-providers.js"; +import { promptRemoteGatewayConfig } from "./onboard-remote.js"; import { setupSkills } from "./onboard-skills.js"; import type { AuthChoice, @@ -126,17 +127,11 @@ export async function runInteractiveOnboarding( ) as OnboardMode); if (mode === "remote") { - note( - [ - "Run on the gateway host:", - "- clawdis setup", - "- clawdis gateway-daemon --port 18789", - "- OAuth creds: ~/.clawdis/credentials/oauth.json", - "- Workspace: ~/clawd", - ].join("\n"), - "Remote setup", - ); - outro("Done. Local config unchanged."); + let nextConfig = await promptRemoteGatewayConfig(baseConfig, runtime); + nextConfig = applyWizardMetadata(nextConfig, { command: "onboard", mode }); + await writeConfigFile(nextConfig); + runtime.log(`Updated ${CONFIG_PATH_CLAWDIS}`); + outro("Remote gateway configured."); return; } diff --git a/src/commands/onboard-non-interactive.ts b/src/commands/onboard-non-interactive.ts index d4164755e..2307f1aca 100644 --- a/src/commands/onboard-non-interactive.ts +++ b/src/commands/onboard-non-interactive.ts @@ -35,19 +35,38 @@ export async function runNonInteractiveOnboarding( const mode: OnboardMode = opts.mode ?? "local"; if (mode === "remote") { + const remoteUrl = opts.remoteUrl?.trim(); + if (!remoteUrl) { + runtime.error("Missing --remote-url for remote mode."); + runtime.exit(1); + return; + } + + let nextConfig: ClawdisConfig = { + ...baseConfig, + gateway: { + ...baseConfig.gateway, + mode: "remote", + remote: { + url: remoteUrl, + token: opts.remoteToken?.trim() || undefined, + }, + }, + }; + nextConfig = applyWizardMetadata(nextConfig, { command: "onboard", mode }); + await writeConfigFile(nextConfig); + runtime.log(`Updated ${CONFIG_PATH_CLAWDIS}`); + const payload = { mode, - instructions: [ - "clawdis setup", - "clawdis gateway-daemon --port 18789", - "OAuth creds: ~/.clawdis/credentials/oauth.json", - "Workspace: ~/clawd", - ], + remoteUrl, + auth: opts.remoteToken ? "token" : "none", }; if (opts.json) { runtime.log(JSON.stringify(payload, null, 2)); } else { - runtime.log(payload.instructions.join("\n")); + runtime.log(`Remote gateway: ${remoteUrl}`); + runtime.log(`Auth: ${payload.auth}`); } return; } diff --git a/src/commands/onboard-remote.ts b/src/commands/onboard-remote.ts new file mode 100644 index 000000000..ad19defab --- /dev/null +++ b/src/commands/onboard-remote.ts @@ -0,0 +1,172 @@ +import { confirm, note, select, spinner, text } from "@clack/prompts"; + +import type { ClawdisConfig } from "../config/config.js"; +import type { GatewayBonjourBeacon } from "../infra/bonjour-discovery.js"; +import { discoverGatewayBeacons } from "../infra/bonjour-discovery.js"; +import type { RuntimeEnv } from "../runtime.js"; +import { detectBinary, guardCancel } from "./onboard-helpers.js"; + +const DEFAULT_GATEWAY_URL = "ws://127.0.0.1:18789"; + +function pickHost(beacon: GatewayBonjourBeacon): string | undefined { + return beacon.tailnetDns || beacon.lanHost || beacon.host; +} + +function buildLabel(beacon: GatewayBonjourBeacon): string { + const host = pickHost(beacon); + const port = beacon.gatewayPort ?? beacon.port ?? 18789; + const title = beacon.displayName ?? beacon.instanceName; + const hint = host ? `${host}:${port}` : "host unknown"; + return `${title} (${hint})`; +} + +function ensureWsUrl(value: string): string { + const trimmed = value.trim(); + if (!trimmed) return DEFAULT_GATEWAY_URL; + return trimmed; +} + +export async function promptRemoteGatewayConfig( + cfg: ClawdisConfig, + runtime: RuntimeEnv, +): Promise { + let selectedBeacon: GatewayBonjourBeacon | null = null; + let suggestedUrl = cfg.gateway?.remote?.url ?? DEFAULT_GATEWAY_URL; + + const hasBonjourTool = + (await detectBinary("dns-sd")) || (await detectBinary("avahi-browse")); + const wantsDiscover = hasBonjourTool + ? guardCancel( + await confirm({ + message: "Discover gateway on LAN (Bonjour)?", + initialValue: true, + }), + runtime, + ) + : false; + + if (!hasBonjourTool) { + note( + "Bonjour discovery requires dns-sd (macOS) or avahi-browse (Linux).", + "Discovery", + ); + } + + if (wantsDiscover) { + const spin = spinner(); + spin.start("Searching for gateways…"); + const beacons = await discoverGatewayBeacons({ timeoutMs: 2000 }); + spin.stop( + beacons.length > 0 + ? `Found ${beacons.length} gateway(s)` + : "No gateways found", + ); + + if (beacons.length > 0) { + const selection = guardCancel( + await select({ + message: "Select gateway", + options: [ + ...beacons.map((beacon, index) => ({ + value: String(index), + label: buildLabel(beacon), + })), + { value: "manual", label: "Enter URL manually" }, + ], + }), + runtime, + ); + if (selection !== "manual") { + const idx = Number.parseInt(String(selection), 10); + selectedBeacon = Number.isFinite(idx) ? (beacons[idx] ?? null) : null; + } + } + } + + if (selectedBeacon) { + const host = pickHost(selectedBeacon); + const port = selectedBeacon.gatewayPort ?? 18789; + if (host) { + const mode = guardCancel( + await select({ + message: "Connection method", + options: [ + { + value: "direct", + label: `Direct gateway WS (${host}:${port})`, + }, + { value: "ssh", label: "SSH tunnel (loopback)" }, + ], + }), + runtime, + ); + if (mode === "direct") { + suggestedUrl = `ws://${host}:${port}`; + } else { + suggestedUrl = DEFAULT_GATEWAY_URL; + note( + [ + "Start a tunnel before using the CLI:", + `ssh -N -L 18789:127.0.0.1:18789 @${host}${ + selectedBeacon.sshPort ? ` -p ${selectedBeacon.sshPort}` : "" + }`, + ].join("\n"), + "SSH tunnel", + ); + } + } + } + + const urlInput = guardCancel( + await text({ + message: "Gateway WebSocket URL", + initialValue: suggestedUrl, + validate: (value) => + String(value).trim().startsWith("ws://") || + String(value).trim().startsWith("wss://") + ? undefined + : "URL must start with ws:// or wss://", + }), + runtime, + ); + const url = ensureWsUrl(String(urlInput)); + + const authChoice = guardCancel( + await select({ + message: "Gateway auth", + options: [ + { value: "token", label: "Token (recommended)" }, + { value: "off", label: "No auth" }, + ], + }), + runtime, + ) as "token" | "off"; + + let token = cfg.gateway?.remote?.token ?? ""; + if (authChoice === "token") { + token = String( + guardCancel( + await text({ + message: "Gateway token", + initialValue: token, + validate: (value) => (value?.trim() ? undefined : "Required"), + }), + runtime, + ), + ).trim(); + } else { + token = ""; + } + + return { + ...cfg, + gateway: { + ...cfg.gateway, + mode: "remote", + remote: { + url, + token: token || undefined, + }, + }, + }; +} diff --git a/src/commands/onboard-types.ts b/src/commands/onboard-types.ts index fb7cda1e9..876f3514f 100644 --- a/src/commands/onboard-types.ts +++ b/src/commands/onboard-types.ts @@ -24,5 +24,7 @@ export type OnboardOptions = { skipSkills?: boolean; skipHealth?: boolean; nodeManager?: NodeManagerChoice; + remoteUrl?: string; + remoteToken?: string; json?: boolean; }; diff --git a/src/config/config.ts b/src/config/config.ts index ed0247fc3..4d3c9ccc0 100644 --- a/src/config/config.ts +++ b/src/config/config.ts @@ -295,6 +295,13 @@ export type GatewayTailscaleConfig = { resetOnExit?: boolean; }; +export type GatewayRemoteConfig = { + /** Remote Gateway WebSocket URL (ws:// or wss://). */ + url?: string; + /** Token for remote auth (when the gateway requires token auth). */ + token?: string; +}; + export type GatewayConfig = { /** * Explicit gateway mode. When set to "remote", local gateway start is disabled. @@ -309,6 +316,7 @@ export type GatewayConfig = { controlUi?: GatewayControlUiConfig; auth?: GatewayAuthConfig; tailscale?: GatewayTailscaleConfig; + remote?: GatewayRemoteConfig; }; export type SkillConfig = { @@ -949,6 +957,12 @@ const ClawdisSchema = z.object({ resetOnExit: z.boolean().optional(), }) .optional(), + remote: z + .object({ + url: z.string().optional(), + token: z.string().optional(), + }) + .optional(), }) .optional(), skills: z diff --git a/src/gateway/call.ts b/src/gateway/call.ts index c2b14623b..cc135e4f3 100644 --- a/src/gateway/call.ts +++ b/src/gateway/call.ts @@ -1,4 +1,5 @@ import { randomUUID } from "node:crypto"; +import { loadConfig } from "../config/config.js"; import { GatewayClient } from "./client.js"; import { PROTOCOL_VERSION } from "./protocol/index.js"; @@ -23,6 +24,24 @@ export async function callGateway( opts: CallGatewayOptions, ): Promise { const timeoutMs = opts.timeoutMs ?? 10_000; + const config = loadConfig(); + const remote = + config.gateway?.mode === "remote" ? config.gateway.remote : undefined; + const url = + (typeof opts.url === "string" && opts.url.trim().length > 0 + ? opts.url.trim() + : undefined) || + (typeof remote?.url === "string" && remote.url.trim().length > 0 + ? remote.url.trim() + : undefined) || + "ws://127.0.0.1:18789"; + const token = + (typeof opts.token === "string" && opts.token.trim().length > 0 + ? opts.token.trim() + : undefined) || + (typeof remote?.token === "string" && remote.token.trim().length > 0 + ? remote.token.trim() + : undefined); return await new Promise((resolve, reject) => { let settled = false; let ignoreClose = false; @@ -35,8 +54,8 @@ export async function callGateway( }; const client = new GatewayClient({ - url: opts.url, - token: opts.token, + url, + token, password: opts.password, instanceId: opts.instanceId ?? randomUUID(), clientName: opts.clientName ?? "cli", diff --git a/src/infra/bonjour-discovery.ts b/src/infra/bonjour-discovery.ts new file mode 100644 index 000000000..210a1a605 --- /dev/null +++ b/src/infra/bonjour-discovery.ts @@ -0,0 +1,195 @@ +import { runCommandWithTimeout } from "../process/exec.js"; + +export type GatewayBonjourBeacon = { + instanceName: string; + displayName?: string; + host?: string; + port?: number; + lanHost?: string; + tailnetDns?: string; + bridgePort?: number; + gatewayPort?: number; + sshPort?: number; + cliPath?: string; + txt?: Record; +}; + +export type GatewayBonjourDiscoverOpts = { + timeoutMs?: number; +}; + +const DEFAULT_TIMEOUT_MS = 2000; + +function parseIntOrNull(value: string | undefined): number | undefined { + if (!value) return undefined; + const parsed = Number.parseInt(value, 10); + return Number.isFinite(parsed) ? parsed : undefined; +} + +function parseTxtTokens(tokens: string[]): Record { + const txt: Record = {}; + for (const token of tokens) { + const idx = token.indexOf("="); + if (idx <= 0) continue; + const key = token.slice(0, idx).trim(); + const value = token.slice(idx + 1).trim(); + if (!key) continue; + txt[key] = value; + } + return txt; +} + +function parseDnsSdBrowse(stdout: string): string[] { + const instances = new Set(); + for (const raw of stdout.split("\n")) { + const line = raw.trim(); + if (!line || !line.includes("_clawdis-bridge._tcp")) continue; + if (!line.includes("Add")) continue; + const match = line.match(/_clawdis-bridge\._tcp\.?\s+(.+)$/); + if (match?.[1]) { + instances.add(match[1].trim()); + } + } + return Array.from(instances.values()); +} + +function parseDnsSdResolve( + stdout: string, + instanceName: string, +): GatewayBonjourBeacon | null { + const beacon: GatewayBonjourBeacon = { instanceName }; + let txt: Record = {}; + for (const raw of stdout.split("\n")) { + const line = raw.trim(); + if (!line) continue; + + if (line.includes("can be reached at")) { + const match = line.match(/can be reached at\s+([^\s:]+):(\d+)/i); + if (match?.[1]) { + beacon.host = match[1].replace(/\.$/, ""); + } + if (match?.[2]) { + beacon.port = parseIntOrNull(match[2]); + } + continue; + } + + if (line.startsWith("txt") || line.includes("txtvers=")) { + const tokens = line.split(/\s+/).filter(Boolean); + txt = parseTxtTokens(tokens); + } + } + + beacon.txt = Object.keys(txt).length ? txt : undefined; + if (txt.displayName) beacon.displayName = txt.displayName; + if (txt.lanHost) beacon.lanHost = txt.lanHost; + if (txt.tailnetDns) beacon.tailnetDns = txt.tailnetDns; + if (txt.cliPath) beacon.cliPath = txt.cliPath; + beacon.bridgePort = parseIntOrNull(txt.bridgePort); + beacon.gatewayPort = parseIntOrNull(txt.gatewayPort); + beacon.sshPort = parseIntOrNull(txt.sshPort); + + if (!beacon.displayName) beacon.displayName = instanceName; + return beacon; +} + +async function discoverViaDnsSd( + timeoutMs: number, +): Promise { + const browse = await runCommandWithTimeout( + ["dns-sd", "-B", "_clawdis-bridge._tcp", "local."], + { timeoutMs }, + ); + const instances = parseDnsSdBrowse(browse.stdout); + const results: GatewayBonjourBeacon[] = []; + for (const instance of instances) { + const resolved = await runCommandWithTimeout( + ["dns-sd", "-L", instance, "_clawdis-bridge._tcp", "local."], + { timeoutMs }, + ); + const parsed = parseDnsSdResolve(resolved.stdout, instance); + if (parsed) results.push(parsed); + } + return results; +} + +function parseAvahiBrowse(stdout: string): GatewayBonjourBeacon[] { + const results: GatewayBonjourBeacon[] = []; + let current: GatewayBonjourBeacon | null = null; + + for (const raw of stdout.split("\n")) { + const line = raw.trimEnd(); + if (!line) continue; + if (line.startsWith("=") && line.includes("_clawdis-bridge._tcp")) { + if (current) results.push(current); + const marker = " _clawdis-bridge._tcp"; + const idx = line.indexOf(marker); + const left = idx >= 0 ? line.slice(0, idx).trim() : line; + const parts = left.split(/\s+/); + const instanceName = parts.length > 3 ? parts.slice(3).join(" ") : left; + current = { + instanceName, + displayName: instanceName, + }; + continue; + } + + if (!current) continue; + + const trimmed = line.trim(); + if (trimmed.startsWith("hostname =")) { + const match = trimmed.match(/hostname\s*=\s*\[([^\]]+)\]/); + if (match?.[1]) current.host = match[1]; + continue; + } + + if (trimmed.startsWith("port =")) { + const match = trimmed.match(/port\s*=\s*\[(\d+)\]/); + if (match?.[1]) current.port = parseIntOrNull(match[1]); + continue; + } + + if (trimmed.startsWith("txt =")) { + const tokens = Array.from(trimmed.matchAll(/"([^"]*)"/g), (m) => m[1]); + const txt = parseTxtTokens(tokens); + current.txt = Object.keys(txt).length ? txt : undefined; + if (txt.displayName) current.displayName = txt.displayName; + if (txt.lanHost) current.lanHost = txt.lanHost; + if (txt.tailnetDns) current.tailnetDns = txt.tailnetDns; + if (txt.cliPath) current.cliPath = txt.cliPath; + current.bridgePort = parseIntOrNull(txt.bridgePort); + current.gatewayPort = parseIntOrNull(txt.gatewayPort); + current.sshPort = parseIntOrNull(txt.sshPort); + } + } + + if (current) results.push(current); + return results; +} + +async function discoverViaAvahi( + timeoutMs: number, +): Promise { + const browse = await runCommandWithTimeout( + ["avahi-browse", "-rt", "_clawdis-bridge._tcp"], + { timeoutMs }, + ); + return parseAvahiBrowse(browse.stdout); +} + +export async function discoverGatewayBeacons( + opts: GatewayBonjourDiscoverOpts = {}, +): Promise { + const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS; + try { + if (process.platform === "darwin") { + return await discoverViaDnsSd(timeoutMs); + } + if (process.platform === "linux") { + return await discoverViaAvahi(timeoutMs); + } + } catch { + return []; + } + return []; +}