Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,6 @@ content/docs
*.log
.DS_Store
*.tsbuildinfo

# Pairing service worker bundle — built by scripts/build-sw.mjs
public/pair-sw.js
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,45 @@ Env vars at build time:

Set them when you want to publish from a fork or a non-main branch.

## Phone pairing (`/pair`, `/d/<id>/`)

`agentproto pair offer --qr` prints a QR for
`https://cli.agentproto.sh/pair#<offer>`. The offer rides in the fragment,
so it never reaches this server.

- **`/pair`** reads the offer, runs the end-to-end handshake through the
rendezvous (`@agentproto/pair-client`), shows the daemon's name and
fingerprint to confirm, and stores the credential in IndexedDB (never
localStorage). With no offer, it lists the paired daemons.
- **`/d/<id>`** (`<id>` = daemon fingerprint) is the state page: not paired,
connecting, daemon offline (retrying), revoked.
- **`/d/<id>/…`** is answered by a service worker registered for that scope
(`src/sw/pair-sw.ts`, bundled by `scripts/build-sw.mjs` to
`public/pair-sw.js`). It holds the one tunnel to the daemon and proxies
every request under the scope to it. The Control Center
(`/d/<id>/apps/@agentik/session-chat/ui/`) and its REST, `/mcp` and SSE
calls all come from the daemon. cli-site serves none of it.

`public/pair.webmanifest` makes it installable (add to home screen).

**One origin per daemon.** Served at `https://<daemon-fingerprint>.agentproto.cloud`,
the origin belongs to that one daemon (`src/lib/pair-host.ts`). `/pair` refuses
offers for any other daemon, and the credential store only holds that daemon.
Browsers isolate storage and service workers per origin, so no daemon's
Control Center can reach another daemon's pairing. Any other host
(cli.agentproto.sh, localhost) is a shared origin: it still works, and says
so. The pair domain is set at build time:

| Var | Default |
| ------------------------------------- | ------------------ |
| `NEXT_PUBLIC_AGENTPROTO_PAIR_DOMAIN` | `agentproto.cloud` |

To try per-daemon origins locally, build with
`NEXT_PUBLIC_AGENTPROTO_PAIR_DOMAIN=localhost` and open
`http://<fingerprint>.localhost:3010/pair`. Chrome resolves `*.localhost` to
loopback and treats it as a secure context, which service workers and
WebCrypto need.

## Structure

```
Expand Down
Binary file added docs/pair/1-confirm.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/pair/2-control-center.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/pair/3-sessions-panel.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/pair/4-offline.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/pair/5-revoked.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/pair/6-not-paired.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/pair/7-outdated.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/pair/8-wrong-origin.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/pair/9-shared-origin-confirm.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,18 @@
"license": "Apache-2.0",
"type": "module",
"scripts": {
"predev": "node scripts/sync-content.mjs",
"predev": "node scripts/sync-content.mjs && node scripts/build-sw.mjs",
"dev": "next dev --turbopack -p 3010",
"prebuild": "node scripts/sync-content.mjs",
"prebuild": "node scripts/sync-content.mjs && node scripts/build-sw.mjs",
"build": "next build",
"start": "next start",
"lint": "next lint",
"pretypecheck": "node scripts/sync-content.mjs && fumadocs-mdx",
"typecheck": "tsc --noEmit",
"typecheck": "tsc --noEmit && tsc --noEmit -p src/sw",
"clean": "rm -rf .next .source content/docs .cache"
},
"dependencies": {
"@agentproto/pair-client": "^0.1.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"clsx": "^2.1.1",
Expand All @@ -41,6 +42,7 @@
"@types/node": "^24.12.3",
"@types/react": "19.2.14",
"@types/react-dom": "19.2.3",
"esbuild": "^0.28.2",
"tailwindcss": "^4.3.0",
"typescript": "^5.9.3"
},
Expand Down
Binary file added public/pair-icon-192.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/pair-icon-512.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
16 changes: 16 additions & 0 deletions public/pair.webmanifest
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "agentproto Control Center",
"short_name": "agentproto",
"description": "Your agentproto daemon on your phone, end-to-end encrypted through the rendezvous.",
"id": "/pair",
"start_url": "/pair?launch=1",
"scope": "/",
"display": "standalone",
"background_color": "#0d1512",
"theme_color": "#0d1512",
"icons": [
{ "src": "/pair-icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/pair-icon-512.png", "sizes": "512x512", "type": "image/png" },
{ "src": "/pair-icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
]
}
37 changes: 37 additions & 0 deletions scripts/build-sw.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#!/usr/bin/env node
/**
* build-sw.mjs — bundle the pairing service worker (src/sw/pair-sw.ts) for
* the browser into public/pair-sw.js.
*
* A service worker is a classic script at a fixed URL, outside Next's module
* graph, so it is built separately: one self-contained IIFE with
* @agentproto/pair-client inlined. Served from the root, its default max
* scope is `/`, which covers every `/d/<id>/` registration without a
* `Service-Worker-Allowed` header. Runs before `dev` and `build`; the output
* is gitignored.
*/

import { build } from "esbuild"
import path from "node:path"
import { fileURLToPath } from "node:url"

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")

await build({
entryPoints: [path.join(root, "src/sw/pair-sw.ts")],
outfile: path.join(root, "public/pair-sw.js"),
bundle: true,
format: "iife",
platform: "browser",
target: ["es2022"],
minify: process.env.NODE_ENV === "production",
sourcemap: process.env.NODE_ENV === "production" ? false : "inline",
legalComments: "none",
// Same pair domain the pages get from Next (src/lib/pair-host.ts).
define: {
"process.env.NEXT_PUBLIC_AGENTPROTO_PAIR_DOMAIN": JSON.stringify(
process.env.NEXT_PUBLIC_AGENTPROTO_PAIR_DOMAIN ?? "",
),
},
logLevel: "info",
})
235 changes: 235 additions & 0 deletions src/app/d/[id]/[[...rest]]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
"use client"

import { useEffect, useRef, useState } from "react"
import { useParams } from "next/navigation"
import { Fingerprint, HowToPair, PairButton, PairShell } from "@/components/pair-shell"
import { controlCenterUrl, isPairWorkerStatus, isPairingId, pairingScope, type PairState } from "@/lib/pair"
import { daemonOrigin, PAIR_DOMAIN } from "@/lib/pair-host"
import {
forgetPairing,
hostMode,
pairStore,
postToWorker,
registerPairingWorker,
serviceWorkersSupported,
} from "@/lib/pair-worker"

/** How often to ask the worker for its state. Each message also keeps a worker
* that would otherwise idle out alive while this page waits on it. */
const POLL_MS = 2_500

type View =
| { state: "loading" }
| { state: PairState; error?: { code: string; message: string } }
| { state: "error"; error: { code: string; message: string } }

/** Only ever send the user back inside this pairing's own scope. */
function resolveNext(id: string, fromQuery: string | null, here: string | null): string {
for (const candidate of [fromQuery, here]) {
if (candidate && candidate.startsWith(pairingScope(id)) && !candidate.includes("//")) return candidate
}
return controlCenterUrl(id)
}

function isPairState(s: string | null): s is PairState {
return (
s === "connecting" ||
s === "open" ||
s === "offline" ||
s === "revoked" ||
s === "not_paired" ||
s === "outdated"
)
}

/**
* `/d/<id>` — the state page for one paired daemon: registers the pairing's
* service worker, follows its tunnel state (the worker owns the one
* connection; this page only asks it), and opens the Control Center as soon
* as the tunnel is up. The worker sends the Control Center back here when
* the daemon goes offline or revokes this device.
*
* Also catches `/d/<id>/…` loaded while no worker controls it (first visit on
* a new tab, site data cleared): the worker is installed, then the same URL
* is loaded again through it.
*/
export default function DaemonStatusPage(): React.ReactElement {
const params = useParams<{ id: string; rest?: string[] }>()
const id = params.id
const deep = (params.rest?.length ?? 0) > 0
const [view, setView] = useState<View>({ state: "loading" })
const [name, setName] = useState<string | null>(null)
const [fingerprint, setFingerprint] = useState<string | null>(null)
const regRef = useRef<ServiceWorkerRegistration | null>(null)
/** Set on a per-daemon origin asked for another daemon: that origin's id. */
const [originOwner, setOriginOwner] = useState<string | null>(null)

useEffect(() => {
if (!isPairingId(id)) {
setView({ state: "not_paired" })
return
}
const mode = hostMode()
if (mode.kind === "daemon" && mode.fingerprint !== id) {
setOriginOwner(mode.fingerprint)
setView({ state: "not_paired" })
return
}
if (!serviceWorkersSupported()) {
setView({ state: "error", error: { code: "unsupported", message: "This browser has no service workers." } })
return
}
const search = new URLSearchParams(window.location.search)
const hinted = search.get("state")
if (isPairState(hinted)) setView({ state: hinted })
const next = resolveNext(id, search.get("next"), deep ? window.location.pathname + window.location.search : null)

let stopped = false
let timer: ReturnType<typeof setInterval> | undefined
const onMessage = (event: MessageEvent): void => {
const status = event.data
if (stopped || !isPairWorkerStatus(status) || status.id !== id) return
if (status.daemonName) setName(status.daemonName)
setView(status.error ? { state: status.state, error: status.error } : { state: status.state })
if (status.state === "open") {
stopped = true
window.location.replace(next)
}
}
const onOnline = (): void => {
if (regRef.current) postToWorker(regRef.current, { type: "agentproto-pair:reconnect" })
}
navigator.serviceWorker.addEventListener("message", onMessage)
window.addEventListener("online", onOnline)

void (async () => {
const credential = await pairStore().get(id)
if (stopped) return
if (!credential) {
setView({ state: "not_paired" })
return
}
setName(credential.name)
setFingerprint(credential.fingerprint)
const reg = await registerPairingWorker(id)
if (stopped) return
regRef.current = reg
const poll = (): void => {
postToWorker(reg, { type: "agentproto-pair:status" })
}
poll()
timer = setInterval(poll, POLL_MS)
})().catch(err => {
if (!stopped) {
setView({ state: "error", error: { code: "error", message: err instanceof Error ? err.message : String(err) } })
}
})

return () => {
stopped = true
clearInterval(timer)
navigator.serviceWorker.removeEventListener("message", onMessage)
window.removeEventListener("online", onOnline)
}
}, [id, deep])

const daemon = name ?? "your daemon"

const forget = async () => {
await forgetPairing(id)
window.location.replace("/pair")
}

switch (view.state) {
case "loading":
case "connecting":
case "closed":
return (
<PairShell eyebrow="paired · connecting" title={`Connecting to ${daemon}…`} tone="warn">
{fingerprint && <Fingerprint value={fingerprint} />}
<p>Opening the end-to-end tunnel through the rendezvous. The Control Center loads from the daemon itself.</p>
</PairShell>
)

case "open":
return (
<PairShell eyebrow="connected" title={`Connected to ${daemon}`} tone="ok">
<p>Opening the Control Center…</p>
</PairShell>
)

case "offline":
return (
<PairShell eyebrow="daemon offline · retrying" title={`${daemon} is unreachable`} tone="danger">
<p>
Retrying on its own. Check that the computer is awake and the daemon is running (
<code>agentproto serve</code>).
</p>
{view.error && <p className="break-words font-mono text-xs">{view.error.message}</p>}
<PairButton
variant="secondary"
onClick={() => regRef.current && postToWorker(regRef.current, { type: "agentproto-pair:reconnect" })}
>
Retry now
</PairButton>
</PairShell>
)

case "revoked":
return (
<PairShell eyebrow="revoked" title={`This phone was unpaired from ${daemon}`} tone="danger">
<p>The daemon revoked this device, so it can&apos;t reconnect. To use it again, pair from a new QR.</p>
<HowToPair />
<PairButton variant="danger" onClick={() => void forget()}>
Forget this daemon
</PairButton>
</PairShell>
)

case "outdated":
return (
<PairShell eyebrow="not paired · outdated pairing" title="Pair this phone again" tone="danger">
<p>
This phone was paired with {daemon} using an older pairing protocol, which the daemon no longer
accepts. Make sure agentproto is up to date on the computer, then pair again from a new QR.
</p>
<HowToPair />
<PairButton variant="danger" onClick={() => void forget()}>
Forget the old pairing
</PairButton>
</PairShell>
)

case "not_paired":
if (originOwner) {
return (
<PairShell eyebrow="wrong address" title="This address serves another daemon" tone="danger">
<p>
This address belongs to daemon <code>{originOwner}</code> only. Daemon <code>{id}</code> has its own:
</p>
<a
href={`${daemonOrigin(id, window.location)}/d/${id}`}
className="flex min-h-11 items-center justify-center rounded-md bg-fd-primary px-4 text-sm font-medium text-fd-primary-foreground hover:opacity-90"
>
Open {id}.{PAIR_DOMAIN}
</a>
</PairShell>
)
}
return (
<PairShell eyebrow="not paired" title="This phone isn't paired with that daemon">
<HowToPair />
<PairButton variant="secondary" onClick={() => window.location.assign("/pair")}>
See paired daemons
</PairButton>
</PairShell>
)

case "error":
return (
<PairShell eyebrow="error" title="Couldn't start the Control Center" tone="danger">
<p className="break-words font-mono text-xs">{view.error.message}</p>
</PairShell>
)
}
}
13 changes: 13 additions & 0 deletions src/app/d/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { Metadata, Viewport } from "next"
import { pairMetadata, pairViewport } from "@/components/pair-shell"

export const viewport: Viewport = pairViewport

export const metadata: Metadata = { ...pairMetadata, title: "Control Center" }

/** `/d/<id>` is the status page for one paired daemon. Everything under
* `/d/<id>/` is answered by that pairing's service worker; these routes only
* render when it isn't in control yet (see src/lib/pair.ts). */
export default function DaemonLayout({ children }: { children: React.ReactNode }): React.ReactElement {
return <>{children}</>
}
10 changes: 10 additions & 0 deletions src/app/pair/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { Metadata, Viewport } from "next"
import { pairMetadata, pairViewport } from "@/components/pair-shell"

export const viewport: Viewport = pairViewport

export const metadata: Metadata = { ...pairMetadata, title: "Pair a phone" }

export default function PairLayout({ children }: { children: React.ReactNode }): React.ReactElement {
return <>{children}</>
}
Loading
Loading