# Uncage documentation (all pages) > Source: https://uncage.vercel.app/docs/ · Index: https://uncage.vercel.app/docs/llms.txt · Generated API reference: https://uncage.vercel.app/docs/api/hub/ and siblings. # Uncage > Let your website drive Claude Code on your users’ own computers. The work happens on their machine; the conversation, the approvals and the results stay on your site. ## What Uncage is Uncage is a set of npm packages that put Claude Code (and Codex) behind your own web UI, with approvals, streaming, Stop and reload-safe history. It has two modes. Both use the same protocol, the same React hooks and the same `` UI. | | **Connected Mode** (new in 0.2) | **Local Mode** | | --- | --- | --- | | Who runs the agent | Each end user, on their own computer, with their own Claude Code login | You, on the machine that runs your app | | What you add to your site | `@uncage/hub` in your Node backend, `` in a page, an approval page at `/device` | A same-origin proxy route and `` | | What the user does | Runs one command once and approves the computer in the browser: `curl -fsSL https://your.site/api/uncage/install.sh \| bash` on macOS and Linux, `irm https://your.site/api/uncage/install.ps1 \| iex` on Windows | Nothing: it is your machine | | Good for | SaaS products where users have Claude Code and want it to work with your product | Internal tools, desktop-style apps, developer dashboards | ## What your users get - A chat on your website that drives **their** Claude Code. Nothing runs on your servers except your own code. - Live streaming of the answer and of every tool step. - **Allow / Deny** cards for commands, file edits and any of your tools that need confirmation. - Stop, attachments, model, effort and permission-mode pickers, and history that survives a reload. - With site storage on, the conversation stays readable on your site even when their computer is off. ## More entry points - **React Native apps** use `@uncage/client` and `@uncage/react` unchanged: streaming, approvals, photos, resume after background, approve a computer from a phone. - **Browser extensions** run `` in a side panel against your hub, with `trustedOrigins`. - **One agent, every site:** a user installs the agent once, and every site that embeds Uncage connects in one click. ## What you get as the website - **Site tools.** Declare a capability with `defineTool` (a name, a zod schema, a handler). Claude Code sees it as an MCP tool. The handler runs **in your backend, as the signed-in user**, and can pull files from the run’s workspace (`ctx.files.pull`). - **Skills.** Give Claude Code your house rules and templates as plain markdown. It loads them like any Claude Code skill. - **Per-run choice.** `selectManifest` picks the tools and skills for each run from the prompt and the user. - **Your auth, your storage, your scale.** `getUser(req)` plugs in your sign-in. Postgres and Redis adapters let the hub run on several nodes behind a load balancer. ## What Uncage never does - It never sends code or shell commands from your website to a user’s machine. The hub sends only data: tool names and schemas, skill text, and a fixed set of commands such as “start a run”. - It never shares one Claude login among users. Every machine uses its owner’s own Claude Code. - A website can never switch on “bypass permissions”. Only the user can, in a file on their own computer. See [the trust model](https://uncage.vercel.app/docs/concepts/trust-model.md) for the full list. ## Where to start - **Building a website?** Read [How it works](https://uncage.vercel.app/docs/start/how-it-works.md), then do the [Connected Mode quickstart](https://uncage.vercel.app/docs/start/quickstart-connected.md) (about 15 minutes). - **The agent runs on the same machine as your app?** The [Local Mode quickstart](https://uncage.vercel.app/docs/start/quickstart-local.md) takes 5 minutes. - **Building a mobile app or a browser extension?** [React Native apps](https://uncage.vercel.app/docs/guides/react-native.md) and [browser extensions](https://uncage.vercel.app/docs/guides/browser-extension.md) are more entry points to the same hub, with [app sign-in](https://uncage.vercel.app/docs/guides/authenticate-apps.md) and [push notifications](https://uncage.vercel.app/docs/guides/push-notifications.md). - **Already use Uncage on your computer?** Other Uncage sites connect in [one click](https://uncage.vercel.app/docs/guides/one-click-connect.md), with an identity check and a local dashboard. - **Using a coding agent?** Give it [the Uncage skill](https://uncage.vercel.app/docs/skills/uncage/SKILL.md) or [`llms.txt`](https://uncage.vercel.app/docs/llms.txt). Every page is also available as plain markdown: add `.md` to its URL. See [For coding agents](https://uncage.vercel.app/docs/start/for-coding-agents.md). :::note[Status] Connected Mode is part of Uncage 0.4 (`@uncage/hub`, `@uncage/agent`, and the `uncage setup` / `uncage agent` commands in `@uncage/cli`). The agent side runs on **macOS, Linux and Windows** as a per-user background service, with Node.js 22 or newer (the installer sets it up). macOS is verified on a real device; Linux and Windows are CI verified, awaiting real-device confirmation. Claude Code is verified live; Codex is implemented but has not been run against a real binary, and it does not support site tools yet. Details: [compatibility](https://github.com/ptmafia/uncage/blob/main/docs/compatibility.md). ::: --- # How it works > The pieces of Connected Mode (browser, website with the hub, the user's computer with the agent), how computers connect (WebSocket or HTTP streaming), what happens when a user connects, sends a task, and Claude Code calls one of your tools, and what happens when something fails. Connected Mode has three places where code runs. Only one of them is yours to deploy. ```mermaid flowchart TB subgraph B["User's browser"] UI["Your pages
AgentChat · ConnectMachine"] end subgraph S["Your website (Node server or serverless functions)"] AUTH["Your sign-in
getUser(req)"] HUB["@uncage/hub
device login · routing
site tools · skills · replica"] DB[("HubStore
PGlite or Postgres")] CL[("ClusterAdapter
memory, Postgres or Redis")] end subgraph M["User's computer (macOS, Linux, Windows)"] AG["uncage agent
(background service)"] CORE["@uncage/core
local PGlite"] CC["Claude Code, Codex
or an ACP agent
user's own login"] WS["~/Uncage/site/session/"] end UI -- "HTTPS + SSE, same origin
/api/uncage/*" --> HUB HUB --- AUTH HUB --- DB HUB --- CL HUB <-- "outbound WSS or HTTPS streaming
/api/uncage/agent" --> AG AG --> CORE --> CC --> WS ``` - **The browser** talks only to your website, under `/api/uncage/*`, with the user’s normal session cookie. `` from `@uncage/react-ui` does this for you. - **Your website** mounts `@uncage/hub`, in a long-running Node process (traditional mode) or in serverless functions (FaaS mode, see [Choose a deployment mode](https://uncage.vercel.app/docs/start/choose-deployment-mode.md)). The hub does device login, keeps every connected computer reachable, routes browser requests to the right computer, runs your site tools, and (optionally) keeps a copy of every conversation. - **The user’s computer** runs `uncage agent`, a per-user background service installed by `uncage setup`. It dials **out** to your hub (WebSocket or HTTPS streaming, see [below](#how-a-computer-connects)), so the user needs no public IP, port forwarding or tunnel. It runs the user’s coding agent through `@uncage/core`, the same engine as Local Mode, in a fresh folder per session: Claude Code, Codex, or any agent that speaks the [Agent Client Protocol](https://uncage.vercel.app/docs/guides/use-any-acp-agent.md) (Gemini CLI, OpenCode, …). ACP agents installed on the computer are found by themselves, from the ACP registry, and enabled only after they answer the protocol handshake; one that would be downloaded (`npx`, `uvx`) never runs until the user consents with `uncage runtimes enable `. The session’s source of truth is the user’s computer (its local PGlite database). The hub stores an index of sessions, and with `sessionStorage: 'site'` an append-only replica of their events. ## How a computer connects The hub offers one or two **transports**, and the agent picks one by itself. The developer only chooses where the hub runs. ```mermaid flowchart TD A["uncage agent starts
(or reconnects)"] --> I["GET /api/uncage/agent/info
→ protocol, minAgentVersion, transports"] I --> Q{"ws offered?"} Q -- "yes (traditional mode:
attachWebSocket runs)" --> W["WebSocket
wss://…/api/uncage/agent"] Q -- "no (FaaS mode)" --> H["HTTP streaming
POST /agent/connect
GET /agent/stream · POST /agent/events"] W -- "3 failed attempts
(a proxy blocks upgrades)" --> H H -- "every 30 min, if ws is offered:
try WebSocket again" --> W ``` - **WebSocket** (traditional mode). One connection carries everything both ways; the hub pushes commands at once and pings every 10 s. - **HTTP streaming** (FaaS mode, and the fallback in traditional mode). Downstream, the agent holds `GET /agent/stream?cursor=` open: the hub writes the computer’s commands to a durable **outbox** in its store, each with a sequence number, and streams them as NDJSON lines. Before the platform’s time limit (`stream.maxDurationMs`, 250 s by default) the hub ends the stream with a `rotate` line and the agent reopens it at once, with the cursor of the last line it processed. Upstream, the agent sends events, tool calls and file chunks with `POST /agent/events`, in batches of at most 1 MB; every message carries an idempotent id, so a retried POST is never applied twice. The stream polls the outbox every 300 ms while a run is active and backs off to 2 s when idle. Any function instance can serve any request: there is no state in memory. Either way the computer is **online** while its connection is live (WebSocket answering pings, or a stream open), and offline about 30 s after it goes silent. Routes and frames: [HTTP API → Agent transport](https://uncage.vercel.app/docs/reference/http-api.md#agent-transport-http-streaming). ## What happens, step by step ```mermaid sequenceDiagram autonumber actor U as User participant B as Browser participant H as Hub (your site) participant A as uncage agent participant C as Claude Code Note over U,A: Connect (once per computer) U->>A: curl …/install.sh | bash (or irm …/install.ps1 | iex), which runs uncage setup https://your.site A->>H: POST /device/code A-->>U: opens /device?code=ABCD-2345 in the browser U->>H: Approve (signed in, POST) A->>H: POST /device/token → machine token A->>H: connect: WSS, or HTTPS stream H-->>B: computer online Note over U,C: Task U->>B: "Build a landing page and publish it" B->>H: POST /sessions, POST /sessions/:id/runs H->>H: selectManifest → tools + skills for this run H->>A: startRun (prompt + manifest) A->>C: run in the session folder, site tools as MCP, skills in .claude/skills C-->>A: text, tool steps, approval requests A-->>H: events (numbered) H-->>B: SSE stream Note over U,C: Tool call C->>A: mcp__site__publish_asset({assetId, dir}) A-->>B: approval card (tool has requiresConfirmation) U->>B: Allow A->>H: tool_call H->>H: your handler(args, ctx) runs as the user H->>A: file pull of dir A-->>H: the files (at most 50 MiB) H-->>A: tool_result A->>C: tool result Note over U,C: Asset C-->>B: "Published" · run.completed H-->>B: your pages show the new asset ``` ### 1. Connect 1. Your page shows one command, for the user’s operating system. `` renders it from the hub (`GET /api/uncage/machines/install`) and starts on the tab of the visitor’s OS: ```sh curl -fsSL https://your.site/api/uncage/install.sh | bash # macOS, Linux irm https://your.site/api/uncage/install.ps1 | iex # Windows PowerShell ``` For a computer that already has the CLI, it also shows `uncage setup https://your.site`. 2. `install.sh` (macOS, Linux) and `install.ps1` (Windows) are fixed scripts served by the hub. They check the computer (OS, Node.js 22+, npm, an installed coding agent) and ask `[Y/n]` before each step they need: Node.js through the user’s own version manager when there is one (nvm, fnm, volta, …; never `sudo`, never admin rights, the default Node version is not changed without a yes), a user-owned npm folder if the global one is not writable, then `@uncage/cli`. They never install the coding agent itself; they point to Claude Code’s installer if none is found. At the end they offer to run `uncage setup` for this website. Details per OS: [Install on your computer](https://uncage.vercel.app/docs/start/install-on-your-computer.md). 3. `uncage setup` starts a device login. It gets an 8-character code (valid for 10 minutes) and opens `https://your.site/device?code=…`. 4. The user, signed in to your site, checks the code and clicks **Approve**. Your approval page calls `hub.approveDevice(code, user)`. This binds the computer to that user. 5. The CLI receives a **machine token** (random, one per computer and website), saves it in `~/.uncage/agent.yaml` (mode 0600), and installs the agent as a per-user background service (launchd on macOS, a systemd user service on Linux, a scheduled task on Windows) that runs the exact Node.js it was installed with. 6. The agent connects ([WebSocket or HTTP streaming](#how-a-computer-connects)). Your page switches from “Waiting for your computer…” to “Connected”. ### 2. Send a task 1. The user types in ``. The browser calls the hub’s browser API (the same shapes as the Local Mode daemon’s `/v1` API). 2. For every run, the hub calls your `selectManifest({ user, prompt, sessionId, runtime })` to pick the tools and skills this run may use. Without it, every registered tool and skill is offered. A runtime without site tool support (Codex) gets the skills only, and the session shows a `site_tools_unsupported` warning. (The Codex runtime receives the skills but does not use them yet.) 3. The hub sends `startRun` to the computer with the prompt and the **manifest**: the tools’ names, descriptions and JSON Schemas, and the skills’ text. No code. 4. The agent runs the session’s runtime in `~/Uncage///`. Site tools appear to Claude Code as `mcp__site__`. Skills are written to `.claude/skills//SKILL.md` in that folder (ACP agents get them as text in the first prompt). 5. Every event (text, tool steps, approvals, run state) is numbered and stored locally first, then sent to the hub and on to the browser over SSE. ### 3. Claude Code calls your tool 1. Claude Code calls `mcp__site__publish_asset`. If the tool has `requiresConfirmation: true`, the user first gets an approval card in your UI, even in `bypassPermissions` mode. 2. The agent sends a `tool_call` to the hub. The hub instance that receives it (the node holding the WebSocket, or whichever function instance gets the POST) runs the handler, after checking that the session belongs to this computer and its user, and that the tool was in the run’s manifest. 3. Your handler gets `ctx.user` (the session owner), `ctx.sessionId`, `ctx.runId`, `ctx.signal` and `ctx.files`. `ctx.files.pull('landing')` asks the agent for that folder of the session workspace. The agent refuses paths outside the workspace and never follows symlinks. 4. The handler’s return value goes back to Claude Code as the tool result. Every call, and its result, is recorded in the hub’s store. ### 4. The result lives on your site Your handler stored the files, so your own pages can show them. With `sessionStorage: 'site'` the conversation is replicated to your store too. Reload the page with the computer switched off and the whole process is still there; the composer says the computer is offline until it reconnects. ## When something fails | What happens | Result | | --- | --- | | A connection drops (network, proxy, a stream rotation) | Nothing is lost or done twice. The agent reconnects with its cursor; commands it has not processed are delivered again, and its own messages are re-sent with the same ids, which the hub deduplicates. A site tool call is stored with its result, so a re-sent call gets the stored result: **exactly once** (on FaaS platforms: when the hub is given the platform's `waitUntil`; see [Workers → FAQ](https://uncage.vercel.app/docs/deploy/cloudflare-workers.md#do-site-tools-run-exactly-once-on-workers)). Runs keep going on the computer meanwhile, and events backfill. | | The hub instance running a site tool handler is stopped (crash, deploy, platform time limit) | **At most once**: the call fails with “Site tool "" timed out on the website. Please try again.” once its lease ends (`toolTimeoutMs` + 10 s), and is never re-run by itself. Claude Code sees the error and usually tries again. Stored results are kept 24 h. | | The agent process on the computer crashes or restarts | Commands the hub delivered but the agent had not acknowledged yet are delivered again and run after the restart. A command it had acknowledged but not answered times out on the website (`commandTimeoutMs`, 30 s): the user retries. | | The computer goes offline | The website shows it offline within about 30 s. With `sessionStorage: 'site'` the history stays readable. | | An agent older than the hub’s `minAgentVersion` connects | Over WebSocket it is told to upgrade and does so itself. In FaaS mode the website shows “Agent update needed” with the command to run. | ## Where things are stored | What | Where | | --- | --- | | Machine token | Only in `~/.uncage/agent.yaml` on the user’s computer (mode 0600). The hub keeps a SHA-256 hash. | | Session data (truth) | The user’s computer, `~/.uncage/sites//data` (PGlite) | | Session workspace | `~/Uncage///` on the user’s computer | | Activity log | `~/.uncage/sites//activity.log` on the user’s computer (`uncage activity`) | | Machines, session index, tool-call audit, outbox | The hub’s `HubStore` (PGlite in traditional mode, Postgres for several nodes and FaaS mode) | | Conversation replica | The hub’s `HubStore`, only with `sessionStorage: 'site'` | | Files your tools pulled | Wherever your handler puts them | ## Next - [Choose a deployment mode](https://uncage.vercel.app/docs/start/choose-deployment-mode.md): traditional or FaaS. - [Connected Mode quickstart](https://uncage.vercel.app/docs/start/quickstart-connected.md): build all of this into a Next.js app. - [Concepts](https://uncage.vercel.app/docs/concepts.md): the vocabulary, one section per idea. - [Trust model](https://uncage.vercel.app/docs/concepts/trust-model.md): what a website can and cannot do on a user’s computer. --- # Choose a deployment mode > Traditional mode (a long-running Node process, zero dependencies, WebSocket) or FaaS mode (Vercel, Cloudflare Workers and other Fetch platforms, Postgres, HTTP streaming)? A comparison of dependencies, latency, cost and platforms, a decision flow, and when to switch. The hub (`@uncage/hub`) runs wherever your website runs. There are two ways to deploy it. They use the same hub, the same `createHub` options, the same site tools, skills and UI. Only three things differ: where the hub keeps its state, how users’ computers connect, and how you mount it. - **Traditional mode**: your website is a long-running Node process (a VM, a container, Railway, Fly.io, Render, your own server). The hub keeps its data in an embedded database folder and holds a WebSocket to every connected computer. Nothing else to install. - **FaaS mode**: your website runs as serverless functions or on a Fetch platform (Next.js on Vercel, Cloudflare Workers, Netlify, Deno Deploy, …). Function instances come and go, so the hub keeps everything in Postgres, and computers connect over **HTTP streaming**: a long request that the hub ends before the platform’s time limit and the agent reopens at once. You do not have to tell the users’ computers which mode you use. The agent asks the hub which transports it offers (`GET /agent/info`) and picks one by itself. ## Compare | | Traditional mode | FaaS mode | | --- | --- | --- | | **Where your site runs** | A long-running Node.js 22+ process | Serverless functions or a Fetch platform | | **Dependencies** | None: `pgliteHubStore` (embedded Postgres in a folder) and an in-memory cluster. Several nodes: Postgres + Redis | Postgres (`DATABASE_URL`). Redis optional | | **Computers connect over** | WebSocket (HTTP streaming is offered too, as a fallback) | HTTP streaming (`/agent/stream` + `/agent/events`) | | **Delay before a computer gets a command** | Immediate (pushed over the socket) | About 300 ms while a run is active; up to about 2 s after 30 s of quiet | | **Cost shape** | One always-on process, whatever the number of computers | Each online computer holds about **one continuous function invocation** (its stream, reopened every ~250 s), plus database polling (below) | | **Instances** | One by default; add nodes with Postgres + Redis | Always several (every function instance is a hub); no sticky sessions needed | | **Platform limits to plan for** | The proxy in front must pass WebSocket upgrades | Function duration (Vercel: 300 s by default), request body size (Vercel: about 4.5 MB), CPU time (Workers) | | **How you mount it** | `toNodeHandler(hub)` + `attachWebSocket(hub, server)` from `@uncage/hub/node` | `toNextHandlers(…)` (Next.js), `fetchOnce(…)` (Workers) or `hub.fetch(req)` | | **Guide** | [Node (traditional)](https://uncage.vercel.app/docs/deploy/node.md) | [Next.js on Vercel](https://uncage.vercel.app/docs/deploy/vercel.md), [Cloudflare Workers](https://uncage.vercel.app/docs/deploy/cloudflare-workers.md), [Other Fetch platforms](https://uncage.vercel.app/docs/deploy/other-fetch-platforms.md) | ## Decide ```mermaid flowchart TD Q{"Where does your website run?"} Q -- "A process that keeps running:
VM, Docker, Railway, Fly.io, Render" --> N["Traditional mode
Deploy → Node"] Q -- "Next.js on Vercel" --> V["FaaS mode
Deploy → Next.js on Vercel"] Q -- "Cloudflare Workers" --> W["FaaS mode
Deploy → Cloudflare Workers"] Q -- "Netlify, Deno Deploy, Bun,
another Fetch platform" --> O["FaaS mode
Deploy → Other Fetch platforms"] Q -- "Vercel without Next.js
(plain Vercel Functions)" --> O N --> R{"More than one node?"} R -- "yes" --> M["Postgres + Redis
Guides → Multi-node"] V --> C{"Many computers online all day,
or commands must arrive instantly?"} W --> C O --> C C -- "yes" --> T["Run the hub as a small Node service
on the same origin (traditional mode)"] C -- "no" --> F["Stay on FaaS mode"] ``` Rules of thumb: - **You already run a Node server**: traditional mode. It is the simplest and the fastest, and needs nothing new. - **Your site is on Vercel, Workers or another serverless platform**: FaaS mode. Add a Postgres database and you are done; no second service to run. - **Not sure yet**: start with whichever matches your site today. Switching later changes only the store, the cluster and a few lines of mounting code (see [switching later](#switching-later)). ## What FaaS mode costs FaaS platforms bill for the time your functions run, in one form or another. Vercel (Fluid compute) bills active CPU time plus the memory provisioned for as long as an instance runs, so an open stream that mostly waits costs memory-time but little CPU. Cloudflare Workers bills CPU time only. In FaaS mode: - **Each online computer keeps one request open**: its HTTP stream. The hub ends it after `stream.maxDurationMs` (250 s by default, below Vercel’s 300 s limit) and the agent reopens it at once. So a computer that stays online all day keeps a function instance busy all day, whether or not it does any work (on Vercel, several streams can share one instance). On Cloudflare Workers waiting for I/O does not count as CPU time. - **Each open stream polls its computer’s outbox** in Postgres: every 300 ms while something happened in the last 30 s or a run is active, backing off to every 2 s when idle (`polling: { activeMs, idleMs, activeWindowMs }`). Measured on Postgres 16: about **0.5 queries per second per idle computer** and **2.3 per second while a run is active**. - **`postgresCluster` polls too** (every 300 ms while busy, every 2 s when quiet, per instance), to pass wake-ups between instances. - **Your database never sleeps while a computer is online.** A scale-to-zero Postgres (Neon’s free tier, for example) stays awake as long as any stream or instance is polling. That is fine for a demo or a handful of users: the reference demo is designed to run on Vercel Hobby with a few computers online. It adds up when many computers stay online for hours. ### When to switch to traditional mode or add Redis - **Many computers online all day** (dozens or more): function hours grow with every online computer. A single Node process (traditional mode) holds thousands of idle WebSockets for the price of one small server. - **Commands must arrive instantly** (interactive tools where 300 ms to 2 s is noticeable): traditional mode pushes over WebSocket. - **Database load from polling**: add Redis (`cluster: redisCluster({ url })`). Wake-ups between instances then travel over Redis pub/sub instead of a polled table, which removes the cluster polling and delivers a command to an idle computer’s stream at once. The outbox polling of each open stream stays. - **Long site tool handlers** (minutes): FaaS functions have a time limit and every tool call runs inside one request. Run the hub where handlers can take as long as they need, or move the long work to a background job and return an id. You can also keep your site on Vercel and run only the hub as a small Node service on the **same origin** (your edge routes `/api/uncage/*` to it). See [Node → FAQ](https://uncage.vercel.app/docs/deploy/node.md#faq). ## What is the same in both modes - `createHub` options, `defineTool`, skills, `selectManifest`, `sessionStorage`, `getUser`, `` and the `/device` approval page. - **Guarantees.** A tool call runs **exactly once** when a connection drops (the call and its result are stored, ids are idempotent, the agent re-sends) (on FaaS platforms: when the hub is given the platform's `waitUntil`; see [Workers → FAQ](https://uncage.vercel.app/docs/deploy/cloudflare-workers.md#do-site-tools-run-exactly-once-on-workers)). If the instance running your handler is stopped mid-call (a crash, a deploy, a platform time limit), the call runs **at most once**: it fails with “Site tool "" timed out on the website. Please try again.” and is never re-run by itself. Events, approvals and file pulls are neither lost nor duplicated across drops, stream rotations and retries. Details: [Define tools → When connections drop](https://uncage.vercel.app/docs/guides/define-tools.md#when-connections-drop-or-instances-stop). - **Security.** Rate limits and failed-code counters are stored in the hub’s store, so every node and every function instance shares one count. ## Switching later Your tools, skills, sign-in and pages do not change. What changes: | From → to | Change | | --- | --- | | Traditional → FaaS | `store`: `pgliteHubStore` → `postgresHubStore`. Add `cluster: postgresCluster(…)` (or Redis). Mount with `toNextHandlers` / `fetchOnce` / `hub.fetch` instead of `toNodeHandler` + `attachWebSocket`. Set `stream.maxDurationMs` below the platform limit. | | FaaS → traditional | Mount with `toNodeHandler` + `attachWebSocket` in a Node server. Keep `postgresHubStore` (no data moves), or switch to `pgliteHubStore` for a single node. | Connected computers follow the switch by themselves when the database stays the same: the agent re-reads the offered transports. **A new database means new pairings**: computers paired with the old store are unknown to the new one and must run `uncage setup ` again. --- # Quickstart: Connected Mode > Add Uncage to a Next.js app so signed-in users can connect their own computer and drive their own Claude Code from your site, with one site tool. About 15 minutes. By the end of this page: - your Next.js app serves the Uncage hub at `/api/uncage`; - a page shows ``, which first offers “Connect your computer”; - `/device` is where users approve their computer; - Claude Code on the user’s computer can call one of your tools, `save_note`, which runs in your server as that user. You play both roles: the website developer, then the user who connects a computer. ## Copy prompt for your coding agent If you use Claude Code, Codex or another coding agent, paste this into it instead of following the steps by hand: ```text wrap Add Uncage Connected Mode to this Next.js (App Router) app, following https://uncage-dev.vercel.app/docs/start/quickstart-connected.md exactly. Read https://uncage-dev.vercel.app/docs/skills/uncage/SKILL.md first and follow its rules. 1. Install @uncage/hub, @uncage/react-ui and zod. 2. Create lib/auth.ts, lib/tools.ts, lib/uncage-hub.ts, lib/hub-registry.ts, server.ts, app/uncage/page.tsx, app/device/page.tsx, app/device/actions.ts, app/device/approve-page.tsx and the headers in next.config.ts, as on that page. 3. Wire lib/auth.ts to this app's existing sign-in (find how the app reads the current user). Do not keep the development user unless the app has no sign-in at all. 4. Change the "dev" and "start" scripts to run server.ts with node (Node.js 22.18 or newer), set "type": "module" in package.json and "allowImportingTsExtensions": true in tsconfig.json. 5. Add .uncage-hub/ to .gitignore. Verify: start the dev server, then curl -s http://localhost:3000/api/uncage/install.sh | head -3 prints the installer, and curl -sI http://localhost:3000/device shows the headers Content-Security-Policy: frame-ancestors 'none' and X-Frame-Options: DENY (no ?code=: unknown codes count as failed guesses and are rate limited). Report what you changed and anything you could not wire. ``` ## Before you start - **Website side:** a Next.js 16 app (App Router) that you run with Node. Node.js **22.18 or newer**, because the custom server below is a `.ts` file that Node runs directly. Starting fresh: `npx create-next-app@latest my-site` (TypeScript, App Router). - **User side (your own computer for this test):** Node.js 22+ (the installer below can set it up), and Claude Code installed and signed in: `npm i -g @anthropic-ai/claude-code`, then run `claude` once and type `/login`. macOS, Linux or Windows (macOS is verified on a real device; Linux and Windows are CI verified, awaiting real-device confirmation). :::note[Why a custom server] This quickstart uses **traditional mode**: the hub keeps a WebSocket open to every connected computer and stores its data in an embedded database folder, so you need nothing else. That takes a long-running Node process with access to the HTTP server, which Next.js route handlers alone do not give. Deploying to **Vercel** or another serverless platform instead? Use [Next.js on Vercel](https://uncage.vercel.app/docs/deploy/vercel.md) (a route handler and Postgres, no custom server). Which one: [Choose a deployment mode](https://uncage.vercel.app/docs/start/choose-deployment-mode.md). ::: ## 1. Install ```sh npm i @uncage/hub @uncage/react-ui zod ``` ## 2. Who is signed in The hub asks your app who the user is, on every browser request. For this quickstart, use a fixed development user. The [auth guide](https://uncage.vercel.app/docs/guides/auth-and-device-approval.md) shows how to connect a real sign-in. ```ts title="lib/auth.ts" /** * Replace both functions with your real sign-in before you deploy. * `userFromRequest` is used by the hub (a Fetch `Request`); `currentUser` by your pages. */ export async function userFromRequest(_req: Request): Promise { return developmentUser(); } export async function currentUser(): Promise { return developmentUser(); } function developmentUser(): HubUser { if (process.env.NODE_ENV === 'production') { throw new Error('lib/auth.ts still returns the development user: connect it to your sign-in.'); } return { id: 'dev-user', name: 'Developer' }; } ``` ## 3. Define a tool A site tool is a capability of your website that Claude Code can call. Its handler runs **in your server**, as the user who owns the session. The user’s computer only receives the name, the description and the JSON Schema generated from `input`. ```ts title="lib/tools.ts" /** Stand-in for your database. */ // Kept on globalThis: server.ts and Next.js pages load separate copies of this module, // so a plain module-level Map would look empty from a page that lists the notes. type Notes = Map>; const g = globalThis as typeof globalThis & { __demoNotes?: Notes }; const notes: Notes = (g.__demoNotes ??= new Map()); export const saveNote = defineTool({ name: 'save_note', description: 'Save a note to the signed-in user’s notes on the website. Returns the note id.', input: z.object({ title: z.string().min(1).max(120), text: z.string().min(1).max(10_000), }), handler: async ({ title, text }, ctx) => { const mine = notes.get(ctx.user.id) ?? []; const note = { id: `note_${mine.length + 1}`, title, text }; notes.set(ctx.user.id, [...mine, note]); return { saved: note.id }; }, }); export const tools: SiteTool[] = [saveNote]; ``` ## 4. Create the hub The hub is created once, by your custom server. Your pages need it too (the approval page calls it), but Next.js bundles page code separately, so the server hands the instance over through `globalThis`. ```ts title="lib/uncage-hub.ts" export async function createAppHub(): Promise { return createHub({ // The URL your users open. Also what `uncage setup ` is given. publicUrl: process.env.PUBLIC_URL ?? 'http://localhost:3000', getUser: userFromRequest, // The hub's own database: embedded Postgres in this folder (computers, sessions, tool calls). store: await pgliteHubStore({ dataDir: './.uncage-hub' }), tools, // Keep a copy of every conversation on the website (readable while the computer is off). sessionStorage: 'site', }); } ``` ```ts title="lib/hub-registry.ts" const KEY = Symbol.for('my-site.uncage-hub'); /** Called once by server.ts. */ export function publishHub(hub: Hub): void { (globalThis as Record)[KEY] = hub; } /** The hub server.ts created, for pages and Server Actions. */ export function getHub(): Hub { const hub = (globalThis as Record)[KEY] as Hub | undefined; if (!hub) throw new Error('The Uncage hub is not running: start the app with `node server.ts`, not `next dev`.'); return hub; } ``` `pgliteHubStore` keeps the hub’s data in `./.uncage-hub` (embedded PGlite, one process per folder). Add that folder to `.gitignore`, and keep it on a persistent disk when you deploy. ## 5. The custom server One Node HTTP server carries everything: the hub’s HTTP API under `/api/uncage`, the computers’ WebSockets at `/api/uncage/agent`, and the Next.js app for every other path. `toNodeHandler` and `attachWebSocket` come from `@uncage/hub/node`, the Node-only part of the hub. ```ts title="server.ts" const dev = process.env.NODE_ENV !== 'production'; // If you change PORT, also set PUBLIC_URL (lib/uncage-hub.ts) to the URL users open. const port = Number(process.env.PORT ?? 3000); const hub = await createAppHub(); publishHub(hub); const hubHandler = toNodeHandler(hub); const server = createServer(); const app = next({ dev, hostname: 'localhost', port, httpServer: server }); const handle = app.getRequestHandler(); await app.prepare(); server.on('request', (req, res) => { // Paths under /api/uncage go to the hub; everything else falls through to Next.js. hubHandler(req, res, () => void handle(req, res)); }); attachWebSocket(hub, server); // computers connect to ws(s):///api/uncage/agent if (dev) { // Next.js hot reload uses WebSockets too; leave the hub's path to the hub. const upgrade = app.getUpgradeHandler(); server.on('upgrade', (req, socket, head) => { if ((req.url ?? '').split('?')[0] !== `${hub.basePath}/agent`) void upgrade(req, socket, head); }); } server.on('error', (err: NodeJS.ErrnoException) => { // Exit (and release ./.uncage-hub) instead of lingering when the port is taken. if (err.code === 'EADDRINUSE') console.error(`Port ${port} is in use: set PORT (and PUBLIC_URL).`); else console.error(err); process.exit(1); }); server.listen(port, () => console.log(`ready on http://localhost:${port}`)); ``` Run it with Node instead of `next dev`. Node runs `server.ts` directly (it strips the types), and the files it imports use explicit `.ts` extensions, so: ```json title="package.json (excerpt)" { "type": "module", "scripts": { "dev": "node server.ts", "build": "next build", "start": "NODE_ENV=production node server.ts" } } ``` ```json title="tsconfig.json (excerpt)" { "compilerOptions": { "allowImportingTsExtensions": true } } ``` ## 6. The chat page `` talks to `/api/uncage` by default. It notices that this is a hub (not a local daemon) and switches to Connected Mode by itself: with no computer yet, it shows `` with the one-command installer; afterwards, the header shows which computer the conversation runs on. ```tsx title="app/uncage/page.tsx" 'use client'; export default function UncagePage() { return (
); } ``` ## 7. The approval page `uncage setup` sends the user to `/device?code=…` on your site. Approving there gives that computer access to the user’s account, so the page must be served only to the signed-in user, must not be framable, and must record the decision with a POST that only your own origin can send. Next.js Server Actions are POST-only and check the `Origin`, which covers the last point. A code from the link is never trusted on its own: `` shows the request time and IP and asks for the code’s last 4 characters ([phishing links](https://uncage.vercel.app/docs/guides/auth-and-device-approval.md#phishing-links)). ```tsx title="app/device/page.tsx" export const dynamic = 'force-dynamic'; type DeviceError = NonNullable; export default async function DevicePage({ searchParams }: { searchParams: Promise<{ code?: string }> }) { const { code = '' } = await searchParams; const user = await currentUser(); if (!user) return

Sign in first, then open this link again.

; // or redirect to your login page let lookup: ApproveDeviceProps['lookup'] = null; let error: DeviceError | undefined; try { lookup = code ? await getHub().lookupDevice(code, user) : null; } catch (e) { // Unknown codes count as failed guesses; after 10 in 10 minutes lookupDevice throws `rate_limited`. // shows the error, localized, in place of "code not found". const err = e as { code?: string; message?: string }; error = { code: err.code === 'rate_limited' ? 'rate_limited' : 'internal_error', message: err.message ?? 'Could not check this code.' }; } return ; } ``` ```ts title="app/device/actions.ts" 'use server'; export type DecideResult = { result: 'ok' | 'not_found' | 'expired' } | { error: { code: string; message: string } }; /** A Server Action: a POST that Next.js only accepts from this site's own Origin. */ export async function decide(code: string, approve: boolean): Promise { const user = await currentUser(); if (!user) return { error: { code: 'unauthorized', message: 'Sign in again.' } }; try { const hub = getHub(); return { result: await (approve ? hub.approveDevice(code, user) : hub.denyDevice(code, user)) }; } catch (e) { const err = e as { code?: string; message?: string }; return { error: { code: err.code ?? 'internal_error', message: err.message ?? 'Failed' } }; } } ``` ```tsx title="app/device/approve-page.tsx" 'use client'; export function ApprovePage({ code, lookup, initialError, }: Pick & { initialError?: ApproveDeviceProps['error'] }) { const [state, setState] = useState('idle'); const [error, setError] = useState(initialError); const act = async (approve: boolean) => { setState(approve ? 'approving' : 'denying'); setError(undefined); const r = await decide(code, approve); if ('error' in r) { setState('idle'); // the buttons stay enabled for a retry setError(r.error as ApproveDeviceProps['error']); } else { setState(r.result === 'ok' ? (approve ? 'approved' : 'denied') : r.result); } }; return void act(true)} onDeny={() => void act(false)} />; } ``` Refuse framing for the approval page (and, simplest, for every page): :::caution[Replace the whole file] Recent `create-next-app` templates add `cacheComponents: true` to `next.config.ts`. It conflicts with `export const dynamic = 'force-dynamic'` on the `/device` page (`next build` fails with “Route segment config "dynamic" is not compatible with `nextConfig.cacheComponents`”). Replace the generated file with the one below instead of merging into it. ::: ```ts title="next.config.ts" const config: NextConfig = { async headers() { return [ { source: '/:path*', headers: [ { key: 'Content-Security-Policy', value: "frame-ancestors 'none'" }, { key: 'X-Frame-Options', value: 'DENY' }, ], }, ]; }, }; export default config; ``` ## 8. Run the website ```sh npm run dev ``` Check the hub answers: ```sh curl -s http://localhost:3000/api/uncage/install.sh | head -3 ``` It prints the start of the installer (`#!/usr/bin/env bash`, `# Uncage installer: …`). ## 9. Connect your computer (the user’s side) Open `http://localhost:3000/uncage`. The chat shows **Connect your computer** with one command, on the tab of your operating system. On a real deployment the user copies it. For this local test: 1. **Run the command.** On macOS or Linux, `curl -fsSL http://localhost:3000/api/uncage/install.sh | bash`; on Windows (PowerShell), `irm http://localhost:3000/api/uncage/install.ps1 | iex`. The installer checks the computer first (Node.js 22+, npm, a coding agent), asks `[Y/n]` before each step it needs (using your Node version manager if you have one; never `sudo` or admin rights), installs `@uncage/cli`, and offers to run `uncage setup http://localhost:3000` for you: answer **Y**. See [Install on your computer](https://uncage.vercel.app/docs/start/install-on-your-computer.md) for what it does on each OS. 2. **Already have the CLI** (`npm i -g @uncage/cli`)? Run the setup command the page shows under **Already have the CLI?** instead: ```sh uncage setup http://localhost:3000 ``` 3. **Approve.** Setup prints a code and opens `http://localhost:3000/device?code=…`. The page warns you never to approve a code someone sent you, and hides the code’s last 4 characters: type them from the terminal, then click **Approve**. Setup saves the machine token in `~/.uncage/agent.yaml` and starts the background agent (a per-user service: launchd on macOS, systemd on Linux, a scheduled task on Windows; `uncage agent status` shows it). Back on the chat page, the status changes from “Waiting for your computer…” to **Connected: <your computer’s name>**. :::tip[Plain http] The agent accepts `http://` only for `localhost` and `127.0.0.1`. Every other website must use `https://` (the WebSocket then uses `wss://`). ::: ## 10. Send a task Click the starter prompt, or type: “Write a short poem about this website and save it with save_note”. - Claude Code runs on your computer, in `~/Uncage/localhost-3000//`. - It calls `mcp__site__save_note`. The handler runs in your Next.js server as `dev-user`. - The answer streams into the chat. Commands and file edits show approval cards with **Allow once** / **Deny**. Stop the agent (`uncage agent uninstall`, or quit `uncage agent` if you ran it in the foreground) and reload the page: the conversation is still there (the URL keeps `?session=…`; it is also in the sidebar), because of `sessionStorage: 'site'`, and the composer says the computer is offline. ## What you built | File | Role | | --- | --- | | `lib/auth.ts` | Who is signed in (replace with your auth) | | `lib/tools.ts` | Your site tools | | `lib/uncage-hub.ts`, `lib/hub-registry.ts` | Creating the hub, sharing it with pages | | `server.ts` | One HTTP server: hub API, computer WebSockets, Next.js | | `app/uncage/page.tsx` | The chat | | `app/device/*`, `next.config.ts` | The approval page, safely | The repository’s [`examples/connected-demo`](https://github.com/ptmafia/uncage/tree/main/examples/connected-demo) is the same setup, grown into a full site: sign-in, two tools that create and publish a landing page (pulling the files from the user’s computer), a skill, an assets gallery, and a two-node mode with Redis and Postgres. It is tested end to end against real Claude Code. ## Next - [Define tools](https://uncage.vercel.app/docs/guides/define-tools.md): validation, errors, confirmation, the file channel. - [Write skills](https://uncage.vercel.app/docs/guides/write-skills.md) and [choose them per run](https://uncage.vercel.app/docs/guides/select-manifest.md). - [Auth and device approval](https://uncage.vercel.app/docs/guides/auth-and-device-approval.md): connect your real sign-in. - [Deploy](https://uncage.vercel.app/docs/deploy/node.md): put it on a server (traditional mode), or move to [Vercel](https://uncage.vercel.app/docs/deploy/vercel.md) (FaaS mode). - [Multi-node](https://uncage.vercel.app/docs/guides/multi-node.md): Postgres + Redis behind a load balancer. - **Before you deploy behind a proxy:** set the client IP (`trust proxy` or `rateLimits.clientIp`), or every user shares one `uncage setup` rate-limit bucket. See [behind a proxy](https://uncage.vercel.app/docs/guides/mount-the-hub.md#behind-a-reverse-proxy-or-load-balancer). --- # Quickstart: Local Mode > Run Claude Code on the machine that runs your app, behind a local daemon (uncage serve) and a same-origin proxy, with the ready-made chat UI. About 5 minutes. Local Mode is for apps that run on the **same machine** as the agent: a developer dashboard, an internal tool, a desktop-style app. The daemon `uncage serve` runs Claude Code under that machine’s Claude login; your app reaches it through a same-origin proxy that adds the daemon token on the server. If your users each have their own computer, use [Connected Mode](https://uncage.vercel.app/docs/start/quickstart-connected.md) instead. ## Copy prompt for your coding agent ```text wrap Add Uncage Local Mode to this Next.js (App Router) app, following https://uncage-dev.vercel.app/docs/start/quickstart-local.md exactly. 1. npm i @uncage/server @uncage/react-ui @uncage/cli 2. Create app/api/uncage/[...path]/route.ts with createUncageHandler from @uncage/server/proxy (runtime 'nodejs', dynamic 'force-dynamic', export GET, POST, PATCH). 3. Create a page that renders from @uncage/react-ui inside a full-height container, and import '@uncage/react-ui/styles.css'. Do not expose the daemon token to the browser and do not call the daemon from client code directly. Verify: run "npx uncage doctor" and report each line; with "npx uncage serve --workspace " running in another terminal and the app on http://localhost:3000, curl -s http://localhost:3000/api/uncage/runtimes returns a JSON array that contains "claude". ``` ## 1. Prerequisites - macOS, Linux or Windows, and Node.js **22 or newer** (`node -v`). `uncage serve` runs wherever the CLI does; macOS is verified on real devices, Linux and Windows are CI verified and await real-device confirmation. - Claude Code installed and signed in: `npm i -g @anthropic-ai/claude-code`, then run `claude` once and type `/login`. - A Next.js (App Router) app. Starting fresh: `npx create-next-app@latest my-app` (TypeScript, App Router). ## 2. Install ```sh npm i @uncage/server @uncage/react-ui @uncage/cli ``` ## 3. Add two files The route handler is a same-origin proxy. It reads the daemon token on the server, so the token never reaches the browser. ```ts title="app/api/uncage/[...path]/route.ts" export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; export const { GET, POST, PATCH } = createUncageHandler(); ``` ```tsx title="app/page.tsx" 'use client'; export default function Page() { return (
); } ``` `locale` is `'en'` (the default) or `'zh-CN'`. ## 4. Start the daemon Leave it running in its own terminal: ```sh npx uncage serve --workspace /absolute/path/to/the/project/the/agent/works/in ``` `--workspace` is the folder the agent reads and edits. On first start the daemon creates `~/.uncage/token` (mode 600) and `~/.uncage/data`, then prints: ```text Uncage listening on http://127.0.0.1:4783 · workspace /…/project · runtimes: claude ✓, codex ✗ (not installed) ``` Check everything with `npx uncage doctor`. Every line is ✓ or ✗, and every ✗ prints the exact `fix:` command. Codex showing “not installed” is fine; it is optional. ## 5. Run your app ```sh npm run dev ``` Open `http://localhost:3000`, pick **Claude Code**, and ask something like “Scan this repo and run the tests”. - Commands and file edits show an approval card: **Allow once** / **Deny**. - **Stop** cancels the run and kills its processes. - Refresh any time: `` keeps the open conversation in `?session=`, so history and pending approvals come back. ## How it fits together ```mermaid flowchart LR B["Browser
AgentChat"] -- "/api/uncage/*
same origin" --> P["Your app's server
createUncageHandler"] P -- "Bearer token
127.0.0.1:4783" --> D["uncage serve
daemon"] D --> C["Claude Code
this machine's login"] ``` The browser talks only to your app. Your app’s server forwards to the daemon on `127.0.0.1:4783` with the token. The daemon runs Claude Code on the same machine. It is not a multi-tenant cloud service: don’t expose it to the internet or share one Claude login among many users. ## Other frameworks - **Fetch-style servers** (Remix / React Router, SvelteKit, Hono, Bun): `createUncageHandler()` returns standard `(Request) => Promise` handlers. Mount them under `/api/uncage/*` (or pass `basePath`). - **Express, Connect, Fastify, `node:http`**: use `createUncageNodeHandler()` from `@uncage/server/proxy`, mounted before any body parser: ```ts title="server.ts (Express)" const app = express(); app.use('/api/uncage', createUncageNodeHandler()); // before express.json() and compression() app.listen(3000); ``` - **A Vite or webpack SPA with a separate backend**: keep the browser’s `Host` in the dev proxy (`changeOrigin: false`). With `changeOrigin: true` every POST gets 403 `forbidden_origin`, because the proxy compares `Origin` with the rewritten `Host`. [Local Mode in depth](https://uncage.vercel.app/docs/reference/local-mode.md) covers the composer, attachments, configuration (`uncage.config.yaml`) and the Local Mode security model. The [CLI reference](https://uncage.vercel.app/docs/reference/cli.md) lists every flag. ## Next - [Custom UI with hooks](https://uncage.vercel.app/docs/guides/custom-ui.md): build your own chat with `@uncage/react`. - [Troubleshooting](https://uncage.vercel.app/docs/reference/troubleshooting.md): `forbidden_origin`, ports, sign-in. --- # Try the demo > Connect your own computer (macOS, Linux or Windows) to a live Uncage site with one command, ask for a landing page, and watch your own Claude Code build it and publish it through the site's tools, with approval cards in the browser. The demo is a small website built with Uncage (the [`connected-demo` example](https://github.com/ptmafia/uncage/tree/main/examples/connected-demo)). You connect your own computer to it and ask for a landing page. Your own Claude Code builds the page on your computer and publishes it to the site through the site's tools, and you approve the steps in the browser. It takes about five minutes. The demo's interface is in Chinese. This page gives each label with its meaning, for example **允许执行** (Allow once). ## Before you start - A computer with macOS, Linux or Windows. Node.js 22 is not needed up front: the command below installs it if it is missing. - Claude Code installed and signed in: `curl -fsSL https://claude.ai/install.sh | bash` (macOS, Linux) or `irm https://claude.ai/install.ps1 | iex` (Windows PowerShell), then run `claude` once and type `/login`. ## Sign in as a guest Open the demo and click **以访客身份进入** (Enter as a guest). The site gives this browser a random guest account; there is nothing to sign up for. The chat then shows **连接你的电脑** (Connect your computer) with one command, on the tab of your operating system. *(Screenshot: The demo's chat with the card 连接你的电脑: under 在你的电脑上运行这条命令 (Run this command on your computer), the tabs macOS / Linux and Windows and the curl command with the demo's address; below it, 已经装好 CLI? (Already have the CLI?) with the uncage setup command, and a line saying it is waiting for the computer to come online.)* ## Connect your computer In a terminal (PowerShell on Windows), run the command the card shows, with the demo's address in place of ``: ```sh curl -fsSL /api/uncage/install.sh | bash # macOS, Linux irm /api/uncage/install.ps1 | iex # Windows PowerShell ``` It checks your computer and asks `[Y/n]` before installing anything that is missing (Node.js 22, the Uncage CLI); see [Install on your computer](https://uncage.vercel.app/docs/start/install-on-your-computer.md). At the end, answer **Y** to run `uncage setup` for the demo. Already have the CLI? Run `uncage setup ` instead. Setup prints a code and opens the demo's approval page in your browser. *(Screenshot: The approval page 连接这台电脑? names the computer asking to connect, shows the 验证码 (verification code) in large letters, and offers 拒绝 (Deny) and 批准 (Approve).)* *Check that the **验证码** (verification code) matches the one in your terminal, then click **批准** (Approve). The chat shows your computer's name with a green dot: it is online.* ## Ask for a landing page Send, for example, 「做一个介绍 Uncage 的落地页并发布」 ("build a landing page about Uncage and publish it"). Claude Code runs on your computer, under your own login, in a folder of its own under `~/Uncage/`. It loads the site's `landing-page` skill, calls the site tool `create_asset`, writes the page, and then asks to run `publish_asset`. *(Screenshot: The chat while the run is going: the steps Skill and mcp__site__create_asset with check marks, and Claude Code thinking about the next step.)* *The steps appear in the chat as they happen. `mcp__site__create_asset` is the site's tool: it runs on the site's server, as your guest account, and needs no question.* Claude Code asks before steps that its permission mode does not allow on its own (the composer shows **每次询问**, Ask every time), such as running a command or writing a file. `publish_asset` is defined with `requiresConfirmation`, so the site asks before every call, in every mode. Each question is an approval card, and the run waits until you answer. *(Screenshot: An approval card for mcp__site__publish_asset, showing the call publish_asset with the asset ID and the folder landing, the working folder, and the buttons 拒绝 (Deny) and 允许执行 (Allow once).)* *The approval card for `publish_asset`. Click **允许执行** (Allow once) or **拒绝** (Deny). After **允许执行**, the site copies the page's folder from your computer and publishes it. Steps such as a command or a file write get the same kind of card.* *(Screenshot: The finished conversation: Claude Code's summary says the landing page is published at /assets, and describes the page's hero, features, how to start and closing sections, with 完成 (Done) and the time taken below.)* *When the run is done, Claude Code summarizes what it built. The site's `landing-page` skill gives it the facts about Uncage to build from.* ## See the result on the site Open **素材** (Assets, `/assets`). The published page is listed there; click it to see it in a sandboxed preview. The page lives on the website, not on your computer, and only you can open it. *(Screenshot: The 素材 (Assets) page lists one landing page with the badge 已发布 (Published).)* *(Screenshot: The asset's page in the sandboxed preview: a dark landing page headed 让网站驱动你自己的 Claude Code (Let your website drive your own Claude Code), with the badge 已发布 (Published).)* Now close the lid, or stop the agent (`uncage agent uninstall` stops the background agent). The conversation stays readable, because the site keeps it, and the computer in the header turns offline. Run `uncage agent` to bring it back. *(Screenshot: The end of the finished conversation, with a notice that the computer is offline and waiting to reconnect, which says to run uncage agent on that computer.)* *The notice reads "你的电脑离线了,等待重新连接…" (Your computer is offline, waiting to reconnect).* ## About your data - You are signed in to the demo as a guest, identified by the browser you use. Another browser sees none of your conversations or pages. - The demo is public and shared. Running on a single server without a persistent volume, all of its data is cleared on every deploy and restart; on Vercel it is kept in Postgres. Either way, assets (the pages you create) are removed 24 hours after they were last created or published. - Requests for a published page are owner-only: only your guest account can open it. The files the page loads are guarded by the page's unguessable ID. - Do not put anything private in the demo. To disconnect your computer when you are done, run `uncage sites` to list the sites it is connected to and `uncage sites remove ` with the demo's ID to remove it. See the [CLI reference](https://uncage.vercel.app/docs/reference/cli.md). ## Run the demo yourself The demo's source is an ordinary Uncage Connected Mode site with two entry points over the same tools, skills and pages: `server.ts` for traditional mode (one Node process, for example on Railway) and a Next.js route handler for FaaS mode (Vercel, with Postgres). To run it on your own machine, follow [the example's README](https://github.com/ptmafia/uncage/tree/main/examples/connected-demo#run-it-single-node). To build your own, continue with [Quickstart: Connected Mode](https://uncage.vercel.app/docs/start/quickstart-connected.md), and see [Choose a deployment mode](https://uncage.vercel.app/docs/start/choose-deployment-mode.md) for where to host it. --- # Install on your computer > The one command a website shows to connect your computer, on macOS, Linux and Windows. What it checks and installs, which Node.js version managers it uses, the background service, flags, non-interactive runs, manual install and uninstall. A website built with Uncage shows one command to connect your computer. The command checks the computer and asks `[Y/n]` before each thing it installs: Node.js 22 (with your own version manager when you have one), then the Uncage CLI. It lists the coding agents it finds and then offers to run `uncage setup` for that website, which opens the browser so you can approve the computer. It never uses `sudo` or admin rights, and it never changes your default Node.js unless you say yes. One-click connect to more sites needs `@uncage/cli` 0.4 or newer. If you installed 0.3, run `npm i -g @uncage/cli@latest` and then `uncage agent install` (or `uncage setup`) again: that is the only place the `uncage://` handler is registered. The examples use `https://your.site`; copy the command the website shows, which has its own address. ## macOS ```sh curl -fsSL https://your.site/api/uncage/install.sh | bash ``` Run it in Terminal. The answers come from your keyboard even though the script arrives through a pipe. ### What it checks and installs 1. **The computer.** macOS on Apple silicon or Intel. Anything else stops with exit code 3. 2. **Node.js 22 or newer.** If `node` is older or missing, it installs Node.js 22 with the first version manager it finds (see the table below). Without one, it uses Homebrew (`brew install node@22`, which is keg-only and does not replace your `node`), and without Homebrew it installs fnm into `~/.local/share/fnm`. Then a separate question: “Use Node.js 22 as your default Node.js?” With **n**, your default stays as it is and the script uses Node.js 22 by its full path. 3. **npm’s global folder.** If it is not writable without `sudo`, the script offers to move it to `~/.npm-global` (never for an nvm Node, which does not allow it). 4. **The Uncage CLI.** `npm install -g @uncage/cli` with the version range the website asks for. 5. **Coding agents.** Claude Code, Codex and ACP agents that are installed. With none, it prints how to install Claude Code and stops; run the command again afterwards. 6. **Setup.** It offers to run `uncage setup https://your.site`. PATH changes go into one marked block (`# >>> uncage >>>` … `# <<< uncage <<<`) in the profile of your shell: `~/.zshrc` for zsh, `~/.bash_profile` for bash, `~/.profile` otherwise. For fish it prints the line to add. Open a new terminal afterwards. ### Version managers The first one found is used, in this order. Node.js 22 is installed without becoming the default; the default changes only after a separate yes. | Version manager | Installs Node.js 22 with | After “yes” to the default | | --- | --- | --- | | nvm | `nvm install 22` | `nvm alias default 22` | | fnm | `fnm install 22` | `fnm default 22` | | mise | `mise install node@22` | `mise use -g node@22` | | asdf | `asdf install nodejs latest:22` (adds the `nodejs` plugin if missing) | `asdf set -u nodejs ` (`asdf global` on asdf before 0.16) | | volta | `volta fetch node@22` | `volta install node@22` | | n | `n download 22` | `n 22` | volta is unmaintained upstream: an existing volta is used, but the script never installs it. nvm and fnm make the first version they install the default by themselves; when you answer **n**, the script undoes that. ### Background service `uncage setup` installs the agent as a launchd user agent (`~/Library/LaunchAgents/dev.uncage.agent.plist`). It starts at login and is restarted after a crash or a self-upgrade. It runs the exact Node.js it was installed with. `uncage agent status` shows it. A Homebrew upgrade (`brew upgrade node` or `node@22`) or removing an nvm / fnm version deletes that Node.js. `uncage doctor` then says so; run `uncage agent install` again. ### Uninstall ```sh uncage agent uninstall uncage sites remove npm uninstall -g @uncage/cli ``` `uncage sites` lists the ids. Then remove `~/.uncage` and `~/Uncage` if you no longer want the data and the session folders, and delete the `# >>> uncage >>>` block from your shell profile. Node.js stays; remove it with your version manager if you want. ## Linux ```sh curl -fsSL https://your.site/api/uncage/install.sh | bash ``` ### What it checks and installs The same steps as on macOS, on x64 and arm64. Without a version manager, it installs fnm into `~/.local/share/fnm`; fnm’s installer needs `curl` and `unzip`, and without `unzip` the script stops with the commands to run (it never calls your package manager). The PATH block goes into `~/.zshrc` for zsh, `~/.bashrc` for bash, `~/.profile` otherwise. ### Version managers The same order and commands as on macOS: nvm, fnm, mise, asdf, volta, n. There is no Homebrew fallback; without a version manager, fnm is installed in your home folder. | Version manager | Installs Node.js 22 with | After “yes” to the default | | --- | --- | --- | | nvm | `nvm install 22` | `nvm alias default 22` | | fnm | `fnm install 22` | `fnm default 22` | | mise | `mise install node@22` | `mise use -g node@22` | | asdf | `asdf install nodejs latest:22` | `asdf set -u nodejs ` | | volta | `volta fetch node@22` | `volta install node@22` | | n | `n download 22` | `n 22` | ### Background service `uncage setup` installs a systemd user service, `~/.config/systemd/user/uncage-agent.service` (`Restart=on-failure`), pinned to the Node.js it was installed with. `uncage agent status` shows it. A user service stops when you log out unless lingering is on. `uncage doctor` tells you; this keeps the agent running: ```sh loginctl enable-linger $USER ``` Without a user systemd (some containers and WSL setups), there is no service: run `uncage agent` in the foreground, for example in `tmux`. ### Uninstall ```sh uncage agent uninstall uncage sites remove npm uninstall -g @uncage/cli ``` Then remove `~/.uncage`, `~/Uncage` and the `# >>> uncage >>>` block from your shell profile if you want. ## Windows ```powershell irm https://your.site/api/uncage/install.ps1 | iex ``` Run it in PowerShell (Windows PowerShell 5.1 or PowerShell 7), as your normal user. ### What it checks and installs 1. **The computer.** Windows on x64 or arm64. 2. **Node.js 22 or newer**, with nvm-windows, fnm or volta when one is installed. Without one, it installs fnm for your user: with winget (`winget install --id Schniz.fnm`, a per-user package with no admin prompt), else from fnm’s release zip into `%LOCALAPPDATA%\fnm`. It never installs Node.js through winget, because that package asks for admin rights. Then the same “Use Node.js 22 as your default Node.js?” question. 3. **npm's global folder.** If it is not writable, the script offers to move it to `%USERPROFILE%\.npm-global`. 4. **The Uncage CLI.** `npm install -g @uncage/cli`. The script runs it as `uncage.cmd`. 5. **Coding agents**, then the offer to run `uncage setup`, as on macOS. Folders it adds to PATH go into your user `Path` (not your PowerShell profile). Open a new terminal afterwards. ### Version managers | Version manager | Installs Node.js 22 with | After “yes” to the default | | --- | --- | --- | | nvm-windows | `nvm install 22` | Not done by the script: switching needs admin rights, so it prints `nvm use 22` for you to run | | fnm | `fnm install 22` | `fnm default 22` | | volta | `volta fetch node@22` | `volta install node@22` | ### Background service `uncage setup` registers a scheduled task, `UncageAgent`, that starts the agent when you sign in: for your user only, with least privilege, and no admin prompt. If Task Scheduler refuses (“Access is denied”), it adds a `UncageAgent` entry under `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` instead. The task runs a small supervisor that restarts the agent after a crash or a self-upgrade. Logs are in `%USERPROFILE%\.uncage\logs`. `uncage agent status` shows which one is in use. ### Uninstall ```powershell uncage.cmd agent uninstall uncage.cmd sites remove npm uninstall -g @uncage/cli ``` Then remove `%USERPROFILE%\.uncage` and `%USERPROFILE%\Uncage` if you want. Folders the script added to your user `Path` can be removed in **Settings → System → About → Advanced system settings → Environment Variables**. ## Another site: one click Once `uncage setup` has installed the background agent, it also registers an `uncage://` link handler for your user (a small app on macOS, a `.desktop` file on Linux, a `HKCU` registry key on Windows; no admin rights). Any other Uncage site can then offer **Connect in one click**: the link opens a dialog on your computer that names the site’s domain and warns about look-alikes, and only after you press Connect does the usual approval start. No terminal and no second install. You can also run `uncage connect https://other.site` yourself, and `uncage dashboard` lists and disconnects every site. [Details](https://uncage.vercel.app/docs/guides/one-click-connect.md). `uncage agent uninstall` removes the handler. Run `uncage agent uninstall` before `npm uninstall -g @uncage/cli`: it removes the handler, and removing the CLI first leaves a dead one behind. ## Flags Pass flags after `bash -s --` on macOS and Linux: ```sh curl -fsSL https://your.site/api/uncage/install.sh | bash -s -- --yes ``` On Windows, run the script as a script block to pass parameters: ```powershell & ([scriptblock]::Create((irm https://your.site/api/uncage/install.ps1))) -Yes ``` | install.sh | install.ps1 | Environment | | | --- | --- | --- | --- | | `--yes`, `-y` | `-Yes` | `UNCAGE_YES=1` | Answer yes to every install step. The default Node.js still changes only when there was no Node.js at all. | | `--no-setup` | `-NoSetup` | `UNCAGE_NO_SETUP=1` | Install only; do not offer `uncage setup`. | | `--lang en\|zh\|ja` | `-Lang en\|zh\|ja` | `UNCAGE_LANG` | The language of the messages. By default, your system language. | The environment variables are the way to pass options through `irm … | iex`, which cannot take parameters. ## Non-interactive and CI Without a terminal to ask (a CI job, `ssh host 'curl … | bash'`), the script changes nothing unless you pass `--yes` (`-Yes`). It lists what is missing with the commands to run by hand and exits with code 2. | Exit code | Meaning | | --- | --- | | `0` | Done (also when you declined setup) | | `1` | A step failed; the reason and the command to run by hand are printed | | `2` | A confirmation was needed but there was no terminal; nothing was changed | | `3` | Unsupported operating system or processor | ## Manual install If you already have Node.js 22 or newer and npm, install the CLI yourself and run the setup command the website shows: ```sh npm i -g @uncage/cli uncage setup https://your.site ``` On Windows, use `uncage.cmd setup https://your.site` if PowerShell refuses to run `uncage` (see [Troubleshooting](https://uncage.vercel.app/docs/reference/troubleshooting.md#windows-running-scripts-is-disabled-on-this-system)). --- # For coding agents > How Claude Code, Codex and other coding agents should read this site, the skill to install, and ready-to-paste prompts for integrating Uncage. This site is written to be read by coding agents as well as people. Everything below is plain text that an agent can fetch. ## What to give your agent | Resource | URL | Use it for | | --- | --- | --- | | Uncage skill | [`/skills/uncage/SKILL.md`](https://uncage.vercel.app/docs/skills/uncage/SKILL.md) | “Integrate Uncage into a website”: when to use which mode, exact steps, verification commands, pitfalls. Install it as a skill, or paste its URL into the prompt. | | Index | [`/llms.txt`](https://uncage.vercel.app/docs/llms.txt) | One line per page, with its markdown URL ([llmstxt.org](https://llmstxt.org) format). | | Everything | [`/llms-full.txt`](https://uncage.vercel.app/docs/llms-full.txt) | All guide pages in reading order, in one markdown file (the generated API reference is linked, not included). | | Any page | add `.md` to its URL | For example `https://uncage-dev.vercel.app/docs/guides/define-tools.md`. The **View as Markdown** link at the top of every page goes there. | Links inside the markdown versions point to the markdown versions of other pages, so an agent can follow them without parsing HTML. ### Install the skill For Claude Code, put it in your project (or in `~/.claude/skills/` for every project): ```sh mkdir -p .claude/skills/uncage curl -fsSL https://uncage-dev.vercel.app/docs/skills/uncage/SKILL.md -o .claude/skills/uncage/SKILL.md ``` The same file is in the repository at [`skills/uncage/SKILL.md`](https://github.com/ptmafia/uncage/blob/main/skills/uncage/SKILL.md). ## Prompts Each quickstart starts with a **Copy prompt for your coding agent** block. Here they are together, plus common follow-ups. ### Pick the integration for this project Use this first when you do not know where the website will run. The skill tells the agent which page to follow for each platform. ```text wrap Add Uncage Connected Mode to this website. Read https://uncage-dev.vercel.app/docs/skills/uncage/SKILL.md and https://uncage-dev.vercel.app/docs/start/choose-deployment-mode.md first. Find out where this site runs (package.json scripts, vercel.json, wrangler.toml, netlify.toml, Dockerfile, Procfile, the hosting docs in the repo) and tell me which deployment mode fits and why: - a long-running Node server or container → traditional mode, https://uncage-dev.vercel.app/docs/deploy/node.md (or the Next.js custom server in https://uncage-dev.vercel.app/docs/start/quickstart-connected.md); - Next.js on Vercel → FaaS mode, https://uncage-dev.vercel.app/docs/deploy/vercel.md; - Cloudflare Workers → FaaS mode, https://uncage-dev.vercel.app/docs/deploy/cloudflare-workers.md; - another Fetch platform → FaaS mode, https://uncage-dev.vercel.app/docs/deploy/other-fetch-platforms.md. Then follow that page exactly, wire getUser to this app's existing sign-in, and run every item of its Verify checklist that can run locally. Report the mode you chose, the files you changed, the checklist output, and which environment variables I must set before deploying. ``` ### Add Connected Mode to a Next.js app The same prompt as on the [Connected Mode quickstart](https://uncage.vercel.app/docs/start/quickstart-connected.md#copy-prompt-for-your-coding-agent): ```text wrap Add Uncage Connected Mode to this Next.js (App Router) app, following https://uncage-dev.vercel.app/docs/start/quickstart-connected.md exactly. Read https://uncage-dev.vercel.app/docs/skills/uncage/SKILL.md first and follow its rules. 1. Install @uncage/hub, @uncage/react-ui and zod. 2. Create lib/auth.ts, lib/tools.ts, lib/uncage-hub.ts, lib/hub-registry.ts, server.ts, app/uncage/page.tsx, app/device/page.tsx, app/device/actions.ts, app/device/approve-page.tsx and the headers in next.config.ts, as on that page. 3. Wire lib/auth.ts to this app's existing sign-in (find how the app reads the current user). Do not keep the development user unless the app has no sign-in at all. 4. Change the "dev" and "start" scripts to run server.ts with node (Node.js 22.18 or newer), set "type": "module" in package.json and "allowImportingTsExtensions": true in tsconfig.json. 5. Add .uncage-hub/ to .gitignore. Verify: start the dev server, then curl -s http://localhost:3000/api/uncage/install.sh | head -3 prints the installer, and curl -sI http://localhost:3000/device shows the headers Content-Security-Policy: frame-ancestors 'none' and X-Frame-Options: DENY (no ?code=: unknown codes count as failed guesses and are rate limited). Report what you changed and anything you could not wire. ``` ### Add Connected Mode to a Next.js app on Vercel ```text wrap Add Uncage Connected Mode to this Next.js (App Router) app for Vercel (FaaS mode), following https://uncage-dev.vercel.app/docs/deploy/vercel.md exactly. Read https://uncage-dev.vercel.app/docs/skills/uncage/SKILL.md first and follow its rules. 1. npm i @uncage/hub @uncage/react-ui pg zod and npm i -D @types/pg. 2. Create lib/auth.ts, lib/uncage-hub.ts, app/api/uncage/[...path]/route.ts (toNextHandlers with waitUntil: after, maxDuration 300, dynamic 'force-dynamic', runtime 'nodejs'), app/uncage/page.tsx, app/device/page.tsx, app/device/actions.ts, app/device/approve-page.tsx, next.config.ts headers and vercel.json (the maintenance cron), as on that page. 3. Wire lib/auth.ts to this app's existing sign-in. Do not keep the development user unless the app has no sign-in at all. 4. Do not add a custom server, WebSocket code or @uncage/hub/node imports: on Vercel the hub runs in the route handler and needs only Postgres. Verify: with a local Postgres in DATABASE_URL, run next build && next start, then curl -s http://localhost:3000/api/uncage/agent/info shows a single "http" transport, and curl -sI http://localhost:3000/device shows Content-Security-Policy: frame-ancestors 'none'. List the environment variables to set on Vercel (DATABASE_URL, PUBLIC_URL, CRON_SECRET). Report what you changed. ``` ### Add Local Mode to a Next.js app ```text wrap Add Uncage Local Mode to this Next.js (App Router) app, following https://uncage-dev.vercel.app/docs/start/quickstart-local.md exactly. 1. npm i @uncage/server @uncage/react-ui @uncage/cli 2. Create app/api/uncage/[...path]/route.ts with createUncageHandler from @uncage/server/proxy (runtime 'nodejs', dynamic 'force-dynamic', export GET, POST, PATCH). 3. Create a page that renders from @uncage/react-ui inside a full-height container, and import '@uncage/react-ui/styles.css'. Do not expose the daemon token to the browser and do not call the daemon from client code directly. Verify: run "npx uncage doctor" and report each line; with "npx uncage serve --workspace " running in another terminal and the app on http://localhost:3000, curl -s http://localhost:3000/api/uncage/runtimes returns a JSON array that contains "claude". ``` ### Expose one of our features as a site tool ```text wrap Expose to Uncage as a site tool. Read https://uncage-dev.vercel.app/docs/guides/define-tools.md first. Use defineTool from @uncage/hub with a zod input schema and a description written for the model. Check ownership with ctx.user.id inside the handler. Throw only user-safe messages. Set requiresConfirmation: true if the tool changes or publishes anything. Add it to the hub's tools option and, if this app uses selectManifest, to the runs that need it. Add a unit test that calls the handler with a fake ctx. ``` ### Move the hub to several nodes ```text wrap Make our Uncage hub run on several nodes, following https://uncage-dev.vercel.app/docs/guides/multi-node.md. Use postgresHubStore with DATABASE_URL, and redisCluster with REDIS_URL (or postgresCluster on the same pool if we have no Redis); attach 'error' listeners to any pool or client we create ourselves; make sure the load balancer passes WebSocket upgrades on /api/uncage/agent and does not buffer streams; configure the client IP for rate limits. ``` ### Upgrade from Uncage 0.2 ```text wrap Upgrade this project's Uncage packages from 0.2 to 0.3, following https://uncage-dev.vercel.app/docs/reference/migrate-from-0-2.md. Update every @uncage/* package together. Import toNodeHandler, attachWebSocket and pgliteHubStore from @uncage/hub/node; replace hub.attach(server) with attachWebSocket(hub, server) and hub.handler with hub.fetch; pass an explicit store to createHub (pgliteHubStore with the data folder we used before, default ./.uncage-hub, so paired computers carry over) and close it after hub.close(). Verify: the project type-checks and builds, and curl -s http://localhost:3000/api/uncage/agent/info shows "protocol":2. ``` ## Rules of thumb for agents - **Pick the mount by platform.** Long-running Node server: `toNodeHandler(hub)` + `attachWebSocket(hub, server)` + `pgliteHubStore` from `@uncage/hub/node`. Next.js on Vercel: `toNextHandlers(getHub, { waitUntil: after })` + `postgresHubStore` + `postgresCluster`, no custom server. Cloudflare Workers: `fetchOnce` with a per-request pool. Anything else that speaks Fetch: `hub.fetch(req, { clientIp, waitUntil })`. Never import `@uncage/hub/node` in serverless or Worker code. [Choose a deployment mode](https://uncage.vercel.app/docs/start/choose-deployment-mode.md) explains the trade-offs. - **Names are exact.** Use the API names exactly as written on this site (`createHub`, `defineTool`, `toNodeHandler`, `attachWebSocket`, `toNextHandlers`, `fetchOnce`, `hub.fetch`, `selectManifest`, `sessionStorage`, `ctx.files.pull`). The [glossary](https://uncage.vercel.app/docs/reference/glossary.md) defines every term; the [generated API reference](https://uncage.vercel.app/docs/api/hub.md) has every signature. - **The user picks the coding agent.** Websites get whatever runtimes the user’s computer offers: Claude Code, Codex, and [ACP agents](https://uncage.vercel.app/docs/guides/use-any-acp-agent.md) (found from the ACP registry, enabled after a handshake, and run from `npx`/`uvx` only after the user’s `uncage runtimes enable`). Do not hard-code a runtime id where the runtime picker can choose. - **Code samples compile.** Every TypeScript sample on this site is type-checked against the current packages in CI. Files named in a sample’s title (`lib/tools.ts`) import each other with relative paths; a module that is not shown (such as your app’s `./auth`) is yours to write. - **Never add a way for the website to run shell commands on the user’s computer**, and never try to enable `bypassPermissions` from the website. Uncage refuses both by design ([trust model](https://uncage.vercel.app/docs/concepts/trust-model.md)). - **Check, don’t assume.** After an integration, run the verification commands from the skill and the quickstart and include their output in your report. --- # Node (traditional mode) > Deploy the hub in a long-running Node.js process with zero external dependencies (PGlite + WebSocket), behind a reverse proxy, with a complete server, environment variables, deploy steps, a verification checklist and an FAQ. Traditional mode is the hub inside a Node.js process that keeps running: a VM, a container, Railway, Fly.io, Render or your own server. It needs **no external service**: the hub keeps its data in an embedded Postgres (PGlite) folder, and users’ computers hold a WebSocket to it. Not sure this is your mode? See [Choose a deployment mode](https://uncage.vercel.app/docs/start/choose-deployment-mode.md). ## Prerequisites - Node.js **22.18 or newer**: it runs the `.ts` server below directly, without a build step (older versions need `--experimental-strip-types`, or compile with `tsc` first). - A host that keeps the process running and gives it a **persistent disk** for the hub’s data folder (`.uncage-hub`). Without one, every restart forgets the paired computers and users must run `uncage setup` again. - In front of it, a proxy or load balancer that forwards **WebSocket upgrades** on `/api/uncage/agent` (most hosts do by default) and serves `https://`. - Your app’s sign-in, readable from a Fetch `Request` (a session cookie). ```sh npm i @uncage/hub express ``` ## Code Two files. `auth.ts` stands for your sign-in; replace its body. ```ts title="auth.ts" /** Your sign-in: the user a request belongs to, or null. */ export async function getSessionUser(req: Request): Promise { const cookie = req.headers.get('cookie') ?? ''; // Look the session cookie up in your session store here. return cookie.includes('session=') ? { id: 'user-123', name: 'Ada' } : null; } ``` ```ts title="server.ts" const port = Number(process.env.PORT ?? 3000); // Embedded Postgres in a folder: one process per folder, kept across restarts. const store = await pgliteHubStore({ dataDir: process.env.UNCAGE_DATA_DIR ?? './.uncage-hub' }); const hub = await createHub({ publicUrl: process.env.PUBLIC_URL ?? `http://localhost:${port}`, getUser: getSessionUser, store, sessionStorage: 'site', // keep a copy of every conversation on your site }); const app = express(); if (process.env.TRUST_PROXY) app.set('trust proxy', Number(process.env.TRUST_PROXY)); // proxies in front: req.ip is the client app.use(toNodeHandler(hub)); // first, before express.json() or compression() app.use(express.json()); app.get('/', (_req, res) => { res.send('Your website'); }); const server = createServer(app); attachWebSocket(hub, server); // computers connect to ws(s):///api/uncage/agent server.listen(port, () => console.log(`ready on http://localhost:${port}`)); // On deploy or restart: stop taking requests, let running site tools finish, then close the store. process.once('SIGTERM', () => { server.close(); void hub .close() .then(() => store.close()) .finally(() => process.exit(0)); }); ``` What each piece does: - `toNodeHandler(hub)` serves everything under `/api/uncage` (the browser API, the device login, `install.sh` and `install.ps1`, and the HTTP streaming transport) and passes other paths to `next()`. It hands the hub `req.ip` for per-IP rate limits. - `attachWebSocket(hub, server)` accepts the computers’ WebSockets on the same HTTP server and runs the hub’s maintenance (retention cleanup) every minute. With it, the hub offers both transports: agents use WebSocket, and fall back to HTTP streaming by themselves if WebSockets keep failing (a proxy that blocks upgrades, for example). - `hub.close()` never closes your `store`: close it after the hub. Using Fastify, Hono or a Next.js custom server instead of Express? [Mount the hub](https://uncage.vercel.app/docs/guides/mount-the-hub.md) has a complete server for each. Next.js on its own: the [Connected Mode quickstart](https://uncage.vercel.app/docs/start/quickstart-connected.md) builds this setup into a Next.js app. ## Environment variables | Variable | Required | What it is | | --- | --- | --- | | `PUBLIC_URL` | yes, in production | The exact origin users open, for example `https://app.example.com`. It goes into the install and setup commands, so it must be `https://` (plain `http://` only for `localhost`). | | `PORT` | no | The port to listen on (default `3000`). | | `UNCAGE_DATA_DIR` | no | The hub’s PGlite folder (default `./.uncage-hub`). Put it on the persistent disk. Add it to `.gitignore`. | | `TRUST_PROXY` | behind a proxy | The number of proxies in front of the app, for `app.set('trust proxy', …)`. Without it, every user shares one rate-limit bucket (see the FAQ). | These names are this page’s choice; the hub itself reads no environment variables. ## Deploy 1. **Build and start** with `node server.ts` (Node 22.18+). In a container, for example: ```dockerfile title="Dockerfile" # Node 22.18 or newer runs server.ts directly (type stripping); node:22 is the latest 22.x. FROM node:22-slim WORKDIR /app COPY package*.json ./ RUN npm ci --omit=dev COPY . . ENV UNCAGE_DATA_DIR=/data/uncage-hub VOLUME /data EXPOSE 3000 CMD ["node", "server.ts"] ``` 2. **Give it a persistent volume** at the data folder (`/data` above). Railway, Fly.io and Render call it a volume or disk. 3. **Set `PUBLIC_URL`** to your `https://` origin, and `TRUST_PROXY=1` if a proxy or load balancer sits in front (it almost always does on a platform). 4. **Check the proxy** in front: - forwards WebSocket upgrades on `/api/uncage/agent`, with an idle timeout above 30 s (the hub pings every 10 s); - does not buffer `text/event-stream` responses (browser events) or `application/x-ndjson` ones (agent streams); - keeps the original `Host` header. nginx, for example: ```nginx title="nginx.conf (excerpt)" location / { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_buffering off; proxy_read_timeout 300s; } ``` 5. **Run one process per data folder.** PGlite locks its folder. For more than one process, see [Multi-node](https://uncage.vercel.app/docs/guides/multi-node.md). ## Verify Replace `https://your.site` with your `PUBLIC_URL`. - [ ] `curl -s https://your.site/api/uncage/install.sh | head -2` prints `#!/usr/bin/env bash` and `# Uncage installer…`. - [ ] `curl -s https://your.site/api/uncage/agent/info` lists **both** transports, `ws` first: ```json {"protocol":2,"minAgentVersion":"0.3.0","transports":[{"kind":"ws","url":"wss://your.site/api/uncage/agent"},{"kind":"http","url":"https://your.site/api/uncage/agent"}]} ``` Only `http`? `attachWebSocket` did not run in this process. - [ ] `curl -s -o /dev/null -w '%{http_code}\n' https://your.site/api/uncage/health` prints `401` (signed out). Signed in, the browser gets `{"ok":true,…}`. - [ ] On a computer, run the command your page shows (or `uncage setup https://your.site`), approve the code on `/device`, and the page shows the computer **online**. - [ ] Restart the server: the computer comes back online within about 30 s without a new `uncage setup` (the data folder survived). ## FAQ ### My site is on Vercel or Netlify. Can I still use traditional mode? Yes, as a separate service. Run this server on a host with WebSockets, and route `https://your.site/api/uncage/*` **including WebSocket upgrades** to it at your edge (a load balancer, Cloudflare, nginx in front of both), so it is the **same origin** as your site: the browser API relies on your site’s cookies and same-origin checks. Vercel rewrites do not proxy WebSockets (agents then fall back to HTTP streaming, which works but loses the instant delivery). In `getUser`, verify your site’s session cookie without your framework’s helpers (for example the signed JWT your auth library issues). Your `/device` approval page needs `hub.approveDevice`, which lives in this process: serve `/device` from it too, or expose a small authenticated, CSRF-protected endpoint your page calls. Often simpler: use [FaaS mode on Vercel](https://uncage.vercel.app/docs/deploy/vercel.md) directly. ### `uncage setup` fails with `429 rate_limited` for many users at once Behind a proxy the hub sees the proxy’s address unless told otherwise, so all users share one bucket of 20 device codes per minute. Set `TRUST_PROXY` (above), or pass `rateLimits: { clientIp: (req) => req.headers.get('x-real-ip') ?? undefined }` with your proxy’s client-IP header. Details: [behind a proxy](https://uncage.vercel.app/docs/guides/mount-the-hub.md#behind-a-reverse-proxy-or-load-balancer). ### The proxy blocks WebSockets. Does it still work? Yes. After three failed WebSocket attempts the agent switches to HTTP streaming (served by the same `toNodeHandler`) and tries WebSocket again every 30 minutes. Fix the proxy anyway: WebSocket delivers commands instantly and costs less. ### Can I use Postgres instead of PGlite? Yes: `store: await postgresHubStore({ connectionString: process.env.DATABASE_URL! })` (install `pg`). Do it when you want managed backups or more than one node. Pooled connection strings (PgBouncer, Neon `-pooler`) work: migrations use transaction-scoped locks. ### Do I need Redis? Not for one process. For several nodes, add `redisCluster` (or `postgresCluster`) as shown in [Multi-node](https://uncage.vercel.app/docs/guides/multi-node.md). ### A deploy restarted the server. What happened to running work? Computers reconnect by themselves (backoff from 1 s up to 30 s). Runs keep going on the users’ computers and their events backfill on reconnect. A site tool handler still running when the process stops fails with “Site tool "" timed out on the website. Please try again.”: `hub.close()` gives running handlers `toolDrainMs` (5 s) to finish first. ### Old agents (0.2) cannot connect The hub tells them to upgrade (`upgrade_required`) and 0.2 agents upgrade themselves with `npm i -g @uncage/cli@latest`. See [Troubleshooting](https://uncage.vercel.app/docs/reference/troubleshooting.md#agent-update-needed--426-upgrade_required). --- # Next.js on Vercel (FaaS mode) > Run the hub in a Next.js App Router route handler on Vercel with Postgres only — toNextHandlers with waitUntil after, maxDuration, the maintenance cron, Neon and pooled URLs — with complete files, environment variables, deploy steps, a verification checklist and an FAQ. On Vercel the hub runs inside a Next.js **route handler**: no custom server, no WebSocket, no second service. Every function instance is a hub; they share one Postgres database, and users’ computers connect over **HTTP streaming** (a long request the hub ends before Vercel’s time limit, reopened by the agent at once). The same files run under `next start` anywhere. Why FaaS mode, and what it costs: [Choose a deployment mode](https://uncage.vercel.app/docs/start/choose-deployment-mode.md). ## Prerequisites - A Next.js **15.1 or newer** app with the App Router (the files below use `after` from `next/server`), on Vercel. - A **Postgres** database reachable from Vercel: Neon, Supabase, Vercel’s Postgres integrations, or your own. Its connection string becomes `DATABASE_URL`. A pooled URL (Neon’s `-pooler` host, PgBouncer) is fine and recommended. - Your app’s sign-in, readable from a `Request` (the hub) and from `cookies()` (your pages). ```sh npm i @uncage/hub @uncage/react-ui pg zod npm i -D @types/pg ``` ## Code Seven files. Paths are relative to your project root. ### Who is signed in ```ts title="lib/auth.ts" /** * Replace both functions with your real sign-in before you deploy. * `userFromRequest` is used by the hub (a Fetch `Request`); `currentUser` by your pages. */ export async function userFromRequest(_req: Request): Promise { return developmentUser(); } export async function currentUser(): Promise { return developmentUser(); } function developmentUser(): HubUser { if (process.env.NODE_ENV === 'production') { throw new Error('lib/auth.ts still returns the development user: connect it to your sign-in.'); } return { id: 'dev-user', name: 'Developer' }; } ``` ### The hub One hub per function instance, created on the first request (so `next build` never connects to the database) and shared by the route handler and your pages. ```ts title="lib/uncage-hub.ts" async function createAppHub(): Promise { const url = process.env.DATABASE_URL; if (!url) throw new Error('DATABASE_URL is not set: add your Postgres connection string to the project’s environment variables.'); const publicUrl = process.env.PUBLIC_URL ?? (process.env.VERCEL ? undefined : 'http://localhost:3000'); if (!publicUrl) throw new Error('PUBLIC_URL is not set: add your site’s https:// origin to the project’s environment variables.'); // One small pool per function instance, shared by the store and the cluster. const pool = new pg.Pool({ connectionString: url, max: 5 }); pool.on('error', (err) => console.error('postgres pool error:', err.message)); // required for your own pool const store = await postgresHubStore({ pool }); return createHub({ publicUrl, // what users open; localhost only outside Vercel getUser: userFromRequest, store, cluster: postgresCluster({ pool }), // wake-ups between function instances, through Postgres sessionStorage: 'site', // End long responses (agent streams, browser events) before the route's maxDuration (300 s). stream: { maxDurationMs: 250_000 }, // A site tool runs inside one request: keep its limit well inside maxDuration. toolTimeoutMs: 120_000, // Enables GET /api/uncage/maintenance for Vercel Cron (it sends Authorization: Bearer $CRON_SECRET). ...(process.env.CRON_SECRET ? { maintenance: { secret: process.env.CRON_SECRET } } : {}), }); } const KEY = Symbol.for('my-site.uncage-hub'); type Holder = { [KEY]?: Promise }; /** The hub of this function instance. A failed start (database briefly down) is retried on the next call. */ export function getHub(): Promise { const g = globalThis as Holder; const hub = (g[KEY] ??= createAppHub()); hub.catch(() => { if (g[KEY] === hub) delete g[KEY]; }); return hub; } ``` ### The route handler ```ts title="app/api/uncage/[...path]/route.ts" // `after`: the hub's background work (maintenance) never delays a response. export const { GET, POST, PATCH, DELETE } = toNextHandlers(getHub, { waitUntil: after }); /** Seconds a request may run on Vercel. The hub ends its streams earlier (stream.maxDurationMs). */ export const maxDuration = 300; export const dynamic = 'force-dynamic'; export const runtime = 'nodejs'; ``` `toNextHandlers` passes each request to `hub.fetch` with: - **the client IP** for per-IP rate limits: on Vercel (the `VERCEL` environment variable is set) the address Vercel’s edge puts in `x-real-ip`, which clients cannot spoof there. Anywhere else, pass `clientIp: (req) => …` yourself; - **`waitUntil`**: Next's `after`, so maintenance runs after the response and a site tool call finishes even if the agent's request drops. ### The chat page ```tsx title="app/uncage/page.tsx" 'use client'; export default function UncagePage() { return (
); } ``` ### The approval page Where `uncage setup` sends the user to approve their computer. Signed-in only, never framed, decided with a Server Action (a POST that Next.js accepts only from your own origin). The same files as in the [quickstart](https://uncage.vercel.app/docs/start/quickstart-connected.md#7-the-approval-page), with `await getHub()`. ```tsx title="app/device/page.tsx" export const dynamic = 'force-dynamic'; type DeviceError = NonNullable; export default async function DevicePage({ searchParams }: { searchParams: Promise<{ code?: string }> }) { const { code = '' } = await searchParams; const user = await currentUser(); if (!user) return

Sign in first, then open this link again.

; // or redirect to your login page let lookup: ApproveDeviceProps['lookup'] = null; let error: DeviceError | undefined; try { lookup = code ? await (await getHub()).lookupDevice(code, user) : null; } catch (e) { // Unknown codes count as failed guesses; after 10 in 10 minutes lookupDevice throws `rate_limited`. const err = e as { code?: string; message?: string }; error = { code: err.code === 'rate_limited' ? 'rate_limited' : 'internal_error', message: err.message ?? 'Could not check this code.' }; } return ; } ``` ```ts title="app/device/actions.ts" 'use server'; export type DecideResult = { result: 'ok' | 'not_found' | 'expired' } | { error: { code: string; message: string } }; /** A Server Action: a POST that Next.js only accepts from this site's own Origin. */ export async function decide(code: string, approve: boolean): Promise { const user = await currentUser(); if (!user) return { error: { code: 'unauthorized', message: 'Sign in again.' } }; try { const hub = await getHub(); return { result: await (approve ? hub.approveDevice(code, user) : hub.denyDevice(code, user)) }; } catch (e) { const err = e as { code?: string; message?: string }; return { error: { code: err.code ?? 'internal_error', message: err.message ?? 'Failed' } }; } } ``` ```tsx title="app/device/approve-page.tsx" 'use client'; export function ApprovePage({ code, lookup, initialError, }: Pick & { initialError?: ApproveDeviceProps['error'] }) { const [state, setState] = useState('idle'); const [error, setError] = useState(initialError); const act = async (approve: boolean) => { setState(approve ? 'approving' : 'denying'); setError(undefined); const r = await decide(code, approve); if ('error' in r) { setState('idle'); // the buttons stay enabled for a retry setError(r.error as ApproveDeviceProps['error']); } else { setState(r.result === 'ok' ? (approve ? 'approved' : 'denied') : r.result); } }; return void act(true)} onDeny={() => void act(false)} />; } ``` ### Headers and the cron ```ts title="next.config.ts" const config: NextConfig = { async headers() { return [ { source: '/:path*', headers: [ { key: 'Content-Security-Policy', value: "frame-ancestors 'none'" }, { key: 'X-Frame-Options', value: 'DENY' }, ], }, ]; }, }; export default config; ``` ```json title="vercel.json" { "crons": [{ "path": "/api/uncage/maintenance", "schedule": "0 4 * * *" }] } ``` Maintenance (retention cleanup, failing tool calls whose instance died) also runs by itself on ordinary requests, at most once a minute across all instances, through `after`. The cron is a safety net for quiet periods. Vercel Hobby allows one run a day; Pro can run it hourly or more often. ## Environment variables Set them in the Vercel project (Settings → Environment Variables) for Production and Preview, and in `.env.local` for `next dev`. | Variable | Required | What it is | | --- | --- | --- | | `DATABASE_URL` | yes | Your Postgres connection string. Pooled URLs (Neon `-pooler`, PgBouncer in transaction mode) work. The hub creates its tables on the first request. | | `PUBLIC_URL` | yes | The exact origin users open, for example `https://app.example.com` (your production domain, not a preview URL). It goes into the install and setup commands. | | `CRON_SECRET` | recommended | A random string (`openssl rand -hex 32`). Vercel Cron sends it as `Authorization: Bearer …`; the hub’s `/maintenance` endpoint exists only when it is set. | | Your auth secrets | yes | Whatever `lib/auth.ts` needs. | ## Deploy 1. **Create the database.** For example Neon through the Vercel Marketplace (it sets `DATABASE_URL` for you), or any Postgres 14+. Pick a region close to your Vercel functions’ region: every poll is a round trip. 2. **Set the environment variables** above. 3. **Deploy**: push to the connected Git repository, or `npx vercel --prod`. 4. **Open your site** at `/uncage`, connect a computer, and work through the checklist below. To try it on your own machine first: `next build && next start` with a local Postgres (`docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=uncage postgres:16-alpine` and `DATABASE_URL=postgres://postgres:uncage@localhost:5432/postgres`). ## Verify Replace `https://your.site` with your `PUBLIC_URL`. - [ ] `curl -s https://your.site/api/uncage/agent/info` lists only the `http` transport: ```json {"protocol":2,"minAgentVersion":"0.3.0","transports":[{"kind":"http","url":"https://your.site/api/uncage/agent"}]} ``` - [ ] `curl -s https://your.site/api/uncage/install.sh | head -2` prints `#!/usr/bin/env bash` and `# Uncage installer…`. - [ ] `curl -s -o /dev/null -w '%{http_code}\n' https://your.site/api/uncage/maintenance` prints `401` (with `CRON_SECRET` set; `404` without). With the secret, `curl -s -H "Authorization: Bearer $CRON_SECRET" https://your.site/api/uncage/maintenance` answers `{"ran":true,…}` (or `"ran":false` if another instance ran it within the last minute). - [ ] Connect a computer from `/uncage` (the page shows the commands to run; approve the code on `/device`). It shows **online** within a few seconds. - [ ] Send a prompt. The answer streams. The agent’s log (`uncage agent` in a terminal, or `~/.uncage/logs/agent.log`) shows `http stream rotated` about every 250 s, and the chat keeps working across rotations. - [ ] Vercel’s function logs show no `504` on `/api/uncage/agent/stream`. Streams end with status 200 before 300 s. ## FAQ ### I see 504 errors (`FUNCTION_INVOCATION_TIMEOUT`) A request ran longer than `maxDuration`. Keep **`stream.maxDurationMs` below `maxDuration`**, with a margin of about 50 s: `maxDuration = 300` → `250_000` (the default). If you lower `maxDuration` (to 60, say), lower `stream.maxDurationMs` too (`10_000` less, at least). Pro plans may raise `maxDuration` to 800; you can raise `stream.maxDurationMs` with it, but there is little gain: a rotation costs one reconnect. ### `maxDuration` vs `stream.maxDurationMs` vs `toolTimeoutMs` - `maxDuration` (seconds, in `route.ts`) is Vercel’s hard limit for any request to the route. - `stream.maxDurationMs` is when the hub itself ends its long responses (agent streams and browser event streams) so clients reconnect cleanly. It must be below `maxDuration`. - `toolTimeoutMs` is how long one site tool handler may run. Each tool call is handled during one request from the agent, under `after` (or Vercel's request-context `waitUntil`), so a dropped request does not stop it; but that work is still bounded by `maxDuration`, so `toolTimeoutMs` must fit inside it, including any file pull. If Vercel stops the function mid-handler, the call fails with “Site tool "" timed out on the website. Please try again.” and is never re-run (at most once). ### Attachments over about 4 MB fail Vercel refuses request bodies over about 4.5 MB with its own `413` before the hub sees them. The hub itself accepts 10 MiB. Users get a generic error unless you check `Content-Length` on `POST /api/uncage/sessions/:id/attachments` first and answer the hub’s `attachment_too_large` shape; the reference demo’s [route handler](https://github.com/ptmafia/uncage/blob/main/examples/connected-demo/app/api/uncage/%5B%5B...path%5D%5D/route.ts) does this with a 4 MB limit. Agent traffic is never affected: the agent sends at most 1 MB per request and pulls files in chunks. ### Uploads fail on slow connections with `400` A request body is refused with `400` when no bytes arrive for `bodyTimeoutMs` (30 s by default), or when it takes more than 4 times that in total. The timer restarts on every chunk, so a slow but steady upload gets through and you rarely need to change it; keep it below `maxDuration`. ### Neon: which driver? Use `pg` (as above) or Neon’s `@neondatabase/serverless` **`Pool`** (`postgresHubStore({ pool })` accepts either). Do not use the HTTP-only `neon()` function: the hub needs transactions on one connection. The pooled `-pooler` URL is fine: the hub’s migrations take transaction-scoped locks, which work behind transaction-mode poolers. ### Does Neon’s free tier ever go to sleep? Not while a computer is online or a function instance is warm: open agent streams and `postgresCluster` poll every 0.3 to 2 s. Budget for an always-on compute while you have users connected, or see [what FaaS mode costs](https://uncage.vercel.app/docs/start/choose-deployment-mode.md#what-faas-mode-costs). ### Do I need Redis? No. Add it (`cluster: redisCluster({ url: process.env.REDIS_URL! })`, install `ioredis`) for lower latency and less database polling with many instances. Upstash Redis works if it speaks the Redis protocol over TCP (`rediss://`). ### Rate limits behind another proxy `toNextHandlers` reads `x-real-ip`, which Vercel’s edge sets. If another proxy or CDN sits in front of Vercel, that header holds the proxy’s address: pass `toNextHandlers(getHub, { waitUntil: after, clientIp: (req) => req.headers.get('cf-connecting-ip') ?? undefined })` with your proxy’s client-IP header. ### Users see “Agent update needed” Their computer runs an agent older than 0.3, which cannot connect over HTTP streaming. The page shows the fix: `npm i -g @uncage/cli@latest`, then the setup command again. See [Troubleshooting](https://uncage.vercel.app/docs/reference/troubleshooting.md#agent-update-needed--426-upgrade_required). ### Can a site tool handler run for minutes? Not on Vercel: it runs inside one request, limited by `maxDuration`. Start the long work as a background job and return an id the model can check with a second tool, or host the hub in [traditional mode](https://uncage.vercel.app/docs/deploy/node.md). --- # Cloudflare Workers (FaaS mode) > Run the hub in a native Cloudflare Worker with Postgres through Hyperdrive — one hub per request with fetchOnce, ctx.waitUntil, cf-connecting-ip, nodejs_compat for pg, a Cron Trigger for maintenance — with complete files, environment, deploy steps, a verification checklist and an FAQ. A Worker cannot keep objects that do I/O (database sockets) between requests, so on Workers the hub is created **per request**: `fetchOnce` builds a hub on a fresh Postgres pool, serves the request, and closes both once the response has finished (streams included). Everything that must outlive a request lives in Postgres, reached through **Hyperdrive**. Users’ computers connect over HTTP streaming. Why FaaS mode: [Choose a deployment mode](https://uncage.vercel.app/docs/start/choose-deployment-mode.md). :::note[Status] This setup runs on `wrangler dev` (workerd) with a real Uncage agent, in the repository’s [`examples/connected-cloudflare`](https://github.com/ptmafia/uncage/tree/main/examples/connected-cloudflare). A deployed Worker has not been verified end to end by the Uncage team yet; tell us how it goes. ::: ## Prerequisites - A Cloudflare account and `wrangler` 4.158 or newer (`npm i -D wrangler`). Older versions do not accept the `compatibility_date` below. - A **Postgres** database reachable from Cloudflare (Neon, Supabase, your own), and a **Hyperdrive** configuration for it. Locally, any Postgres (for example in Docker). - Your site’s sign-in, readable from a `Request` inside the Worker (a session cookie you can verify). ```sh npm i @uncage/hub pg npm i -D wrangler @types/pg ``` ## Code Four files. ```toml title="wrangler.toml" name = "my-site" main = "src/worker.ts" compatibility_date = "2026-10-01" # For the pg driver only (TCP sockets); @uncage/hub itself uses Web APIs only. compatibility_flags = ["nodejs_compat"] [vars] PUBLIC_URL = "http://localhost:8787" # set your deployed origin before going live [[hyperdrive]] binding = "HYPERDRIVE" id = "" # wrangler hyperdrive create … --caching-disabled prints it localConnectionString = "postgres://postgres:uncage@127.0.0.1:5432/postgres" # used by wrangler dev # Maintenance (retention cleanup) once a day; requests also run it opportunistically. [triggers] crons = ["0 4 * * *"] ``` ```ts title="src/auth.ts" /** * Your sign-in: the user a request belongs to, or null. Replace the body with a real check of * your session cookie, for example a signed token verified with crypto.subtle, or a lookup in * your session table. Until then, only local development (wrangler dev) has a user. */ export async function userFromRequest(req: Request, env: Env): Promise { const local = ['localhost', '127.0.0.1'].includes(new URL(req.url).hostname); if (local && env.PUBLIC_URL.startsWith('http://localhost')) return { id: 'dev-user', name: 'Developer' }; return null; } ``` ```ts title="src/hub.ts" export interface Env { /** Hyperdrive binding (wrangler.toml); wrangler dev uses its localConnectionString. */ HYPERDRIVE: { connectionString: string }; /** The Worker's public origin, e.g. https://my-site.example.workers.dev. */ PUBLIC_URL: string; } /** A pool for one request: Workers forbid reusing sockets across requests. At most 5 connections. */ export function newPool(env: Env): pg.Pool { const pool = new pg.Pool({ connectionString: env.HYPERDRIVE.connectionString, max: 5 }); // workerd closes a finished request's sockets; pg reports that on idle clients. Log anything else. pool.on('error', (err) => { if (!/socket has been closed/i.test(err.message)) console.error('postgres pool error:', err.message); }); return pool; } /** The hub for one request on `pool`, and the cleanup of what was built for it (the pool is the caller's). */ export async function makeHub(env: Env, pool: pg.Pool): Promise<{ hub: Hub; close(): Promise }> { const store = await postgresHubStore({ pool }); const cluster = postgresCluster({ pool }); const close = async () => { await cluster.close(); await store.close(); // leaves the pool open }; try { const hub = await createHub({ publicUrl: env.PUBLIC_URL, getUser: (req) => userFromRequest(req, env), store, cluster, sessionStorage: 'site', }); return { hub, close }; } catch (e) { await close(); throw e; } } ``` ```ts title="src/worker.ts" /** The part of Workers' ExecutionContext used here (`wrangler types` generates the full one). */ interface ExecutionContext { waitUntil(p: Promise): void; } export default { async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise { const url = new URL(req.url); if (url.pathname.startsWith('/api/uncage/')) { return fetchOnce( async (defer) => { const pool = newPool(env); defer(() => pool.end()); // runs after the response, also if building the hub fails return makeHub(env, pool); }, req, // Bound: an unbound ctx.waitUntil throws "Illegal invocation". { waitUntil: ctx.waitUntil.bind(ctx), clientIp: req.headers.get('cf-connecting-ip') ?? undefined }, ); } if (url.pathname === '/device') return devicePage(req, url, env, ctx); return new Response('Your website'); }, /** Cron Trigger: run the hub's maintenance (it skips if another instance ran it within the minute). */ async scheduled(_event: unknown, env: Env, ctx: ExecutionContext): Promise { const pool = newPool(env); const work = (async () => { const { hub, close } = await makeHub(env, pool); try { console.log('uncage maintenance', JSON.stringify(await hub.maintain())); } finally { await hub.close(); await close(); } })().finally(() => pool.end()); ctx.waitUntil(work); }, }; /** /device: where a signed-in user approves `uncage setup`'s code. Never framed; POST from this origin only. */ async function devicePage(req: Request, url: URL, env: Env, ctx: ExecutionContext): Promise { const user = await userFromRequest(req, env); if (!user) return page('

Sign in first, then open this link again.

', 401); if (req.method === 'POST' && req.headers.get('origin') !== url.origin) return page('

Cross-site request refused.

', 403); const pool = newPool(env); try { const { hub, close } = await makeHub(env, pool); try { if (req.method === 'POST') { const form = await req.formData(); const code = String(form.get('code') ?? ''); const approve = form.get('decision') === 'approve'; // The code came in a link (anyone can send one): approve only with its last 4 characters typed. const tail = String(form.get('tail') ?? '').toUpperCase().replace(/[\s-]/g, ''); if (approve && tail !== code.toUpperCase().replace(/[\s-]/g, '').slice(-4)) { return page('

The last 4 characters do not match. Check your terminal and try again.

', 400); } const result = approve ? await hub.approveDevice(code, user) : await hub.denyDevice(code, user); if (result === 'ok') return page(approve ? '

Approved. You can close this tab.

' : '

Denied.

'); return page(`

This code is ${result === 'expired' ? 'expired' : 'unknown'}. Run uncage setup again.

`, 410); } const code = (url.searchParams.get('code') ?? '').trim(); // Exactly what the CLI prints: padding such as ABCD-EFGH---- is not a valid link. if (!/^[A-Z0-9]{4}-?[A-Z0-9]{4}$/i.test(code)) return page('

This link is not valid. Run uncage setup again.

', 400); const info = await hub.lookupDevice(code, user); if (!info) return page('

Unknown or expired code. Run uncage setup again.

', 404); const repair = info.repairsMachine ? `

This re-pairs ${esc(info.repairsMachine.name)}.

` : ''; const ip = info.requestIp ? ` · IP as seen by the server: ${esc(info.requestIp)}` : ''; const asked = `

Requested ${esc(info.requestedAt)}${ip}. Name and system: reported by the computer, not verified.

`; return page( `

Only approve if you just ran uncage setup on a computer in front of you. Never approve a code someone sent you.

` + `

Connect ${esc(info.name ?? 'a computer')} to your account?

${asked}${repair}` + `` + `
`, ); } finally { await hub.close(); await close(); } } catch (e) { // Unknown codes count as failed guesses: after 10 in 10 minutes the hub refuses with rate_limited. if ((e as { code?: string }).code === 'rate_limited') return page('

Too many attempts. Try again in a few minutes.

', 429); console.error('device page failed:', e); return page('

Something went wrong. Try again shortly.

', 500); } finally { ctx.waitUntil(pool.end()); } } function page(body: string, status = 200): Response { return new Response(`Connect your computer${body}`, { status, headers: { 'content-type': 'text/html; charset=utf-8', 'content-security-policy': "frame-ancestors 'none'", 'x-frame-options': 'DENY' }, }); } function esc(s: string): string { return s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); } ``` What matters here: - **One hub per request.** `fetchOnce(create, req, …)` calls `create(defer)` for every request. Register cleanups with `defer` as you open things; return the hub, or `{ hub, close }`. After the response body has finished or was cancelled (never earlier, so streams keep working), it runs `hub.close()`, then `close`, then the deferred cleanups. - **Migrations are checked once per isolate**: a fresh pool costs one cheap `SELECT max(id)`, no lock and no DDL. - **`waitUntil: ctx.waitUntil.bind(ctx)`** keeps the isolate alive for site tool calls whose request dropped, the hub’s background work and the cleanup. Always pass it. - **`clientIp` from `cf-connecting-ip`**, which Cloudflare sets, for per-IP rate limits. - Your sign-in goes in `getUser` (`src/auth.ts`). The repository example has a demo sign-in that lets anyone become any user; it refuses to work on a public host, and it is **not** something to copy into a real site. ## Environment variables | Name | Kind | What it is | | --- | --- | --- | | `HYPERDRIVE` | Hyperdrive binding | Your Postgres, through Hyperdrive (`[[hyperdrive]]` in `wrangler.toml`). `wrangler dev` uses `localConnectionString` instead, or the `CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE` environment variable. | | `PUBLIC_URL` | var | The exact origin users open, `https://…` (plain `http://` only for localhost). It goes into the install and setup commands. | | Your auth secrets | secret | Whatever `src/auth.ts` needs: `wrangler secret put `. For `wrangler dev`, put them in `.dev.vars`. | No `CRON_SECRET` is needed: the Cron Trigger calls `scheduled` directly. (If you prefer an HTTP cron, set `maintenance: { secret }` in `createHub` and call `GET /api/uncage/maintenance` with `Authorization: Bearer `.) ## Deploy 1. **Run it locally first.** Start a Postgres matching `localConnectionString`, then: ```sh docker run -d --name pg -p 5432:5432 -e POSTGRES_PASSWORD=uncage postgres:16-alpine npx wrangler dev # http://localhost:8787 ``` 2. **Create the Hyperdrive configuration** with query caching off (the hub polls with repeated identical queries and needs fresh results) and put its id in `wrangler.toml`: ```sh npx wrangler login npx wrangler hyperdrive create my-site-db --connection-string="postgres://user:password@host:5432/db" --caching-disabled ``` 3. **Deploy once** to learn your Worker’s URL: `npx wrangler deploy`. 4. **Set `PUBLIC_URL`** in `wrangler.toml` to that URL (or your custom domain), add your auth secrets with `wrangler secret put`, and deploy again. 5. **Wire your real sign-in** into `src/auth.ts` before you send anyone the link. ## Verify Replace `https://my-site.example.workers.dev` with your `PUBLIC_URL` (or use `http://localhost:8787` under `wrangler dev`). - [ ] `curl -s https://my-site.example.workers.dev/api/uncage/agent/info` lists only `http`: ```json {"protocol":2,"minAgentVersion":"0.3.0","transports":[{"kind":"http","url":"https://my-site.example.workers.dev/api/uncage/agent"}]} ``` - [ ] `curl -s https://my-site.example.workers.dev/api/uncage/install.sh | head -2` prints the installer’s first lines. - [ ] `npx wrangler tail` while you connect a computer (`uncage setup https://my-site.example.workers.dev`, approve on `/device`): no errors, and the computer shows online. - [ ] Run a prompt that calls one of your site tools; the tool step completes. - [ ] `npx wrangler deploy --dry-run --outdir dist` bundles without errors. (The root `@uncage/hub` entry is Web-standard and `@uncage/hub/node` is never imported here; only `pg` needs `nodejs_compat`.) ## FAQ ### Why a new hub for every request? Isn’t that slow? Workers forbid sharing sockets between requests, so a shared pool is not an option. Building a hub is cheap: no migrations after the first request of an isolate (one `SELECT max(id)`), and Hyperdrive keeps the real database connections warm. The repository example measured about 350 ms for a command’s round trip through the stream on workerd. ### Do site tools run exactly once on Workers? On Workers the hub runs each tool call under the `waitUntil` you pass to `fetchOnce`, so a dropped POST does not stop the handler: its result is stored and the agent's resend gets it (exactly once). Workers keeps `waitUntil` work alive for only about 30 s after the client disconnects. A handler still running after that is cancelled. Once its lease runs out (`toolTimeoutMs` + 10 s), the call fails with "Site tool "" timed out on the website. Please try again." and is never re-run (at most once). Without `waitUntil`, any dropped POST leads to this. So: always pass `waitUntil: ctx.waitUntil.bind(ctx)`, keep handlers well under 30 s, and make them idempotent where you can. ### 504s or streams cut early? HTTP Workers have no wall-clock limit while the client stays connected, and waiting on I/O does not count as CPU time, so the default `stream.maxDurationMs` (250 s) is fine. If your plan or a proxy in front cuts long requests earlier, lower `stream.maxDurationMs` below that limit. ### Neon or Supabase without Hyperdrive? Use Hyperdrive: it pools connections close to the Worker. Create it with `--caching-disabled`: the hub polls with repeated identical queries and needs fresh results, which Hyperdrive's query cache would serve stale. Without it, Neon’s `@neondatabase/serverless` `Pool` (WebSockets) also works with `postgresHubStore({ pool })`; its HTTP-only `neon()` function does not (the hub needs transactions on one connection). ### Why `nodejs_compat`? Only for `pg`, which opens TCP sockets through `cloudflare:sockets`. `@uncage/hub`’s root entry uses Web APIs only; `@uncage/hub/node` (WebSocket server, PGlite) is never bundled. ### Can computers use WebSockets here? Not with this setup: nothing in a Worker accepts the agents’ WebSockets (that would need Durable Objects). The hub offers only `http`, and agents use it. An agent older than 0.3 that tries a WebSocket gets `426 upgrade_required` and the site shows “Agent update needed”. ### Rate limits behind another proxy? `cf-connecting-ip` is the client address as Cloudflare saw it. With another proxy in front of Cloudflare, read that proxy’s client-IP header instead. --- # Other Fetch platforms (FaaS mode) > Run the hub on any platform that speaks Fetch Request/Response — Netlify Functions, Deno, Bun, other serverless hosts — with hub.fetch and Postgres; what the platform must support, complete files, environment variables, deploy steps, a verification checklist and an FAQ. `hub.fetch(request)` is a plain Fetch handler: `Request` in, `Response` out, Web APIs only. Any platform that runs Fetch handlers and can stream a response can host the hub in FaaS mode. This page gives the general recipe, with Netlify Functions and Bun / Deno as examples. For Vercel and Cloudflare Workers, use their own pages: [Next.js on Vercel](https://uncage.vercel.app/docs/deploy/vercel.md), [Cloudflare Workers](https://uncage.vercel.app/docs/deploy/cloudflare-workers.md). :::note[Status] The hub runs on these platforms through the same `hub.fetch` that Vercel and Workers use, but the Uncage team has not verified each platform end to end. The checklist below tells you within minutes whether yours works. ::: :::caution[Netlify: short limit] Netlify documents a **60-second execution limit for streaming functions** (and 20 MB per streamed response). The hub works within it, with caveats: set the hub's `stream.maxDurationMs` to about `50000` (the example `hub.ts` below reads it from `UNCAGE_STREAM_MAX_MS`; streams rotate every ~50 s, so more reconnects and more invocations than on Vercel), and keep `toolTimeoutMs` well under 60 s (for example `40_000`), because every site tool call must finish inside one invocation. If your tools need longer, use [Vercel](https://uncage.vercel.app/docs/deploy/vercel.md) or [traditional mode](https://uncage.vercel.app/docs/deploy/node.md). ::: ## Prerequisites The platform must: 1. **Stream responses** without buffering them: the agent’s stream (`application/x-ndjson`) and browser events (`text/event-stream`) send lines for minutes. 2. **Let a request run for at least about 30 s**, ideally several minutes. Set `stream.maxDurationMs` below the limit. Every site tool call also runs inside one request, so `toolTimeoutMs` must fit too. 3. **Reach Postgres** through `pg` or a pg-compatible `Pool` (Neon’s `@neondatabase/serverless` `Pool` works; HTTP-only query functions do not, because the hub needs transactions). 4. Tell you the **client IP** (a header or a context field), for per-IP rate limits. **Strongly recommended**: a `waitUntil(promise)` hook. Tool calls run under it, so a dropped connection cannot cut a handler off, and maintenance and cleanup run after the response. Helpful: a cron feature (for the maintenance endpoint). If the platform forbids sharing sockets between requests (like Workers), create the hub per request with `fetchOnce`, as on the [Workers page](https://uncage.vercel.app/docs/deploy/cloudflare-workers.md#code). ```sh npm i @uncage/hub pg npm i -D @types/pg ``` ## Code The hub, created once per instance (process or isolate) and reused by every request it serves: ```ts title="hub.ts" /** Your sign-in: verify the session cookie of a request. Replace the body. */ async function getUser(req: Request): Promise { const cookie = req.headers.get('cookie') ?? ''; // Look the session cookie up in your session store here. return cookie.includes('session=') ? { id: 'user-123', name: 'Ada' } : null; } async function createAppHub(): Promise { const url = process.env.DATABASE_URL; if (!url) throw new Error('DATABASE_URL is not set.'); const pool = new pg.Pool({ connectionString: url, max: 5 }); pool.on('error', (err) => console.error('postgres pool error:', err.message)); const ipHeader = process.env.CLIENT_IP_HEADER?.toLowerCase(); const publicUrl = process.env.PUBLIC_URL ?? (process.env.NODE_ENV === 'production' || process.env.VERCEL ? undefined : 'http://localhost:3000'); if (!publicUrl) throw new Error('PUBLIC_URL is not set: set it to your site’s https:// origin.'); return createHub({ publicUrl, // what users open; localhost only for local development getUser, store: await postgresHubStore({ pool }), cluster: postgresCluster({ pool }), sessionStorage: 'site', // Below the platform's request time limit (default 250 s). stream: { maxDurationMs: Number(process.env.UNCAGE_STREAM_MAX_MS) || 250_000 }, ...(ipHeader ? { rateLimits: { clientIp: (req: Request) => req.headers.get(ipHeader) ?? undefined } } : {}), ...(process.env.CRON_SECRET ? { maintenance: { secret: process.env.CRON_SECRET } } : {}), }); } let hub: Promise | undefined; /** The hub of this instance; a failed start (database briefly down) is retried on the next request. */ export function getHub(): Promise { const p = (hub ??= createAppHub()); p.catch(() => { if (hub === p) hub = undefined; }); return p; } ``` ### Netlify Functions ```ts title="netlify/functions/uncage.ts" /** The fields of Netlify's function context used here. */ interface NetlifyContext { ip: string; waitUntil(p: Promise): void; } export default async (req: Request, context: NetlifyContext): Promise => { const hub = await getHub(); return hub.fetch(req, { clientIp: context.ip, waitUntil: (p) => context.waitUntil(p) }); }; export const config = { path: '/api/uncage/*' }; ``` ### Bun or Deno (a long-running Fetch server) Both run a file whose default export has a `fetch` handler: `bun server.ts` (Bun reads `port` from the export) or `deno serve --port 3000 server.ts`. The process keeps running, so the hub lives as long as it does: ```ts title="server.ts" /** Bun passes its server as the second argument, `deno serve` a connection info object. */ interface BunServer { requestIP(req: Request): { address: string } | null; } interface DenoServeInfo { remoteAddr: { hostname: string }; } function clientIpOf(req: Request, second: unknown): string | undefined { const s = second as Partial | undefined; if (typeof s?.requestIP === 'function') return s.requestIP(req)?.address; return s?.remoteAddr?.hostname; } export default { port: 3000, async fetch(req: Request, second?: unknown): Promise { if (new URL(req.url).pathname.startsWith('/api/uncage/')) { const hub = await getHub(); // The socket address; behind a proxy set CLIENT_IP_HEADER instead (it wins, see hub.ts). const clientIp = clientIpOf(req, second); return hub.fetch(req, clientIp ? { clientIp } : {}); } return new Response('Your website'); }, }; ``` You also need the approval page at `/device` (signed-in only, never framed, decided by a POST from your own origin). It calls `hub.lookupDevice`, `hub.approveDevice` and `hub.denyDevice`; the [Workers page](https://uncage.vercel.app/docs/deploy/cloudflare-workers.md#code) has a framework-free version (`devicePage`) you can adapt, and [Auth and device approval](https://uncage.vercel.app/docs/guides/auth-and-device-approval.md) explains the rules. ## Environment variables | Variable | Required | What it is | | --- | --- | --- | | `DATABASE_URL` | yes | Your Postgres connection string. Pooled URLs (PgBouncer in transaction mode, Neon `-pooler`) work. | | `PUBLIC_URL` | yes | The exact `https://` origin users open. | | `UNCAGE_STREAM_MAX_MS` | if the platform’s limit is under 300 s | When the hub ends long responses: about 10–50 s below the platform’s request time limit. | | `CLIENT_IP_HEADER` | behind a proxy | The header that carries the client address (for example `x-real-ip`, `cf-connecting-ip`, `x-nf-client-connection-ip`). Only set it if every request really comes through that proxy. | | `CRON_SECRET` | optional | Enables `GET /api/uncage/maintenance` with `Authorization: Bearer `, for the platform’s cron. | The names are this page’s choice; the hub reads no environment variables itself. ## Deploy 1. **Create the database** and set `DATABASE_URL` and `PUBLIC_URL` on the platform. 2. **Find the request time limit** of your plan in the platform’s docs, and set the hub's `stream.maxDurationMs` below it (`UNCAGE_STREAM_MAX_MS` in the example; skip if it is 300 s or more). 3. **Deploy** the way the platform expects (for Netlify, `netlify deploy --prod` with the function above; for Bun or Deno, run `bun server.ts` or `deno serve --port 3000 server.ts` on your host). 4. **Optional:** schedule a daily call to `/api/uncage/maintenance` with the `CRON_SECRET` bearer token. Without it, maintenance still runs opportunistically on requests. ## Verify - [ ] `curl -s https://your.site/api/uncage/agent/info` answers with the `http` transport (`{"protocol":2,…,"transports":[{"kind":"http",…}]}`). - [ ] `curl -sN https://your.site/api/uncage/agent/stream` answers `401` quickly (no token); that proves the route reaches the hub. - [ ] Connect a computer (`uncage setup https://your.site`, approve on `/device`): it shows **online** and stays online for longer than your platform’s time limit. The agent log shows `http stream rotated` lines, not errors. - [ ] A prompt streams in the chat **while it is being written**, not all at once at the end. If it arrives in one piece, the platform buffers responses: this platform cannot host the hub. - [ ] A site tool call completes. ## FAQ ### Which platforms are known not to work? Platforms that buffer the whole response before sending it, or that limit requests to a few seconds. The hub needs streamed responses that stay open for at least about 30 s. ### Can I skip Postgres on a single long-running process? If your Fetch server is one long-running process (Bun or Deno on a VM), you are effectively in traditional mode. Use Node with `@uncage/hub/node` ([Node page](https://uncage.vercel.app/docs/deploy/node.md)) for WebSockets and the embedded store; on other runtimes, keep Postgres (the embedded store and the WebSocket server are tested on Node only). ### How short can the platform’s time limit be? The hub works with any `stream.maxDurationMs` above a few seconds, but each rotation is a reconnect and every tool call must finish within the limit. Below about 30 s it is not worth it. ### 504s, cut connections A request outlived the platform limit: lower `stream.maxDurationMs` (`UNCAGE_STREAM_MAX_MS` in the example), and keep `toolTimeoutMs` (120 s by default) below the limit too. A connection cut by a proxy or the network is harmless: the agent reconnects with its cursor, and nothing is lost or delivered twice. --- # Concepts > The ideas behind Uncage, one section each: website and hub, machine and agent, session, run, events, approvals and permission modes, site tools, skills, manifest, file channel, storage, cluster, and the trust model. This page explains each idea once. The words are used the same way everywhere on this site; the [glossary](https://uncage.vercel.app/docs/reference/glossary.md) has the one-line versions. ## Website and hub The **website** is your web application. The **hub** (`@uncage/hub`) is the part of Uncage you mount inside its backend with `createHub()`: in a long-running Node process (**traditional mode**) or in serverless functions (**FaaS mode**, see [Choose a deployment mode](https://uncage.vercel.app/docs/start/choose-deployment-mode.md)). It is a Fetch handler (`hub.fetch`) and serves, under one base path (default `/api/uncage`): - the **browser API** your UI uses (the same request and response shapes as the Local Mode daemon’s `/v1` API, so `@uncage/client`, `@uncage/react` and `@uncage/react-ui` work unchanged); - the **device endpoints** and the installers (`install.sh`, `install.ps1`) that connect a computer; - the **transports** connected computers dial into at `/agent`: a **WebSocket** (traditional mode, via `attachWebSocket(hub, server)` from `@uncage/hub/node`) and **HTTP streaming** (any platform). The hub offers them, the agent picks one. Each website runs its own hub. There is no Uncage cloud service in between. A website has an **id** and a **name** that computers see when they connect. By default both come from the host of `publicUrl` (`app.example.com`); set `site: { id, name }` to choose them. Computers use the id for their local folders, so keep it stable. ## Machine (computer) and agent A **machine** is one user’s computer connected to your website. In UI text it is called a **computer**. A user can connect several; each one has an id (`mch_…`), a name, its OS, the agent version, the runtimes it has (Claude Code, Codex) and whether it is **online**. The **agent** is the background process on that computer: `uncage agent`, installed by `uncage setup` as a per-user background service (launchd on macOS, systemd on Linux, a scheduled task on Windows). In Chinese UI text it is called **守护进程**. One agent can be connected to several websites at once, with one machine token, one connection and one workspace root per website. A machine is **online** while its connection is live: a WebSocket answering heartbeats, or an open HTTP stream. The hub pings every 10 seconds and marks a silent machine offline after two missed pings, so the UI shows “offline” within about 30 seconds. **Pairing** uses a device login, much like signing in to a TV app: `uncage setup ` gets a short **user code**, the user approves it on your website’s `/device` page, and the CLI receives a **machine token**. The token is stored only on the computer (`~/.uncage/agent.yaml`, mode 0600); the hub keeps its SHA-256 hash. Revoking a machine (from your website, or with `uncage sites remove` on the computer) makes the token stop working at once. ## Session A **session** is one conversation, with one runtime, on one machine. Its id is chosen by the machine. Every session the hub returns carries `machineId`, so your UI can show the state of that computer. - On the machine, each session gets its own **workspace** folder, `~/Uncage///`. A browser cannot choose the folder. - The session’s **source of truth** is the machine’s local database (`~/.uncage/sites//data`). - A new session runs on the computer you pass as `machineId`, else on the user’s most recently seen computer that is online. With none online, creating a session fails with `machine_offline` (or `machine_not_found` if the user has never connected one). ## Run A **run** is one prompt and everything the agent does to answer it. A session has at most one active run at a time (a second one gets `session_busy`). Run states: | State | Meaning | | --- | --- | | `queued`, `running` | Working | | `waiting_approval` | Paused on an approval card | | `completed` | Finished normally | | `failed` | Ended with an error | | `cancelled` | Stopped by the user (Stop) | | `interrupted` | The process went away mid-run (for example the agent restarted) | Starting a run needs an `Idempotency-Key` header, so a retried request never starts a second run. `@uncage/client` sets it for you. ## Events Everything that happens in a session is an **event** with a per-session **sequence** number: `session.created`, `run.started`, `message.delta`, `tool.started`, `approval.requested`, `run.completed`, and so on. The browser receives them over **SSE** (`GET /sessions/:id/events`) and can resume after a disconnect from the last sequence it saw (`Last-Event-ID`). The machine writes events to its local database first, so a run keeps going while the network is down; when the connection comes back, the browser catches up without duplicates. ## Approvals and permission modes When Claude Code wants to run a command, edit a file or call a tool that needs confirmation, the run pauses and the UI shows an **approval** card (**Allow** / **Deny**). The decision travels browser → hub → machine, and the machine decides atomically: if two tabs (or two hub nodes) answer at once, the first decision wins and the other gets `409`. Pending approvals expire after 10 minutes. The **permission mode** of a session controls how much needs approval: | Mode | Behaviour | | --- | --- | | `default` | Ask before commands and edits (Claude Code still auto-allows what it considers safe, such as reads) | | `acceptEdits` | Edit files without asking; still ask for commands | | `plan` | Plan only, change nothing | | `auto` | The runtime decides what needs the user | | `bypassPermissions` | Never ask. **Only available if the user enabled it on their own computer** (see [trust model](https://uncage.vercel.app/docs/concepts/trust-model.md)) | ## Site tools A **site tool** is a capability of your website that Claude Code can call, declared with `defineTool({ name, description, input, handler, requiresConfirmation? })`. - The machine receives only the name, the description and the JSON Schema of `input`. Claude Code sees the tool as `mcp__site__`. - The **handler runs in your backend**, on the hub node that holds the machine’s connection, with `ctx.user` set to the session’s owner. - `requiresConfirmation: true` makes every call show an approval card first, even in `bypassPermissions` mode. - Every call is checked (the session belongs to this machine and user, the tool was offered to this run, the arguments match `input`) and recorded in the hub’s store. Guide: [Define tools](https://uncage.vercel.app/docs/guides/define-tools.md). ## Skills A **skill** is instructions (markdown) plus optional template files, declared as a `SkillSpec` (`{ name, description, markdown, files? }`). The agent writes it to `.claude/skills//SKILL.md` in the session workspace before the run, and Claude Code loads it like any Claude Code skill: when the task matches its description. Skills are data, never code that the hub runs. Guide: [Write skills](https://uncage.vercel.app/docs/guides/write-skills.md). ## Manifest The **manifest** is the set of tools and skills offered to one run. By default it is every tool and skill you registered. With `selectManifest({ user, prompt, sessionId, runtime })` you choose per run, for example only offering the publishing tools to users on a paid plan, or only the `invoice` skill when the prompt is about invoices. The hub records each run’s tool list; a call to a tool outside it fails with `tool_failed` (`details.reason: 'not_in_manifest'`). Changes to your tools or skills apply from the next run. Runtimes without site tool support (Codex) get the skills only, with a `site_tools_unsupported` warning in the session. Guide: [Choose tools and skills per run](https://uncage.vercel.app/docs/guides/select-manifest.md). ## File channel The **file channel** lets a tool handler read files from the run’s workspace on the machine, instead of passing whole files through JSON arguments: `ctx.files.pull(path)` (a file or a folder, at most 50 MiB in total and 10 MiB per file) and `ctx.files.read(path)` (one file). The machine refuses paths outside the workspace, never follows symlinks, and skips hard-linked files in folders. Guide: [Define tools → Reading files](https://uncage.vercel.app/docs/guides/define-tools.md#reading-files-from-the-users-computer). ## Storage There are two stores: - **On the machine:** the session data (truth), in PGlite under `~/.uncage/sites//`. - **On the hub (`HubStore`):** machines, device codes, the session index (who owns which session, on which machine), run manifests, attachments uploaded through the hub and the tool-call audit. In FaaS mode it also holds each machine’s **outbox** (the numbered commands it has not processed yet) and the tool-call results. `pgliteHubStore` (embedded, one process, from `@uncage/hub/node`) is for traditional mode; `postgresHubStore` is for several nodes and FaaS mode. You always pass one as `store`. **Session storage** (`sessionStorage` option) decides whether the hub also keeps the conversation: - `'machine'` (default): history is read from the machine. While it is offline, the user cannot see past conversations. - `'site'`: the machine replicates every event to the hub, in order, and resends from the last acknowledged sequence after a reconnect. History stays readable on your site while the machine is off. Guide: [Site storage](https://uncage.vercel.app/docs/guides/site-storage.md). ## Cluster A hub can run on several **nodes** behind a load balancer; in FaaS mode every function instance is a node. A machine’s WebSocket lives on one node; a browser request may land on another. The **cluster adapter** (`ClusterAdapter`) shares which node holds which machine and carries commands, wake-ups and events between nodes. `memoryCluster()` (default) is for one process; `redisCluster()` or `postgresCluster()` is for several. Every node must also share one `HubStore` (Postgres). Guide: [Multi-node](https://uncage.vercel.app/docs/guides/multi-node.md). ## Local policy and activity The user’s computer has the last word. In `~/.uncage/agent.yaml`, `localPolicy.allowBypass` (default `false`) is the only switch that makes `bypassPermissions` possible, and `localPolicy.allowedPermissionModes` can cap the modes any website may use. Every command, tool call, file pull and approval a website causes is written to a local **activity log**, shown by `uncage activity`. Guide: [Local policy](https://uncage.vercel.app/docs/guides/local-policy.md). ## Trust model The website is trusted to act for its signed-in users, within limits the website cannot change: no code or shell from the website, bypass only by the user, a local log of everything. Read [the trust model](https://uncage.vercel.app/docs/concepts/trust-model.md). ## Local Mode Everything above is **Connected Mode**. In **Local Mode**, there is no hub and no pairing: `uncage serve` (the **daemon**) runs on the same machine as your app, and your app talks to it through a same-origin **proxy** (`createUncageHandler` from `@uncage/server/proxy`) that adds the daemon’s bearer token on the server. Sessions, runs, events and approvals work the same way. See the [Local Mode quickstart](https://uncage.vercel.app/docs/start/quickstart-local.md). --- # Trust model > What a website using Uncage can and cannot do on a user's computer, what the user controls locally, and which guarantees are built in and cannot be switched off. Connected Mode lets a website start work on a user’s own computer. That needs a clear answer to “what can the website do?”. Here it is. ## The short version - **The website is trusted to act for its signed-in user.** What the user does on your website counts as the user’s own action: starting runs, approving cards, calling your tools as that user. - **Within limits the website cannot change.** These are enforced on the user’s computer, by the agent, not by the hub: | Guarantee | How | | --- | --- | | No code or shell from the website | The hub sends only data: tool names, descriptions and JSON Schemas, skill text and template files, and commands from a fixed list (create session, start run, cancel, decide, update settings, add attachment, read snapshot / sessions / events). Tool **handlers** run on your server, never on the user’s computer. | | `bypassPermissions` only by the user | The agent refuses the mode with `policy_denied` unless `localPolicy.allowBypass: true` is set in `~/.uncage/agent.yaml` on that computer. No hub option can change this. | | Optional local cap | `localPolicy.allowedPermissionModes` limits which modes any website may use on this computer. | | Confirmation tools always ask | A site tool with `requiresConfirmation: true` raises an approval card on every call, even in `bypassPermissions` mode. | | A full local record | Every command, site tool call, file pull and approval is appended to `~/.uncage/sites//activity.log`. `uncage activity` shows it. | | Fenced folders | Every session runs in its own folder, `~/Uncage///`, never in the user’s existing projects. File pulls are refused outside it, and symlinks are never followed. | | The user can disconnect at any time | `uncage sites remove ` revokes the computer on the website and deletes the token locally; `uncage agent uninstall` stops the agent. | ## What the website can do - Start sessions and runs on the user’s connected computers, as that user, with the permission modes the computer allows. - Show the user approval cards and receive the user’s decisions. - Offer site tools and skills. Claude Code decides when to call a tool; the call runs your handler on your server. - Read files **from the session’s own folder** through the file channel, from inside a tool handler. - Keep a replica of the conversation on its own storage (`sessionStorage: 'site'`). - Revoke a computer from its side (`hub.revokeMachine` or the machine list in the UI). ## What the website cannot do - Run anything on the user’s computer other than Claude Code (or Codex) itself, in a session folder. - Turn on `bypassPermissions`, or use a mode outside the computer’s `allowedPermissionModes`. - Choose where a session runs on disk. The browser’s `workspace` field is ignored in Connected Mode; the agent creates the folder. - Reach another user’s computer or session. Every browser request is checked against `getUser(req)`, and a session or machine of another user answers `404`, exactly like one that does not exist. - See the machine token. The hub stores only its hash; the token is never logged or put in events. - Read the user’s Claude login. Claude Code uses its own credentials on that computer. ## What the user should know These are the trade-offs the user accepts by connecting a computer: - **Claude Code acts within the session folder and its permission mode, with the user’s own account.** In `default` mode the user approves commands and edits. Claude Code itself auto-allows some actions it considers safe, such as reading files. Those still appear as tool steps. - **A command the user approves runs with the user’s rights**, like any Claude Code command. Approval cards show the command or path; read them. - **Approve only a computer you just connected yourself.** Approving a code links that computer to the account: it then receives the account’s prompts, attachments and site-tool calls. Anyone can start `uncage setup` against the website on their own computer and send a user the link, so the approve page warns, shows when and from which IP the code was requested, and asks for the code’s last 4 characters from the user’s own terminal before Approve works. Never approve a code someone sent you. - **The website sees the conversation** (it routes it, and may store it). It does not see other files on the computer unless Claude Code reads them into the conversation or a tool pulls them from the session folder. ## For website developers: your side of the deal Uncage cannot protect against a website that misuses its own users’ trust, but it gives you the pieces to deserve it: - **Authenticate every request.** `getUser(req)` must return the real signed-in user or `null`. See [Auth and device approval](https://uncage.vercel.app/docs/guides/auth-and-device-approval.md). - **Protect `/device`.** Approving a code links a computer to an account. Serve it only to the signed-in user, refuse framing, decide with a CSRF-protected POST, and never trust a code that arrived in the link: warn, show the request time and IP, and require the code’s last 4 characters ([phishing links](https://uncage.vercel.app/docs/guides/auth-and-device-approval.md#phishing-links)). - **Check ownership in tool handlers.** `ctx.user` is the session owner; use it for every lookup (`WHERE owner = ctx.user.id`). - **Throw user-safe errors.** A handler’s thrown message is shown to the user and the model. - **Use `requiresConfirmation`** for any tool that publishes, sends, pays or deletes. See also [Security](https://uncage.vercel.app/docs/reference/security.md) for the transport, tokens and limits. --- # Glossary > One-line definitions of every Uncage term (agent, computer, hub, deployment mode, transport, site tool, skill, manifest, file channel, site storage, cluster, permission mode, Local and Connected Mode), with the exact API names and the Chinese UI words. The words on this site, in the UI and in the API mean the same thing everywhere. The **UI words** column is what end users see in `@uncage/react-ui` (English / 简体中文). | Term | Definition | API name | UI words | | --- | --- | --- | --- | | **Connected Mode** | A website drives Claude Code on each user’s own computer through a hub. | `@uncage/hub`, `@uncage/agent` | | | **Local Mode** | An app drives Claude Code on the machine it runs on, through a local daemon and a same-origin proxy. | `uncage serve`, `createUncageHandler` | | | **Website / site** | Your web application. It runs one hub. Computers know it by a site id and name. | `HubOptions.site`, `publicUrl` | site / 网站 | | **Hub** | The part of Uncage mounted in your website’s backend: device login, computer connections, browser API, site tools. A Fetch handler. | `createHub()`, `Hub`, `hub.fetch()` | | | **Deployment mode** | Where and how the hub runs: traditional mode or FaaS mode. | | | | **Traditional mode** | The hub in a long-running Node process: embedded store, WebSocket, no external dependency. | `@uncage/hub/node`: `toNodeHandler`, `attachWebSocket`, `pgliteHubStore` | | | **FaaS mode** | The hub in serverless functions or on a Fetch platform (Vercel, Cloudflare Workers): Postgres, HTTP streaming. | `toNextHandlers`, `fetchOnce`, `postgresHubStore`, `postgresCluster` | | | **Function instance** | One running copy of a serverless function. In FaaS mode every instance is a hub node. | | | | **Transport** | How a computer is linked to the hub: WebSocket (`ws`) or HTTP streaming (`http`). The hub offers, the agent chooses. | `TransportKind`, `transports`, `GET /agent/info` | | | **HTTP streaming** | The `http` transport: a long `GET /agent/stream` downstream (rotated before the platform limit) and `POST /agent/events` upstream. | `stream.maxDurationMs`, `polling` | | | **Outbox** | The durable, numbered queue of commands for one computer, in the hub’s store. The agent resumes from its cursor. | `OutboxItem`, `cursor`, `ack` | | | **Maintenance** | The hub’s periodic cleanup (retention, failing calls of dead instances), at most once per interval across instances. | `maintenance`, `hub.maintain()`, `/maintenance` | | | **Base path** | Where the hub is mounted. | `basePath`, default `/api/uncage` | | | **Computer / machine** | One user’s computer connected to your website. “Machine” in the API, “computer” in the UI. | `MachineInfo`, `machineId`, `useMachines()` | computer / 电脑 | | **Agent** | The background process on the user’s computer that connects to hubs and runs Claude Code. | `uncage agent`, `@uncage/agent` | the agent / 守护进程 | | **Online** | The computer’s connection is live (a WebSocket answering heartbeats, or an open HTTP stream). Offline within about 30 s of going silent. | `MachineInfo.online`, `MachineInfo.transport` | online / 在线, offline / 离线 | | **Agent update needed** | The computer’s agent is older than the hub’s `minAgentVersion`. | `MachineInfo.agentOutdated`, `upgrade_required` | Agent update needed / 需要更新守护进程 | | **Pairing / device login** | Linking a computer to a user: `uncage setup` gets a code, the user approves it on `/device`. | `approveDevice`, `lookupDevice`, `denyDevice` | | | **User code** | The 8-character code (`ABCD-2345`) the user compares and approves. Valid 10 minutes. | `?code=` | | | **Approval page** | Your page at `/device` where a signed-in user approves a code. | `verificationPath`, `` | | | **Machine token** | The secret a computer uses to connect to one website. Stored only in `~/.uncage/agent.yaml`. | | | | **Revoke** | Disconnect a computer from a website for good; its token stops working. | `revokeMachine`, `uncage sites remove` | | | **Runtime** | The coding agent that does the work: Claude Code (`claude`), Codex (`codex`) or an ACP agent (`acp-`). | `RuntimeInfo`, `RuntimeAdapter` | | | **ACP agent** | Any coding agent that speaks the Agent Client Protocol (Gemini CLI, OpenCode, …), offered as a runtime. | `runtimes.acp`, `uncage runtimes` | | | **Session** | One conversation with one runtime on one computer. | `Session`, `sessionId` | session / 会话 | | **Workspace** | The folder a session works in. Connected Mode: `~/Uncage///`. | `Session.workspace` | | | **Run** | One prompt and everything the agent does to answer it. | `Run`, `runId`, `RunState` | | | **Event** | One numbered thing that happened in a session, streamed over SSE. | `UncageEvent`, `sequence` | | | **Sequence** | The per-session event number; resuming and replication use it. | `UncageEvent.sequence`, `Last-Event-ID` | | | **Approval** | A request for the user to allow or deny an action. | `ApprovalRequest`, `useApprovals()` | Allow once / Deny, 允许执行 / 拒绝 | | **Permission mode** | How much needs approval: `default`, `acceptEdits`, `plan`, `auto`, `bypassPermissions`. | `PermissionMode`, `useSessionSettings()` | | | **Bypass permissions** | The mode with no approvals. Only the user can allow it, on their own computer. | `localPolicy.allowBypass` | | | **Site tool** | A capability of your website that Claude Code can call; the handler runs on your server as the user. | `defineTool()`, `SiteTool`, `ToolContext` | | | **Confirmation** | A site tool that asks the user before every call. | `requiresConfirmation: true` | | | **Skill** | Markdown instructions plus optional template files that Claude Code loads when relevant. | `SkillSpec`, `skills` | | | **Manifest** | The tools and skills offered to one run. | `selectManifest()`, `SessionManifest` | | | **File channel** | How a tool handler reads files from the run’s workspace on the computer. | `ctx.files.pull()`, `ctx.files.read()` | | | **Site storage** | The hub keeps a replica of every conversation, readable while the computer is off. | `sessionStorage: 'site'` | | | **Hub store** | The hub’s database: computers, session index, outbox, tool-call state and audit, rate-limit counters, replicas. | `HubStore`, `pgliteHubStore`, `postgresHubStore` | | | **Node** | One hub process or function instance. Several nodes share a store and a cluster adapter. | | | | **Cluster adapter** | Shares presence and carries messages between hub nodes. | `ClusterAdapter`, `memoryCluster`, `redisCluster`, `postgresCluster` | | | **Local policy** | Limits the user sets on their own computer for every website. | `localPolicy` in `~/.uncage/agent.yaml` | | | **Activity log** | The local record of everything websites did on a computer. | `uncage activity` | | | **Daemon** | Local Mode’s server, `uncage serve`, on `127.0.0.1:4783`. | `@uncage/server` | | | **Proxy** | Local Mode’s same-origin route in your app that forwards to the daemon with its token. | `createUncageHandler`, `createUncageNodeHandler` | | | **Draft** | A session-to-be in the UI, before the first prompt, holding settings and files. | `openDraft()`, `commitDraft()`, `isDraft` | | --- # Mount the hub > Complete Node servers that mount @uncage/hub in Express, Fastify, Hono, a Next.js custom server or plain node:http (traditional mode), the hub as a Fetch handler for serverless platforms, every createHub option, and proxies. The hub is a Fetch handler: `hub.fetch(request)` answers everything under its base path (default `/api/uncage`): the browser API, the device login, `install.sh` / `install.ps1`, and the computers’ HTTP streaming transport. How you mount it depends on where your website runs ([Choose a deployment mode](https://uncage.vercel.app/docs/start/choose-deployment-mode.md)): - **A long-running Node process (traditional mode)**: this page. From `@uncage/hub/node`, `toNodeHandler(hub)` mounts `hub.fetch` as Node middleware and `attachWebSocket(hub, server)` accepts the computers’ WebSockets on your HTTP server. The store is `pgliteHubStore`, an embedded Postgres in a folder: nothing else to run. - **Serverless or a Fetch platform (FaaS mode)**: [Next.js on Vercel](https://uncage.vercel.app/docs/deploy/vercel.md) (`toNextHandlers`), [Cloudflare Workers](https://uncage.vercel.app/docs/deploy/cloudflare-workers.md) (`fetchOnce`), [other Fetch platforms](https://uncage.vercel.app/docs/deploy/other-fetch-platforms.md) (`hub.fetch`). These need Postgres. Each example below is a complete Node.js 22+ server file. All of them import the same `getSessionUser` from `./auth`, which stands for your app’s sign-in (see [Auth and device approval](https://uncage.vercel.app/docs/guides/auth-and-device-approval.md)): ```ts title="auth.ts" /** Your sign-in: the user a request belongs to, or null. */ export async function getSessionUser(req: Request): Promise { const cookie = req.headers.get('cookie') ?? ''; // Look the session cookie up in your session store here. return cookie.includes('session=') ? { id: 'user-123', name: 'Ada' } : null; } ``` ## Express ```ts title="express-server.ts" const store = await pgliteHubStore({ dataDir: './.uncage-hub' }); const hub = await createHub({ publicUrl: process.env.PUBLIC_URL ?? 'http://localhost:3000', getUser: getSessionUser, store, }); const app = express(); // app.set('trust proxy', 1); // behind one reverse proxy: makes req.ip the client address (rate limits) app.use(toNodeHandler(hub)); // first, before express.json() or compression() app.use(express.json()); app.get('/', (_req, res) => { res.send('Your website'); }); const server = createServer(app); attachWebSocket(hub, server); // computers connect to ws(s):///api/uncage/agent server.listen(3000, () => console.log('http://localhost:3000')); ``` `toNodeHandler(hub)` only handles paths under `hub.basePath` and passes everything else to `next()`. Mounting it with a prefix (`app.use('/api/uncage', toNodeHandler(hub))`) works too; it reads `req.originalUrl`. ## Fastify Fastify parses request bodies itself, so give the hub a scope with no body parsers and hand it the raw request: ```ts title="fastify-server.ts" const store = await pgliteHubStore({ dataDir: './.uncage-hub' }); const hub = await createHub({ publicUrl: process.env.PUBLIC_URL ?? 'http://localhost:3000', getUser: getSessionUser, store, }); const hubHandler = toNodeHandler(hub); const app = Fastify(); await app.register(async (scope) => { // Leave the request body unread: the hub streams it itself. scope.removeAllContentTypeParsers(); scope.addContentTypeParser('*', (_req, _payload, done) => done(null)); for (const url of [hub.basePath, `${hub.basePath}/*`]) { scope.all(url, (req, reply) => { reply.hijack(); hubHandler(req.raw, reply.raw); }); } }); app.get('/', async () => 'Your website'); await app.ready(); attachWebSocket(hub, app.server); await app.listen({ port: 3000 }); ``` ## Hono (Node) With `@hono/node-server`, pass the Fetch `Request` straight to `hub.fetch` and give it the client address for rate limits: ```ts title="hono-server.ts" const store = await pgliteHubStore({ dataDir: './.uncage-hub' }); const hub = await createHub({ publicUrl: process.env.PUBLIC_URL ?? 'http://localhost:3000', getUser: getSessionUser, store, }); const app = new Hono(); const toHub = (c: Context) => hub.fetch(c.req.raw, { clientIp: getConnInfo(c).remote.address }); app.all(hub.basePath, toHub); app.all(`${hub.basePath}/*`, toHub); app.get('/', (c) => c.text('Your website')); const server = serve({ fetch: app.fetch, port: 3000 }); attachWebSocket(hub, server as Server); ``` ## Next.js (custom server) To keep traditional mode (WebSocket, embedded store, no database to run) in a Next.js app, run Next.js inside your own Node server and put the hub next to it: route handlers cannot accept WebSocket upgrades. This is what the [Connected Mode quickstart](https://uncage.vercel.app/docs/start/quickstart-connected.md) and the `connected-demo` example do. (Without a custom server, mount the hub in a route handler instead: [Next.js on Vercel](https://uncage.vercel.app/docs/deploy/vercel.md), which works under `next start` too.) ```ts title="server.ts" const dev = process.env.NODE_ENV !== 'production'; const port = Number(process.env.PORT ?? 3000); const hub = await createHub({ publicUrl: process.env.PUBLIC_URL ?? `http://localhost:${port}`, getUser: getSessionUser, store: await pgliteHubStore({ dataDir: './.uncage-hub' }), }); // Pages and Server Actions (for example /device) get the hub from here. (globalThis as Record)[Symbol.for('my-site.uncage-hub')] = hub; const hubHandler = toNodeHandler(hub); const server = createServer(); const app = next({ dev, hostname: 'localhost', port, httpServer: server }); const handle = app.getRequestHandler(); await app.prepare(); server.on('request', (req, res) => { hubHandler(req, res, () => void handle(req, res)); }); attachWebSocket(hub, server); if (dev) { const upgrade = app.getUpgradeHandler(); // hot reload server.on('upgrade', (req, socket, head) => { if ((req.url ?? '').split('?')[0] !== `${hub.basePath}/agent`) void upgrade(req, socket, head); }); } server.listen(port); ``` Start it with `node server.ts` (Node 22.18+ runs TypeScript directly) instead of `next dev`. The quickstart shows the matching `package.json` and `tsconfig.json` settings and a typed `getHub()` helper for pages. ## Plain `node:http` ```ts title="node-server.ts" const store = await pgliteHubStore({ dataDir: './.uncage-hub' }); const hub = await createHub({ publicUrl: 'http://localhost:3000', getUser: getSessionUser, store }); const hubHandler = toNodeHandler(hub); const server = createServer((req, res) => hubHandler(req, res)); // no next(): other paths get 404 attachWebSocket(hub, server); server.listen(3000); ``` ## Check it ```sh curl -s http://localhost:3000/api/uncage/install.sh | head -3 # public: prints the installer curl -s http://localhost:3000/api/uncage/agent/info # public: protocol and offered transports curl -s http://localhost:3000/api/uncage/health # needs a signed-in user: 401 without ``` `/agent/info` lists `ws` then `http` when `attachWebSocket` runs in this process (only `http` otherwise). `/health` answers `{"ok":true,"protocol":"1.0","version":"…"}` for a signed-in user and `401 unauthorized` otherwise. Add `.uncage-hub/` to `.gitignore`, and keep that folder on a persistent disk in production: it holds the paired computers. One process per folder (PGlite locks it); for several processes see [Multi-node](https://uncage.vercel.app/docs/guides/multi-node.md). ## `createHub` options `publicUrl`, `getUser` and `store` are required. | Option | Default | What it does | | --- | --- | --- | | `publicUrl` | (required) | Your website’s public origin, for example `https://app.example.com`. Used for the install and setup commands, the `/device` link, the transport URLs and the CSRF origin check. Must be `https://` (plain `http://` only for `localhost`, `127.0.0.1`, `[::1]`). | | `getUser(req)` | (required) | Your auth: `{ id, name? }` for a signed-in browser request or app (`Authorization: Bearer …`, [guide](https://uncage.vercel.app/docs/guides/authenticate-apps.md)), else `null`. | | `trustedOrigins` | `[]` | Extra exact origins allowed past the cross-site guard, such as `chrome-extension://` ([guide](https://uncage.vercel.app/docs/guides/browser-extension.md)). No wildcards or paths; https, extension schemes, or `http` on localhost only. Only origins you control. Native apps need none: they send no `Origin`. It adds no CORS headers: the hub does not answer preflights, so a trusted `https` origin only helps where your own framework adds CORS; extensions with host permissions bypass CORS. | | `onAttention(event, ctx)` | none | Called when an approval is requested or a run completes or fails, to send a push notification. At most once per event, never for events older than 10 minutes. `expoPushNotifier` is a ready handler. [Guide](https://uncage.vercel.app/docs/guides/push-notifications.md) | | `store` | (required) | `HubStore`. `pgliteHubStore({ dataDir })` from `@uncage/hub/node` for one Node process; `postgresHubStore({ connectionString } \| { pool })` for several nodes and FaaS. The hub never closes it. | | `cluster` | `memoryCluster()` | `ClusterAdapter`. `redisCluster` or `postgresCluster` for several nodes and FaaS. [Guide](https://uncage.vercel.app/docs/guides/multi-node.md) | | `basePath` | `/api/uncage` | Where the hub is mounted. If you change it, pass the same path to `UncageProvider` as `baseUrl`. | | `tools` | `[]` | Site tools from `defineTool`. [Guide](https://uncage.vercel.app/docs/guides/define-tools.md) | | `skills` | `[]` | `SkillSpec[]`. [Guide](https://uncage.vercel.app/docs/guides/write-skills.md) | | `selectManifest(ctx)` | all tools and skills | Picks tools and skills per run. [Guide](https://uncage.vercel.app/docs/guides/select-manifest.md) | | `sessionStorage` | `'machine'` | `'site'` keeps a replica of every conversation. [Guide](https://uncage.vercel.app/docs/guides/site-storage.md) | | `attachmentRetentionDays` | `30` | Days the hub keeps its copy of attachments sent through the website (`Infinity` keeps them). A revoked computer's attachments are deleted at once. [Details](https://uncage.vercel.app/docs/guides/site-storage.md#attachments) | | `site` | id and name from `publicUrl`’s host | `{ id?, name? }` shown to computers at pairing. Keep `id` stable. | | `verificationPath` | `/device` | Your approval page. [Guide](https://uncage.vercel.app/docs/guides/auth-and-device-approval.md) | | `minAgentVersion` | `0.3.0` | Older agents are told to upgrade (`upgrade_required`). Over WebSocket they upgrade themselves; in FaaS mode the website shows “Agent update needed”. | | `cliVersionRange` | `^` of the hub | Which `@uncage/cli` version `install.sh` / `install.ps1` install (`^0.3`, `~0.3.1`, `0.3.0` or `latest`). | | `installScript` | none | Static extra text for the installers: a step after the CLI install and/or your own “no agent found” help. | | `transports` | `['ws', 'http']` with `attachWebSocket`, else `['http']` | Transports offered to agents. List `ws` when another process serves the WebSockets at `/agent`; leave `http` out to offer WebSockets only. | | `stream` | `{ maxDurationMs: 250000 }` | The hub ends agent streams and browser event streams after this long, and clients reconnect at once without a gap. Keep it below your platform’s request time limit. | | `polling` | `{ activeMs: 300, idleMs: 2000, activeWindowMs: 30000 }` | How often an agent’s HTTP stream polls its outbox: fast while active, backing off to `idleMs` when quiet. | | `heartbeat` | `{ pingIntervalMs: 10000, missedPings: 2 }` | A silent computer shows offline after about 30 s. | | `sseHeartbeatMs` | `15000` | Keep-alive comments on browser event streams. | | `commandTimeoutMs` | `30000` | How long a browser request waits for the computer. | | `bodyTimeoutMs` | `30000` | A request body is refused with `400` if no bytes arrive for this long, or if it takes more than 4 times this long in total. Slow but steady uploads get through. | | `logger` | the console | Where the hub reports warnings and errors (`{ warn(obj, msg), error(obj, msg) }`; pino and most loggers fit). The default writes `[uncage] …` lines with `console.warn` and `console.error`. Pass `{ warn() {}, error() {} }` to silence it. On Vercel and Workers, `toNextHandlers` and `fetchOnce` log a one-time warning when the hub has no `cluster` (presence is then per instance); see [serverless hosting](#serverless-hosting-vercel-netlify-workers). | | `toolTimeoutMs` | `120000` | A tool handler still running after this fails with `tool_failed`. In FaaS mode keep it inside the platform’s time limit. | | `toolDrainMs` | `5000` | `hub.close()` lets running tool handlers finish for this long, then aborts them. | | `maxConcurrentToolCalls` | `8` | Tool calls one computer may have running at once on one hub instance. | | `rateLimits` | see below | Abuse limits for device login and machine tokens. | | `maintenance` | `{ intervalMs: 60000 }` | Retention cleanup, see below. | `rateLimits`: `deviceCodesPerMinute` (20 per client IP), `userCodeFailures` (10 failed code guesses per user) per `userCodeWindowMs` (10 minutes), `agentAuthFailuresPerMinute` (60 requests with a missing or wrong machine token per client IP; valid tokens are never limited), `clientIp(req)` and `trustForwardedFor` (see [behind a proxy](#behind-a-reverse-proxy-or-load-balancer)). Exceeding a limit answers `429 rate_limited`. The counts live in the store, so every node and function instance shares them. `maintenance` deletes what is no longer needed (unanswered run manifests after 1 h, others after 7 days; attachment copies after `attachmentRetentionDays`; deduplication rows and stored tool results after 24 h; expired outbox items and device codes) and fails site tool calls whose instance died mid-handler. It runs at most once per `intervalMs` across all instances: on a timer when `attachWebSocket` runs, otherwise triggered by requests (after the response when the platform gives a `waitUntil`). `secret` enables `GET|POST /maintenance` with `Authorization: Bearer `, for a platform cron (Vercel Cron sends `CRON_SECRET` this way). `onRun()` runs your own cleanup after each run. The `Hub` you get back has `basePath`, `fetch(req, info?)`, `approveDevice`, `denyDevice`, `lookupDevice`, `revokeMachine`, `maintain()` and `close()`. `info` is `{ clientIp?, waitUntil? }`. `close()` never closes the store, and closes the cluster only if the hub created it; close yours after it. ## Behind a reverse proxy or load balancer :::caution[Set the client IP before you go live] `POST /device/code` (every `uncage setup`) is limited to **20 per minute per client IP**. Behind a reverse proxy, load balancer or CDN the hub sees the proxy's address, not the user's, unless you tell it otherwise. Then **all your users share one bucket**: from the 21st setup in a minute, site-wide, `uncage setup` fails with `429 rate_limited`. Fix it with one of: - Express: `app.set('trust proxy', 1)` (the number of proxies in front of the app). `toNodeHandler` then passes `req.ip`. - Next.js on Vercel: nothing to do, `toNextHandlers` reads the address Vercel’s edge sets. Cloudflare Workers: pass `clientIp: req.headers.get('cf-connecting-ip') ?? undefined` to `fetchOnce`. - Any server: `rateLimits: { clientIp: (req) => req.headers.get('cf-connecting-ip') ?? undefined }` (use your platform's client-IP header). - `rateLimits: { trustForwardedFor: true }`, only if your proxy appends the client address to `X-Forwarded-For` (the hub uses the rightmost entry). ::: - **Forward WebSocket upgrades** on `/agent` (nginx: `proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";`), and allow long-lived connections (the hub pings every 10 s). If upgrades fail, agents fall back to HTTP streaming by themselves, but WebSocket is faster. - **Keep the original `Host`** (nginx: `proxy_set_header Host $host;`). The hub compares a request’s `Origin` with `publicUrl` and its `Host` to refuse cross-site POSTs. - **Do not buffer streams**: SSE on `/sessions/*/events` and NDJSON on `/agent/stream` (nginx: `proxy_buffering off;`). Allow requests of at least `stream.maxDurationMs` (250 s). - **Client IP for rate limits.** Express: `app.set('trust proxy', 1)`, and `toNodeHandler` uses `req.ip`. Fetch-style servers: pass `hub.fetch(req, { clientIp })`, or `rateLimits: { clientIp: (req) => req.headers.get('cf-connecting-ip') ?? undefined }` (or your platform’s header), or `trustForwardedFor: true` if your proxy appends the client address to `X-Forwarded-For`. Without any of these, every client is counted as the proxy's address (or as one `shared` bucket), so the limit applies to all users together. - **TLS.** Terminate it wherever you like, but `publicUrl` must be the `https://` URL users open. The agent refuses plain `http://` for anything but `localhost` and `127.0.0.1`. ## Serverless hosting (Vercel, Netlify, Workers) Serverless functions cannot hold WebSockets, but they do not need to: in FaaS mode the hub runs in your functions, keeps its state in Postgres, and computers connect over HTTP streaming. Follow the page for your platform: - [Next.js on Vercel](https://uncage.vercel.app/docs/deploy/vercel.md): `toNextHandlers(getHub, { waitUntil: after })` in `app/api/uncage/[...path]/route.ts`. - [Cloudflare Workers](https://uncage.vercel.app/docs/deploy/cloudflare-workers.md): `fetchOnce` creates a hub per request on a Hyperdrive pool. - [Other Fetch platforms](https://uncage.vercel.app/docs/deploy/other-fetch-platforms.md): `hub.fetch(req, { clientIp, waitUntil })`. Prefer to keep traditional mode next to a serverless site? Run one of the servers above as its own service on the same origin: [Node → FAQ](https://uncage.vercel.app/docs/deploy/node.md#my-site-is-on-vercel-or-netlify-can-i-still-use-traditional-mode). --- # Auth and device approval > Connect the hub to your sign-in with getUser, and build the /device approval page safely (signed-in only, frame-ancestors 'none', CSRF-protected POST), in Next.js or any Node server. The hub has no accounts of its own. It asks your website who is signed in, and it asks your website’s approval page to link a computer to that person. ## `getUser(req)` `getUser` receives every browser request to the hub as a Fetch `Request` and returns the signed-in user, or `null`: ```ts nocheck getUser(req: Request): Promise<{ id: string; name?: string } | null> ``` - `id` must be stable and unique per user: the hub stores machines, sessions and tool-call records under it, and passes it to your tool handlers as `ctx.user.id`. - `name` is optional, for display. - Returning `null` makes the request fail with `401 unauthorized`. The device endpoints the CLI uses (`/device/code`, `/device/token`, `/machine/revoke`) and `install.sh` are public and never call `getUser`. - It runs on every request (including each SSE connection), so make it fast: a signed-cookie check or a cached session lookup. ### From a session cookie Most sign-in libraries keep a session id or a signed token in a cookie. Read it from the `Cookie` header: ```ts title="auth.ts" /** Your session store: session id → user. */ declare function findSession(sessionId: string): Promise<{ userId: string; displayName: string } | null>; function readCookie(req: Request, name: string): string | undefined { for (const part of (req.headers.get('cookie') ?? '').split(';')) { const eq = part.indexOf('='); if (eq !== -1 && part.slice(0, eq).trim() === name) return decodeURIComponent(part.slice(eq + 1).trim()); } return undefined; } export async function getUser(req: Request): Promise { const sid = readCookie(req, 'session_id'); if (!sid) return null; const session = await findSession(sid); return session ? { id: session.userId, name: session.displayName } : null; } ``` If your library gives you a helper that takes a Fetch `Request` (many do), call it directly. The `examples/connected-demo` app uses an HMAC-signed cookie; see its `lib/auth.ts`. ### Cookies and CSRF The browser API is authenticated by your cookies, so the hub protects it against cross-site requests: a non-GET request whose `Origin` is neither `publicUrl` nor the request’s own host, or that is marked `Sec-Fetch-Site: cross-site`, gets `403 forbidden_origin`. Keep your session cookie `SameSite=Lax` (or `Strict`) and `Secure` as well. ## The approval page (`/device`) `uncage setup https://your.site` opens `https://your.site/device?code=ABCD-2345`. Change the path with the `verificationPath` option. On that page the signed-in user approves or denies the code. **Approving gives that computer access to the user’s account**, so the page is a target for clickjacking and CSRF. It must: 1. **Require the normal signed-in session.** If the user is not signed in, send them to your login page and back. 2. **Refuse framing:** `Content-Security-Policy: frame-ancestors 'none'` and `X-Frame-Options: DENY`. 3. **Decide with a CSRF-protected POST.** Never approve from a GET, or from the link alone. 4. **Show what is being approved:** the computer’s name and OS, and when and from which IP the code was requested (`requestedAt`, `requestIp`), all from `hub.lookupDevice`. 5. **Never trust a code that arrived in the link.** Warn, and enable Approve only after the user typed the code’s last 4 characters from their own terminal (see [Phishing links](#phishing-links)). ### Phishing links Anyone can run `uncage setup https://your.site` on **their own** computer and send one of your users the link it prints (or a QR code, or an app deep link). The page then opens pre-filled, and “check that the code matches your terminal” means nothing to someone who has no terminal. If the user approves, the sender’s computer is linked to the user’s account and receives their prompts, attachments and site-tool calls. The computer name and OS on the page come from the sender and prove nothing. So a code from the URL is not trusted on its own: - Show the warning “Only approve if you just ran `uncage setup` on a computer in front of you. Never approve a code someone sent you.” - Show when the code was requested (relative time: a code someone sent is usually minutes old) and the IP as seen by the server (`requestIp`, from the hub’s client-IP resolution; `null`, and not shown, when the hub had no trusted client IP). The IP is coarse on purpose: no geolocation. - Label the computer’s name and OS as reported by the computer, not verified. The hub drops a reported name or OS that contains the code’s last 4 characters, and strips control characters. - Hide the code’s last 4 characters and enable Approve only once the user typed them from the terminal of a computer they are sitting at. An attacker may try to tell the user those characters (in the message, on the phone): never type characters someone gave you; choose Deny. - Accept a code from the URL only in the exact shape the CLI prints (`ABCD-EFGH` or `ABCDEFGH`); anything else (extra dashes or spaces) is “not a valid link” and is not looked up, and the masked code is built from the compacted code. - When the user typed the whole code on your page (no code in the URL), no extra step is needed. Never decide that from the URL itself. - Deny stays one click. `` does all of this with `source="link"`, its default; pass `source="typed"` only for a code the user typed. `useDeviceApproval(code, { source })` does the same for your own screens. The hub gives you three calls, each taking the code and the signed-in user: | Call | Returns | | --- | --- | | `hub.lookupDevice(code, user)` | `{ name?, os?, expiresAt, requestedAt, requestIp, repairsMachine }` for a pending code, else `null`. `requestedAt` is when `uncage setup` asked for the code (ISO), `requestIp` the IP the hub saw then (or `null`). `repairsMachine` is set when approving would re-pair one of this user’s computers: it keeps its id and sessions, and its old token stops working. | | `hub.approveDevice(code, user)` | `'ok'`, `'not_found'` or `'expired'` | | `hub.denyDevice(code, user)` | `'ok'`, `'not_found'` or `'expired'` | Codes are 8 characters from `ABCDEFGHJKMNPQRSTUVWXYZ23456789`, shown as `ABCD-2345`, and valid for 10 minutes. Case, spaces and the dash are ignored. Unknown codes count as failed guesses: after 10 in 10 minutes (`rateLimits.userCodeFailures`, `userCodeWindowMs`) these calls throw an error with `code: 'rate_limited'` (`details.retryAfterSec`). `` from `@uncage/react-ui` renders the page: the computer, the request time and IP, the code, the phishing warning and the last-4 input (`source="link"`, the default), a re-pair warning, Approve and Deny, and the result. It is presentational; you make the decision on the server. Pass a failed call’s error to its `error` prop: it is shown localized (for `rate_limited`: “Too many requests. Wait a moment and try again.”), above the buttons when there is a lookup, or instead of “This code is invalid or has expired” when `lookupDevice` itself failed and `lookup` is `null`. ### Next.js The [Connected Mode quickstart](https://uncage.vercel.app/docs/start/quickstart-connected.md#7-the-approval-page) has the complete Next.js version: a server component that calls `lookupDevice`, a Server Action that calls `approveDevice` / `denyDevice` (Server Actions are POST-only and Next.js checks their `Origin`, which is the CSRF protection), a client component around ``, and the headers in `next.config.ts`. The same pattern, with a real sign-in redirect, is in `examples/connected-demo/app/device/`. Adding the headers only to the approval page: ```ts title="next.config.ts" const config: NextConfig = { async headers() { return [ { source: '/device', headers: [ { key: 'Content-Security-Policy', value: "frame-ancestors 'none'" }, { key: 'X-Frame-Options', value: 'DENY' }, ], }, ]; }, }; export default config; ``` ### Express (any Node server) Without Server Actions, write two small endpoints and check the origin yourself. This is a complete server (`getUser` is the one from [above](#from-a-session-cookie)); the page itself can be any React page that renders `` and calls these endpoints with `fetch`. ```ts title="server.ts" const PUBLIC_URL = process.env.PUBLIC_URL ?? 'http://localhost:3000'; const store = await pgliteHubStore({ dataDir: './.uncage-hub' }); const hub = await createHub({ publicUrl: PUBLIC_URL, getUser, store }); /** Your sign-in for Express requests (the same session as getUser). */ declare function userOf(req: ExpressRequest): Promise; const app = express(); app.use(toNodeHandler(hub)); app.use(express.json()); // Never framed. app.use('/device', (_req: ExpressRequest, res: Response, next: NextFunction) => { res.setHeader('Content-Security-Policy', "frame-ancestors 'none'"); res.setHeader('X-Frame-Options', 'DENY'); next(); }); /** CSRF: state-changing requests must come from this site. */ function sameOrigin(req: ExpressRequest): boolean { const origin = req.get('origin'); if (origin) return origin === new URL(PUBLIC_URL).origin; return req.get('sec-fetch-site') === 'same-origin'; } app.get('/device/lookup', async (req, res) => { const user = await userOf(req); if (!user) return void res.status(401).json({ code: 'unauthorized' }); const code = String(req.query.code ?? ''); try { res.json({ lookup: code ? await hub.lookupDevice(code, user) : null }); } catch (e) { const err = e as { code?: string; message?: string }; res.status(err.code === 'rate_limited' ? 429 : 500).json({ code: err.code ?? 'internal_error', message: err.message }); } }); app.post('/device/decision', async (req, res) => { if (!sameOrigin(req)) return void res.status(403).json({ code: 'forbidden_origin' }); const user = await userOf(req); if (!user) return void res.status(401).json({ code: 'unauthorized' }); const { code, approve } = req.body as { code?: unknown; approve?: unknown }; if (typeof code !== 'string' || typeof approve !== 'boolean') return void res.status(400).json({ code: 'invalid_request' }); try { const result = approve ? await hub.approveDevice(code, user) : await hub.denyDevice(code, user); res.json({ result }); // 'ok' | 'not_found' | 'expired' } catch (e) { const err = e as { code?: string; message?: string }; res.status(err.code === 'rate_limited' ? 429 : 500).json({ code: err.code ?? 'internal_error', message: err.message }); } }); const server = createServer(app); attachWebSocket(hub, server); server.listen(3000); ``` On the page, call `GET /device/lookup?code=…`, render `` (a code from the URL keeps the default `source="link"`), and `POST /device/decision` with `{ code, approve }` (the browser sends `Origin` on `fetch` POSTs). Map the answers to `ApproveDevice`’s `state`: `'ok'` → `'approved'` or `'denied'`; `'not_found'` and `'expired'` as they are; errors go to its `error` prop (the buttons stay enabled for a retry; with `lookup: null` the error replaces the “code not found” message). ## Revoking computers - **From your website:** ``’s computer menu lists the user’s computers. In your own UI, `useMachines().revoke(id)` or `DELETE /machines/:id`. On the server: `await hub.revokeMachine(machineId, user)` (throws `machine_not_found` for someone else’s or unknown id). - **From the computer:** `uncage sites remove ` revokes it on the website with its own token and removes the token locally. Either way the token stops working immediately and the computer is disconnected. Its sessions stay in your store (and on the computer). --- # React Native apps > Use @uncage/client and @uncage/react in an Expo / React Native app: streaming with expo/fetch, bearer-token headers, a storage adapter for the open session, photo uploads, resuming after the app was in the background, and approving a new computer from a phone. A native app is one more entry point to the same hub. It talks only to **your backend** (the hub), signs in with a bearer token you issue, and drives the user’s own computer exactly like your website does. The app never holds a machine token and never talks to the computer directly. `@uncage/client` and `@uncage/react` (the headless hooks) run in React Native without changes. They import nothing from `react-native` or `expo-*`; everything platform-specific is an adapter your app passes in. There is no React Native UI kit: [`examples/connected-expo`](https://github.com/ptmafia/uncage/tree/main/examples/connected-expo) shows how to build the screens with the hooks, to copy rather than install. :::note[Status] Built and unit-tested in a simulated React Native environment (no `window.location`, no `localStorage`, no `EventSource`, a streaming `fetch`, async headers). Verified on a real device: not yet, awaiting device confirmation. Expo Go covers chat, computers, approvals and photos; push and app links need a development build ([push notifications](https://uncage.vercel.app/docs/guides/push-notifications.md)). ::: ## 1. Hub side Your hub needs two things for apps: a `getUser` that accepts your app’s token ([authenticate apps](https://uncage.vercel.app/docs/guides/authenticate-apps.md)), and, optionally, push ([push notifications](https://uncage.vercel.app/docs/guides/push-notifications.md)). Native requests carry no `Origin` header, so the hub’s cross-site guard lets them through; a browser page from another site is still refused. ## 2. The client Install the packages and create the client with a streaming `fetch` and your token: ```ts nocheck export const client = createUncageClient({ baseUrl: 'https://your.site/api/uncage', fetch: streamFetch, // Called for every request and every stream (re)connect; may be async (token refresh). headers: async () => ({ authorization: `Bearer ${await getToken()}` }), }); ``` - **Streaming.** React Native’s built-in `fetch` cannot stream a response body, and the client reads events from `response.body.getReader()`. Expo’s `expo/fetch` streams. In bare React Native use any `fetch` polyfill that exposes `body.getReader()`. Where `TextDecoder` is missing (older Hermes) the client uses a small built-in UTF-8 decoder. - **Uploads.** `uploadAttachment` accepts a browser `File` or an `{ uri, name, type }` object from `expo-image-picker`. For the second form the client reads the file with the global `fetch(uri)` then sends it through your `fetch`. In Expo SDK 58 and later the global `fetch` is `expo/fetch` (React Native’s own `fetch` only with `EXPO_PUBLIC_USE_RN_FETCH=1`). It reads `file://` URIs but **not** `content://`: `expo-image-picker` already hands over `file://` copies, and any `content://` URI must be copied to a cache file first. `examples/connected-expo` keeps event streams on `expo/fetch` and sends other requests through the global one. `useAttachments().add()` accepts the same `{ uri, name, type, size? }` file references (the `AttachmentFile` type) as well as named `Blob`s. - **Images.** `client.attachmentUrl(id)` needs the auth header, so render with ``. - **Async headers.** If `headers()` throws (a failed token refresh) requests fail with `unauthorized` and `details.reason: 'headers'`; the stream reports it through `onError` and retries. ## 3. Hooks Wrap the app in `UncageProvider` and use the hooks as on the web (`useMachines`, `useSession`, `useRuns`, `useApprovals`, … ). Three things are specific to apps: ```tsx nocheck const storage: PersistSessionStorage = { get: () => SecureStore.getItemAsync('uncage.session'), set: (id) => (id === undefined ? SecureStore.deleteItemAsync('uncage.session') : SecureStore.setItemAsync('uncage.session', id)), }; export function useAppLifecycle() { usePersistSession(storage); // reopen the last conversation after a restart const reconnect = useReconnect(); useEffect(() => { const sub = AppState.addEventListener('change', (s) => s === 'active' && reconnect()); return () => sub.remove(); }, [reconnect]); } ``` - **`usePersistSession(storage)`** takes an adapter `{ get, set }` (sync or async: AsyncStorage, SecureStore, MMKV). With the default `'url'` or with `'localStorage'` and no `window` / `localStorage` it does nothing and never throws. - **`useReconnect()`** returns `client.reconnect()`: it restarts every open event stream at once from its last sequence, so after the app was in the background for minutes nothing is lost and nothing repeats. Call it when `AppState` becomes `active`. A stream that is healthy (bytes arrived in the last 20 seconds) is kept; `reconnect({ force: true })` restarts it anyway. - **`useDeviceApproval(code, { source })`** drives the approve screen below. ## 4. Approving a computer from the phone `uncage setup` prints the approval link as a terminal QR code (`--no-qr` turns it off; it is skipped when the output is not a terminal). If you map the hub’s verification path (`/device` by default) to your app with Android App Links or iOS universal links, scanning the code opens your approval screen; otherwise the phone opens your mobile web approval page. ```tsx nocheck export function ApproveScreen({ code, source }: { code: string; source: DeviceCodeSource }) { // source: 'link' (a verified app link: untrusted on its own) or 'typed' (the user typed the whole code). const { lookup, state, error, confirmation, approve, deny } = useDeviceApproval(code, { source }); // state: 'loading' | 'idle' | 'approving' | 'denying' | 'approved' | 'denied' // | 'not_found' | 'expired' | 'error' // lookup: { name?, os?, expiresAt, requestedAt, requestIp, repairsMachine } | null. // confirmation: { required, typed, matched, setTyped }: with 'link', approve() waits until // the user typed the code's last 4 characters (setTyped) and matched is true. // error: { code, message }, e.g. 'rate_limited' (10 wrong codes in 10 minutes). return null; // render the warning, lookup, a last-4 input, error, and approve() / deny() buttons } ``` **Phishing guard.** Anyone can run `uncage setup` against your site on their own computer and send a user the link, and any app or web page can open your custom URL scheme. So: - **Never pre-fill a code from your custom scheme** (`yourapp://device?code=…`): open the screen where the user types the code (`source: 'typed'`). - A code from a **verified** https App Link / universal link for your own site (the OS checked your `assetlinks.json` / `apple-app-site-association`) may be pre-filled, as `source: 'link'` (the default): `approve()` does nothing until the user typed the code’s last 4 characters (`confirmation.setTyped`, `confirmation.matched`). Hide those 4 characters on screen. - Either way show the warning “Only approve if you just ran `uncage setup` on a computer in front of you. Never approve a code someone sent you.”, the request time (`lookup.requestedAt`, as relative time) and IP (`lookup.requestIp`). `deny()` never needs the extra step. `examples/connected-expo` does exactly this (`app/+native-intent.tsx`, `lib/links.ts`, `app/device.tsx`). `state` is `'error'` when the lookup itself failed (for example `rate_limited`); call `retry()` to run the lookup again; a failed decision returns to `'idle'` with `error` set so the user can retry. `approve()` and `deny()` act only from `'idle'`. Under the hood these call [`GET /device/lookup` and `POST /device/decision`](https://uncage.vercel.app/docs/reference/http-api.md#device-approval-for-apps); `client.lookupDevice(code)` and `client.decideDevice(code, approve)` are the same without React. - **Android App Links:** serve `/.well-known/assetlinks.json` (package name and signing-certificate fingerprint) from your site. `examples/connected-demo` builds it from `ANDROID_PACKAGE` and `ANDROID_SHA256`. Built and unit-tested; awaiting device confirmation. - **iOS universal links:** serve `/.well-known/apple-app-site-association` (Team ID and bundle id: `APPLE_TEAM_ID`, `IOS_BUNDLE_ID` in the demo). Needs a paid Apple Developer account; implemented and configurable, **not verified on a device**. On iOS the QR code falls back to the mobile web approval page. ## Without a paid account Everything except iOS links and iOS push works with free tools: Expo Go for chat, computers, approvals, pickers and photos; a free Expo account with EAS for an Android development build (push, App Links); a free Firebase project for Android push. The example’s README has the steps. ## Next [Authenticate apps](https://uncage.vercel.app/docs/guides/authenticate-apps.md) · [Push notifications](https://uncage.vercel.app/docs/guides/push-notifications.md) · [Custom UI](https://uncage.vercel.app/docs/guides/custom-ui.md) · [HTTP API](https://uncage.vercel.app/docs/reference/http-api.md) --- # Authenticate apps > How a mobile app or other native client signs in to your hub: your getUser reads an Authorization bearer token that you issue, apps send no cookies and no Origin, and a website request from a foreign Origin is still refused. The hub never issues credentials for users. For apps, `getUser(req)` does what it does for the website: it returns the signed-in user, or `null`. The only difference is where it looks: an `Authorization: Bearer ` header instead of a cookie. ## What the hub does with an app request - A request with **no `Origin` header** (every native HTTP stack) passes the cross-site guard on every browser-API route, state-changing ones included. CSRF is a browser problem: only a browser attaches cookies to a request made by another site, and a browser always sends `Origin` on such a request. - A request with a **foreign `Origin`** (a web page on another site) is still refused with `403 forbidden_origin`, even with a valid cookie. - A bearer header is never added by a browser on its own, so a token cannot be abused through CSRF. So: let `getUser` accept either a cookie or a bearer token, and never trust the `Origin` yourself. ## `getUser` with a bearer token ```ts title="auth.ts" /** Your token check: a signed token, an OAuth access token, a session id … → user or null. */ declare function userForToken(token: string): Promise<{ id: string; name: string } | null>; /** Your cookie check (the web sign-in). */ declare function userForCookie(req: Request): Promise<{ id: string; name: string } | null>; export async function getUser(req: Request): Promise { const header = req.headers.get('authorization'); if (header !== null) { // A bearer header decides alone: an invalid token is never rescued by a cookie sent with it. const m = /^Bearer\s+(\S+)$/i.exec(header.trim()); return m ? await userForToken(m[1]!) : null; } return userForCookie(req); } ``` Issue the token from the sign-in you already have (OAuth, your session system, a magic link). Give it an expiry and a renewal route, store it in the platform keychain in the app (`expo-secure-store`), and send it with the client’s async `headers` option ([React Native apps](https://uncage.vercel.app/docs/guides/react-native.md#2-the-client)). ## The demo’s tokens `examples/connected-demo` shows the minimum, **for a demo only**: - `POST /api/app/token` returns `{ token, user, expiresAt }`. The token is `uat1...`, valid 30 days, signed with a key derived from the cookie key under its own label, so a cookie is never a valid app token and the reverse. It answers, in this order: a renewal for a valid bearer token (an invalid one is `401`), the signed-in cookie user, on the public demo (`DEMO_PUBLIC=1`) a fresh random guest (at most 10 new guests per client IP per minute, then `429` with `Retry-After`), else `{ "username": "…" }` from the body (no password: demo only). - It refuses a request with a foreign `Origin`, like every state-changing route. - A real site issues tokens from its own authentication and verifies them in `getUser` as above. ## Checklist - [ ] Tokens are random or signed, expire, and can be revoked; they are stored in the keychain, not in plain storage. - [ ] `getUser` returns `null` for a bad bearer token; it does not fall back to a cookie. - [ ] The token endpoint is rate limited and refuses foreign `Origin`s. - [ ] You do not list `null` / `file://` or wildcards in `trustedOrigins`: apps do not need it ([browser extensions](https://uncage.vercel.app/docs/guides/browser-extension.md) do). See also [auth and device approval](https://uncage.vercel.app/docs/guides/auth-and-device-approval.md) and the [security page](https://uncage.vercel.app/docs/reference/security.md#app-bearer-tokens). --- # Push notifications > Notify users when their computer needs them: the hub's onAttention hook (approval requested, run completed or failed), at-most-once delivery with stale-event suppression, the ready expoPushNotifier for Expo Push, registering device tokens, and how to test. When an approval is waiting or a run ends, a user with the app in their pocket should find out. The hub calls your `onAttention` hook for that; you send the push through your own provider. For Expo Push there is a ready handler. ## `onAttention` ```ts title="attention.ts" export const onAttention: OnAttention = async (e: AttentionEvent, { waitUntil }) => { // e.kind: 'approval_requested' | 'run_completed' | 'run_failed' // e.userId, e.sessionId, e.sessionTitle?, e.machineId, e.machineName?, e.runtime?, // e.approval?: { id, title, category }, e.at (when it happened on the computer) waitUntil(sendPush(e.userId, `${e.kind}: ${e.sessionTitle ?? e.sessionId}`)); }; declare function sendPush(userId: string, text: string): Promise; ``` Pass it as `createHub({ …, onAttention })`. How it behaves: - **Once per event.** It fires after the hub accepted the event, in both `sessionStorage` modes, once per `sessionId:sequence:kind`: an agent that resends, or several hub nodes that all see the event, notify once. The dedupe uses the optional store method `claimOnce(key, { ttlSec, now })` (implemented by the SQL, Postgres and PGlite stores, claims kept for a day). A custom store without `claimOnce` gets per-node in-memory dedupe, best effort. - **Delivery is at most once.** If your handler throws or rejects, the error goes to `logger.error` and the event is **not** retried. - **Never blocks ingest.** Errors never fail the event. On FaaS platforms the call runs under the request’s `waitUntil`; `ctx.waitUntil` hands more work to the same context. - **Stale events are skipped.** An event whose time is older than **10 minutes** (an agent backfilling after a reconnect) never notifies. In `'site'` mode an approval that the stored snapshot already shows answered is skipped too. - **Clock note.** “Older” compares the event’s time from the computer’s clock with the hub’s clock. Keep both within a few minutes (NTP). A computer whose clock is more than 10 minutes behind never notifies; the hub logs a warning about it, at most once an hour per machine. ## What leaves your hub A push goes from your hub to Expo, then to Apple or Google, and shows on the lock screen. So by default `expoPushNotifier` sends **no conversation content**: only “An approval needs you”, “A run finished” or “A run failed” (with a short “Open the app…” body) and the deep-link `data` (`sessionId`, `approvalId?`, `kind`). The app loads the details over its own signed-in connection. `includeContent: true` is an explicit opt-in to the older, more specific text: the session title and the **approval title**. Runtimes set the approval title from the tool call, so it often names a shell command or a file path. Each text is one line of at most 180 characters, but it still passes through Expo, Apple or Google, and shows on the lock screen. Turn it on only if your users accept that: ```ts declare const tokensFor: (userId: string) => Promise; // Default: generic text only ("An approval needs you", "A run finished", "A run failed"). expoPushNotifier({ tokensFor }); // Opt in: the session title and the approval title (often a command or a path) go to the lock screen. expoPushNotifier({ tokensFor, includeContent: true }); ``` ## `expoPushNotifier` ```ts title="hub.ts" declare const tokenDb: { list(userId: string): Promise; remove(token: string): Promise; }; export const onAttention = expoPushNotifier({ // The user's Expo push tokens, from YOUR database: the hub never stores them. tokensFor: (userId) => tokenDb.list(userId), // Expo reported DeviceNotRegistered (app uninstalled): delete the token. onInvalidToken: (token) => tokenDb.remove(token), }); ``` It uses only `fetch`, so it runs anywhere the hub does (it is exported from the Web-standard root). It sends one message per token, in requests of at most 100, with `data: { sessionId, approvalId?, kind }` so the app can open the right chat. | Option | | | --- | --- | | `tokensFor(userId)` | Required. The user’s Expo push tokens. | | `accessToken` | Expo access token when enhanced push security is on. | | `message(e)` | `{ title, body }` per event, or `null` to send nothing. The default is short generic English text without conversation content (`defaultPushMessage`); localize here. | | `includeContent` | `true` adds the session title and the approval title to the default text (they reach Expo, Apple / Google and the lock screen). Default `false`. Ignored when you pass `message`. | | `onInvalidToken(token)` | Called for tokens Expo reports as `DeviceNotRegistered`. | | `fetch`, `endpoint` | Replace `fetch` or the Expo endpoint (tests). | | `timeoutMs` | A request to Expo unanswered after this is aborted and the call rejects (the hub logs it). Default `15000`. | It rejects (and the hub logs, with error codes and counts but never tokens) when a request fails or times out, when `onInvalidToken` throws, or when Expo refused messages for another reason, for example `InvalidCredentials`. When several sends fail, it rejects with an `AggregateError` that holds all of them. ## Registering tokens The app asks permission, gets its token with `expo-notifications` (`getExpoPushTokenAsync({ projectId })`) and sends it to **your** backend, which stores it per user. `examples/connected-demo` has `POST /api/app/push-token` `{ token }` (and `DELETE` on sign-out), validates the token shape and keeps at most 10 per user (oldest dropped). It also drops tokens not re-registered for 30 days. A token belongs to one user at a time: the latest sign-in on the device wins, so a shared device does not leak notifications to the previous user. Treat tokens as semi-secret. In the demo, set `EXPO_PUSH=1` (and optionally `EXPO_ACCESS_TOKEN`) to switch the hub’s `onAttention` on. ## What works where - Remote push needs a **development build**: Expo Go has none on Android since SDK 53. - **Android:** a free Expo account with EAS builds an Android development build; a free Firebase project supplies FCM credentials. Built and unit-tested against a fake Expo endpoint; **awaiting device confirmation**. - **iOS:** needs a paid Apple Developer account (APNs). Implemented and configurable; **not verified on a device**. ## Testing Unit-test the handler with a fake `fetch` (the option exists for that) and a hub whose agent emits `approval.requested`: expect one call, none for the same sequence again, none for events older than ten minutes. The hub’s own tests do exactly this. See also [mount the hub](https://uncage.vercel.app/docs/guides/mount-the-hub.md#createhub-options) and [React Native apps](https://uncage.vercel.app/docs/guides/react-native.md). --- # Browser extensions > Put the agent in a Chrome Manifest V3 side panel: AgentChat against your hub with the site's cookies, trustedOrigins for chrome-extension:// (exact origins only), stable extension ids, cookie and SameSite caveats, and bearer tokens as the alternative. A browser extension is a client like any other: the side panel renders `` from `@uncage/react-ui` against your hub. [`examples/connected-extension`](https://github.com/ptmafia/uncage/tree/main/examples/connected-extension) is a complete Chrome (Manifest V3) side panel built with Vite. :::note[Status] Built and tested: the repository’s `extension-mock` end-to-end project loads the unpacked extension in Chromium, signs in on the demo, connects a fake agent and runs a session from the panel. Using it by hand in your own Chrome profile: awaiting confirmation. ::: ## The panel ```tsx nocheck const client = createUncageClient({ baseUrl: `${HUB_ORIGIN}/api/uncage`, fetch: (url, init) => fetch(url, { ...init, credentials: 'include' }), }); export const Panel = () => ( ); ``` There is no sign-in screen in the extension. The manifest’s host permission for your site’s origin plus `credentials: 'include'` send the user’s **cookies for your site**, so `getUser` sees the user who is already signed in there. If you would rather not depend on cookies, send a bearer token instead (`createUncageClient({ headers })`, see [authenticate apps](https://uncage.vercel.app/docs/guides/authenticate-apps.md)). ## Tell the hub to trust the extension The extension’s origin, `chrome-extension://`, is a different origin from your site, so the hub’s cross-site guard refuses its state-changing requests. List it: ```ts title="hub.ts" declare const base: Omit; export const hub = createHub({ ...base, trustedOrigins: ['chrome-extension://abcdefghijklmnopabcdefghijklmnop'], }); ``` `trustedOrigins` rules (`createHub` throws on a bad entry): - Exact origins only: `scheme://host[:port]`, lower case, no wildcard, path, query, credentials or trailing slash. List every id you ship (store build, development build). - Allowed schemes: `https`, `chrome-extension`, `moz-extension`, `safari-web-extension`, and `http` only for `localhost`, `127.0.0.1` and `[::1]`. `file:`, `data:`, `javascript:`, `blob:` and others are refused. - **Only origins you control.** A trusted origin is allowed to make state-changing requests with the user’s cookies. Any script that runs in that extension acts as the user, so ship it like a first-party app. - This does not weaken the guard for websites: every other foreign `Origin` is still refused. - It does not add CORS. The hub sends no CORS headers and does not answer preflight, so it is meant for extensions (whose host permission bypasses CORS) and native shells. A web page on a trusted `https` origin can call the hub from a browser only if your framework adds CORS. In `examples/connected-demo`, set `TRUSTED_ORIGINS=chrome-extension://` (comma-separated). ## Extension ids An unpacked extension’s id depends on its path unless `manifest.json` carries a fixed public `key`. The example ships a throwaway key so its id is stable (`chrome-extension://bocaoaanfikfdhmnhipmjpkcepaioapj`) in development; remove it for your own extension. Chrome Web Store builds get their id from the store: put that one in `trustedOrigins`. ## Build and load ```sh HUB_ORIGIN=https://your.site pnpm --filter connected-extension build ``` `HUB_ORIGIN` (the site’s origin, no path) becomes the manifest’s only `host_permissions` entry and the panel’s `baseUrl`. For a local hub, run the demo in development mode, `TRUSTED_ORIGINS=chrome-extension:// pnpm --filter connected-demo dev` (the `start` script is production mode and needs `pnpm build` first). Open `chrome://extensions`, turn on Developer mode, **Load unpacked** and pick the `dist` folder; click the toolbar icon to open the side panel. Sign in on the site in the same Chrome profile and connect a computer ([one-click connect](https://uncage.vercel.app/docs/guides/one-click-connect.md) or `uncage setup`). ## Cookies and SameSite Chrome sends a site’s cookies to extension pages that hold the host permission, including `SameSite=Lax` ones. If your session cookie is `SameSite=Strict`, or the user blocks third-party cookies for your site, the panel shows the signed-out state: use a bearer token. See also [mount the hub](https://uncage.vercel.app/docs/guides/mount-the-hub.md#createhub-options) and the [security page](https://uncage.vercel.app/docs/reference/security.md). --- # One agent, every site > Connect a computer that already runs Uncage to another Uncage site in one click: the uncage:// link handler, uncage connect, the native confirmation with site identity checks (domain, IDN, IP, first time, look-alike), the local dashboard, and the phishing threat model. A user installs the Uncage agent once. Every site that embeds Uncage can then use it, without another terminal: the site shows a link, the user clicks it, confirms on their own computer, and approves on the site as usual. :::note[Status] Built and unit-tested on macOS, Linux and Windows. The test that registers the real handler runs on the macOS, Linux and Windows CI runners (throwaway scheme, temporary home). One-click on a user’s own computer, the real dialogs and the dashboard in a real browser: awaiting device confirmation. ::: ## How it works 1. `uncage setup` (or `uncage agent install`) installs the background agent **and** registers a handler for `uncage://` links with the operating system. `uncage agent uninstall` removes it again. - **macOS:** a small per-user application, `~/Library/Application Support/Uncage/UncageConnect.app`, registered with LaunchServices. No admin rights. - **Linux:** `~/.local/share/applications/uncage-connect.desktop` and `xdg-mime default` for `x-scheme-handler/uncage`. Skipped with a note when `xdg-mime` is missing. - **Windows:** `HKCU\Software\Classes\uncage` (the current user only). 2. Your site shows **Already use Uncage on this computer? Connect in one click**: the `` panel links to `uncage://connect?url=` (the hub’s [`installInfo.connectUrl`](https://uncage.vercel.app/docs/reference/http-api.md); hidden on mobile). The install command stays the primary path, because a page cannot tell whether the handler exists. 3. The OS runs `uncage connect `, which validates the link, shows the **native confirmation** and, only on Connect, starts the normal device flow: the browser opens the site’s `/device` page and the user clicks Approve. 4. The new site is saved in `~/.uncage/agent.yaml` and the background agent restarts. You can also run it by hand: `uncage connect https://app.example.com`. See the [CLI reference](https://uncage.vercel.app/docs/reference/cli.md#uncage-connect). One-click needs `@uncage/cli` 0.4 or newer. An existing 0.3 install gets the handler only after `npm i -g @uncage/cli@latest` and running `uncage agent install` (or `uncage setup`) again, because that is the only place it is registered. ## What is accepted `uncage connect` accepts `uncage://connect?url=` with **exactly one** parameter, or a bare URL. It refuses, before anything else happens, a site URL that: - is not `https://` (plain `http://` only for `localhost`, `127.0.0.1`, `[::1]`), - carries a user name or password, a query or a fragment, - contains spaces or control characters, or is longer than 2048 characters, - has any other scheme (`javascript:`, `data:`, `file:`) or any other `uncage://` action or parameter. ## The confirmation and site identity checks Before any pairing, a dialog on this computer asks: **Connect this computer to `example.com`?** It shows the site’s **registrable domain** first (from the Public Suffix List, including private suffixes such as `vercel.app`, so each project there is its own owner), then the full hub URL, and what connecting allows: whoever runs the site can start coding-agent sessions on this computer at any time and answer their approval prompts within your local policy, so only connect sites you trust. The warnings come before the URL, and a very long URL is shortened. **Cancel is the default.** The dialog is in the system language (English, Chinese or Japanese). It adds a line for each of these: | Warning | When | | --- | --- | | International characters | The host is an IDN; its punycode form is shown. | | Bare IP address | The site is an IP, not a domain. | | A specific page | The path is neither the root nor the default `/api/uncage`: on a shared origin a path can belong to someone other than the domain’s owner. | | First time | This computer never connected to that registrable domain before. | | Looks like another site | The label has the same look-alike skeleton as a connected domain (digits and Cyrillic or Greek letters mapped to Latin, `rn` ≈ `m`, …), or is within edit distance 2 of it. For names shorter than 4 characters, only a look-alike match counts. | How the question is asked, per operating system: | OS | Dialog | | --- | --- | | macOS | `/usr/bin/osascript` (an alert that gives up, as a No, after 10 minutes) | | Windows | A message box (`WScript.Shell` Popup) with OK and Cancel (default Cancel), shown through the system’s own Windows PowerShell | | Linux | `zenity` (preferred), else `kdialog`, when a display is available (`DISPLAY` or `WAYLAND_DISPLAY`). With only `kdialog` the buttons are “Don’t connect” (the default), Connect and Cancel | If there is no dialog tool, or it could not be shown (no graphical session), and the command runs in a terminal, it asks `Connect? [y/N]` there. Without a dialog and without a terminal it refuses and prints how to run it by hand. **No dialog, no connection.** Also: - Only one question at a time: a page that fires links repeatedly cannot stack dialogs. - Every prompt, including the terminal one, counts as a No after 10 minutes. - After the user cancels, the same domain cannot ask again for 30 seconds (for links). - The registered handler runs `uncage connect --from-link `, and the outcome, connected or not and why, is shown as a system notification: on macOS in Notification Center through `osascript` (notifications may need to be allowed for Script Editor), on Linux with `notify-send` when installed, on Windows as a message box that closes after 60 seconds (the run is hidden, so the console only flashes). - Connecting restarts the background agent, which interrupts running sessions of the other sites. - After the user confirms, the approval page the hub announces must be on the confirmed origin, and the site that answers must be the confirmed URL; otherwise nothing is saved. - A site’s self-declared name is never shown without its domain. - Exit codes: `0` connected, `1` cancelled, refused or pairing failed (`Not connected: `), `2` bad link. ## The local dashboard `uncage dashboard` opens a page for this computer’s connected sites: - each site with its name and domain, machine id, connected since, status (online, offline, revoked) and transport, the runtimes it is offered, and its recent redacted activity; - **Disconnect**: revokes the machine token on the site (like `uncage sites remove`) and restarts the agent; - turn ACP agents on or off (the same consent as `uncage runtimes enable|disable`), and a read-only view of the local policy. It is a page on `127.0.0.1` at a random port. The link is `http://127.0.0.1:/#t=…`: the one-time token sits in the fragment, which browsers never send to a server. The page trades it once for an API token that it keeps in `sessionStorage` and removes the fragment from the address bar; there is no cookie. Reloading works in that tab; another tab or browser cannot use the link again. Every request must have the right `Host` (`127.0.0.1:`, which defeats DNS rebinding), no foreign `Origin` and the API token in a header, otherwise it gets `403`. There are no CORS headers. It exits when the page is closed or after 30 minutes without a request (`--no-browser` prints the link instead of opening it). The page follows the system language. ## Threat model One-click makes a phishing attempt cheaper: any web page can fire `uncage://connect?url=https://evil.example`. If it worked silently, the attacker, who is signed in on their own site, would approve the victim’s computer into **their** account and could then drive the user’s coding agent there. What stops that: - **The native confirmation** shows who is asking, outside the web page, and defaults to No. A page cannot click it. - **Identity warnings** make look-alikes, IDNs, IP hosts and first-time sites stand out. - **Against a hostile site the device flow adds nothing:** the site controls its own `/device` page and can approve on its side. **The native confirmation is the only gate**, so confirm only sites you trust. (For an honest site the device flow still compares the code and shows the computer.) - **No central registry:** Uncage does not vouch for sites. The dialog shows what the link says, not a verdict; users should only confirm a connection they just started. - What a connected site can do on the computer is unchanged: the [trust model](https://uncage.vercel.app/docs/concepts/trust-model.md), the [local policy](https://uncage.vercel.app/docs/guides/local-policy.md) and per-tool approvals. The dashboard shows and revokes every connection. See the [security page](https://uncage.vercel.app/docs/reference/security.md#one-click-connect). --- # Define tools > Give Claude Code your website's capabilities with defineTool, run them as the signed-in user, ask for confirmation, return results, read files from the user's computer with ctx.files, and test handlers. A **site tool** is a function of your website that Claude Code, running on the user’s computer, can call. You write it once, in your backend: ```ts title="tools.ts" /** Stand-in for your database. */ declare const db: { orders: { find(q: { id: string; userId: string }): Promise<{ id: string; status: string; total: number } | null> }; }; export const lookupOrder = defineTool({ name: 'lookup_order', description: 'Look up one of the signed-in user’s orders by its id (for example "ord_123"). Returns status and total.', input: z.object({ id: z.string().regex(/^ord_\w+$/).describe('The order id, as shown on the website'), }), handler: async ({ id }, ctx) => { const order = await db.orders.find({ id, userId: ctx.user.id }); if (!order) throw new Error(`No order ${id} in your account.`); return { id: order.id, status: order.status, total: order.total }; }, }); ``` and pass it to the hub: `createHub({ …, tools: [lookupOrder] })`. ## What happens on a call 1. The user’s computer only ever receives the tool’s **name**, **description** and the **JSON Schema** of `input` (generated with `z.toJSONSchema`). Claude Code sees the tool as `mcp__site__lookup_order`. 2. When Claude Code calls it, the agent sends the call to the hub (over its WebSocket, or as an HTTP POST in FaaS mode). The hub instance that receives it checks that: - the session belongs to this computer and to its user; - the run was started through the hub, and the tool was in **this run’s manifest** (see [selectManifest](https://uncage.vercel.app/docs/guides/select-manifest.md)); - the arguments match `input`. They are parsed with it, so zod defaults and transforms apply. A mismatch fails with `invalid_request` and the handler is not called. 3. Your handler runs **in your backend** with the parsed arguments and a `ctx`. 4. The return value goes back to Claude Code as the tool result. The call is recorded in the hub’s store (`store.listToolCalls(sessionId)`), and the browser sees it in the session’s events as a normal tool step. ## The pieces of `defineTool` | Field | Rules | | --- | --- | | `name` | `^[a-z][a-z0-9_]{0,47}$`, no `__`. Unique among your tools. | | `description` | Up to 1000 characters. Written **for the model**: say what it does, when to use it, what it returns, and what to call before or after. | | `input` | A zod schema (zod 4) for an object. Use `.describe()` on fields: descriptions end up in the JSON Schema the model reads. The schema must be representable as JSON Schema; keep it simple (no transforms that change the JSON shape the model must send). | | `requiresConfirmation` | `true`: the user approves every call in your UI first. | | `handler(args, ctx)` | `args` is typed from `input`. Returns a value (below) or throws. | `createHub` throws at startup on an invalid tool (bad name, duplicate name, or a schema over 64 KB). ## `ctx` | Property | What it is | | --- | --- | | `ctx.user` | `{ id, name? }`: the session’s owner, as your `getUser` returned it. Use it for every lookup and write. | | `ctx.sessionId`, `ctx.runId` | The session and run that made the call. | | `ctx.signal` | An `AbortSignal`, aborted when the call is abandoned: it timed out (`toolTimeoutMs`, 120 s by default), the run ended (Stop), or the hub is closing and `toolDrainMs` ran out. A dropped connection does **not** abort it: the result is stored and delivered when the computer reconnects. Pass it to your own I/O (`fetch(url, { signal: ctx.signal })`). | | `ctx.files` | The [file channel](#reading-files-from-the-users-computer). | ## Returning results - A **string** becomes one text block. - Any other **JSON value** (object, array, number) becomes one JSON block. - For full control, return a `ToolCallResult`: `{ content: [{ type: 'text', text }, { type: 'json', json }], isError?: boolean }`. `isError: true` tells the model the call did not work, without throwing. - `undefined` / `null` becomes an empty result. The result must fit in one message: a little under 1 MiB of JSON. Larger results fail with `tool_failed`. Return an id or a URL instead of a large payload. ## Errors **A thrown error’s message is shown to the user and to the model.** It travels to the computer as the tool error (`tool_failed`, with your message). So: - throw messages that help the model recover: `No order ord_9 in your account.`, `Title is already used; pick another.`; - never put stack traces, SQL, internal hostnames, tokens or other users’ data in them; - log the details on your side. Other failures you may see in the tool step: `invalid_request` (arguments did not match `input`), `tool_failed` with `details.reason: 'not_in_manifest'` (the tool was not offered to this run), `'too_many_concurrent'` (more than `maxConcurrentToolCalls`, 8 by default, running for one computer), or a timeout. ## Asking for confirmation ```ts title="invoice-tools.ts" declare const mailer: { send(o: { from: string; to: string; subject: string; text: string }): Promise }; export const sendInvoice = defineTool({ name: 'send_invoice', description: 'Email an invoice to the customer. The user confirms each send.', input: z.object({ invoiceId: z.string(), to: z.string().email() }), requiresConfirmation: true, handler: async ({ invoiceId, to }, ctx) => { await mailer.send({ from: ctx.user.id, to, subject: `Invoice ${invoiceId}`, text: '…' }); return `Sent ${invoiceId} to ${to}.`; }, }); ``` With `requiresConfirmation: true`, every call shows an approval card in your UI (category `mcp`, titled with the tool’s description, showing `send_invoice({"invoiceId":…,"to":…})`). The handler only runs after **Allow once**. This happens in every permission mode, including `bypassPermissions` and `auto`. If the user denies, Claude Code is told and usually asks what to change. Use it for anything that publishes, sends, pays, deletes or is visible to other people. Tools without it run without a card (Claude Code may still show the step). ## Reading files from the user’s computer The run’s files live on the user’s computer, in the session workspace. A handler reads them through `ctx.files` instead of having Claude Code paste contents into arguments: - `ctx.files.pull(path, { maxBytes? })` returns every file under `path` (a file or a folder, relative to the workspace). Iterate it with `for await`. Limits: `maxBytes` total (default and maximum 50 MiB), 10 MiB per file. - `ctx.files.read(path)` returns one file’s bytes (`Uint8Array`, at most 10 MiB). A folder fails with `invalid_request`, a missing path with `not_found`. Rules the computer enforces: - Paths must stay inside the session workspace. `../x`, absolute paths and anything resolving outside are refused. - Symlinks are never followed. - In a folder pull, files with more than one hard link are skipped and listed in `pull.skipped` (`{ path, reason }`) once iteration finishes. - A pull is **all-or-nothing**: files are yielded only after all of them arrived. If anything fails part-way (too large, disconnect, the call ends), nothing is yielded and the loop throws. Paths are normalized first (`./site//index.html` → `site/index.html`). Pulled `path`s are relative to the workspace (`site/index.html`), not to the folder you asked for. This is the publishing tool from `examples/connected-demo`, slightly trimmed: ```ts title="publish.ts" /** Your asset storage. */ declare const assets: { get(id: string): Promise<{ id: string; owner: string } | null>; publish(id: string, files: Array<{ path: string; data: Uint8Array }>): Promise<{ url: string }>; }; export const publishAsset = defineTool({ name: 'publish_asset', description: 'Publish a folder of the workspace as the asset’s files (index.html entry, at most 20 MB). The user confirms each publish.', input: z.object({ assetId: z.string().min(1).max(40).describe('The assetId returned by create_asset'), dir: z.string().trim().min(1).max(200).describe('Folder relative to the workspace, e.g. "landing"'), }), requiresConfirmation: true, handler: async ({ assetId, dir }, ctx) => { const asset = await assets.get(assetId); // Same message for "missing" and "someone else's": never confirm that another user's id exists. if (!asset || asset.owner !== ctx.user.id) throw new Error(`Unknown asset ${assetId}. Create one with create_asset first.`); const pull = ctx.files.pull(dir, { maxBytes: 20 * 1024 * 1024 }); const prefix = `${dir.replace(/^\.\/+|\/+$/g, '')}/`; const files: Array<{ path: string; data: Uint8Array }> = []; for await (const f of pull) { if (!f.path.startsWith(prefix)) throw new Error(`"${dir}" must be a folder containing index.html.`); files.push({ path: f.path.slice(prefix.length), data: f.data }); } const { url } = await assets.publish(assetId, files); return { assetId, url, files: files.map((f) => f.path), ...(pull.skipped.length > 0 ? { skipped: pull.skipped } : {}) }; }, }); ``` Treat pulled files as **untrusted input**: they were written by an AI agent on someone else’s computer. If you serve them (HTML, SVG), serve them from a sandbox. The demo serves published pages with `Content-Security-Policy: sandbox allow-scripts; default-src 'none'; …` and shows them in `