feat: add remote gateway client config
This commit is contained in:
@@ -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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.<key>.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`.
|
||||
|
||||
|
||||
@@ -67,7 +67,10 @@ type A2UIVersion = "v0.8" | "v0.9";
|
||||
|
||||
const canvasCallOpts = (cmd: Command) =>
|
||||
cmd
|
||||
.option("--url <url>", "Gateway WebSocket URL", "ws://127.0.0.1:18789")
|
||||
.option(
|
||||
"--url <url>",
|
||||
"Gateway WebSocket URL (defaults to gateway.remote.url when configured)",
|
||||
)
|
||||
.option("--token <token>", "Gateway token (if required)")
|
||||
.option("--timeout <ms>", "Timeout in ms", "10000")
|
||||
.option("--json", "Output JSON", false);
|
||||
|
||||
@@ -105,7 +105,10 @@ async function runGatewayLoop(params: {
|
||||
|
||||
const gatewayCallOpts = (cmd: Command) =>
|
||||
cmd
|
||||
.option("--url <url>", "Gateway WebSocket URL", "ws://127.0.0.1:18789")
|
||||
.option(
|
||||
"--url <url>",
|
||||
"Gateway WebSocket URL (defaults to gateway.remote.url when configured)",
|
||||
)
|
||||
.option("--token <token>", "Gateway token (if required)")
|
||||
.option("--password <password>", "Gateway password (password auth)")
|
||||
.option("--timeout <ms>", "Timeout in ms", "10000")
|
||||
|
||||
@@ -10,7 +10,10 @@ export type GatewayRpcOpts = {
|
||||
|
||||
export function addGatewayClientOptions(cmd: Command) {
|
||||
return cmd
|
||||
.option("--url <url>", "Gateway WebSocket URL", "ws://127.0.0.1:18789")
|
||||
.option(
|
||||
"--url <url>",
|
||||
"Gateway WebSocket URL (defaults to gateway.remote.url when configured)",
|
||||
)
|
||||
.option("--token <token>", "Gateway token (if required)")
|
||||
.option("--timeout <ms>", "Timeout in ms", "10000")
|
||||
.option("--expect-final", "Wait for final response (agent)", false);
|
||||
|
||||
@@ -94,7 +94,10 @@ type PairingList = {
|
||||
|
||||
const nodesCallOpts = (cmd: Command, defaults?: { timeoutMs?: number }) =>
|
||||
cmd
|
||||
.option("--url <url>", "Gateway WebSocket URL", "ws://127.0.0.1:18789")
|
||||
.option(
|
||||
"--url <url>",
|
||||
"Gateway WebSocket URL (defaults to gateway.remote.url when configured)",
|
||||
)
|
||||
.option("--token <token>", "Gateway token (if required)")
|
||||
.option(
|
||||
"--timeout <ms>",
|
||||
|
||||
@@ -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 <mode>", "Wizard mode: local|remote")
|
||||
.option("--remote-url <url>", "Remote Gateway WebSocket URL")
|
||||
.option("--remote-token <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 <mode>", "Gateway auth: off|token|password")
|
||||
.option("--gateway-token <token>", "Gateway token (token auth)")
|
||||
.option("--gateway-password <password>", "Gateway password (password auth)")
|
||||
.option("--remote-url <url>", "Remote Gateway WebSocket URL")
|
||||
.option("--remote-token <token>", "Remote Gateway token (optional)")
|
||||
.option("--tailscale <mode>", "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),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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}`);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
172
src/commands/onboard-remote.ts
Normal file
172
src/commands/onboard-remote.ts
Normal file
@@ -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<ClawdisConfig> {
|
||||
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 <user>@${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,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -24,5 +24,7 @@ export type OnboardOptions = {
|
||||
skipSkills?: boolean;
|
||||
skipHealth?: boolean;
|
||||
nodeManager?: NodeManagerChoice;
|
||||
remoteUrl?: string;
|
||||
remoteToken?: string;
|
||||
json?: boolean;
|
||||
};
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<T = unknown>(
|
||||
opts: CallGatewayOptions,
|
||||
): Promise<T> {
|
||||
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<T>((resolve, reject) => {
|
||||
let settled = false;
|
||||
let ignoreClose = false;
|
||||
@@ -35,8 +54,8 @@ export async function callGateway<T = unknown>(
|
||||
};
|
||||
|
||||
const client = new GatewayClient({
|
||||
url: opts.url,
|
||||
token: opts.token,
|
||||
url,
|
||||
token,
|
||||
password: opts.password,
|
||||
instanceId: opts.instanceId ?? randomUUID(),
|
||||
clientName: opts.clientName ?? "cli",
|
||||
|
||||
195
src/infra/bonjour-discovery.ts
Normal file
195
src/infra/bonjour-discovery.ts
Normal file
@@ -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<string, string>;
|
||||
};
|
||||
|
||||
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<string, string> {
|
||||
const txt: Record<string, string> = {};
|
||||
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<string>();
|
||||
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<string, string> = {};
|
||||
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<GatewayBonjourBeacon[]> {
|
||||
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<GatewayBonjourBeacon[]> {
|
||||
const browse = await runCommandWithTimeout(
|
||||
["avahi-browse", "-rt", "_clawdis-bridge._tcp"],
|
||||
{ timeoutMs },
|
||||
);
|
||||
return parseAvahiBrowse(browse.stdout);
|
||||
}
|
||||
|
||||
export async function discoverGatewayBeacons(
|
||||
opts: GatewayBonjourDiscoverOpts = {},
|
||||
): Promise<GatewayBonjourBeacon[]> {
|
||||
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 [];
|
||||
}
|
||||
Reference in New Issue
Block a user