From e3f871ef4918172f7163122e735d573391adc7b3 Mon Sep 17 00:00:00 2001 From: agentiknet Date: Sat, 26 Sep 2026 01:47:22 +0200 Subject: [PATCH 1/3] feat(runtime,cli): remote_enable returns a phoneUrl; agentproto remote enable --qr MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PHONE-PLAN.md P1.2. remote_enable (MCP tool and the new POST /remote/enable REST route) now also returns phoneUrl: the installed session-chat app's UI when present (/apps/@agentik/session-chat/ui#token=), else the hosted panel fallback (https://cli.agentproto.sh/panel#daemon=&token=). The token rides in a URL fragment, never a query string, so it never reaches a server log — matching agentproto/cli-site#14's readFragmentConnection. Omitted for passthrough tunnels, same condition as bearerToken/mcpEndpoint. Adds GET/POST /remote/status/enable/disable REST routes (RemoteController was previously MCP-only) and a new `agentproto remote enable/disable/status` CLI verb built on them, mirroring `agentproto tunnel`'s discoverDaemon() pattern. `--qr` renders phoneUrl as a terminal QR code via the existing qrcode-terminal dependency, extracted from pair.ts's printQr into a shared util so both commands use the same renderer. --- packages/cli/src/cli.ts | 7 + packages/cli/src/commands/pair.ts | 17 +- packages/cli/src/commands/remote.ts | 243 ++++++++++++++++++ packages/cli/src/util/qr.ts | 22 ++ .../remote-controller-phone-url.test.ts | 87 +++++++ packages/runtime/src/http-server.ts | 75 ++++++ packages/runtime/src/index.ts | 36 +-- packages/runtime/src/remote-controller.ts | 27 ++ packages/runtime/src/remote-tools.ts | 6 +- 9 files changed, 487 insertions(+), 33 deletions(-) create mode 100644 packages/cli/src/commands/remote.ts create mode 100644 packages/cli/src/util/qr.ts create mode 100644 packages/runtime/src/__tests__/remote-controller-phone-url.test.ts diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 63163e5419..4023e91a0c 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -34,6 +34,7 @@ import { runConversation } from "./commands/conversation.js" import { runUsage } from "./commands/usage.js" import { runBrain } from "./commands/brain.js" import { runTunnel } from "./commands/tunnel.js" +import { runRemote } from "./commands/remote.js" import { runProviderPresets } from "./commands/presets.js" import { runPreset } from "./commands/preset.js" import { runBrowser } from "./commands/browser.js" @@ -109,6 +110,9 @@ Usage: agentproto tunnel list [--active] [--json] agentproto tunnel stop [--json] agentproto tunnel status [--json] + agentproto remote enable [--qr] [--target-port ] [--json] + publish this gateway (or another local port) to the internet + agentproto remote disable | status [--json] agentproto provider-preset list [--json] provider gateway definitions + key-env status agentproto presets list [--json] deprecated alias for provider-preset agentproto preset saved user spawn configurations @@ -215,6 +219,7 @@ const VERBS = new Set([ "usage", "brain", "tunnel", + "remote", "presets", "provider-preset", "preset", @@ -322,6 +327,8 @@ async function main(argv: readonly string[]): Promise { return runBrain(rest) case "tunnel": return runTunnel(rest) + case "remote": + return runRemote(rest) case "presets": process.stderr.write("agentproto presets is deprecated; use `agentproto provider-preset list`.\n") return runProviderPresets(rest) diff --git a/packages/cli/src/commands/pair.ts b/packages/cli/src/commands/pair.ts index 10465373ff..b82c0cb248 100644 --- a/packages/cli/src/commands/pair.ts +++ b/packages/cli/src/commands/pair.ts @@ -34,6 +34,7 @@ import { removeClientPairing, findClientPairing, } from "../util/client-pairings.js" +import { printQr } from "../util/qr.js" const USAGE = `agentproto pair — end-to-end daemon pairing over an untrusted rendezvous @@ -405,19 +406,3 @@ function parseTtlMinutes(raw: string): number | null { return Math.max(1, Math.round(minutes)) } -/** Render the offer URL as an in-terminal QR (best-effort — prints nothing extra - * if the optional `qrcode-terminal` dep isn't available). */ -async function printQr(url: string): Promise { - try { - const mod = await import("qrcode-terminal") - const qr = mod.default ?? mod - await new Promise(resolve => { - qr.generate(url, { small: true }, (out: string) => { - process.stdout.write(out + "\n") - resolve() - }) - }) - } catch { - // qrcode-terminal not installed — the URL above is enough to pair. - } -} diff --git a/packages/cli/src/commands/remote.ts b/packages/cli/src/commands/remote.ts new file mode 100644 index 0000000000..654e5c02a0 --- /dev/null +++ b/packages/cli/src/commands/remote.ts @@ -0,0 +1,243 @@ +/** + * `agentproto remote enable [--qr] [--provider quick] [--target-port ] + * [--target-host ] [--json]` + * `agentproto remote disable [--json]` + * `agentproto remote status [--json]` + * + * CLI twin of the MCP `remote_enable` / `remote_disable` / `remote_status` + * tools (packages/runtime/src/remote-tools.ts) — same `RemoteController` + * singleton on the daemon, driven over its `/remote/*` REST routes + * (http-server.ts's `handleRemoteControl`). Discovers the daemon via the + * same layered `discoverDaemon()` fallback as `agentproto tunnel` / + * `agentproto sessions`. + * + * `--qr` renders `phoneUrl` (PHONE-PLAN.md P1.2) as an in-terminal QR code + * so a phone can scan it straight into Control Center, or the hosted panel + * when session-chat isn't installed — see `EnableResult.phoneUrl`'s doc in + * remote-controller.ts for the two link shapes. + */ +import { parseArgs } from "node:util" +import type { EnableResult, RemoteStatus } from "@agentproto/runtime" +import { + discoverDaemon, + printNoDaemonError, + httpPostJson, + httpGetJson, +} from "./_daemon-helpers.js" +import { printQr } from "../util/qr.js" + +const USAGE = `agentproto remote — publish this gateway to the internet via Cloudflare + +Usage: + agentproto remote enable [--qr] [--provider quick] [--target-port ] + [--target-host ] [--json] + agentproto remote disable [--json] + agentproto remote status [--json] + +Discovers the daemon the same layered way \`agentproto tunnel\` / \`agentproto +sessions\` does — see \`agentproto sessions --help\` for the full fallback order. + +enable By default exposes the daemon's own gateway and gates it with a + bearer token, shown ONCE — only its hash is persisted. Pass + --target-port to tunnel a different local service instead (in that + mode the daemon does not gate the traffic; the upstream handles its + own auth). Re-running while a tunnel is already active errors — run + \`agentproto remote disable\` first to rotate. +--qr Print the response's \`phoneUrl\` as an in-terminal QR code (gateway + mode only) — scan it to open Control Center (or the hosted panel, + if session-chat isn't installed) straight from a phone. + +Examples: + agentproto remote enable --qr + agentproto remote enable --target-port 5173 # tunnel a dev server instead + agentproto remote status + agentproto remote disable +` + +export async function runRemote(args: readonly string[]): Promise { + if (args.includes("--help") || args.includes("-h")) { + process.stdout.write(USAGE) + return 0 + } + + const sub = args[0] + if (sub === "enable") return runEnable(args.slice(1)) + if (sub === "disable") return runDisable(args.slice(1)) + if (sub === "status") return runStatus(args.slice(1)) + + if (!sub) { + process.stdout.write(USAGE) + return 0 + } + process.stderr.write( + `agentproto remote: unknown subcommand "${sub}"\n` + + ` Known: enable | disable | status\n`, + ) + return 2 +} + +// ── enable ──────────────────────────────────────────────────────────── + +async function runEnable(args: readonly string[]): Promise { + const { values } = parseArgs({ + args: [...args], + allowPositionals: false, + strict: true, + options: { + qr: { type: "boolean" }, + provider: { type: "string" }, + "target-port": { type: "string" }, + "target-host": { type: "string" }, + json: { type: "boolean" }, + }, + }) + + const report = await discoverDaemon() + if (!report.found) { + printNoDaemonError(report, "agentproto remote enable") + return 2 + } + const endpoint = report.found + + const body: Record = {} + if (values.provider) body.provider = values.provider + if (values["target-port"]) { + const targetPort = Number.parseInt(values["target-port"], 10) + if (!Number.isFinite(targetPort) || targetPort < 1 || targetPort > 65535) { + process.stderr.write( + `agentproto remote enable: --target-port must be 1-65535, got "${values["target-port"]}"\n`, + ) + return 2 + } + body.targetPort = targetPort + } + if (values["target-host"]) body.targetHost = values["target-host"] + + let result: EnableResult + try { + result = await httpPostJson( + `${endpoint.url}/remote/enable`, + body, + endpoint.token, + ) + } catch (err) { + process.stderr.write( + `agentproto remote enable: ${err instanceof Error ? err.message : String(err)}\n`, + ) + return 1 + } + + if (values.json) { + process.stdout.write(JSON.stringify(result, null, 2) + "\n") + } else { + process.stdout.write(`tunnel up ${result.publicUrl}\n`) + if (result.bearerToken) { + process.stdout.write( + ` bearer ${result.bearerToken} (shown once — only its hash is persisted)\n`, + ) + } + if (result.mcpEndpoint) process.stdout.write(` mcp ${result.mcpEndpoint}\n`) + if (result.phoneUrl) process.stdout.write(` phone ${result.phoneUrl}\n`) + if (result.warning) process.stdout.write(` ${result.warning}\n`) + } + + if (values.qr) { + if (result.phoneUrl) { + await printQr(result.phoneUrl) + } else { + process.stderr.write( + "agentproto remote enable: --qr has nothing to render — no phoneUrl " + + "(passthrough --target-port tunnels don't get one).\n", + ) + } + } + + return 0 +} + +// ── disable ─────────────────────────────────────────────────────────── + +async function runDisable(args: readonly string[]): Promise { + const { values } = parseArgs({ + args: [...args], + allowPositionals: false, + strict: true, + options: { json: { type: "boolean" } }, + }) + + const report = await discoverDaemon() + if (!report.found) { + printNoDaemonError(report, "agentproto remote disable") + return 2 + } + const endpoint = report.found + + try { + const result = await httpPostJson<{ disabled: boolean }>( + `${endpoint.url}/remote/disable`, + {}, + endpoint.token, + ) + if (values.json) { + process.stdout.write(JSON.stringify(result, null, 2) + "\n") + } else { + process.stdout.write(result.disabled ? "tunnel disabled\n" : "no tunnel was active\n") + } + return 0 + } catch (err) { + process.stderr.write( + `agentproto remote disable: ${err instanceof Error ? err.message : String(err)}\n`, + ) + return 1 + } +} + +// ── status ──────────────────────────────────────────────────────────── + +async function runStatus(args: readonly string[]): Promise { + const { values } = parseArgs({ + args: [...args], + allowPositionals: false, + strict: true, + options: { json: { type: "boolean" } }, + }) + + const report = await discoverDaemon() + if (!report.found) { + printNoDaemonError(report, "agentproto remote status") + return 2 + } + const endpoint = report.found + + let status: RemoteStatus + try { + status = await httpGetJson(`${endpoint.url}/remote/status`) + } catch (err) { + process.stderr.write( + `agentproto remote status: ${err instanceof Error ? err.message : String(err)}\n`, + ) + return 1 + } + + if (values.json) { + process.stdout.write(JSON.stringify(status, null, 2) + "\n") + return 0 + } + + if (!status.enabled) { + process.stdout.write( + `disabled${status.lastError ? `\n last error ${status.lastError}` : ""}\n`, + ) + return 0 + } + process.stdout.write( + `enabled\n` + + ` provider ${status.provider}\n` + + ` url ${status.publicUrl}\n` + + ` target ${status.target?.host}:${status.target?.port}\n` + + ` pid ${status.pid ?? "—"}\n` + + ` created ${status.createdAt}\n` + + (status.lastError ? ` error ${status.lastError}\n` : ""), + ) + return 0 +} diff --git a/packages/cli/src/util/qr.ts b/packages/cli/src/util/qr.ts new file mode 100644 index 0000000000..bd6bd27e7b --- /dev/null +++ b/packages/cli/src/util/qr.ts @@ -0,0 +1,22 @@ +/** + * Shared in-terminal QR rendering — extracted from `pair.ts`'s `printQr` so + * `agentproto remote enable --qr` (phoneUrl) can reuse the exact same + * best-effort behaviour instead of a second copy. + */ + +/** Render `url` as an in-terminal QR (best-effort — prints nothing extra if + * the `qrcode-terminal` dep isn't available). */ +export async function printQr(url: string): Promise { + try { + const mod = await import("qrcode-terminal") + const qr = mod.default ?? mod + await new Promise(resolve => { + qr.generate(url, { small: true }, (out: string) => { + process.stdout.write(out + "\n") + resolve() + }) + }) + } catch { + // qrcode-terminal not installed — the URL above is enough. + } +} diff --git a/packages/runtime/src/__tests__/remote-controller-phone-url.test.ts b/packages/runtime/src/__tests__/remote-controller-phone-url.test.ts new file mode 100644 index 0000000000..624b1b9da0 --- /dev/null +++ b/packages/runtime/src/__tests__/remote-controller-phone-url.test.ts @@ -0,0 +1,87 @@ +/** + * `RemoteController.enable()`'s `phoneUrl` (PHONE-PLAN.md P1.2) — a single + * link a phone can open, with the bearer riding in a URL *fragment* + * (`#token=`), never a `?` query string (fragments never reach a server). + * Two shapes, chosen by `isSessionChatInstalled`: + * - installed: `/apps/@agentik/session-chat/ui#token=` + * - not installed: `https://cli.agentproto.sh/panel#daemon=&token=` + * Mocks the quick-tunnel provider so no real `cloudflared` process is + * spawned — `start()` resolves immediately with a fake public URL. + */ + +import { afterEach, describe, expect, it, vi } from "vitest" +import { mkdtemp, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" + +const FAKE_PUBLIC_URL = "https://fake-tunnel.trycloudflare.com" + +vi.mock("../remote-providers/quick.js", () => ({ + quickTunnelProvider: () => ({ + id: "quick", + async start() { + return { publicUrl: FAKE_PUBLIC_URL, pid: 4242 } + }, + async stop() {}, + }), +})) + +import { RemoteController } from "../remote-controller.js" + +describe("RemoteController.enable() — phoneUrl", () => { + let dir: string + + afterEach(async () => { + if (dir) await rm(dir, { recursive: true, force: true }) + }) + + it("links straight into session-chat when it's installed", async () => { + dir = await mkdtemp(join(tmpdir(), "agentproto-remote-phoneurl-")) + const controller = new RemoteController({ + workspace: dir, + port: 18790, + isSessionChatInstalled: () => true, + }) + const result = await controller.enable({}) + expect(result.bearerToken).toBeTruthy() + expect(result.phoneUrl).toBe( + `${FAKE_PUBLIC_URL}/apps/@agentik/session-chat/ui#token=${result.bearerToken}`, + ) + }) + + it("falls back to the hosted panel when session-chat isn't installed", async () => { + dir = await mkdtemp(join(tmpdir(), "agentproto-remote-phoneurl-")) + const controller = new RemoteController({ + workspace: dir, + port: 18790, + isSessionChatInstalled: () => false, + }) + const result = await controller.enable({}) + expect(result.bearerToken).toBeTruthy() + expect(result.phoneUrl).toBe( + `https://cli.agentproto.sh/panel#daemon=${encodeURIComponent(FAKE_PUBLIC_URL)}&token=${result.bearerToken}`, + ) + }) + + it("also falls back to the hosted panel when isSessionChatInstalled is omitted", async () => { + dir = await mkdtemp(join(tmpdir(), "agentproto-remote-phoneurl-")) + const controller = new RemoteController({ workspace: dir, port: 18790 }) + const result = await controller.enable({}) + expect(result.phoneUrl).toBe( + `https://cli.agentproto.sh/panel#daemon=${encodeURIComponent(FAKE_PUBLIC_URL)}&token=${result.bearerToken}`, + ) + }) + + it("omits phoneUrl for a passthrough tunnel (targetPort != gateway port)", async () => { + dir = await mkdtemp(join(tmpdir(), "agentproto-remote-phoneurl-")) + const controller = new RemoteController({ + workspace: dir, + port: 18790, + isSessionChatInstalled: () => true, + }) + const result = await controller.enable({ targetPort: 54371 }) + expect(result.exposesGateway).toBe(false) + expect(result.bearerToken).toBeUndefined() + expect(result.phoneUrl).toBeUndefined() + }) +}) diff --git a/packages/runtime/src/http-server.ts b/packages/runtime/src/http-server.ts index 08f3f53b30..09da2f640a 100644 --- a/packages/runtime/src/http-server.ts +++ b/packages/runtime/src/http-server.ts @@ -41,6 +41,7 @@ import type { SessionsRegistry, AgentSessionLike, RestartPolicy, SessionDescript import { SessionNotAliveError, applyBracketedPasteWrap } from "./sessions.js" import type { WorkspaceBrains } from "./workspace-brains.js" import type { TunnelRegistry } from "./tunnel-registry.js" +import type { RemoteController, EnableInput } from "./remote-controller.js" import type { PairingRegistry } from "./pairing-registry.js" import { createReconnectLogGate } from "./reconnect-log-gate.js" import type { WorkflowRunner, WorkflowStage } from "./workflow-runner.js" @@ -789,6 +790,11 @@ export interface RuntimeHttpServerOptions { /** Optional — when wired, exposes /tunnels/* routes for creating and * managing public tunnels for local ports. Without it the routes 404. */ tunnels?: TunnelRegistry + /** Optional — when wired, exposes POST /remote/enable, POST /remote/disable, + * GET /remote/status — the REST twin of the MCP `remote_enable` / + * `remote_disable` / `remote_status` tools (remote-tools.ts), for + * `agentproto remote enable/disable/status`. Without it the routes 404. */ + remote?: RemoteController /** Optional — when wired, exposes /pairings/* routes for minting offers, * listing pairings, and revoking them (E2E daemon pairing). Same service the * MCP `pair_offer` / `pair_list` / `pair_revoke` tools call. Without it the @@ -3030,6 +3036,15 @@ export async function startHttpServer( if (handled) return } + // Remote-control routes — the REST twin of the MCP remote_enable/ + // remote_disable/remote_status tools, for `agentproto remote + // enable/disable/status`. Only registered when the gateway was + // built with a RemoteController. + if (opts.remote && path.startsWith("/remote")) { + const handled = await handleRemoteControl(req, res, path, opts.remote) + if (handled) return + } + // GET /routines — AIP-41 routine DEFINITIONS from the registrar. // Mirrors the MCP `routine_list` tool (orchestration-tools.ts). if (opts.routineRegistrar && path === "/routines") { @@ -6149,6 +6164,66 @@ async function handleTunnels( return false } +/** + * REST twin of the MCP `remote_enable` / `remote_disable` / `remote_status` + * tools (remote-tools.ts) — same `RemoteController` singleton, so the two + * surfaces can never disagree about whether a tunnel is up. Exists for + * `agentproto remote enable/disable/status`: unlike an MCP tool call, a CLI + * subcommand talking to an already-running daemon goes over REST, the same + * way `agentproto tunnel` / `agentproto sessions` do (see + * `_daemon-helpers.ts`'s `discoverDaemon`). + * + * No gate beyond what already applies to every route (the P0 tunnel-bearer + * gate for non-loopback traffic, `tunnelBearerAllowed`) — same trust model + * as `/tunnels`, which has none either: a loopback CLI caller is trusted, + * exactly as it is for `agent_start`/`file_write`/every other MCP tool. + */ +async function handleRemoteControl( + req: IncomingMessage, + res: ServerResponse, + path: string, + controller: RemoteController, +): Promise { + const json = (status: number, body: unknown): void => { + res.writeHead(status, { "content-type": "application/json" }) + res.end(JSON.stringify(body)) + } + + if (path === "/remote/status" && req.method === "GET") { + json(200, controller.status()) + return true + } + + if (path === "/remote/enable" && req.method === "POST") { + const body = await readJsonBody(req) + const b: Record = + typeof body === "object" && body !== null ? (body as Record) : {} + const input: EnableInput = { + ...(b.provider === "quick" ? { provider: "quick" as const } : {}), + ...(typeof b.targetPort === "number" ? { targetPort: b.targetPort } : {}), + ...(typeof b.targetHost === "string" ? { targetHost: b.targetHost } : {}), + } + try { + const result = await controller.enable(input) + json(200, result) + } catch (err) { + json(409, { + error: "remote_enable_failed", + message: err instanceof Error ? err.message : String(err), + }) + } + return true + } + + if (path === "/remote/disable" && req.method === "POST") { + const result = await controller.disable() + json(200, result) + return true + } + + return false +} + /** * GET /routines → { routines: RoutineFrontmatter[] } — the AIP-41 * registrar's `list()` (routine DEFINITIONS from `.routines/*`), mirroring diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts index 97bfebb8ba..5a56d1ebf0 100644 --- a/packages/runtime/src/index.ts +++ b/packages/runtime/src/index.ts @@ -507,6 +507,7 @@ export type { HeartbeatRunner, BuildHeartbeatAgent, HeartbeatAgent } from "./hea export type { RuntimeEvent, RuntimeEvents } from "./events.js" export type { WorkspaceFs } from "./workspace-fs.js" export type { TunnelDescriptor, TunnelStatus, TunnelProvider } from "./tunnel-registry.js" +export type { EnableInput, EnableResult, RemoteStatus } from "./remote-controller.js" export { decideWorktreeIsolation, loadWorktreeIsolation, @@ -1167,21 +1168,6 @@ export async function createGateway( const conversations = fileConversationStore({ workspace }) const workspaceFs = createWorkspaceFs({ workspace }) - // Singleton controller for "publish to the internet" state. Created - // disabled — auth stays `mode: "none"` until `remote_enable` is - // called. Tunnel logs flow through the events stream so `/events` - // subscribers see cloudflared chatter. - const remote = new RemoteController({ - workspace, - port, - onLog: line => - events.emit({ - type: "remote-log", - at: new Date().toISOString(), - line, - }), - }) - // Multi-tunnel registry — independent from RemoteController. Manages // the general "create a public URL for any local port" surface // (tunnel_create / tunnel_list / tunnel_stop MCP tools + /tunnels HTTP @@ -1517,6 +1503,25 @@ export async function createGateway( } } + // Singleton controller for "publish to the internet" state. Created + // disabled — auth stays `mode: "none"` until `remote_enable` is + // called. Tunnel logs flow through the events stream so `/events` + // subscribers see cloudflared chatter. `isSessionChatInstalled` decides + // which of `EnableResult.phoneUrl`'s two shapes `enable()` builds + // (PHONE-PLAN.md P1.2) — the same call-time check the builtin-panel mount + // and `registerSessionTools` already share, so all three surfaces agree. + const remote = new RemoteController({ + workspace, + port, + onLog: line => + events.emit({ + type: "remote-log", + at: new Date().toISOString(), + line, + }), + isSessionChatInstalled, + }) + // HTML cache for installed apps' `ui.path` panels (app-ui-apps.ts) — // gateway-scope singleton so a `/mcp` request doesn't re-read an // unchanged panel's HTML off disk every time `mcpServerFactory` rebuilds @@ -2307,6 +2312,7 @@ export async function createGateway( token, ptyEnabled: opts.spawnPty != null, tunnels, + remote, ...(opts.pairingRegistry ? { pairings: opts.pairingRegistry } : {}), sessionEvents, eventRing, diff --git a/packages/runtime/src/remote-controller.ts b/packages/runtime/src/remote-controller.ts index f1a979c7a2..9173db876e 100644 --- a/packages/runtime/src/remote-controller.ts +++ b/packages/runtime/src/remote-controller.ts @@ -38,6 +38,7 @@ import { randomBytes, createHash } from "node:crypto" import { mkdir, writeFile, readFile, chmod, rm } from "node:fs/promises" import { existsSync } from "node:fs" import { join } from "node:path" +import { SESSION_CHAT_APP_ID } from "@agentproto/apps" import type { AuthOptions } from "./http-server.js" import { quickTunnelProvider } from "./remote-providers/quick.js" @@ -102,6 +103,21 @@ export interface EnableResult { * gateway. */ mcpConfigSnippet?: string + /** + * A single link to open on a phone (PHONE-PLAN.md P1.2) — the token rides + * in a URL *fragment* (`#token=`), never a `?` query string, since + * fragments never reach a server (no Referer, no access/proxy log, no CDN + * cache key). Two shapes, chosen by whether this daemon has the + * `@agentik/session-chat` app installed with a UI: + * - installed: `/apps/@agentik/session-chat/ui#token=` — + * the phone lands directly in Control Center. + * - not installed: `https://cli.agentproto.sh/panel#daemon=&token=` + * — the hosted panel, which speaks the same fragment shape (see + * agentproto/cli-site's `readFragmentConnection`). + * Only emitted when exposing the gateway (same condition as `bearerToken`) + * — a passthrough tunnel has no daemon UI to link to. + */ + phoneUrl?: string provider: "quick" target: { host: string; port: number } exposesGateway: boolean @@ -132,6 +148,14 @@ export interface RemoteControllerOptions { port: number /** Hook for surfacing provider logs through RuntimeEvents. */ onLog?: (line: string) => void + /** + * Whether the `@agentik/session-chat` app is installed with a `ui` block + * on THIS daemon — decides which of the two `EnableResult.phoneUrl` shapes + * `enable()` builds. Resolved at call time (matches `index.ts`'s own + * `isSessionChatInstalled`), so installing the app after boot is picked + * up without a restart. Omitted ⇒ always the hosted-panel fallback. + */ + isSessionChatInstalled?: () => boolean } const STATE_FILE_REL = ".agentproto/remote.json" @@ -245,6 +269,9 @@ export class RemoteController { result.bearerToken = bearerToken result.mcpEndpoint = mcpEndpoint result.mcpConfigSnippet = buildMcpConfigSnippet(mcpEndpoint, bearerToken) + result.phoneUrl = this.opts.isSessionChatInstalled?.() + ? `${started.publicUrl}/apps/${SESSION_CHAT_APP_ID}/ui#token=${bearerToken}` + : `https://cli.agentproto.sh/panel#daemon=${encodeURIComponent(started.publicUrl)}&token=${bearerToken}` } else { // Passthrough tunnel: the daemon gates nothing on this URL. Make the // unauthenticated exposure explicit (structured + logged) rather than diff --git a/packages/runtime/src/remote-tools.ts b/packages/runtime/src/remote-tools.ts index 98a66f22cf..bcbce96887 100644 --- a/packages/runtime/src/remote-tools.ts +++ b/packages/runtime/src/remote-tools.ts @@ -53,8 +53,10 @@ export function registerRemoteTools( "tunnel a different local service (Supabase, dev server, …); in that mode " + "the daemon does not gate the proxied traffic — the upstream service " + "handles its own auth. Returns the public URL plus a paste-ready " + - "`.mcp.json` snippet (gateway mode only). Re-running while a tunnel is " + - "already up errors; call `remote_disable` first to rotate.", + "`.mcp.json` snippet and a `phoneUrl` — a single link to open on a " + + "phone, with the token in a URL fragment (gateway mode only). " + + "Re-running while a tunnel is already up errors; call `remote_disable` " + + "first to rotate.", { provider: z .enum(["quick"]) From ff6f91fe741dfcf8923f221b09046594ffd8ef42 Mon Sep 17 00:00:00 2001 From: agentiknet Date: Sat, 26 Sep 2026 02:52:26 +0200 Subject: [PATCH 2/3] docs(cli): add agentproto remote verb page The docs.mjs --check gate failed CI: a new verb (remote) with no docs/cli/verbs/ page is a hard error. Covers enable [--qr]/disable/status, the two phoneUrl shapes (session-chat link vs. the cli.agentproto.sh/panel fallback) and why the token rides in a URL fragment, and the post-#1398 security model (every non-loopback route needs the bearer once enabled). --- docs/cli/README.md | 1 + docs/cli/verbs/remote.md | 138 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 139 insertions(+) create mode 100644 docs/cli/verbs/remote.md diff --git a/docs/cli/README.md b/docs/cli/README.md index 58c3ecc094..b58db8c8ba 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -59,6 +59,7 @@ Pick whichever matches what you're trying to do: - [`agentproto policy`](./verbs/policy.md) — CLI surface for the daemon's completion-policy engine (shell/judge gates, commit + human-ack) - [`agentproto provider-preset`](./verbs/presets.md) — list provider gateway definitions + key-env status - [`agentproto preset`](./verbs/preset.md) — manage saved user spawn configurations +- [`agentproto remote`](./verbs/remote.md) — publish this gateway (or another local port) to the internet via Cloudflare, bearer-gated - [`agentproto rendezvous`](./verbs/rendezvous.md) — self-host the untrusted pairing broker - [`agentproto run`](./verbs/run.md) — one-shot adapter turn - [`agentproto run-swarm`](./verbs/run-swarm.md) — kernel-routed multi-agent loop diff --git a/docs/cli/verbs/remote.md b/docs/cli/verbs/remote.md new file mode 100644 index 0000000000..2cb1c3e87a --- /dev/null +++ b/docs/cli/verbs/remote.md @@ -0,0 +1,138 @@ +# `agentproto remote` + +```text +agentproto remote enable [--qr] [--provider quick] [--target-port ] + [--target-host ] [--json] +agentproto remote disable [--json] +agentproto remote status [--json] +``` + +Publish this daemon's gateway to the internet via a Cloudflare tunnel, gated +with a bearer token minted for the session. CLI twin of the MCP +`remote_enable` / `remote_disable` / `remote_status` tools — same +`RemoteController` on the daemon, driven over its `/remote/*` HTTP routes. + +Requires a running daemon ([`serve.md`](./serve.md) or +[`daemon.md`](./daemon.md)). Discovery follows the same layered order as +[`sessions.md`](./sessions.md): env override → +`~/.agentproto/runtime.json` (pid-checked) → the central registry → each +configured workspace's own `runtime.json`. + +## Subverbs + +### `enable` + +Starts a tunnel via `POST /remote/enable`. By default it exposes **this +gateway** and mints a bearer token, printed exactly **once** — only its +SHA-256 hash is persisted (`.agentproto/remote.json`), so there is no way to +recover a lost token short of `remote disable` + `remote enable` again to +rotate it. Re-running `enable` while a tunnel is already active errors for +the same reason. + +| Flag | Default | Description | +|------|---------|-------------| +| `--qr` | `false` | Render the response's `phoneUrl` (see below) as an in-terminal QR code. | +| `--provider ` | `quick` | Tunnel backend. `quick` = Cloudflare Quick Tunnel — no API key, ephemeral `*.trycloudflare.com` URL. | +| `--target-port ` | this gateway's own port | Tunnel a *different* local service instead (e.g. a dev server). In this mode the daemon does **not** gate the traffic — no bearer token is issued, and `phoneUrl` is omitted — the upstream service must handle its own auth. | +| `--target-host ` | `127.0.0.1` | Host the tunnel forwards to. | +| `--json` | `false` | Emit the full `EnableResult` (see below) as JSON. | + +```bash +agentproto remote enable --qr +``` + +```text +tunnel up https://ensure-opera-satisfactory-embassy.trycloudflare.com + bearer bE2C9kyQ2fgcodKsG9nY2mPRF24razhjAZSlm4RPM38 (shown once — only its hash is persisted) + mcp https://ensure-opera-satisfactory-embassy.trycloudflare.com/mcp + phone https://ensure-opera-satisfactory-embassy.trycloudflare.com/apps/@agentik/session-chat/ui#token=bE2C9kyQ2fgcodKsG9nY2mPRF24razhjAZSlm4RPM38 +[QR code of the phone URL] +``` + +### `disable` + +Tears down the active tunnel and drops the bearer via `POST /remote/disable`. +Idempotent — calling it with no tunnel active is a no-op (`{"disabled":false}`). + +| Flag | Default | Description | +|------|---------|-------------| +| `--json` | `false` | Emit `{"disabled":bool}` as JSON. | + +### `status` + +Read-only snapshot via `GET /remote/status` — provider, public URL, target, +supervised pid, createdAt, last error. **Never** re-shows the bearer token; +that only ever appears once, in `enable`'s own response. + +| Flag | Default | Description | +|------|---------|-------------| +| `--json` | `false` | Emit the full status object as JSON. | + +## `phoneUrl` — the QR/link target + +`enable`'s response (and MCP `remote_enable`'s) includes a `phoneUrl`: one +link that gets a phone straight into a live view of this daemon, no typing +required. Its shape depends on what's installed: + +- **`@agentik/session-chat` app installed** — `phoneUrl` points directly at + it: `/apps/@agentik/session-chat/ui#token=`. +- **not installed** — falls back to the hosted panel: + `https://cli.agentproto.sh/panel#daemon=&token=`. + +In both shapes the token rides in the URL **fragment** (`#token=…`), never a +`?` query string. A fragment is never sent to a server — no `Referer` +header, no access/proxy log line, no CDN cache key — so the link is exactly +as safe to generate as it is to *display* (a screenshot or shoulder-surf is +the only leak surface, same as the bearer text printed above it). The +receiving page (session-chat, or the hosted panel) reads the fragment client +-side and immediately strips it from the address bar. + +`phoneUrl` is omitted whenever `bearerToken`/`mcpEndpoint` are — i.e. for a +`--target-port` passthrough tunnel, since there's no daemon UI to link a +phone to in that mode. + +## Security model + +Once `remote enable` is active, the daemon is in **bearer mode**: every +request that did **not** originate on the loopback socket must present the +bearer — as `Authorization: Bearer ` on a normal request, or +`?token=` on the SSE stream / PTY WebSocket upgrade (neither can set a +header). This applies uniformly to every route the daemon exposes (sessions, +conversations, `/mcp`, apps, …), with exactly three exceptions: + +- `/health` — the public liveness probe. +- `/inbound/:slug` — gated by its own per-endpoint HMAC signature instead. +- `GET /apps/:appId/ui` (the static page shell only, not the APIs it calls) + — so a phone can load the page before it has anywhere to put the token. + +Critically, an allowlisted `Origin` header or the MCP-Apps widget embed +token (`?et=`) are **not** substitutes for the bearer here — those remain +browser-CSRF / local-widget guards, scoped to loopback. Before this was +tightened, a handful of routes accepted a spoofable `Origin` alone once a +tunnel was up; `curl` can set any `Origin` it likes once a request has +crossed a public tunnel, so anyone holding the tunnel URL could otherwise +have read session data or driven the daemon with no token at all. Loopback +traffic (same machine) is completely unaffected — it never needed the +bearer, before or after. + +## Examples + +```bash +# Publish this gateway and print the phone link + QR +agentproto remote enable --qr + +# Tunnel a dev server instead — no bearer, no phoneUrl, upstream auths itself +agentproto remote enable --target-port 5173 + +# Check what's live +agentproto remote status + +# Tear it down (rotates the token on the next enable) +agentproto remote disable +``` + +## See also + +- [`serve.md`](./serve.md) — `--auth-token` for a *persistent* bearer, independent of `remote enable`'s ephemeral one +- [`tunnel.md`](./tunnel.md) — the general-purpose "expose any local port" surface (no gateway auth of its own) +- [`pair.md`](./pair.md) — end-to-end pairing over an untrusted rendezvous, an alternative to a public tunnel From ac39f9dbe17344da01a93ce76d80cd2633f24399 Mon Sep 17 00:00:00 2001 From: agentproto-bot Date: Sat, 26 Sep 2026 00:55:24 +0000 Subject: [PATCH 3/3] =?UTF-8?q?chore:=20agentic=20reviewer=20=E2=80=94=20c?= =?UTF-8?q?hangeset?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .changeset/pr-1402-agentic.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .changeset/pr-1402-agentic.md diff --git a/.changeset/pr-1402-agentic.md b/.changeset/pr-1402-agentic.md new file mode 100644 index 0000000000..e7c35fe1c4 --- /dev/null +++ b/.changeset/pr-1402-agentic.md @@ -0,0 +1,6 @@ +--- +"@agentproto/runtime": minor +"@agentproto/cli": minor +--- + +`remote_enable` (MCP tool and the new `POST /remote/enable` REST route) now returns a `phoneUrl` — the installed `@agentik/session-chat` app's UI, or the hosted panel fallback — with the token in a URL fragment; adds `GET/POST /remote/*` REST twins of the remote tools and a new `agentproto remote enable|disable|status [--qr]` CLI verb; `printQr` is extracted from `pair.ts` into a shared `util/qr.ts`.