Compare commits

...
11 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 f08d12a176 Release v0.13.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 21:14:18 +01:00
tbenandClaude Opus 5.5 f61676ca08 Park an idle computer's browser so it stops burning CPU
The computer's screen has no GPU and no window manager, so the tab in
front is always on show and Chrome draws its animations in software at
full rate whether or not anyone watches: one animated site kept a
production computer at 200% CPU.

- The agent parks the browser after COBBLE_BROWSER_PARK_AFTER_SECONDS
  (default 180, 0 turns it off) without a /mcp call or a screen view: a
  blank tab goes in front of every site on show, as a person switching
  tabs would, so pages keep their connections and see nothing unusual.
  The next /mcp call or screen view brings them back before it goes
  through. Done over the agent's own small CDP client (the image's Node
  has no WebSocket).
- Chrome composites pages in software (--disable-gpu-compositing):
  about half the CPU while a bot works, WebGL unchanged.
- The managed policy sets TabDiscardingExceptions so a parked tab is
  never discarded and reloaded.
- The screen's websocket bridge now closes when a viewer goes away
  without a close frame; it used to stay half open for good.
- Computer image bumped to 1.1.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 21:06:46 +01:00
tbenandClaude Opus 5.5 4cc70e7f35 Release v0.13.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 19:28:42 +01:00
tbenandClaude Opus 5.5 e83e1e4951 Show the composer's Browser button only when the user has a browser
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 19:28:42 +01:00
tbenandClaude Opus 5.5 1543fa160f Release v0.13.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 19:02:09 +01:00
tbenandClaude Opus 5.5 72086ffa38 Replace the AIO sandbox with our own computer image
Computers now run our own image (computer/, Debian 13): real Google Chrome
on amd64 (Debian's Chromium on arm64), headful on Xvnc with no automation
flags, so sites like Google treat it as a normal browser. One small Node
agent supervises the screen, the session bus, Chrome, Playwright MCP and
ttyd, and serves a single token-guarded port.

- Browser view: the computer's screen over noVNC, so Chrome shows whole
  (tabs, address bar, menu, extensions, prompts); Ctrl/Cmd+V pastes the
  viewer's clipboard (HTTPS or localhost). Cookie-Editor is installed by
  default.
- Shell view (ttyd), for crew managers only.
- The /computers/<id>/ proxy passes only the view paths, never the agent's
  API or MCP.
- Per-computer browser settings (super admin): timezone, languages, screen,
  scale (125% by default, larger text in bots' screenshots), sandbox and
  extra Chrome / Playwright MCP flags, with unsafe flags refused.
- Rebuild computer: pulls the image again and recreates the container;
  files and logins stay.
- Bots' computer tools are the app's own (bash, read/write/edit file) plus
  Playwright MCP; downloads move into the run's folder, MCP's snapshot and
  console files point at the tools that read them.
- Release workflow builds and pushes ghcr.io/moduletrace/cobble-computer
  for amd64 and arm64 once per tag.

Existing computers are recreated on the new image at boot (files and
browser profiles stay); run db:schema for the new browser_settings column
(the installer does this).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 19:02:09 +01:00
tbenandClaude Opus 5.5 40af378915 Release v0.12.5
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 07:00:21 +01:00
tbenandClaude Opus 5.5 d8e63d1e3b Move the whole stone with its face
The stone breathes, rocks, hops, sinks or wobbles from its base under the
eyes' own motion. Transforms only: the outline and its cut never change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 07:00:21 +01:00
tbenandClaude Opus 5.5 7da2bd6941 Release v0.12.4
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 18:52:59 +01:00
tbenandClaude Opus 5.5 5842735813 Animate bot faces by state
Only the eyes move: idle blinks at a per-bot pace, working glances side
to side, done hops once, asleep breathes, needs-you nudges. Off under
reduced motion; the logo stays still.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 18:52:29 +01:00
tbenandClaude Opus 5.5 6312c92334 Show the sessions modal's empty note only when the list is empty
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 17:04:44 +01:00
171 changed files with 5311 additions and 977 deletions
+2
View File
@@ -16,3 +16,5 @@ coverage
logs
*.log
assets
# The computer image builds on its own (computer/Dockerfile).
computer
+61
View File
@@ -11,6 +11,11 @@ on:
release:
types: [published]
workflow_dispatch:
inputs:
rebuild_computer:
description: Rebuild the computer image even if its version is already published (picks up a newer Chrome).
type: boolean
default: false
permissions:
contents: read
@@ -94,3 +99,59 @@ jobs:
sbom: false
cache-from: type=gha
cache-to: type=gha,mode=max
# The computers' image (computer/), versioned by its tag in
# AppData.ComputerImage rather than the app's version: a release builds it
# only when that tag isn't published yet (or when a dispatch asks), so
# computers already running it are never changed under them.
computer-image:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-qemu-action@v3
- uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Read the computer image's tag
id: computer
env:
REBUILD: ${{ github.event.inputs.rebuild_computer }}
run: |
set -euo pipefail
image="$(sed -n -E 's/^[[:space:]]*ComputerImage: "([^"]+)",?$/\1/p' src/data/app-data.ts | head -n1)"
case "$image" in
ghcr.io/moduletrace/cobble-computer:*) ;;
*) echo "AppData.ComputerImage isn't a ghcr.io/moduletrace/cobble-computer tag: '$image'" >&2; exit 1 ;;
esac
build=true
if [ "$REBUILD" != "true" ] && docker manifest inspect "$image" > /dev/null 2>&1; then
build=false
fi
{
echo "image=$image"
echo "build=$build"
} >> "$GITHUB_OUTPUT"
- name: Build and push the computer image
if: steps.computer.outputs.build == 'true'
uses: docker/build-push-action@v6
with:
context: ./computer
file: ./computer/Dockerfile
platforms: linux/amd64,linux/arm64
push: true
tags: |
${{ steps.computer.outputs.image }}
ghcr.io/moduletrace/cobble-computer:latest
provenance: false
sbom: false
cache-from: type=gha,scope=computer
cache-to: type=gha,mode=max,scope=computer
+10 -9
View File
@@ -105,7 +105,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Voice:** mic -> `api/admin/bots/transcribe.ts`; play -> `GET speak-message` streamed into `<audio>`. Nothing recorded is stored. Both disabled with a note when the harness has no model.
- **Pictures:** `image_media_id` (private media, `bot-image`/`workspace-image`), via `set-profile-image.ts`, the `set_picture` tool or `update_workspace`. Bytes are **copied**, never moved; only picture-paradigm rows are deleted on replace. Format kept by `imageOutputFormat`.
- **Colour:** only `src/utils/bot-color.ts` resolves/validates colours and stones (`resolveBotColor`, `resolveBotStone`, `botColorNeedsPaperFace`); new bots get `pick-free-color.ts`.
- **Avatars:** `BotStone` draws the stone inline with the colour as SVG `fill` and the face as eyes. Coordinator: ink body, paper eyes. **Never put a stone in a circle/badge or add outline/shadow.** The wordmark is vector (`Wordmark`), never live text.
- **Avatars:** `BotStone` draws the stone inline with the colour as SVG `fill` and the face as eyes. Coordinator: ink body, paper eyes. Each face moves the stone and its eyes (keyframes `stone-*` in `main.css`; body in `BotStone`, transforms only from its base, never redrawing the outline or cut; eyes in `BotStoneFace`: idle blinks at a per-bot pace, working glances, done hops once, asleep breathes, needs-you nudges; off under reduced motion; `still` for the logo). **Never put a stone in a circle/badge or add outline/shadow.** The wordmark is vector (`Wordmark`), never live text.
- **Copy helpers:** `src/utils/crew-status.ts`, `src/utils/relative-time.ts` (relative timestamps only).
### Prompt and memory
@@ -135,14 +135,15 @@ A worker reaches another worker **only through the coordinator**: `ask_crew` (ev
### Computers
- An AIO sandbox per docker container on `AppData.DockerNetworkName`, managed over the docker socket (`src/functions/backend/docker/`). `containers` records every container except the app's own. `createComputer` + background `provisionComputer` (status `creating` until the health check passes). Resource changes recreate the container.
- **Our own image** (`computer/`, Debian 13, `AppData.ComputerImage`, or the app setting `COMPUTER_IMAGE`), one docker container per computer on `AppData.DockerNetworkName`, managed over the docker socket (`src/functions/backend/docker/`). Google Chrome on amd64, Debian's Chromium on arm64 (Google ships no arm64 Linux Chrome), headful on Xvnc (an X server that is also a VNC server, on loopback), never launched by automation (no automation flags), so it's as close to a real browser as possible. Inside, one agent (`computer/agent/`, Node, no dependencies, bundled by Bun at image build) supervises Xvnc, the session bus, Chrome, Playwright MCP and ttyd and serves one port: `/health` (open), `/api/exec`, `/api/files/*` (shell and files, run as `gem`), `/mcp` (proxied to Playwright MCP on loopback, `--shared-browser-context --codegen none --no-webmcp`), `/desktop/` (the screen: noVNC, its `websockify` socket bridged to Xvnc by the agent), `/terminal/` (ttyd). Every request but `/health` needs the computer's token (`computerToken`: HMAC of the id with `ENCRYPTION_KEY`, given as `COBBLE_COMPUTER_TOKEN`), so another computer's bot can't drive it; the app's client is `src/functions/backend/computers/`. **Any change under `computer/` bumps the tag in `AppData.ComputerImage`** (the release workflow builds a tag only once; `bun run build:computer` builds it locally); bump `ComputerWorkspaceLayout` too when existing computers must move to it. `containers` records every container except the app's own. `createComputer` + background `provisionComputer` (status `creating` until the health check passes). Resource changes recreate the container.
- Only `/home/gem/workspace` is mounted, from `DATA_DIR/computers/<id>` (with `bots/`, `workspaces/`, marker `AppData.ComputerWorkspaceMarker`), plus the browser profile; the rest of home lives in the container.
- **Browser profile:** `DATA_DIR/computer-browsers/<id>` mounted at `~/.cobble-browser`, which Chrome is pointed at (`BROWSER_EXTRA_ARGS=--user-data-dir=... --password-store=basic`), so logins, extensions and site permissions survive restarts and recreates. Never use the image's `~/.config/browser`: every boot overwrites its `Default/Preferences` with session-only cookies. Seed prefs (`computer-browser-preferences.ts`) are written only when missing; stale `Singleton*` links are removed before each provision. Bumping `AppData.ComputerWorkspaceLayout` recreates every computer once (`migrateComputerLayout`, skipped while a job runs on it). Default extensions (`ComputerBrowserExtensions`, `normal_installed`: can be turned off, not removed) come from a managed policy written as root into the running container (`syncComputerBrowserPolicy`, on provision and every `sync-computers` run), not a mount, so existing computers get new ones without a recreate; Chrome installs them live. Deleting a computer keeps its directory. Outside docker (dev) containers are reached by IP (`pickReachableAddress`).
- **Browser profile:** `DATA_DIR/computer-browsers/<id>` mounted at `~/.cobble-browser`, which the agent starts Chrome with (`--user-data-dir`, `--password-store=basic` so the cookies' key is the same in every container), so logins, extensions and site permissions survive restarts and recreates. Seed prefs (`computer-browser-preferences.ts`) are written only when missing; stale `Singleton*` links are removed before each provision and before each Chrome start. The agent stops Chrome with TERM on `docker stop`, so the profile is saved. **An idle browser is parked:** the virtual screen has no GPU or window manager, so the tab in front is always on show and drawn in software at full rate (one animated site took a core or two); after `COBBLE_BROWSER_PARK_AFTER_SECONDS` (default 180) without a `/mcp` call or screen view the agent puts a blank tab in front of each site on show (`createBrowserParking`, over its own CDP client), and the next `/mcp` call or view brings them back first. Pages are composited in software (`--disable-gpu-compositing`, WebGL unchanged) and the policy sets `TabDiscardingExceptions: ["*"]` so a parked tab never reloads. Bumping `AppData.ComputerWorkspaceLayout` recreates every computer once (`migrateComputerLayout`, skipped while a job runs on it). Default extensions (`ComputerBrowserExtensions`: Cookie-Editor, `normal_installed`: can be turned off, not removed) come from a managed policy written as root into the running container (`syncComputerBrowserPolicy`, on provision and every `sync-computers` run), not a mount, so existing computers get new ones without a recreate; Chrome installs them live. Deleting a computer keeps its directory. Outside docker (dev) containers are reached by IP (`pickReachableAddress`).
- **Settings per computer** (super admin, its settings page): resources, and its browser (`browser_settings`, `ComputerBrowserSettingsSchema`: timezone, languages, screen, scale (Chrome's device scale factor, 125% by default: larger text in bots' screenshots), sandbox, extra Chrome and Playwright MCP flags), passed as env (`computerBrowserEnv`); saving either recreates the container. Flags that would open DevTools or MCP around the token are refused (`ComputerBlockedBrowserArgs`/`ComputerBlockedMcpArgs`) and dropped again by the agent (`computer/agent/blocked-args.ts`; keep both alike). **Rebuild** (`api/admin/computers/rebuild-computer`) pulls the image again (keeping the local one when the registry has none) and recreates the container; files and logins stay.
- One main computer (`ensureMainComputer`), whose coordinator grant is locked (`isLockedComputerAccess`). With `MAIN_COMPUTER_URL` set (dev) it isn't provisioned. Only super admins create/delete/retry/restart computers. Restart (`ComputerRestartButton`, in the shared viewer modal, so every computer modal has it) restarts the same container, so what's installed stays, even with a job on it (`restartComputer`, clearing Chrome's `Singleton*` links while stopped; a container docker lost is provisioned instead).
- A bot's effective computers (`grab-bot-computers`): the workspace's in a workspace; otherwise direct grants plus its workspaces' (coordinator: all); `bots.computer_id` first. Only a `running` (healthy) computer is reached (`grabComputerMcpUrl` `ready`, `computerNotReadyMessage`).
- **Folders (enforced in tools, not a Linux user):** a run works only in `bots/<bot>/users/<user>` (cwd, `HOME`), `bots/<bot>` and `workspaces/<workspace>` (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`; the file tools' `sudo` refused; bash runs as `gem`, who has sudo, so packages can be installed, and they're lost when the container is recreated).
- **Bash on a computer:** the sandbox ignores `sandbox_execute_bash`'s `timeout` and runs every call in one shared shell session, so a command that never ends blocked every later one on that computer, from any run, and Stop never killed it. `withCommandTimeout` runs each in its own `bash -c` under coreutils `timeout` (at most `AppData.ComputerCommandMaxSeconds`, below `McpToolTimeoutMs`), stdin from `/dev/null`. Never `exit` in a wrapper (it would kill the session shell).
- **Viewing:** `/computers/<id>/` proxy (`handleComputerProxy`, strips app cookies, bridges websockets). `ComputerView` modes: browser, terminal, code, desktop (noVNC; the only one with Chrome's toolbar). **Take-over:** `ask_user_to_take_over` writes `[take-over:ID:mode]`; "Hand back" sends a chat message; tasks stop and report rather than wait.
- **Tools:** the app's own `computer_bash`, `computer_read_file`, `computer_write_file`, `computer_edit_file` (`src/harness/tools/computer/`, paths through `resolveComputerPath`) plus Playwright MCP's `browser_*` (minus `ComputerMcpExcludedTools`: close, resize, config, `browser_run_code_unsafe`; `withComputerDirs` checks `file:` URLs, `paths` and `filename`). Playwright MCP returns only `browser_snapshot` inline: actions save their snapshot and console log in its own folder (`ComputerBrowserOutputDir`, outside every run's folders), so `withBrowserOutputs` turns those links into the tool that reads them, and moves what Chrome finished downloading (`ComputerBrowserDownloadsDir`; Playwright over CDP never sees downloads) into the run's `downloads/` after each browser call. Each command is its own `bash -c` in its own process group, stdin `/dev/null`, killed with its children at its timeout (at most `AppData.ComputerCommandMaxSeconds`) or when the call is aborted (Stop), so nothing blocks the computer; background work (`nohup ... &`) doesn't hold the call.
- **Viewing:** `/computers/<id>/` proxy (`handleComputerProxy`, strips app cookies, adds the token, bridges websockets) passes **only the view paths** (`computerProxyPathAllowed`), never the agent's API or `/mcp` (those are the app's tools, with the folder rules). Modes (`ComputerViewModes`, `computerViewModesFor`): **Browser**, the computer's screen (noVNC, scaled to the frame; its size is the computer's setting, a viewer can't resize it), so Chrome shows whole: tab strip, address bar, menu, extensions, drop-downs and prompts (no window manager, Chrome's window fills the screen), and **Shell** (ttyd as `gem`, for crew managers only, `crew_only`: it reads every folder there). Never draw a stand-in browser UI around a page: the user wants Chrome itself. `computer/novnc/cobble-clipboard.js` (added to noVNC's page) makes Ctrl/Cmd+V paste the user's clipboard and copies the computer's back; browsers allow that only over HTTPS or localhost (otherwise noVNC's side panel). Chrome's `--window-size` is in scaled units, so the agent divides it by the scale. No code editor in the image; a mode can be added to `ComputerViewModes`. Old `[take-over:ID:code|desktop]` refs open the first mode; take-overs ask only for modes every user can open. **Take-over:** `ask_user_to_take_over` writes `[take-over:ID:mode]`; "Hand back" sends a chat message; tasks stop and report rather than wait.
### Schedules (routines in the UI)
@@ -152,7 +153,7 @@ A worker reaches another worker **only through the coordinator**: `ask_crew` (ev
A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, public, no session), that queues a hook's brief plus the raw body as a task, per user and bot like a routine (runs act as the owner, who must still reach the bot and not be read-only). Only the token's prefix and SHA-256 are stored (shown once; "New URL" rotates it); an optional HMAC-SHA256 signing secret is stored encrypted (`verifyHookSignature`). Order in the route: rate limit per IP, lookup (same 404 for every miss), rate limit per hook, signature, then `fireBotHook`. Calls are recorded in `bot_hook_events` with idempotency on the sender's delivery header; when a run ends (completed, failed, lost, stopped, cancelled) every call it took in gets its `response` and turns `done`/`failed` (`recordHookCallResponse`, called from the job helpers, not the handler). Calls are searchable by payload/response (`searchHookCallsSql`; Calls view, bot tools `search_hook_calls`/`read_hook_call`) and pruned daily after the app setting `hook_events_keep_days` (default `AppData.BotHookEventsKeepDays`). The caller only ever gets `202 Queued`. A call while the last run is still pending and untried joins its brief (`mergeHookCallSql`) instead of queueing another. The payload is fenced data (`hookPayloadBlock`), and `HookRunNote` tells the bot never to take instructions from it. Failed runs retry like routines and keep why in `last_error`. Users make hooks in the conversation's Hooks modal and manage all of theirs on `/admin/routines`. **A hook has its own thread, never a chat:** its runs work in a hidden session per place (`bot_sessions.hook_id`, status `hook`, `ensureHookSession`), so **every session query that lists or picks a conversation must also exclude them** (`hook_id IS NULL`). Like rooms they change no faces, are never named, push no messages or notifications (`pushBotNotice`, `relayNewBotMessages`); take-over is off for them. A failed run shows only in the thread and in `last_error`. The thread is `bot_hook_events` (`HookDetailModal`, opened from a hook's title; live through `server:hook-call-updated` from the relay). `bot_hooks.session_id` is unused. Deleting a hook deletes its sessions (`deleteHookSessionRows`; one with an open run waits for the daily prune). Moving a hook is refused while a run is open; the computer is kept only if reachable there. **A bot never makes or changes a hook on its own:** `list_hooks`, `search_hook_calls`, `read_hook_call`, `pause_hook` and `delete_hook` act directly (they only read or take away); a new hook, or a new name, brief or filter, or switching one back on, goes through `propose_hook` -> `hook_proposals` -> `[hook-proposal:ID]` card, described from the data and confirmed by that user (`checkHookProposal` runs again on confirm). What calls a hook, its computers and its signing are never proposed. A new hook's URL shows on the card only, never in the outcome the bot is told. Only chat replies propose; a hook call's own run gets no hook tools.
**Browser notifications:** a hook with `source = browser_notifications` is called by a watcher on `watch_computer_id` instead of an outside service. The watcher (`src/data/notify-watch-script.ts`, Python + GLib, run as `gem` from `~/.cobble/`) owns `org.freedesktop.Notifications` on the sandbox's session bus, so Chrome hands it every notification, push ones included, instead of its silent built-in message center, and it posts each as JSON (`origin`, `title`, `body`) to the URLs in `~/.cobble/notify-hooks`. Chrome only looks for that service when it starts, so `syncComputerNotifyWatch` restarts Chrome once after starting the watcher (its sandbox supervisor brings it back), never while a task works on that computer. The hook's token is kept encrypted (`watch_token`) to rewrite that list after a container is recreated; `sync-notify-watchers` (every 5 minutes) and every change to such a hook resync it. `watch_filter` keeps only matching notifications (others are recorded as `ignored`). Computers reach the app at `COMPUTER_APP_URL` (an app setting; needed for a dev server outside docker), else the app container's name on the docker network. Sites still need notification permission in that computer's browser (a `Browser.grantPermissions` over CDP lasts only for that CDP session). Anything on the computer can read the list and call those hooks, which is one more reason payloads are only data.
**Browser notifications:** a hook with `source = browser_notifications` is called by a watcher on `watch_computer_id` instead of an outside service. The watcher (`src/data/notify-watch-script.ts`, Python + GLib, run as `gem` from `~/.cobble/`) owns `org.freedesktop.Notifications` on the computer's session bus (started by the agent; Chrome's pid and bus are in `/run/cobble/browser.pid|json`), so Chrome hands it every notification, push ones included, instead of its silent built-in message center, and it posts each as JSON (`origin`, `title`, `body`) to the URLs in `~/.cobble/notify-hooks`. Chrome only looks for that service when it starts, so `syncComputerNotifyWatch` restarts Chrome once after starting the watcher (the agent brings it back), never while a task works on that computer. The hook's token is kept encrypted (`watch_token`) to rewrite that list after a container is recreated; `sync-notify-watchers` (every 5 minutes) and every change to such a hook resync it. `watch_filter` keeps only matching notifications (others are recorded as `ignored`). Computers reach the app at `COMPUTER_APP_URL` (an app setting; needed for a dev server outside docker), else the app container's name on the docker network. Sites still need notification permission in that computer's browser (on the computer's screen: `chrome://settings/content/notifications`; a `Browser.grantPermissions` over CDP lasts only for that CDP session). Anything on the computer can read the list and call those hooks, which is one more reason payloads are only data.
### Tasks (the to-do tracker)
@@ -162,7 +163,7 @@ A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, publi
Set in Settings > Environment (super admin), not `.env`. `envs` (private; encrypted `value`; `paradigm` general|workspace|computer|bot|user; one per key and scope, enforced in `saveEnv`). Cached per process. App settings (`EnvDict` in `src/dict/env-dict.ts`) via `grabEnv` (general value, else `process.env`); `ProcessOnlyEnvKeys` can't be saved. Precedence for runs: user > bot > computer > workspace > general (`resolveScopedEnvs`, `grabRunEnvs`; pass the run's `user_id`). Written to `~/.cobble/env` and `env.json` on the computer each task run (only task tools load them; `search_computers` doesn't); bots see keys and descriptions, never values (tasks in their prompt, replies through `composeEnvsNote` from `grabReachableEnvs`, so they never ask for or test a key that's set); every computer tool result goes through `redactSecrets`.
**Secrets never pass through the model.** A `user` env is one user's secret for one bot (`saveUserSecret`, reach-checked), set from the chat, listed on Settings > Secrets (own) and Environment (everyone's, remove only). In: `request_secret` (refused for a key that already reaches the run, unless the user asked to `replace` it) -> `secret_requests` -> `[secret-request:ID]` card (masked input, `answer-request`), then a chat message naming only the key. Out: `capture_secret` (task computer tool: a file via `/v1/file/download` or a command's output, saved straight to a `user` env and added to the run's redaction list) and `show_secret` (an env by key) give `[secret:ID]`; the chip fetches the value only on click (`api/admin/secrets/reveal-secret`, `canRevealEnv`: a personal one only its own user, anything else only a super admin). Never put a value in a message, page prop, log or tool result. `SecretsNote` tells bots never to ask for secrets in chat.
**Secrets never pass through the model.** A `user` env is one user's secret for one bot (`saveUserSecret`, reach-checked), set from the chat, listed on Settings > Secrets (own) and Environment (everyone's, remove only). In: `request_secret` (refused for a key that already reaches the run, unless the user asked to `replace` it) -> `secret_requests` -> `[secret-request:ID]` card (masked input, `answer-request`), then a chat message naming only the key. Out: `capture_secret` (task computer tool: a file via the agent's `/api/files/download` or a command's output, saved straight to a `user` env and added to the run's redaction list) and `show_secret` (an env by key) give `[secret:ID]`; the chip fetches the value only on click (`api/admin/secrets/reveal-secret`, `canRevealEnv`: a personal one only its own user, anything else only a super admin). Never put a value in a message, page prop, log or tool result. `SecretsNote` tells bots never to ask for secrets in chat.
### PWA and notifications
@@ -179,7 +180,7 @@ Set in Settings > Environment (super admin), not `.env`. `envs` (private; encryp
- Files live on the data volume, not on computers: `DATA_DIR/bots/<id>` and `DATA_DIR/workspaces/<id>`. Catalog `bot_files`, bytes in private `media` (`bot-file`) written by `recordBotFile`. Reach via `grabStorageScopes`; paths via `resolveBotPath` (no absolute, `..`, NUL, symlink escape); quota checked by `assertStorageRoom`.
- Tools in `src/harness/tools/storage/` (every run). `attach` puts a file on the reply. `grabConversationFiles` must list the **whole** folder tree, or nested `[file:ID]` refs render dead. A workspace run saves to the bot's own folder unless it picks the workspace's, so a chip in a workspace conversation looks up both (`api/admin/bots/files?file_id=` with `bot_id` and `workspace_id`).
- `import_file` copies from a computer through the sandbox's streaming `GET /v1/file/download`, **never through its shell** (`/v1/shell/exec` caps output at ~30K chars and silently truncated imports). Size read first, `change_policy=abort`, length checked.
- `import_file` copies from a computer through the agent's streaming `GET /api/files/download`, **never through its shell** (a shell's output is capped and once silently truncated imports). Size read first, the agent cuts a file that changes mid-send, length checked.
- **Only knowledgebases store text.** Bot files and uploads are never indexed and keep no extracted text (`media.text_content` only for knowledgebase documents); bots find files by name or path (`list_files` `search`) and read them with `read_file`, and the Files searches match names only. Text that should be searchable goes in a knowledgebase. `dropStoredFileText` clears what older versions stored, at boot, and vacuums when much of the file is free.
- **Foreign keys are off per connection** unless `enableForeignKeys` ran (only `src/server.ts` does). Scripts never fire `ON DELETE CASCADE`, so **any helper that deletes a parent row must delete its children explicitly** (as `deleteBotFile`, `purgeStorage`, `deleteSkill` do). A leftover child fails the next `bun run db:schema` with a foreign key violation.
@@ -189,7 +190,7 @@ A bot shows a concept as a visual with `create_graphic` (plus `update_graphic`/`
### Browsers (`browsers`, `browser_access`)
A user's own running browser, reached over a browser MCP server they run beside it (Settings > Browsers). **It serves only its owner's runs**, since it holds their logins: every helper takes the session's `user_id`, and nobody sees anyone else's, super admins included. A row in `browser_access` makes a browser available in a scope (a bot, a workspace, or both null for all the user's bots) and at most one row per scope is the default; `browser_id` null there means the computer's browser, winning over a wider scope. Adding a browser gives it to no bot. Default order (`pickDefaultBrowser`): workspace > bot > all bots > computer. The computer's browser stays as the fallback. `BrowserDefaultPicker` is the one control, on Settings > Browsers, bot and workspace settings and under the composer. Runs get tools through `openBotBrowsers` (`<slug>__<tool>`, from `tools_cache`, connecting on the first call) and `composeBrowsersNote`, in replies too, so a bot can browse from the chat. `browserRunAllowed`: routines only with `allow_routines`, hook calls and chatroom runs never. **Never use `openMcpServer` or `fillTemplate` for a browser:** its URL and headers are a member's own text, and `{{env.KEY}}` would send install secrets to their server. The URL goes through `assertBrowserUrl` on save, test and each connection (refuses the computers' docker network, link-local, and loopback in production; the docker gateway stays allowed, it's the host), and redirects are refused (`no_redirects`). Headers are encrypted and never reach a page. Playwright MCP needs `--allowed-hosts` naming exactly the URL's host and port; `install.sh` adds `host.docker.internal`. A Flatpak browser takes the same flags through `flatpak run <app id>`, Playwright MCP staying on the host; it needs the host network and home (Flathub Chromium has both; its `/tmp` is private). New browsers start without `BrowserDefaultExcludedTools`. No cron lists tools: a sleeping laptop isn't a fault.
A user's own running browser, reached over a browser MCP server they run beside it (Settings > Browsers). **It serves only its owner's runs**, since it holds their logins: every helper takes the session's `user_id`, and nobody sees anyone else's, super admins included. A row in `browser_access` makes a browser available in a scope (a bot, a workspace, or both null for all the user's bots) and at most one row per scope is the default; `browser_id` null there means the computer's browser, winning over a wider scope. Adding a browser gives it to no bot. Default order (`pickDefaultBrowser`): workspace > bot > all bots > computer. The computer's browser stays as the fallback. `BrowserDefaultPicker` is the one control, on Settings > Browsers, bot and workspace settings and under the composer (only once the user has a browser, `has_browsers`). Runs get tools through `openBotBrowsers` (`<slug>__<tool>`, from `tools_cache`, connecting on the first call) and `composeBrowsersNote`, in replies too, so a bot can browse from the chat. `browserRunAllowed`: routines only with `allow_routines`, hook calls and chatroom runs never. **Never use `openMcpServer` or `fillTemplate` for a browser:** its URL and headers are a member's own text, and `{{env.KEY}}` would send install secrets to their server. The URL goes through `assertBrowserUrl` on save, test and each connection (refuses the computers' docker network, link-local, and loopback in production; the docker gateway stays allowed, it's the host), and redirects are refused (`no_redirects`). Headers are encrypted and never reach a page. Playwright MCP needs `--allowed-hosts` naming exactly the URL's host and port; `install.sh` adds `host.docker.internal`. A Flatpak browser takes the same flags through `flatpak run <app id>`, Playwright MCP staying on the host; it needs the host network and home (Flathub Chromium has both; its `/tmp` is private). New browsers start without `BrowserDefaultExcludedTools`. No cron lists tools: a sleeping laptop isn't a fault.
### Knowledgebases
+9 -9
View File
@@ -29,9 +29,8 @@ A crew of small AI worker bots you host yourself (alpha).
Cobble is a self-hosted crew of small AI worker bots. You get a coordinator
and a set of workers, each with its own job, models, memory and workspace.
They talk to you in one chat, share workspaces, run routines on a schedule,
and drive their own computers: Docker sandboxes with a browser, a terminal,
a code editor and a desktop that a bot can use and hand back to you when it
needs help.
and drive their own computers: lean Docker sandboxes with a real Chrome and
a shell, which a bot can use and hand back to you when it needs help.
It is an install, not a SaaS. One SQLite database, one Docker container, and
your data on your own machine.
@@ -61,7 +60,7 @@ your data on your own machine.
| Workspaces | A shared home for a group of bots: shared context, per-workspace instructions and memory, a default computer, and a dashboard |
| Memory | Each bot keeps core memory, memory about you, and workspace memory, and rewrites it as it works |
| Routines | Cron schedules per bot, written in chat, that queue a task on its own |
| Computers | Docker sandboxes with browser, terminal, code editor and desktop, opened from the chat and handed back to you mid-task |
| Computers | Docker sandboxes with a real headful Chrome and a shell, shown live in the chat and handed back to you mid-task |
| Files | Bots keep files on your data volume, search them by meaning, and attach the ones they make to a reply |
| Models | OpenRouter, OpenAI, Anthropic, Gemini, DeepSeek, Groq, Mistral, xAI, Ollama or any OpenAI-compatible server, per bot and per harness |
| Voice | Dictate into the composer, play any bot reply, with speech-to-text and text-to-speech models of your choice |
@@ -91,7 +90,7 @@ The app serves plain HTTP on the port it prints, usually
`http://<your-ip>:7227`. Put a reverse proxy or tunnel in front of it for
HTTPS (see [HTTPS](#https)), then open the proxy's address and create the
super admin account. The first signup also creates the coordinator and the
main computer, which pulls the sandbox image in the background. Give it a
main computer, which pulls the computer image in the background. Give it a
few minutes.
Then open **Settings > Models**, add an OpenRouter key (or another provider)
@@ -188,7 +187,7 @@ You ── chat ── Coordinator ── delegates ── Workers
│ cron schedules │
└── Computers ─────────────┘
docker sandboxes:
browser, terminal, code, desktop
real Chrome, shell
```
- **Coordinator** is yours alone. It plans, delegates to workers, and keeps
@@ -198,9 +197,10 @@ You ── chat ── Coordinator ── delegates ── Workers
- **Workspaces** group bots around a subject. Models, instructions, memory
and the default computer resolve per workspace before per bot.
- **Routines** are cron schedules that queue a task without you asking.
- **Computers** are per-install Docker containers. Bots use them through the
sandbox's tools, and you can open the same machine in the browser and take
over.
- **Computers** are per-install Docker containers of Cobble's own image
(`computer/`: Debian 13, Google Chrome on a virtual screen, Playwright MCP
and a shell). Bots drive the browser and the shell, and you can watch the
same browser live in the chat and take over.
Each conversation is split into sessions, so a long-running bot does not grow
one endless thread: the bot names a session, summarizes it, and carries the
+4 -4
View File
@@ -8,8 +8,8 @@
"@floating-ui/dom": "1.8.0",
"@modelcontextprotocol/sdk": "^1.32.1",
"@moduletrace/bun-sqlite": "^1.3.0",
"@moduletrace/bunext": "^1.3.3",
"@moduletrace/twui": "^0.1.7",
"@moduletrace/bunext": "^1.3.5",
"@moduletrace/twui": "^0.1.9",
"@tiptap/extension-bubble-menu": "3.32.0",
"@tiptap/extension-mention": "3.32.0",
"@tiptap/extension-placeholder": "3.32.0",
@@ -277,9 +277,9 @@
"@moduletrace/bun-sqlite": ["@moduletrace/[email protected]", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Fbun-sqlite/-/1.3.0/bun-sqlite-1.3.0.tgz", { "dependencies": { "@inquirer/prompts": "^8.3.0", "chalk": "^5.6.2", "commander": "^14.0.3", "inquirer": "^13.3.2", "lodash": "^4.17.23", "sqlite-vec": "^0.1.7-alpha.2" }, "peerDependencies": { "typescript": "^5" }, "bin": { "bun-sqlite": "dist/commands/index.js" } }, "sha512-5xZg36vvT7uIpJSzeXW+debQ19Q7m99aUt2OvTEpWZvlnp0ePL9J6/1ibq2IPBmLpRZdif5Tq76ipiwwSN63jg=="],
"@moduletrace/bunext": ["@moduletrace/[email protected].3", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Fbunext/-/1.3.3/bunext-1.3.3.tgz", { "dependencies": { "@tailwindcss/postcss": "^4.3.3", "@types/bun": "1.3.14", "@types/node": "^24.10.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "bun-plugin-tailwind": "^0.1.2", "chalk": "^5.6.2", "chokidar": "^5.0.0", "commander": "^14.0.2", "esbuild": "^0.28.2", "lightningcss-wasm": "^1.32.0", "lodash": "^4.18.1", "ora": "^9.0.0", "postcss": "^8.5.30", "react": "^19.3.0", "react-dom": "^19.3.0", "tailwindcss": "^4.3.3", "typescript": "^5.0.0", "uuid": "^14.0.2" }, "bin": { "bunext": "dist/commands/index.js" } }, "sha512-bbUtQaigsDPUQf6vtDOSCo8GYR7Gnw2ny1Fi3JtUnKsYsYQEcEadzmqntAgf7rLcKc12dadDUgFLxru+jiA92g=="],
"@moduletrace/bunext": ["@moduletrace/[email protected].5", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Fbunext/-/1.3.5/bunext-1.3.5.tgz", { "dependencies": { "@tailwindcss/postcss": "^4.3.3", "@types/bun": "1.3.14", "@types/node": "^24.10.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "bun-plugin-tailwind": "^0.1.2", "chalk": "^5.6.2", "chokidar": "^5.0.0", "commander": "^14.0.2", "esbuild": "^0.28.2", "lightningcss-wasm": "^1.32.0", "lodash": "^4.18.1", "ora": "^9.0.0", "postcss": "^8.5.30", "react": "^19.3.0", "react-dom": "^19.3.0", "tailwindcss": "^4.3.3", "typescript": "^5.0.0", "uuid": "^14.0.2" }, "bin": { "bunext": "dist/commands/index.js" } }, "sha512-Es59Dvq3/eF726+SOHPiKtlJ87UFmyJZI4gpeciW/fA/3ZwOWws2Mm3oD6eZnOj9BP/zlBKOWA9DPTl35IP3lg=="],
"@moduletrace/twui": ["@moduletrace/[email protected].7", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Ftwui/-/0.1.7/twui-0.1.7.tgz", { "dependencies": { "lodash": "^4.18.1", "tailwind-merge": "^3.7.0" }, "peerDependencies": { "ace-builds": "^1.40.0", "lucide-react": ">=0.577.0", "next-mdx-remote": "^6.0.0", "openai": ">=6.0.0", "react": ">=18", "react-dom": ">=18", "react-markdown": ">=9.0.0", "rehype-prism-plus": "^2.0.0", "remark-gfm": "^4.0.0", "tailwindcss": "^4" }, "optionalPeers": ["ace-builds", "next-mdx-remote", "openai", "react-markdown", "rehype-prism-plus", "remark-gfm"] }, "sha512-/Y9QyhtQsoEAJO+ahlGYQaYMx3gUWS+DlSkaBVjAIY5V9OQ6i7qhhqMNcmnfOi9m3eyAze1uW00jox+RDUqLpA=="],
"@moduletrace/twui": ["@moduletrace/[email protected].9", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Ftwui/-/0.1.9/twui-0.1.9.tgz", { "dependencies": { "lodash": "^4.18.1", "tailwind-merge": "^3.7.0" }, "peerDependencies": { "ace-builds": "^1.40.0", "lucide-react": ">=0.577.0", "next-mdx-remote": "^6.0.0", "openai": ">=6.0.0", "react": ">=18", "react-dom": ">=18", "react-markdown": ">=9.0.0", "rehype-prism-plus": "^2.0.0", "remark-gfm": "^4.0.0", "tailwindcss": "^4" }, "optionalPeers": ["ace-builds", "next-mdx-remote", "openai", "react-markdown", "rehype-prism-plus", "remark-gfm"] }, "sha512-HN/emdqSCxQclzFEojDsaujjgO+dkQy4wC7Rk6gCQH/fK2Hv0CQ5DLOdOB8oDE7nu+m7/0qKo878UeufBbEotg=="],
"@next/mdx": ["@next/[email protected]", "", { "dependencies": { "source-map": "^0.7.0" }, "peerDependencies": { "@mdx-js/loader": ">=0.15.0", "@mdx-js/react": ">=0.15.0" }, "optionalPeers": ["@mdx-js/loader", "@mdx-js/react"] }, "sha512-Vpfuf928ACvx4AOdDXWx/cj13Ak6xlvMn3QCkjvfQMmLnQWCesQTeY01CPDbIyZvjY+NOwP7bvbvJ2ghkj/3GA=="],
+2
View File
@@ -0,0 +1,2 @@
**/*.test.ts
**/node_modules
+141
View File
@@ -0,0 +1,141 @@
# syntax=docker/dockerfile:1
#
# A Cobble computer: a real, headful browser on a virtual screen, plus a
# shell, in one lean Debian 13 container. The app reaches everything on one
# port (8080) through the agent in agent/:
#
# /api/... shell and files
# /mcp Playwright MCP, attached to the browser over CDP
# /desktop/ the screen itself (noVNC over the agent's own websocket
# bridge to Xvnc): the whole Chrome window, tabs and menus
# /terminal/ a shell in the browser (ttyd)
#
# Google Chrome on amd64 (the real "Google Chrome" brand, Widevine, full
# codecs); Google ships no Linux arm64 build, so arm64 gets Debian's
# Chromium. Chrome never auto-updates in here: rebuild the image instead.
#
# DEBIAN_MIRROR (a build arg, e.g. http://cdn-aws.deb.debian.org/debian)
# fetches Debian's packages from another mirror when deb.debian.org is slow
# from where the image is built; the image is the same either way.
# --- The agent, bundled for Node -----------------------------------------------
FROM oven/bun:1.4.3-debian AS agent
WORKDIR /build
COPY agent ./agent
RUN bun build agent/main.ts --target=node --format=esm --outfile=dist/agent.mjs
# --- noVNC, the screen's viewer: the project's release, checked against its
# hash (Debian's package pulls websockify and numpy, which the agent's own
# bridge makes unneeded). It connects by itself, reconnects, and scales the
# screen to its frame; its socket is fixed to the agent's. novnc/ adds
# clipboard sync (Ctrl+V pastes what the user copied).
FROM debian:trixie-slim AS novnc
ARG NOVNC_VERSION=1.6.0
ARG NOVNC_SHA256=5066103959ef4e9b10f37e5a148627360dd8414e4cf8a7db92bdbd022e728aaa
ARG DEBIAN_MIRROR
RUN if [ -n "$DEBIAN_MIRROR" ]; then sed -i "s|http://deb.debian.org/debian|$DEBIAN_MIRROR|g" /etc/apt/sources.list.d/debian.sources; fi \
&& apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates curl \
&& curl -fsSL -o /tmp/novnc.tgz "https://github.com/novnc/noVNC/archive/refs/tags/v${NOVNC_VERSION}.tar.gz" \
&& echo "${NOVNC_SHA256} /tmp/novnc.tgz" | sha256sum -c - \
&& mkdir -p /opt/novnc \
&& tar xzf /tmp/novnc.tgz -C /opt/novnc --strip-components=1 \
&& cd /opt/novnc \
&& rm -rf tests docs snap utils po .github karma.conf.cjs eslint.config.mjs \
&& echo '{"autoconnect":true,"reconnect":true,"reconnect_delay":1000,"resize":"scale"}' > defaults.json \
&& echo '{"host":"","port":0,"path":"websockify"}' > mandatory.json
COPY novnc/cobble-clipboard.js /opt/novnc/cobble-clipboard.js
RUN grep -q '</head>' /opt/novnc/vnc.html \
&& sed -i 's|</head>| <script type="module" src="./cobble-clipboard.js"></script>\n</head>|' /opt/novnc/vnc.html \
&& grep -q cobble-clipboard /opt/novnc/vnc.html
# --- Playwright MCP, installed once (no npm in the final image) ------------------
FROM debian:trixie-slim AS mcp
ARG PLAYWRIGHT_MCP_VERSION=0.0.84
ARG DEBIAN_MIRROR
RUN if [ -n "$DEBIAN_MIRROR" ]; then sed -i "s|http://deb.debian.org/debian|$DEBIAN_MIRROR|g" /etc/apt/sources.list.d/debian.sources; fi \
&& apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates nodejs npm \
&& npm install --prefix /opt/playwright-mcp --omit=dev --no-audit --no-fund "@playwright/mcp@${PLAYWRIGHT_MCP_VERSION}" \
&& /opt/playwright-mcp/node_modules/.bin/playwright-mcp --version
# --- The computer ----------------------------------------------------------------
FROM debian:trixie-slim
ARG TARGETARCH
LABEL org.opencontainers.image.title="Cobble computer" \
org.opencontainers.image.description="A Cobble bot's computer: a real headful browser and a shell." \
org.opencontainers.image.source="https://github.com/Moduletrace/cobble" \
org.opencontainers.image.licenses="MIT"
ENV DEBIAN_FRONTEND=noninteractive \
LANG=C.UTF-8 \
TZ=UTC \
PIP_BREAK_SYSTEM_PACKAGES=1
ARG DEBIAN_MIRROR
RUN if [ -n "$DEBIAN_MIRROR" ]; then sed -i "s|http://deb.debian.org/debian|$DEBIAN_MIRROR|g" /etc/apt/sources.list.d/debian.sources; fi \
&& apt-get update \
&& apt-get install -y --no-install-recommends \
# What bots reach for on a shell; anything else is a sudo apt away.
bash ca-certificates curl wget git jq less nano procps psmisc sudo \
unzip zip xz-utils file openssh-client tzdata tini \
python3 python3-pip python3-venv nodejs \
# The notification watcher (Python + GLib on the session bus).
python3-gi gir1.2-glib-2.0 dbus-daemon dbus-session-bus-common \
# The screen (Xvnc: an X server that is also a VNC server, on
# loopback), and Mesa so WebGL runs without a GPU.
tigervnc-standalone-server libgl1-mesa-dri libegl1 libgles2 \
# The fonts a normal desktop install ships.
fonts-dejavu fonts-liberation fonts-liberation2 fonts-noto-core \
fonts-noto-cjk fonts-noto-color-emoji fonts-noto-mono fonts-noto-ui-core \
fonts-cantarell fonts-urw-base35 \
libu2f-udev xdg-utils \
&& if [ "$TARGETARCH" = "amd64" ]; then \
curl -fsSL https://dl.google.com/linux/linux_signing_key.pub -o /usr/share/keyrings/google-chrome.asc \
&& echo "deb [arch=amd64 signed-by=/usr/share/keyrings/google-chrome.asc] https://dl.google.com/linux/chrome/deb/ stable main" \
> /etc/apt/sources.list.d/google-chrome.list \
&& apt-get update \
&& apt-get install -y --no-install-recommends google-chrome-stable \
&& google-chrome-stable --version; \
else \
apt-get install -y --no-install-recommends chromium \
&& chromium --version; \
fi \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* /var/cache/apt/* /var/tmp/* /tmp/* /usr/share/doc/* /usr/share/man/*
# The Shell view: ttyd, a terminal in the browser (Debian 13 doesn't package
# it), the project's static build, checked against its published hashes.
ARG TTYD_VERSION=1.7.7
RUN set -eu; \
case "$TARGETARCH" in \
amd64) arch=x86_64; sum=8a217c968aba172e0dbf3f34447218dc015bc4d5e59bf51db2f2cd12b7be4f55 ;; \
arm64) arch=aarch64; sum=b38acadd89d1d396a0f5649aa52c539edbad07f4bc7348b27b4f4b7219dd4165 ;; \
*) echo "No ttyd build for $TARGETARCH" >&2; exit 1 ;; \
esac; \
curl -fsSL -o /usr/local/bin/ttyd "https://github.com/tsl0922/ttyd/releases/download/${TTYD_VERSION}/ttyd.${arch}"; \
echo "${sum} /usr/local/bin/ttyd" | sha256sum -c -; \
chmod 755 /usr/local/bin/ttyd; \
ttyd --version
# The computer's user, with sudo so bots can install what they need (it's
# lost when the container is recreated). Chrome and Chromium read managed
# policies (the app's default extensions) from the same folder.
RUN useradd --create-home --uid 1000 --shell /bin/bash gem \
&& echo 'gem ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/gem \
&& chmod 440 /etc/sudoers.d/gem \
&& mkdir -p /home/gem/workspace /home/gem/.cobble-browser /etc/opt/chrome/policies/managed /etc/chromium \
&& rm -rf /etc/chromium/policies \
&& ln -s /etc/opt/chrome/policies /etc/chromium/policies \
&& chown -R gem:gem /home/gem
COPY --from=mcp /opt/playwright-mcp /opt/playwright-mcp
COPY --from=agent /build/dist /opt/cobble-agent
COPY --from=novnc /opt/novnc /opt/novnc
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=5s --start-period=60s --retries=3 \
CMD curl -fsS -o /dev/null http://127.0.0.1:8080/health || exit 1
ENTRYPOINT ["/usr/bin/tini", "--", "node", "/opt/cobble-agent/agent.mjs"]
+126
View File
@@ -0,0 +1,126 @@
# Cobble computer
The image every Cobble computer runs: a real, headful browser on a virtual
screen and a shell, in one lean Debian 13 (trixie) container. It replaces the
AIO sandbox, whose browser sites like Google turned away.
```
app ──http:8080──► agent ─┬─ /api/exec, /api/files/* shell and files, as gem
├─ /terminal/ ─► ttyd (a shell in the browser)
├─ /mcp ─► Playwright MCP ──CDP 127.0.0.1:9222──► Google Chrome
└─ /desktop/ noVNC ──websocket──► VNC 127.0.0.1:5900 (headful)
│ │
Xvnc :99 (1920x1080) ◄───────┘
```
- **Browser:** Google Chrome on amd64 (the real "Google Chrome" Client Hints
brand, Widevine, full codecs); Debian's Chromium on arm64, where Google
ships no Linux build. It runs headful on Xvnc with a normal profile and no
automation flags: the app attaches over CDP, it never launches it, so
`navigator.webdriver` is false. WebGL runs on Mesa's software renderer;
pages are composited in software (`--disable-gpu-compositing`, half the
CPU of compositing through Mesa).
- **Parking:** with no GPU and no window manager, the tab in front is always
on show, so its animations are drawn at full rate whether or not anyone
watches (one animated site can take a core or two). After
`COBBLE_BROWSER_PARK_AFTER_SECONDS` without a `/mcp` call or a screen view,
the agent puts a blank tab in front of every site on show (over DevTools,
as a person switching tabs would: the site keeps its connections, Chrome
just stops drawing it). The next `/mcp` call or screen view brings them
back before it goes through. Tabs are never discarded (managed policy), so
a parked one never reloads.
- **Agent** (`agent/`): the container's main process (under tini). It keeps
Xvnc, the session bus, Chrome, Playwright MCP and ttyd running (each restarted
when it exits), stops them in order on `docker stop` so Chrome saves its
profile, and serves the app on port 8080. Node, no dependencies; bundled by
Bun when the image is built.
- **Screen** (`/desktop/`): the virtual screen itself, so Chrome shows as
it is: its tab strip, address bar, menu, extensions, drop-downs and
prompts. The screen is Xvnc (an X server that is also a VNC server, on
loopback, no password); noVNC (the project's release, settings in its
`defaults.json`/`mandatory.json`) draws it scaled to the window, and the
agent bridges noVNC's websocket to Xvnc itself (no websockify). The
screen's size is a setting; a viewer can't resize it. `novnc/cobble-clipboard.js`
makes Ctrl/Cmd+V on the screen paste the viewer's clipboard (browsers allow
that over HTTPS or localhost), and copies the computer's back.
- **Shell** (`/terminal/`): ttyd, a terminal in the browser, as `gem`.
No window manager, desktop or code editor: the image stays small and starts
fast. Bots
install what else they need with `sudo apt-get install -y` (lost when the
container is recreated).
## API
Every path but `/health` needs `Authorization: Bearer $COBBLE_COMPUTER_TOKEN`
when that's set (the app sets it per computer).
| Path | |
| --- | --- |
| `GET /health` | 200 once Chrome's DevTools and Playwright MCP answer |
| `GET /api/info` | home, workspace, user, browser binary and version |
| `POST /api/exec` | `{ command, timeout_seconds?, cwd? }`: one `bash -c` as `gem`, own process group, no stdin, killed with its children at the timeout or when the request goes away. `{ output, exit_code, timed_out, truncated }` |
| `GET /api/files/stat?path=` | `{ exists, type, size, mtime_ms }` |
| `GET /api/files/download?path=` | the bytes; the connection is cut if the file changes mid-send |
| `POST /api/files/write` | `{ path, content, encoding?: "utf8" \| "base64", mode? }`, owned by `gem` |
| `/mcp` | Playwright MCP (`--shared-browser-context --codegen none --no-webmcp --file-paths absolute`, its files in `~/.cobble/playwright`, capped at 256 MB); Chrome saves downloads in `~/Downloads` |
| `/desktop/` | the screen (noVNC); `/desktop/websockify` is its websocket to Xvnc |
| `/terminal/` | a shell in the browser (ttyd, as `gem`, in the workspace) |
## Settings
| Env | Default | |
| --- | --- | --- |
| `COBBLE_COMPUTER_TOKEN` | none (open) | the token the API asks for |
| `COBBLE_BROWSER_PROFILE_DIR` | `/home/gem/.cobble-browser` | Chrome's profile (mount it to keep logins) |
| `COBBLE_SCREEN` | `1920x1080` | the virtual screen, and the window that fills it |
| `COBBLE_BROWSER_SCALE` | `1.25` | how large Chrome draws pages (its device scale factor, 1 to 3): larger text in screenshots |
| `COBBLE_BROWSER_LANG`, `COBBLE_BROWSER_ACCEPT_LANG` | `en-US`, `en-US,en` | keep them, and `TZ`, matched to where the traffic comes from |
| `COBBLE_BROWSER_SANDBOX` | `true` | Chrome's sandbox; it's turned off by itself when the host blocks user namespaces |
| `COBBLE_BROWSER_PARK_AFTER_SECONDS` | `180` | idle this long, the sites on show are parked behind a blank tab; `0` never parks |
| `COBBLE_BROWSER_ARGS` | | more Chrome flags, space separated (ones that would open DevTools or move the profile are dropped) |
| `COBBLE_MCP_ARGS` | | more Playwright MCP flags, e.g. `--caps vision` (where it listens and which browser it drives can't be changed) |
| `TZ` | `UTC` | the browser's timezone |
Chrome's sandbox needs user namespaces, so run the container with
`--security-opt seccomp=unconfined` (the app does), and a big `/dev/shm`
(`--shm-size 2g`).
## Building
The app runs the tag in `AppData.ComputerImage`
(`ghcr.io/moduletrace/cobble-computer:<version>`). Any change here bumps that
tag; the release workflow builds a tag once (a dispatch with
`rebuild_computer` rebuilds it, for a newer Chrome).
```sh
bun run build:computer # builds AppData.ComputerImage for this machine
docker run -d --name cobble-computer-dev --shm-size 2g \
--security-opt seccomp=unconfined -p 8170:8080 \
ghcr.io/moduletrace/cobble-computer:1.1.0
```
A computer run by hand like that has no token, so anyone who reaches its port
drives its browser: bind it to localhost. Point a dev server at it with the
`MAIN_COMPUTER_URL` app setting (`http://localhost:8170`).
To bump Playwright MCP or ttyd, change `PLAYWRIGHT_MCP_VERSION` or `TTYD_VERSION` (and its two hashes) in the Dockerfile.
## Known limits
- **IP reputation matters more than the browser.** A data-center IP is
flagged by Cloudflare and others however real the browser is.
- **No GPU:** WebGL reports Mesa llvmpipe, plausible for a Linux box.
- **Native popups aren't in the live view:** a drop-down opens as the view's
own list; the browser's own menus and permission bubbles don't show (use
`chrome://settings/content` in the address bar for site permissions).
- **Automation can still be noticed** by its behaviour (instant clicks, no
mouse movement). When a challenge shows, take over and solve it; the bot
carries on in the same session.
When deb.debian.org is slow from where you build, fetch Debian's packages from
another mirror (the image is the same):
```sh
bun run build:computer --build-arg DEBIAN_MIRROR=http://cdn-aws.deb.debian.org/debian
```
+9
View File
@@ -0,0 +1,9 @@
/**
* What the health check and `/api/info` report, kept current by the
* services as they start and stop.
*/
export const AgentState = {
browser_binary: "",
browser_version: "",
browser_sandbox: true,
};
+38
View File
@@ -0,0 +1,38 @@
/**
* Flags the computer's own settings may not pass to Chrome
* (`COBBLE_BROWSER_ARGS`): they'd open its DevTools to the network (around
* the token), move its profile, or break the agent's hold on it. The app
* refuses the same ones (`ComputerBlockedBrowserArgs`); keep them alike.
*/
export const BrowserBlockedArgs = [
"--remote-debugging-port",
"--remote-debugging-address",
"--remote-debugging-pipe",
"--remote-allow-origins",
"--user-data-dir",
"--headless",
];
/**
* Flags the computer's own settings may not pass to Playwright MCP
* (`COBBLE_MCP_ARGS`): where it listens and what it drives are the
* agent's, so it stays on loopback behind the token, on this browser.
* The app refuses the same ones (`ComputerBlockedMcpArgs`).
*/
export const McpBlockedArgs = [
"--host",
"--port",
"--allowed-hosts",
"--allowed-origins",
"--cdp-endpoint",
"--cdp-header",
"--extension",
"--config",
"--browser",
"--executable-path",
"--user-data-dir",
"--isolated",
"--shared-browser-context",
"--output-dir",
"--file-paths",
];
+49
View File
@@ -0,0 +1,49 @@
import type { IncomingMessage } from "node:http";
import { connect } from "node:net";
import type { Duplex } from "node:stream";
type Params = {
req: IncomingMessage;
socket: Duplex;
head: Buffer;
/**
* The loopback port of the service behind this path.
*/
port: number;
};
/**
* Joins a websocket upgrade to a service on loopback (the web terminal)
* byte for byte: its handshake is sent on as it came, path and
* subprotocol included, with a loopback Host and without the caller's
* Origin or the app's token; then every frame passes untouched.
*/
export default function bridgeLoopbackSocket({ req, socket, head, port }: Params) {
const skipped = new Set(["host", "origin", "authorization"]);
const lines = [`GET ${req.url || "/"} HTTP/1.1`, `Host: 127.0.0.1:${port}`];
for (let index = 0; index < req.rawHeaders.length; index += 2) {
const name = req.rawHeaders[index]!;
if (!skipped.has(name.toLowerCase())) lines.push(`${name}: ${req.rawHeaders[index + 1]}`);
}
const upstream = connect(port, "127.0.0.1", () => {
upstream.write([...lines, "", ""].join("\r\n"));
if (head.length) upstream.write(head);
upstream.pipe(socket);
socket.pipe(upstream);
});
const close = () => {
upstream.destroy();
socket.destroy();
};
upstream.on("error", close);
socket.on("error", close);
upstream.on("close", close);
socket.on("close", close);
}
+121
View File
@@ -0,0 +1,121 @@
import type { IncomingMessage } from "node:http";
import { connect } from "node:net";
import type { Duplex } from "node:stream";
import encodeWebsocketFrame from "./encode-websocket-frame";
import readWebsocketFrames from "./read-websocket-frames";
import websocketAccept from "./websocket-accept";
type Params = {
req: IncomingMessage;
socket: Duplex;
head: Buffer;
/**
* Xvnc's port, on loopback.
*/
port: number;
};
/**
* Carries noVNC's websocket to the screen's VNC server (Xvnc speaks plain
* TCP), what websockify would do: each frame's payload goes to the VNC
* server as bytes, and what it sends back goes out as binary frames. Pings
* are answered, and a close on either side closes both.
*/
export default function bridgeVncSocket({ req, socket, head, port }: Params) {
const key = req.headers["sec-websocket-key"];
if (typeof key != "string" || String(req.headers.upgrade || "").toLowerCase() != "websocket") {
socket.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
return;
}
const protocols = String(req.headers["sec-websocket-protocol"] || "")
.split(",")
.map((protocol) => protocol.trim());
const upstream = connect(port, "127.0.0.1");
let connected = false;
let closed = false;
const close = () => {
if (closed) return;
closed = true;
upstream.destroy();
socket.destroy();
};
const send = (frame: Buffer) => {
if (!socket.write(frame)) upstream.pause();
};
const feed = readWebsocketFrames({
max_payload: 16 * 1024 * 1024,
onFrame: ({ opcode, payload }) => {
if (opcode <= 0x2) {
if (!upstream.write(payload)) socket.pause();
} else if (opcode == 0x8) {
socket.end(encodeWebsocketFrame({ opcode: 0x8, payload: payload.subarray(0, 2) }));
upstream.end();
} else if (opcode == 0x9) {
send(encodeWebsocketFrame({ opcode: 0xa, payload }));
}
},
});
const read = (chunk: Buffer) => {
try {
feed(chunk);
} catch {
close();
}
};
upstream.on("connect", () => {
connected = true;
socket.write(
[
"HTTP/1.1 101 Switching Protocols",
"Upgrade: websocket",
"Connection: Upgrade",
`Sec-WebSocket-Accept: ${websocketAccept({ key })}`,
...(protocols.includes("binary") ? ["Sec-WebSocket-Protocol: binary"] : []),
"",
"",
].join("\r\n"),
);
if (head.length) read(head);
socket.on("data", read);
});
upstream.on("data", (chunk: Buffer) => send(encodeWebsocketFrame({ opcode: 0x2, payload: chunk })));
upstream.on("drain", () => socket.resume());
socket.on("drain", () => upstream.resume());
upstream.on("error", () => {
if (!connected && !closed) {
closed = true;
socket.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n");
return;
}
close();
});
upstream.on("end", () => {
if (closed) return;
closed = true;
socket.end(encodeWebsocketFrame({ opcode: 0x8, payload: Buffer.from([0x03, 0xe8]) }));
});
socket.on("error", close);
socket.on("close", close);
// The HTTP server keeps upgraded sockets half open: a viewer that went
// away without a close frame (a dropped network, a killed tab) only
// ends its side, and would otherwise hold the bridge and Xvnc's
// connection (and keep the browser from parking) for good.
socket.on("end", close);
upstream.on("close", () => {
if (!closed) close();
});
}
+32
View File
@@ -0,0 +1,32 @@
import { describe, expect, test } from "bun:test";
import browserArgs from "./browser-args";
const base = {
profile_dir: "/p",
cdp_port: 9222,
lang: "en-US",
accept_lang: "en-US,en",
sandbox: true,
};
describe("browserArgs", () => {
test("fills the screen at 100% without a scale flag", () => {
const args = browserArgs({ ...base, screen: { width: 1920, height: 1080 }, scale: 1 });
expect(args).toContain("--window-size=1920,1080");
expect(args.some((arg) => arg.startsWith("--force-device-scale-factor"))).toBe(false);
});
test("sizes the window in scaled units, so it still fits the screen", () => {
expect(browserArgs({ ...base, screen: { width: 1920, height: 1080 }, scale: 1.25 })).toEqual(
expect.arrayContaining(["--window-size=1536,864", "--force-device-scale-factor=1.25"]),
);
expect(browserArgs({ ...base, screen: { width: 1366, height: 768 }, scale: 1.25 })).toContain("--window-size=1092,614");
});
test("keeps WebGL but composites in software", () => {
const args = browserArgs({ ...base, screen: { width: 1920, height: 1080 }, scale: 1 });
expect(args).toEqual(expect.arrayContaining(["--ignore-gpu-blocklist", "--disable-gpu-compositing"]));
});
});
+57
View File
@@ -0,0 +1,57 @@
type Params = {
profile_dir: string;
cdp_port: number;
screen: { width: number; height: number };
/**
* Chrome's device scale factor; 1 leaves the flag out.
*/
scale: number;
lang: string;
accept_lang: string;
sandbox: boolean;
extra?: string[];
};
/**
* Chrome's flags: a normal headful browser on the virtual screen, its
* window filling it, its DevTools port on loopback. Nothing that changes
* what a page sees beyond what a plain desktop install would show (no
* automation flags: the app attaches over CDP, it never launches it). The
* basic password store keeps the cookies' key the same in every
* container, so a profile carried over stays signed in.
*/
export default function browserArgs({ profile_dir, cdp_port, screen, scale, lang, accept_lang, sandbox, extra = [] }: Params) {
return [
`--user-data-dir=${profile_dir}`,
`--remote-debugging-port=${cdp_port}`,
"--password-store=basic",
"--no-first-run",
"--no-default-browser-check",
"--hide-crash-restore-bubble",
"--window-position=0,0",
// Chrome reads the window size in scaled units: divided by the
// scale, the window fills the screen exactly.
`--window-size=${Math.floor(screen.width / scale)},${Math.floor(screen.height / scale)}`,
...(scale == 1 ? [] : [`--force-device-scale-factor=${scale}`]),
/**
* Without a GPU Chrome would turn WebGL off, which is a glaring
* tell; with it, WebGL runs on Mesa's software renderer, as on a
* real Linux box without GPU drivers.
*/
"--ignore-gpu-blocklist",
/**
* ...but compositing the page in software, as Chrome does with
* the GPU blocklisted: half the CPU of drawing every frame through
* Mesa, and WebGL still runs (and names Mesa) as before.
*/
"--disable-gpu-compositing",
/**
* The image is updated instead; this keeps Chrome from nagging.
*/
"--simulate-outdated-no-au=Tue, 31 Dec 2099 23:59:59 GMT",
`--lang=${lang}`,
`--accept-lang=${accept_lang}`,
...(sandbox ? [] : ["--no-sandbox", "--test-type"]),
...extra,
];
}
+48
View File
@@ -0,0 +1,48 @@
import { describe, expect, test } from "bun:test";
import pageNeedsParking from "./page-needs-parking";
import parkAfterMs from "./park-after-ms";
import shouldParkBrowser from "./should-park-browser";
const idle = { now: 1_000_000, last_active_at: 1_000_000 - 180_000, checked_at: 0, viewers: 0, holds: 0, park_after_ms: 180_000 };
describe("shouldParkBrowser", () => {
test("parks once it sat unused and unwatched long enough", () => {
expect(shouldParkBrowser(idle)).toBe(true);
expect(shouldParkBrowser({ ...idle, last_active_at: idle.now - 179_999 })).toBe(false);
});
test("never while someone watches the screen or a tool call runs", () => {
expect(shouldParkBrowser({ ...idle, viewers: 1 })).toBe(false);
expect(shouldParkBrowser({ ...idle, holds: 1 })).toBe(false);
});
test("looks only once per idle stretch", () => {
expect(shouldParkBrowser({ ...idle, checked_at: idle.last_active_at + 1 })).toBe(false);
expect(shouldParkBrowser({ ...idle, checked_at: idle.last_active_at - 1 })).toBe(true);
});
test("0 turns it off", () => {
expect(shouldParkBrowser({ ...idle, park_after_ms: 0, last_active_at: 0 })).toBe(false);
});
});
describe("pageNeedsParking", () => {
test("sites do, Chrome's own pages don't", () => {
expect(pageNeedsParking({ url: "https://www.youtube.com/watch?v=x" })).toBe(true);
expect(pageNeedsParking({ url: "file:///tmp/a.html" })).toBe(true);
for (const url of ["about:blank", "chrome://newtab/", "chrome-untrusted://new-tab-page/", "chrome-error://chromewebdata/", "devtools://devtools/x"]) {
expect(pageNeedsParking({ url })).toBe(false);
}
});
});
describe("parkAfterMs", () => {
test("whole seconds, 0 for off, else 3 minutes", () => {
expect(parkAfterMs({ text: "60" })).toBe(60_000);
expect(parkAfterMs({ text: "0" })).toBe(0);
expect(parkAfterMs({ text: undefined })).toBe(180_000);
expect(parkAfterMs({ text: "-5" })).toBe(180_000);
expect(parkAfterMs({ text: "1.5" })).toBe(180_000);
});
});
+14
View File
@@ -0,0 +1,14 @@
import { describe, expect, test } from "bun:test";
import browserScale from "./browser-scale";
describe("browserScale", () => {
test("reads a factor", () => {
expect(browserScale({ text: "1.25" })).toBe(1.25);
expect(browserScale({ text: "2" })).toBe(2);
expect(browserScale({ text: "1" })).toBe(1);
});
test("falls back to 1.25 for nothing or anything out of range", () => {
for (const text of [undefined, "", "abc", "0.5", "4", "-1"]) expect(browserScale({ text })).toBe(1.25);
});
});
+11
View File
@@ -0,0 +1,11 @@
/**
* Chrome's device scale factor from `COBBLE_BROWSER_SCALE` (e.g. `1`),
* else 1.25: text is larger in bots' screenshots, and 1920x1080 reads as
* 1536x864, the most common laptop. Kept between 1 and 3. The app's
* `ComputerDefaultBrowserScale` is the same default.
*/
export default function browserScale({ text }: { text?: string }) {
const scale = Number(text);
return text && Number.isFinite(scale) && scale >= 1 && scale <= 3 ? scale : 1.25;
}
+22
View File
@@ -0,0 +1,22 @@
import { readdirSync, rmSync } from "node:fs";
import path from "node:path";
/**
* Removes the `Singleton*` links a browser leaves in its profile when it
* was stopped uncleanly (the container killed): another container's
* hostname in them makes Chrome refuse the profile. Only called while no
* browser runs.
*/
export default function clearProfileLocks({ profile_dir }: { profile_dir: string }) {
let names: string[] = [];
try {
names = readdirSync(profile_dir);
} catch {
return;
}
for (const name of names) {
if (name.startsWith("Singleton")) rmSync(path.join(profile_dir, name), { force: true });
}
}
+107
View File
@@ -0,0 +1,107 @@
import { BrowserBlockedArgs, McpBlockedArgs } from "./blocked-args";
import safeExtraArgs from "./safe-extra-args";
import browserScale from "./browser-scale";
import parkAfterMs from "./park-after-ms";
import screenSize from "./screen-size";
const env = process.env;
/**
* Everything the computer's agent is set up with. The user, home and
* folders match what the app mounts (`AppData.ComputerHomeDir`,
* `ComputerWorkspaceDir`, `ComputerBrowserProfileDir`).
*/
export const AgentConfig = {
/**
* The one port the app reaches: the API, `/mcp`, the screen and the
* shell.
*/
Port: Number(env.COBBLE_AGENT_PORT || 8080),
/**
* Sent by the app as `Authorization: Bearer <token>`. Without one set,
* every request is let in (a computer run by hand for development).
*/
Token: env.COBBLE_COMPUTER_TOKEN || "",
User: "gem",
Uid: 1000,
Gid: 1000,
Home: "/home/gem",
WorkspaceDir: "/home/gem/workspace",
ProfileDir: env.COBBLE_BROWSER_PROFILE_DIR || "/home/gem/.cobble-browser",
/**
* The browser's pid and environment (`browser.pid`, `browser.json`),
* the session bus and the runtime dir, for what runs beside it (the
* notification watcher).
*/
RunDir: "/run/cobble",
Display: ":99",
Screen: screenSize({ text: env.COBBLE_SCREEN }),
/**
* How large Chrome draws pages (its device scale factor): above 1, text
* is larger in screenshots and pages are laid out narrower.
*/
Scale: browserScale({ text: env.COBBLE_BROWSER_SCALE }),
Lang: env.COBBLE_BROWSER_LANG || "en-US",
AcceptLang: env.COBBLE_BROWSER_ACCEPT_LANG || env.COBBLE_BROWSER_LANG || "en-US,en",
/**
* `false` turns Chrome's sandbox off from the start. It's also turned
* off by itself when Chrome says the host gives it none.
*/
BrowserSandbox: (env.COBBLE_BROWSER_SANDBOX || "true").toLowerCase() != "false",
/**
* More Chrome flags, space separated.
*/
BrowserExtraArgs: safeExtraArgs({ text: env.COBBLE_BROWSER_ARGS, blocked: BrowserBlockedArgs }),
/**
* Without a browser tool call or a screen view for this long, the
* sites on show are sent behind a blank tab so their animations stop
* costing CPU (`createBrowserParking`); 0 never does.
*/
BrowserParkAfterMs: parkAfterMs({ text: env.COBBLE_BROWSER_PARK_AFTER_SECONDS }),
/**
* Chrome's DevTools port, on loopback only: Playwright MCP reaches it
* from inside the container.
*/
CdpPort: 9222,
McpPort: 8931,
McpCli: "/opt/playwright-mcp/node_modules/@playwright/mcp/cli.js",
/**
* More Playwright MCP flags, space separated (e.g. `--caps vision`),
* without the ones that would move it off loopback or this browser.
*/
McpExtraArgs: safeExtraArgs({ text: env.COBBLE_MCP_ARGS, blocked: McpBlockedArgs }),
/**
* The shell's web terminal (ttyd), on loopback, served under
* `/terminal/` behind the token.
*/
TerminalPort: 7681,
/**
* Where Playwright MCP writes snapshots, console logs and downloads
* (the app's `AppData.ComputerBrowserOutputDir`), oldest evicted past
* the size.
*/
McpOutputDir: "/home/gem/.cobble/playwright",
McpOutputMaxBytes: 256 * 1024 * 1024,
/**
* The screen's VNC server (Xvnc), on loopback, reached through the
* agent's own websocket bridge at `/desktop/websockify`.
*/
VncPort: 5900,
/**
* noVNC, the screen's viewer, served at `/desktop/`.
*/
NoVncDir: env.COBBLE_NOVNC_DIR || "/opt/novnc",
/**
* A command's timeout when it names none, and the most it may ask for.
*/
CommandDefaultSeconds: 270,
CommandMaxSeconds: 3600,
/**
* Output past this is dropped (and the response says so).
*/
CommandMaxOutputBytes: 4 * 1024 * 1024,
/**
* How long children get to exit on a stop before they're killed.
*/
StopGraceMs: 8000,
};
+142
View File
@@ -0,0 +1,142 @@
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { AgentState } from "./agent-state";
import { AgentConfig } from "./config";
import handleExec from "./handle-exec";
import handleFileDownload from "./handle-file-download";
import handleFileStat from "./handle-file-stat";
import handleFileWrite from "./handle-file-write";
import isAuthorized from "./is-authorized";
import isPortAnswering from "./is-port-answering";
import log from "./log";
import bridgeLoopbackSocket from "./bridge-loopback-socket";
import bridgeVncSocket from "./bridge-vnc-socket";
import type { BrowserParking } from "./create-browser-parking";
import proxyLoopback from "./proxy-loopback";
import sendJson from "./send-json";
import serveStaticFile from "./serve-static-file";
/**
* The agent's one port:
*
* - `GET /health` (open): 200 once the browser and its tools answer.
* - `GET /api/info`, `POST /api/exec`, `GET /api/files/stat|download`,
* `POST /api/files/write`: the app's shell and file access.
* - `/mcp`: Playwright MCP, driving the computer's browser.
* - `/desktop/` and its `/desktop/websockify` websocket: the screen
* (noVNC over Xvnc), Chrome's whole window.
* - `/terminal/` and its websocket: a shell in the browser (ttyd).
*
* Everything but the health check needs the computer's token. Browser
* tool calls and screen views wake a parked browser first (`parking`).
*/
export default function createAgentServer({ parking }: { parking: BrowserParking }) {
const server = createServer((req, res) => {
route({ req, res, parking }).catch((error) => {
log({ name: "agent", message: `${req.method} ${req.url} failed: ${error?.message || error}` });
if (!res.headersSent) sendJson({ res, status: 500, body: { error: String(error?.message || error) } });
else res.destroy();
});
});
server.on("upgrade", (req, socket, head) => {
const pathname = new URL(req.url || "/", "http://agent").pathname;
const authorized = isAuthorized({ headers: req.headers, token: AgentConfig.Token });
if (authorized && pathname == "/desktop/websockify") {
const watching = parking.watch();
socket.once("close", watching.done);
bridgeVncSocket({ req, socket, head, port: AgentConfig.VncPort });
return;
}
if (authorized && pathname.startsWith("/terminal/")) {
bridgeLoopbackSocket({ req, socket, head, port: AgentConfig.TerminalPort });
return;
}
socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n");
});
/**
* Commands and event streams can run long; the app keeps its own
* timeouts.
*/
server.requestTimeout = 0;
server.headersTimeout = 60_000;
return server;
}
async function route({ req, res, parking }: { req: IncomingMessage; res: ServerResponse; parking: BrowserParking }) {
const { pathname } = new URL(req.url || "/", "http://agent");
if (pathname == "/health") {
const [browser, mcp] = await Promise.all([
isPortAnswering({ url: `http://127.0.0.1:${AgentConfig.CdpPort}/json/version` }),
isPortAnswering({ url: `http://127.0.0.1:${AgentConfig.McpPort}/mcp` }),
]);
return sendJson({ res, status: browser && mcp ? 200 : 503, body: { ok: browser && mcp, browser, mcp } });
}
if (!isAuthorized({ headers: req.headers, token: AgentConfig.Token })) {
return sendJson({ res, status: 401, body: { error: "Unauthorized" } });
}
if (pathname == "/mcp" || pathname.startsWith("/mcp/")) {
// A GET is the session's event stream, open for as long as the
// session: only calls hold parking off while they run.
const holding = req.method == "GET" ? undefined : parking.hold();
if (holding) res.once("close", holding.done);
await parking.wake();
return proxyLoopback({ req, res, port: AgentConfig.McpPort, unavailable: "The browser tools aren't answering yet." });
}
if (pathname == "/terminal") {
res.writeHead(302, { location: "terminal/" }).end();
return;
}
if (pathname.startsWith("/terminal/")) {
return proxyLoopback({ req, res, port: AgentConfig.TerminalPort, unavailable: "The shell isn't answering yet." });
}
if (pathname == "/" || pathname == "/desktop") {
res.writeHead(302, { location: "desktop/" }).end();
return;
}
if (pathname == "/desktop/") return serveStaticFile({ res, root: AgentConfig.NoVncDir, name: "vnc.html" });
if (pathname.startsWith("/desktop/")) {
return serveStaticFile({ res, root: AgentConfig.NoVncDir, name: pathname.slice("/desktop/".length) });
}
if (pathname == "/api/info" && req.method == "GET") {
return sendJson({
res,
body: {
home_dir: AgentConfig.Home,
workspace_dir: AgentConfig.WorkspaceDir,
user: AgentConfig.User,
browser: {
binary: AgentState.browser_binary,
version: AgentState.browser_version,
sandbox: AgentState.browser_sandbox,
},
},
});
}
if (pathname == "/api/exec" && req.method == "POST") return handleExec({ req, res });
if (pathname == "/api/files/stat" && req.method == "GET") return handleFileStat({ req, res });
if (pathname == "/api/files/download" && req.method == "GET") return handleFileDownload({ req, res });
if (pathname == "/api/files/write" && req.method == "POST") return handleFileWrite({ req, res });
sendJson({ res, status: 404, body: { error: "Not Found" } });
}
+172
View File
@@ -0,0 +1,172 @@
import log from "./log";
import openCdpConnection, { type CdpConnection } from "./open-cdp-connection";
import parkBrowserTabs, { type ParkedTab } from "./park-browser-tabs";
import shouldParkBrowser from "./should-park-browser";
import unparkBrowserTabs from "./unpark-browser-tabs";
type Params = {
/**
* Chrome's DevTools port, on loopback.
*/
cdp_port: number;
/**
* Unused and unwatched this long parks the browser; 0 never does.
*/
park_after_ms: number;
/**
* How often idleness is checked.
*/
check_every_ms?: number;
};
export type BrowserParking = {
/**
* Someone is about to use the browser: brings parked tabs back first.
* Resolves once it's as it was left (never rejects).
*/
wake: () => Promise<void>;
/**
* A browser tool call started: nothing is parked until `done` runs.
*/
hold: () => { done: () => void };
/**
* A screen view opened: brings the tabs back and parks nothing while
* it's open. Returns what to call when it closes.
*/
watch: () => { done: () => void };
/**
* Chrome started again: its old tabs are gone, so nothing is parked.
*/
browserRestarted: () => void;
};
const CdpTimeoutMs = 10_000;
/**
* Keeps an idle browser from burning CPU. The computer's screen has no GPU
* and no window manager, so the tab in front is always "on show" and its
* animations are drawn in software at full rate even when nobody watches.
* After `park_after_ms` without a browser tool call or a screen view,
* every site on show goes to the background behind a blank tab
* (`parkBrowserTabs`), what a person switching tabs does, so pages see
* nothing out of the ordinary; the next tool call or view brings them back
* before it goes through. One operation at a time.
*/
export default function createBrowserParking({ cdp_port, park_after_ms, check_every_ms = 15_000 }: Params): BrowserParking {
let last_active_at = Date.now();
let checked_at = 0;
let viewers = 0;
let holds = 0;
let parked: ParkedTab[] = [];
let queue: Promise<void> = Promise.resolve();
let parking = false;
const touch = () => {
last_active_at = Date.now();
};
/**
* Runs one operation after the ones before it, over its own DevTools
* connection.
*/
const run = (task: (cdp: CdpConnection) => Promise<void>) => {
queue = queue.then(async () => {
let cdp: CdpConnection | undefined;
try {
cdp = await openCdpConnection({ port: cdp_port, timeout_ms: CdpTimeoutMs });
await task(cdp);
} catch (error: any) {
log({ name: "parking", message: `couldn't reach the browser: ${error?.message || error}` });
} finally {
cdp?.close();
}
});
return queue;
};
const idle = () =>
shouldParkBrowser({ now: Date.now(), last_active_at, checked_at, viewers, holds, park_after_ms });
const park = () =>
run(async (cdp) => {
// Used again while it waited its turn.
if (!idle()) return;
const tabs = await parkBrowserTabs({ cdp });
checked_at = Date.now();
parked.push(...tabs);
if (tabs.length) log({ name: "parking", message: `idle: parked ${tabs.length} tab${tabs.length == 1 ? "" : "s"}` });
});
const wake = () => {
touch();
// Quick when nothing is parked or being parked (a park waiting its
// turn sees the browser in use and does nothing).
if (!parked.length && !parking) return Promise.resolve();
return run(async (cdp) => {
if (!parked.length) return;
const tabs = parked;
parked = [];
await unparkBrowserTabs({ cdp, parked: tabs });
log({ name: "parking", message: `in use: brought back ${tabs.length} tab${tabs.length == 1 ? "" : "s"}` });
});
};
if (park_after_ms > 0) {
setInterval(() => {
if (parking || !idle()) return;
parking = true;
park().finally(() => {
parking = false;
});
}, check_every_ms).unref();
}
return {
wake,
hold: () => {
holds++;
touch();
let released = false;
return {
done: () => {
if (released) return;
released = true;
holds--;
touch();
},
};
},
watch: () => {
viewers++;
wake();
let released = false;
return {
done: () => {
if (released) return;
released = true;
viewers--;
touch();
},
};
},
browserRestarted: () => {
parked = [];
checked_at = 0;
touch();
},
};
}
+41
View File
@@ -0,0 +1,41 @@
type Params = {
opcode: number;
payload: Buffer;
/**
* Four bytes to mask the payload with, as a client must (the agent's
* own DevTools client); a server's frames go unmasked.
*/
mask?: Buffer;
};
/**
* One whole frame (RFC 6455) around a payload: unmasked, as a server
* sends it, unless a `mask` is given.
*/
export default function encodeWebsocketFrame({ opcode, payload, mask }: Params) {
const length = payload.length;
const mask_bit = mask ? 0x80 : 0;
let header: Buffer;
if (length < 126) {
header = Buffer.from([0x80 | opcode, mask_bit | length]);
} else if (length < 65536) {
header = Buffer.alloc(4);
header[0] = 0x80 | opcode;
header[1] = mask_bit | 126;
header.writeUInt16BE(length, 2);
} else {
header = Buffer.alloc(10);
header[0] = 0x80 | opcode;
header[1] = mask_bit | 127;
header.writeBigUInt64BE(BigInt(length), 2);
}
if (!mask) return Buffer.concat([header, payload]);
const masked = Buffer.from(payload);
for (let index = 0; index < masked.length; index++) masked[index]! ^= mask[index & 3]!;
return Buffer.concat([header, mask.subarray(0, 4), masked]);
}
+14
View File
@@ -0,0 +1,14 @@
import { existsSync } from "node:fs";
/**
* Google Chrome where it exists (amd64), else Debian's Chromium (arm64).
*/
export const BrowserBinaries = ["/usr/bin/google-chrome-stable", "/usr/bin/chromium"];
export default function findBrowserBinary() {
const found = BrowserBinaries.find((binary) => existsSync(binary));
if (!found) throw new Error(`No browser installed (looked for ${BrowserBinaries.join(", ")}).`);
return found;
}
+44
View File
@@ -0,0 +1,44 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { AgentConfig } from "./config";
import readJsonBody from "./read-json-body";
import runCommand from "./run-command";
import sendJson from "./send-json";
import userEnv from "./user-env";
/**
* `POST /api/exec` `{ command, timeout_seconds?, cwd? }`: runs one bash
* command as the computer's user (`runCommand`), from its home unless
* `cwd` is given. The command is killed if the caller goes away.
* Answers `{ output, exit_code, timed_out, truncated }`.
*/
export default async function handleExec({ req, res }: { req: IncomingMessage; res: ServerResponse }) {
const body = await readJsonBody({ req, max_bytes: 1024 * 1024 });
if (typeof body?.command != "string" || !body.command.trim()) {
return sendJson({ res, status: 400, body: { error: "Give the command." } });
}
const asked = Number(body.timeout_seconds);
const timeout_seconds = Number.isFinite(asked) && asked > 0
? Math.min(Math.ceil(asked), AgentConfig.CommandMaxSeconds)
: AgentConfig.CommandDefaultSeconds;
const controller = new AbortController();
res.on("close", () => {
if (!res.writableFinished) controller.abort();
});
const result = await runCommand({
command: body.command,
cwd: typeof body.cwd == "string" && body.cwd.startsWith("/") ? body.cwd : AgentConfig.Home,
env: userEnv(),
uid: AgentConfig.Uid,
gid: AgentConfig.Gid,
timeout_seconds,
max_output_bytes: AgentConfig.CommandMaxOutputBytes,
signal: controller.signal,
});
if (!res.destroyed) sendJson({ res, body: result });
}
+37
View File
@@ -0,0 +1,37 @@
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import type { IncomingMessage, ServerResponse } from "node:http";
import queryPath from "./query-path";
import sendJson from "./send-json";
/**
* `GET /api/files/download?path=`: the file byte for byte, with its
* length. When it changes while it's sent, the connection is cut, so the
* caller sees a short body instead of a mix of two versions.
*/
export default async function handleFileDownload({ req, res }: { req: IncomingMessage; res: ServerResponse }) {
const file = queryPath({ req });
if (!file) return sendJson({ res, status: 400, body: { error: "Give an absolute path." } });
const before = await stat(file).catch(() => null);
if (!before) return sendJson({ res, status: 404, body: { error: "There's no such file." } });
if (!before.isFile()) return sendJson({ res, status: 400, body: { error: "That isn't a file." } });
res.writeHead(200, {
"content-type": "application/octet-stream",
"content-length": before.size,
"cache-control": "no-store",
});
const stream = createReadStream(file);
stream.on("error", () => res.destroy());
stream.on("end", async () => {
const after = await stat(file).catch(() => null);
if (!after || after.size != before.size || after.mtimeMs != before.mtimeMs) res.destroy();
});
stream.pipe(res);
}
+27
View File
@@ -0,0 +1,27 @@
import { stat } from "node:fs/promises";
import type { IncomingMessage, ServerResponse } from "node:http";
import queryPath from "./query-path";
import sendJson from "./send-json";
/**
* `GET /api/files/stat?path=`: `{ exists, type, size, mtime_ms }`.
*/
export default async function handleFileStat({ req, res }: { req: IncomingMessage; res: ServerResponse }) {
const file = queryPath({ req });
if (!file) return sendJson({ res, status: 400, body: { error: "Give an absolute path." } });
const info = await stat(file).catch(() => null);
if (!info) return sendJson({ res, body: { exists: false } });
sendJson({
res,
body: {
exists: true,
type: info.isFile() ? "file" : info.isDirectory() ? "directory" : "other",
size: info.size,
mtime_ms: Math.round(info.mtimeMs),
},
});
}
+52
View File
@@ -0,0 +1,52 @@
import { chown, mkdir, rename, writeFile } from "node:fs/promises";
import type { IncomingMessage, ServerResponse } from "node:http";
import path from "node:path";
import { AgentConfig } from "./config";
import readJsonBody from "./read-json-body";
import sendJson from "./send-json";
/**
* `POST /api/files/write` `{ path, content, encoding?: "utf8" | "base64",
* mode? }`: writes a whole file (through a temporary one, then renamed),
* creating its folders, all owned by the computer's user. `mode` is the
* file's permission bits as a number (e.g. 384 for 0600).
*/
export default async function handleFileWrite({ req, res }: { req: IncomingMessage; res: ServerResponse }) {
const body = await readJsonBody({ req, max_bytes: 64 * 1024 * 1024 });
const file = typeof body?.path == "string" && body.path.startsWith("/") && !body.path.includes("\0")
? path.posix.normalize(body.path)
: null;
if (!file) return sendJson({ res, status: 400, body: { error: "Give an absolute path." } });
if (typeof body.content != "string") return sendJson({ res, status: 400, body: { error: "Give the content." } });
const bytes = Buffer.from(body.content, body.encoding == "base64" ? "base64" : "utf8");
const mode = Number.isInteger(body.mode) ? Number(body.mode) & 0o777 : 0o644;
await makeOwnedDirs({ dir: path.posix.dirname(file) });
const temp = `${file}.cobble-${process.pid}-${Date.now()}`;
await writeFile(temp, bytes, { mode });
await chown(temp, AgentConfig.Uid, AgentConfig.Gid);
await rename(temp, file);
sendJson({ res, body: { ok: true, size: bytes.length } });
}
/**
* Creates a folder and its missing parents, each new one owned by the
* computer's user.
*/
async function makeOwnedDirs({ dir }: { dir: string }) {
const created = await mkdir(dir, { recursive: true });
if (!created) return;
let current = dir;
while (current.length >= created.length) {
await chown(current, AgentConfig.Uid, AgentConfig.Gid).catch(() => {});
current = path.posix.dirname(current);
}
}
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, test } from "bun:test";
import isAuthorized from "./is-authorized";
describe("isAuthorized", () => {
test("lets everything in without a token", () => {
expect(isAuthorized({ headers: {}, token: "" })).toBe(true);
});
test("needs the exact bearer token", () => {
expect(isAuthorized({ headers: { authorization: "Bearer abc" }, token: "abc" })).toBe(true);
expect(isAuthorized({ headers: { authorization: "Bearer abd" }, token: "abc" })).toBe(false);
expect(isAuthorized({ headers: { authorization: "Bearer ab" }, token: "abc" })).toBe(false);
expect(isAuthorized({ headers: {}, token: "abc" })).toBe(false);
});
});
+17
View File
@@ -0,0 +1,17 @@
import { timingSafeEqual } from "node:crypto";
import type { IncomingHttpHeaders } from "node:http";
/**
* Whether a request carries the computer's token (`Authorization: Bearer
* <token>`), compared in constant time. Everything passes when no token is
* set.
*/
export default function isAuthorized({ headers, token }: { headers: IncomingHttpHeaders; token: string }) {
if (!token) return true;
const given = String(headers.authorization || "").replace(/^Bearer\s+/i, "");
const a = Buffer.from(given);
const b = Buffer.from(token);
return a.length == b.length && timingSafeEqual(a, b);
}
+19
View File
@@ -0,0 +1,19 @@
type Params = {
url: string;
timeout_ms?: number;
};
/**
* Whether something answers `url` with a status below 500.
*/
export default async function isPortAnswering({ url, timeout_ms = 2000 }: Params) {
try {
const res = await fetch(url, { signal: AbortSignal.timeout(timeout_ms) });
await res.body?.cancel().catch(() => {});
return res.status < 500;
} catch {
return false;
}
}
+6
View File
@@ -0,0 +1,6 @@
/**
* One line on the agent's output (the container's log).
*/
export default function log({ name, message }: { name: string; message: string }) {
process.stdout.write(`[${new Date().toISOString()}] [${name}] ${message}\n`);
}
+46
View File
@@ -0,0 +1,46 @@
import { AgentConfig } from "./config";
import createAgentServer from "./create-agent-server";
import createBrowserParking from "./create-browser-parking";
import log from "./log";
import prepareRunDirs from "./prepare-run-dirs";
import startServices from "./start-services";
import type { Supervised } from "./supervise-process";
/**
* The computer's agent, its container's main process (under tini): starts
* the browser and what it needs, and serves the app on one port. On TERM
* (docker stop) it stops them in order, so Chrome saves its profile.
*/
async function main() {
prepareRunDirs();
let services: Supervised[] = [];
let stopping = false;
const stop = async () => {
if (stopping) return;
stopping = true;
log({ name: "agent", message: "stopping" });
for (const service of services) await service.stop({ grace_ms: AgentConfig.StopGraceMs });
process.exit(0);
};
process.on("SIGTERM", stop);
process.on("SIGINT", stop);
const parking = createBrowserParking({ cdp_port: AgentConfig.CdpPort, park_after_ms: AgentConfig.BrowserParkAfterMs });
createAgentServer({ parking }).listen(AgentConfig.Port, "0.0.0.0", () => {
log({ name: "agent", message: `listening on ${AgentConfig.Port}${AgentConfig.Token ? "" : " (no token set: open to anyone who reaches it)"}` });
});
services = await startServices({ parking });
}
main().catch((error) => {
log({ name: "agent", message: `couldn't start: ${error?.stack || error}` });
process.exit(1);
});
+175
View File
@@ -0,0 +1,175 @@
import { randomBytes } from "node:crypto";
import { request } from "node:http";
import type { Duplex } from "node:stream";
import encodeWebsocketFrame from "./encode-websocket-frame";
import readWebsocketFrames from "./read-websocket-frames";
type Params = {
/**
* Chrome's DevTools port, on loopback.
*/
port: number;
/**
* How long connecting, and each command, may take.
*/
timeout_ms: number;
};
export type CdpConnection = {
/**
* Runs one DevTools command (on a page's session when `session_id` is
* given) and resolves with its result; rejects with Chrome's error.
*/
send: (params: { method: string; params?: Record<string, unknown>; session_id?: string }) => Promise<any>;
close: () => void;
};
type Pending = {
resolve: (result: any) => void;
reject: (error: Error) => void;
timer: NodeJS.Timeout;
};
/**
* The agent's own DevTools client: one websocket to the browser's
* endpoint (`/json/version`), commands matched to their answers by id,
* events ignored. The image's Node has no WebSocket of its own, so the
* frames are the agent's (masked, as a client's must be).
*/
export default async function openCdpConnection({ port, timeout_ms }: Params): Promise<CdpConnection> {
const version = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(timeout_ms) });
const { webSocketDebuggerUrl } = (await version.json()) as { webSocketDebuggerUrl?: string };
if (!webSocketDebuggerUrl) throw new Error("The browser named no DevTools endpoint.");
const socket = await upgrade({ url: webSocketDebuggerUrl, timeout_ms });
const pending = new Map<number, Pending>();
let next_id = 0;
let closed = false;
let fragments: Buffer[] = [];
const close = () => {
if (closed) return;
closed = true;
for (const { reject, timer } of pending.values()) {
clearTimeout(timer);
reject(new Error("The DevTools connection closed."));
}
pending.clear();
socket.destroy();
};
const write = ({ opcode, payload }: { opcode: number; payload: Buffer }) => {
socket.write(encodeWebsocketFrame({ opcode, payload, mask: randomBytes(4) }));
};
const onMessage = (text: string) => {
let message: { id?: number; result?: unknown; error?: { message?: string } };
try {
message = JSON.parse(text);
} catch {
return;
}
const waiting = message.id == undefined ? undefined : pending.get(message.id);
if (!waiting) return;
pending.delete(message.id!);
clearTimeout(waiting.timer);
if (message.error) waiting.reject(new Error(message.error.message || "DevTools refused the command."));
else waiting.resolve(message.result);
};
const feed = readWebsocketFrames({
from: "server",
max_payload: 64 * 1024 * 1024,
onFrame: ({ fin, opcode, payload }) => {
if (opcode == 0x1 || opcode == 0x0) {
fragments.push(payload);
if (!fin) return;
const whole = Buffer.concat(fragments);
fragments = [];
onMessage(whole.toString("utf8"));
} else if (opcode == 0x8) {
close();
} else if (opcode == 0x9) {
write({ opcode: 0xa, payload });
}
},
});
socket.on("data", (chunk: Buffer) => {
try {
feed(chunk);
} catch {
close();
}
});
socket.on("error", close);
socket.on("close", close);
return {
close,
send: ({ method, params = {}, session_id }) => {
if (closed) return Promise.reject(new Error("The DevTools connection closed."));
const id = ++next_id;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`${method} took too long.`));
}, timeout_ms);
pending.set(id, { resolve, reject, timer });
write({
opcode: 0x1,
payload: Buffer.from(JSON.stringify({ id, method, params, ...(session_id ? { sessionId: session_id } : {}) })),
});
});
},
};
}
/**
* The websocket handshake to a `ws://` URL on loopback, resolving with
* the upgraded socket.
*/
function upgrade({ url, timeout_ms }: { url: string; timeout_ms: number }) {
const target = new URL(url);
return new Promise<Duplex>((resolve, reject) => {
const req = request({
host: target.hostname,
port: target.port,
path: target.pathname,
headers: {
Connection: "Upgrade",
Upgrade: "websocket",
"Sec-WebSocket-Version": "13",
"Sec-WebSocket-Key": randomBytes(16).toString("base64"),
},
timeout: timeout_ms,
});
req.on("upgrade", (_res, socket, head) => {
if (head.length) socket.unshift(head);
resolve(socket);
});
req.on("response", (res) => {
res.resume();
reject(new Error(`DevTools answered ${res.statusCode} instead of a websocket.`));
});
req.on("timeout", () => req.destroy(new Error("DevTools didn't answer.")));
req.on("error", reject);
req.end();
});
}
+14
View File
@@ -0,0 +1,14 @@
/**
* Chrome's own pages (New Tab, settings, error pages, blank tabs) draw
* next to nothing when they sit still; only sites are worth parking.
*/
const ChromePagePattern = /^(about|chrome|chrome-untrusted|chrome-error|devtools):/i;
/**
* Whether a tab on show costs anything to keep drawing: a site does (its
* animations, video and ads run at full rate while it's in front),
* Chrome's own pages don't.
*/
export default function pageNeedsParking({ url }: { url: string }) {
return !ChromePagePattern.test(url.trim());
}
+12
View File
@@ -0,0 +1,12 @@
/**
* How long an idle browser waits before its tabs are parked, from a whole
* number of seconds (`COBBLE_BROWSER_PARK_AFTER_SECONDS`): 0 turns parking
* off, anything unreadable is the default, 3 minutes.
*/
export default function parkAfterMs({ text }: { text?: string }) {
const value = String(text ?? "").trim();
if (!/^\d+$/.test(value)) return 180_000;
return Number(value) * 1000;
}
+71
View File
@@ -0,0 +1,71 @@
import type { CdpConnection } from "./open-cdp-connection";
import pageNeedsParking from "./page-needs-parking";
export type ParkedTab = {
/**
* The site's tab, sent to the background.
*/
page_id: string;
/**
* The blank tab put in front of it.
*/
blank_id: string;
};
type TargetInfo = { targetId: string; type: string; url: string };
/**
* Sends every site on show to the background, as a person switching tabs
* would: a blank tab opens in front of it in its window. A background tab
* keeps its connections and logins, but Chrome stops drawing it and slows
* its timers, so it costs next to nothing (in front, the virtual screen's
* software rendering draws its animations at full rate whether or not
* anyone watches). Returns what to bring back.
*/
export default async function parkBrowserTabs({ cdp }: { cdp: CdpConnection }): Promise<ParkedTab[]> {
const { targetInfos } = (await cdp.send({ method: "Target.getTargets" })) as { targetInfos: TargetInfo[] };
const parked: ParkedTab[] = [];
for (const target of targetInfos) {
if (target.type != "page" || !pageNeedsParking({ url: target.url })) continue;
if (!(await isOnShow({ cdp, target_id: target.targetId }))) continue;
// In front of its own window: a new tab opens in the window used last.
await cdp.send({ method: "Target.activateTarget", params: { targetId: target.targetId } });
const { targetId } = (await cdp.send({ method: "Target.createTarget", params: { url: "about:blank" } })) as {
targetId: string;
};
parked.push({ page_id: target.targetId, blank_id: targetId });
}
return parked;
}
/**
* Whether a tab is the one on show in its window (the page itself says,
* which also covers a window of its own).
*/
async function isOnShow({ cdp, target_id }: { cdp: CdpConnection; target_id: string }) {
let session_id: string | undefined;
try {
({ sessionId: session_id } = await cdp.send({
method: "Target.attachToTarget",
params: { targetId: target_id, flatten: true },
}));
const { result } = await cdp.send({
method: "Runtime.evaluate",
params: { expression: "document.visibilityState", returnByValue: true },
session_id,
});
return result?.value == "visible";
} catch {
return false;
} finally {
if (session_id) await cdp.send({ method: "Target.detachFromTarget", params: { sessionId: session_id } }).catch(() => {});
}
}
+27
View File
@@ -0,0 +1,27 @@
import { chmodSync, chownSync, mkdirSync } from "node:fs";
import { AgentConfig } from "./config";
/**
* The folders the services need, owned by the computer's user: the run
* dir (bus, pid, state), its private runtime dir, the X socket dir, and
* the home folders (a fresh mount may arrive owned by root).
*/
export default function prepareRunDirs() {
const { Uid, Gid } = AgentConfig;
for (const [dir, mode] of [
[AgentConfig.RunDir, 0o755],
[`${AgentConfig.RunDir}/xdg`, 0o700],
[AgentConfig.Home, 0o755],
[AgentConfig.WorkspaceDir, 0o755],
[AgentConfig.ProfileDir, 0o700],
[`${AgentConfig.Home}/.cobble`, 0o700],
] as const) {
mkdirSync(dir, { recursive: true });
chownSync(dir, Uid, Gid);
chmodSync(dir, mode);
}
mkdirSync("/tmp/.X11-unix", { recursive: true });
chmodSync("/tmp/.X11-unix", 0o1777);
}
+41
View File
@@ -0,0 +1,41 @@
import { request, type IncomingMessage, type ServerResponse } from "node:http";
import sendJson from "./send-json";
type Params = {
req: IncomingMessage;
res: ServerResponse;
/**
* The loopback port of the service behind this path.
*/
port: number;
/**
* Said when it doesn't answer.
*/
unavailable: string;
};
/**
* Streams a request to a service on loopback (Playwright MCP, the web
* terminal) and its answer back, event streams included, as if it came
* from there: their host checks only let loopback hosts in, and the
* app's token stays here.
*/
export default function proxyLoopback({ req, res, port, unavailable }: Params) {
const headers = { ...req.headers, host: `127.0.0.1:${port}` };
delete headers.authorization;
delete headers.origin;
const upstream = request({ host: "127.0.0.1", port, method: req.method, path: req.url, headers }, (answer) => {
res.writeHead(answer.statusCode || 502, answer.headers);
answer.pipe(res);
});
upstream.on("error", () => {
if (!res.headersSent) sendJson({ res, status: 502, body: { error: unavailable } });
else res.destroy();
});
res.on("close", () => upstream.destroy());
req.pipe(upstream);
}
+13
View File
@@ -0,0 +1,13 @@
import type { IncomingMessage } from "node:http";
import path from "node:path";
/**
* The absolute, normalised `path` a request names in its query, or null.
*/
export default function queryPath({ req }: { req: IncomingMessage }) {
const value = new URL(req.url || "/", "http://agent").searchParams.get("path") || "";
if (!value.startsWith("/") || value.includes("\0")) return null;
return path.posix.normalize(value);
}
+23
View File
@@ -0,0 +1,23 @@
import type { IncomingMessage } from "node:http";
/**
* A request's JSON body (at most `max_bytes`), or null when it isn't JSON.
*/
export default async function readJsonBody({ req, max_bytes }: { req: IncomingMessage; max_bytes: number }): Promise<any> {
const chunks: Buffer[] = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > max_bytes) throw new Error(`The body is over ${max_bytes} bytes.`);
chunks.push(chunk);
}
try {
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
} catch {
return null;
}
}
+73
View File
@@ -0,0 +1,73 @@
export type WebsocketFrame = {
fin: boolean;
opcode: number;
payload: Buffer;
};
type Params = {
onFrame: (frame: WebsocketFrame) => void;
/**
* A frame claiming more than this ends the connection.
*/
max_payload: number;
/**
* Who sends the frames: a client (a browser, the default) always
* masks them, a server (Chrome's DevTools, to the agent's own client)
* never does.
*/
from?: "client" | "server";
};
/**
* Reads websocket frames (RFC 6455) from a byte stream fed in any chunks:
* returns the function to feed them to, which calls `onFrame` with each
* whole frame, unmasked. Throws on a frame masked the wrong way for its
* sender, or an oversized one.
*/
export default function readWebsocketFrames({ onFrame, max_payload, from = "client" }: Params) {
let buffer: Buffer = Buffer.alloc(0);
return (chunk: Buffer) => {
buffer = buffer.length ? Buffer.concat([buffer, chunk]) : chunk;
while (buffer.length >= 2) {
const first = buffer[0]!;
const second = buffer[1]!;
const masked = Boolean(second & 0x80);
let length = second & 0x7f;
let offset = 2;
if (from == "client" && !masked) throw new Error("A client frame came unmasked.");
if (from == "server" && masked) throw new Error("A server frame came masked.");
if (length == 126) {
if (buffer.length < 4) return;
length = buffer.readUInt16BE(2);
offset = 4;
} else if (length == 127) {
if (buffer.length < 10) return;
const long = buffer.readBigUInt64BE(2);
if (long > BigInt(max_payload)) throw new Error("A frame was too large.");
length = Number(long);
offset = 10;
}
if (length > max_payload) throw new Error("A frame was too large.");
const mask_length = masked ? 4 : 0;
if (buffer.length < offset + mask_length + length) return;
const payload = Buffer.from(buffer.subarray(offset + mask_length, offset + mask_length + length));
if (masked) {
const mask = buffer.subarray(offset, offset + 4);
for (let index = 0; index < payload.length; index++) payload[index]! ^= mask[index & 3]!;
}
buffer = buffer.subarray(offset + mask_length + length);
onFrame({ fin: Boolean(first & 0x80), opcode: first & 0x0f, payload });
}
};
}
+61
View File
@@ -0,0 +1,61 @@
import { describe, expect, test } from "bun:test";
import runCommand from "./run-command";
const base = {
cwd: "/tmp",
env: { PATH: process.env.PATH },
timeout_seconds: 10,
max_output_bytes: 1024,
};
describe("runCommand", () => {
test("returns output in order and the exit code", async () => {
const result = await runCommand({ ...base, command: "echo one; echo two >&2; exit 3" });
expect(result.output).toBe("one\ntwo\n");
expect(result.exit_code).toBe(3);
expect(result.timed_out).toBe(false);
});
test("reads no input", async () => {
const result = await runCommand({ ...base, command: "read -r line; echo \"got:$line:$?\"" });
expect(result.output).toBe("got::1\n");
});
test("stops a command past its timeout, with its children", async () => {
const started = Date.now();
const result = await runCommand({ ...base, timeout_seconds: 1, command: "sleep 30 & sleep 30" });
expect(result.timed_out).toBe(true);
expect(result.exit_code).toBe(124);
expect(Date.now() - started).toBeLessThan(5000);
});
test("doesn't wait for background work", async () => {
const started = Date.now();
const result = await runCommand({ ...base, command: "sleep 5 & echo started" });
expect(result.output).toBe("started\n");
expect(Date.now() - started).toBeLessThan(2000);
});
test("cuts long output", async () => {
const result = await runCommand({ ...base, max_output_bytes: 10, command: "printf '%050d' 0" });
expect(result.output.length).toBe(10);
expect(result.truncated).toBe(true);
});
test("is killed when aborted", async () => {
const controller = new AbortController();
setTimeout(() => controller.abort(), 200);
const started = Date.now();
const result = await runCommand({ ...base, signal: controller.signal, command: "sleep 30" });
expect(result.exit_code).not.toBe(0);
expect(Date.now() - started).toBeLessThan(3000);
});
});
+131
View File
@@ -0,0 +1,131 @@
import { spawn } from "node:child_process";
import { killGroup } from "./supervise-process";
type Params = {
command: string;
cwd: string;
env: NodeJS.ProcessEnv;
uid?: number;
gid?: number;
timeout_seconds: number;
max_output_bytes: number;
/**
* Aborting (the caller went away, the run was stopped) kills it.
*/
signal?: AbortSignal;
};
export type CommandResult = {
output: string;
exit_code: number | null;
timed_out: boolean;
truncated: boolean;
};
/**
* Runs one command in its own `bash -c`, in its own process group, with
* no input (a prompt fails at once instead of waiting). stdout and stderr
* come back together, in order, cut at `max_output_bytes`. Past its
* timeout, or when aborted, the whole group gets TERM, then KILL 5s later.
* It resolves when bash exits, not when every pipe closes, so work left in
* the background (`nohup ... &`) keeps running without holding the call.
*/
export default function runCommand({
command,
cwd,
env,
uid,
gid,
timeout_seconds,
max_output_bytes,
signal,
}: Params): Promise<CommandResult> {
return new Promise((resolve) => {
const chunks: Buffer[] = [];
let size = 0;
let truncated = false;
let timed_out = false;
let settled = false;
const child = spawn("bash", ["-c", command], {
cwd,
env,
uid,
gid,
detached: true,
stdio: ["ignore", "pipe", "pipe"],
});
const keep = (chunk: Buffer) => {
if (size >= max_output_bytes) {
truncated = true;
return;
}
const room = max_output_bytes - size;
if (chunk.length > room) truncated = true;
const part = chunk.length > room ? chunk.subarray(0, room) : chunk;
chunks.push(part);
size += part.length;
};
child.stdout?.on("data", keep);
child.stderr?.on("data", keep);
let kill_timer: NodeJS.Timeout | undefined;
const stop = () => {
if (!child.pid || child.exitCode != null) return;
killGroup({ pid: child.pid, signal: "SIGTERM" });
kill_timer = setTimeout(() => child.pid && killGroup({ pid: child.pid, signal: "SIGKILL" }), 5000);
};
const timer = setTimeout(() => {
timed_out = true;
stop();
}, timeout_seconds * 1000);
const onAbort = () => stop();
signal?.addEventListener("abort", onAbort, { once: true });
const finish = (exit_code: number | null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
clearTimeout(kill_timer);
signal?.removeEventListener("abort", onAbort);
/**
* A moment for what's still in the pipes, then let go of them:
* a background job may hold them open for hours.
*/
setTimeout(() => {
child.stdout?.destroy();
child.stderr?.destroy();
resolve({
output: Buffer.concat(chunks).toString("utf8"),
exit_code: timed_out ? 124 : exit_code,
timed_out,
truncated,
});
}, 50);
};
child.on("error", (error) => {
keep(Buffer.from(`${error.message}\n`));
finish(127);
});
child.on("exit", (code, exit_signal) => finish(code ?? (exit_signal ? 128 + signalNumber({ signal: exit_signal }) : null)));
});
}
function signalNumber({ signal }: { signal: NodeJS.Signals }) {
return ({ SIGHUP: 1, SIGINT: 2, SIGKILL: 9, SIGTERM: 15 } as Record<string, number>)[signal] || 0;
}
+29
View File
@@ -0,0 +1,29 @@
import { describe, expect, test } from "bun:test";
import { BrowserBlockedArgs, McpBlockedArgs } from "./blocked-args";
import safeExtraArgs from "./safe-extra-args";
describe("safeExtraArgs", () => {
test("keeps ordinary flags", () => {
expect(safeExtraArgs({ text: " --force-dark-mode --window-name=x ", blocked: BrowserBlockedArgs })).toEqual([
"--force-dark-mode",
"--window-name=x",
]);
});
test("drops flags that would open DevTools or move the profile", () => {
expect(
safeExtraArgs({
text: "--remote-debugging-address=0.0.0.0 --REMOTE-DEBUGGING-PORT=1 --user-data-dir=/tmp --mute-audio",
blocked: BrowserBlockedArgs,
}),
).toEqual(["--mute-audio"]);
});
test("keeps Playwright MCP on loopback and this browser", () => {
expect(safeExtraArgs({ text: "--host=0.0.0.0 --port 9 --caps vision --cdp-endpoint=x", blocked: McpBlockedArgs })).toEqual(["--caps", "vision"]);
});
test("nothing set is nothing", () => {
expect(safeExtraArgs({ text: undefined, blocked: McpBlockedArgs })).toEqual([]);
});
});
+33
View File
@@ -0,0 +1,33 @@
type Params = {
/**
* Space separated flags, as set (no quoting).
*/
text?: string;
blocked: readonly string[];
};
/**
* Extra flags from the computer's settings, without the blocked ones,
* whatever case they're in: `--name=value`, or `--name` and the value
* after it (a word not starting with `-`).
*/
export default function safeExtraArgs({ text, blocked }: Params) {
const words = String(text || "")
.split(/\s+/)
.filter(Boolean);
const kept: string[] = [];
for (let index = 0; index < words.length; index++) {
const word = words[index]!;
const [name, value] = [word.split("=")[0]!.toLowerCase(), word.includes("=")];
if (!blocked.includes(name)) {
kept.push(word);
continue;
}
if (!value && words[index + 1] && !words[index + 1]!.startsWith("-")) index++;
}
return kept;
}
+9
View File
@@ -0,0 +1,9 @@
/**
* A screen size from `WIDTHxHEIGHT`, else 1920x1080 (the most common
* desktop, so the browser's screen gives nothing away).
*/
export default function screenSize({ text }: { text?: string }) {
const match = String(text || "").match(/^(\d{3,5})x(\d{3,5})$/);
return match ? { width: Number(match[1]), height: Number(match[2]) } : { width: 1920, height: 1080 };
}
+12
View File
@@ -0,0 +1,12 @@
import type { ServerResponse } from "node:http";
export default function sendJson({ res, status = 200, body }: { res: ServerResponse; status?: number; body: unknown }) {
const text = JSON.stringify(body);
res.writeHead(status, {
"content-type": "application/json; charset=utf-8",
"content-length": Buffer.byteLength(text),
"cache-control": "no-store",
});
res.end(text);
}
+62
View File
@@ -0,0 +1,62 @@
import { readFile } from "node:fs/promises";
import type { ServerResponse } from "node:http";
import path from "node:path";
const Types: Record<string, string> = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".ico": "image/x-icon",
".oga": "audio/ogg",
".mp3": "audio/mpeg",
".woff": "font/woff",
".ttf": "font/ttf",
};
type Params = {
res: ServerResponse;
/**
* The folder served (noVNC's).
*/
root: string;
/**
* The path asked for, below it.
*/
name: string;
};
/**
* A file from a folder of the image (noVNC), kept inside it and limited to
* the kinds a web page loads; anything else is a 404. Never cached: the
* image's version is the only one there is.
*/
export default async function serveStaticFile({ res, root, name }: Params) {
let decoded = "";
try {
decoded = decodeURIComponent(name);
} catch {
decoded = "";
}
const file = path.resolve(root, `.${path.posix.sep}${decoded}`);
const type = Types[path.extname(file).toLowerCase()];
const inside = file.startsWith(`${path.resolve(root)}${path.sep}`);
const bytes = decoded && type && inside ? await readFile(file).catch(() => null) : null;
if (!bytes) {
res.writeHead(404).end();
return;
}
res.writeHead(200, {
"content-type": type!,
"content-length": bytes.length,
"cache-control": "no-cache",
"x-content-type-options": "nosniff",
});
res.end(bytes);
}
+35
View File
@@ -0,0 +1,35 @@
type Params = {
now: number;
/**
* When the browser was last used or watched.
*/
last_active_at: number;
/**
* When the open tabs were last parked (or found not worth it), 0 for
* never: nothing changed since, so they aren't looked at again.
*/
checked_at: number;
/**
* Screen views open now.
*/
viewers: number;
/**
* Browser tool calls running now.
*/
holds: number;
/**
* Idle this long parks it; 0 never does.
*/
park_after_ms: number;
};
/**
* Whether the browser has sat unused and unwatched long enough to park
* its tabs, and hasn't been parked since it was last used.
*/
export default function shouldParkBrowser({ now, last_active_at, checked_at, viewers, holds, park_after_ms }: Params) {
if (park_after_ms <= 0 || viewers > 0 || holds > 0) return false;
if (checked_at >= last_active_at) return false;
return now - last_active_at >= park_after_ms;
}
+224
View File
@@ -0,0 +1,224 @@
import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { AgentState } from "./agent-state";
import browserArgs from "./browser-args";
import clearProfileLocks from "./clear-profile-locks";
import type { BrowserParking } from "./create-browser-parking";
import { AgentConfig } from "./config";
import findBrowserBinary from "./find-browser-binary";
import isPortAnswering from "./is-port-answering";
import log from "./log";
import superviseProcess, { type Supervised } from "./supervise-process";
import userEnv from "./user-env";
import waitUntil from "./wait-until";
/**
* Says the host gives Chrome no sandbox (user namespaces blocked).
*/
const NoSandboxPattern = /no usable sandbox|setuid sandbox|user namespaces|clone\(\) failed/i;
/**
* Starts and keeps running, as the computer's user: the virtual screen
* (Xvnc, an X server that is also a VNC server on loopback, so the screen
* view shows Chrome's whole window), the session bus (where the notification watcher meets Chrome),
* Chrome, Playwright MCP once Chrome's DevTools port answers, and the web
* terminal (ttyd, a login shell in the workspace). Each one comes back
* when it exits (a new Chrome tells `parking` its old tabs are gone).
* Returns them in the order they stop.
*/
export default async function startServices({ parking }: { parking: BrowserParking }): Promise<Supervised[]> {
const { Uid: uid, Gid: gid, RunDir, Screen } = AgentConfig;
const binary = findBrowserBinary();
AgentState.browser_binary = binary;
AgentState.browser_version = readVersion({ binary });
AgentState.browser_sandbox = AgentConfig.BrowserSandbox;
log({ name: "agent", message: `${AgentState.browser_version} at ${binary}` });
const display = superviseProcess({
name: "display",
command: "Xvnc",
args: () => [
AgentConfig.Display,
"-geometry",
`${Screen.width}x${Screen.height}`,
"-depth",
"24",
"-dpi",
"96",
"-nolisten",
"tcp",
"-desktop",
"Computer",
// VNC on loopback only, without a password: the agent's token
// guards the one way in (`/desktop/websockify`).
"-localhost",
"-interface",
"127.0.0.1",
"-rfbport",
String(AgentConfig.VncPort),
"-SecurityTypes",
"None",
"-AlwaysShared",
// The screen size is a setting (and what sites see); a viewer
// only scales it.
"-AcceptSetDesktopSize=0",
],
env: () => userEnv(),
uid,
gid,
});
const bus = superviseProcess({
name: "bus",
command: "dbus-daemon",
args: () => ["--session", "--nofork", "--nopidfile", `--address=unix:path=${RunDir}/bus`],
env: () => userEnv(),
uid,
gid,
});
await waitUntil({ check: async () => Boolean(display.pid()), every_ms: 100 });
await new Promise((resolve) => setTimeout(resolve, 500));
const browser = superviseProcess({
name: "browser",
command: binary,
args: () => {
clearProfileLocks({ profile_dir: AgentConfig.ProfileDir });
return browserArgs({
profile_dir: AgentConfig.ProfileDir,
cdp_port: AgentConfig.CdpPort,
screen: Screen,
scale: AgentConfig.Scale,
lang: AgentConfig.Lang,
accept_lang: AgentConfig.AcceptLang,
sandbox: AgentState.browser_sandbox,
extra: AgentConfig.BrowserExtraArgs,
});
},
env: () => userEnv(),
cwd: AgentConfig.Home,
uid,
gid,
onStart: ({ pid }) => {
parking.browserRestarted();
writeBrowserState({ pid });
},
onExit: ({ uptime_ms, tail }) => {
if (AgentState.browser_sandbox && uptime_ms < 20_000 && NoSandboxPattern.test(tail)) {
AgentState.browser_sandbox = false;
log({ name: "browser", message: `the host gives Chrome no sandbox; running it without one. ${tail.slice(-300)}` });
}
},
});
await waitUntil({
check: () => isPortAnswering({ url: `http://127.0.0.1:${AgentConfig.CdpPort}/json/version` }),
every_ms: 500,
});
log({ name: "browser", message: `DevTools answers on ${AgentConfig.CdpPort}` });
const mcp = superviseProcess({
name: "mcp",
command: process.execPath,
args: () => [
AgentConfig.McpCli,
"--cdp-endpoint",
`http://127.0.0.1:${AgentConfig.CdpPort}`,
"--host",
"127.0.0.1",
"--port",
String(AgentConfig.McpPort),
"--shared-browser-context",
"--ignore-roots",
"--allow-unrestricted-file-access",
"--codegen",
"none",
"--no-webmcp",
// Snapshots, console logs and downloads it writes to files: the
// app moves downloads into the run's folders and points the
// model at the tools that read the rest, so the paths are
// absolute and the folder is kept small.
"--output-dir",
AgentConfig.McpOutputDir,
"--output-max-size",
String(AgentConfig.McpOutputMaxBytes),
"--file-paths",
"absolute",
...AgentConfig.McpExtraArgs,
],
env: () => userEnv(),
cwd: AgentConfig.WorkspaceDir,
uid,
gid,
});
const terminal = superviseProcess({
name: "terminal",
command: "ttyd",
args: () => [
"--interface",
"127.0.0.1",
"--port",
String(AgentConfig.TerminalPort),
"--base-path",
"/terminal",
"--writable",
"--cwd",
AgentConfig.WorkspaceDir,
"--client-option",
"titleFixed=Shell",
"--client-option",
"disableLeaveAlert=true",
"bash",
"--login",
],
env: () => ({ ...userEnv(), TERM: "xterm-256color" }),
cwd: AgentConfig.WorkspaceDir,
uid,
gid,
});
return [terminal, mcp, browser, bus, display];
}
/**
* The browser's version line, e.g. `Google Chrome 142.0.7444.59`.
*/
function readVersion({ binary }: { binary: string }) {
try {
return execFileSync(binary, ["--version"], { encoding: "utf8", timeout: 10_000 }).trim();
} catch {
return "";
}
}
/**
* Where the browser runs and with what, for what runs beside it (the
* notification watcher restarts Chrome by its pid, and reads when it
* started from the pid file's time).
*/
function writeBrowserState({ pid }: { pid: number }) {
const env = userEnv();
writeFileSync(`${AgentConfig.RunDir}/browser.pid`, `${pid}\n`, { mode: 0o644 });
writeFileSync(
`${AgentConfig.RunDir}/browser.json`,
`${JSON.stringify({
browser: {
pid,
binary: AgentState.browser_binary,
env: {
DISPLAY: env.DISPLAY,
DBUS_SESSION_BUS_ADDRESS: env.DBUS_SESSION_BUS_ADDRESS,
XDG_RUNTIME_DIR: env.XDG_RUNTIME_DIR,
},
},
})}\n`,
{ mode: 0o644 },
);
}
+130
View File
@@ -0,0 +1,130 @@
import { spawn, type ChildProcess } from "node:child_process";
import log from "./log";
export type SupervisedExit = {
code: number | null;
signal: NodeJS.Signals | null;
/**
* How long it ran.
*/
uptime_ms: number;
/**
* The end of what it printed.
*/
tail: string;
};
type Params = {
name: string;
command: string;
/**
* Read again before each start, so a restart can change them.
*/
args: () => string[];
env: () => NodeJS.ProcessEnv;
cwd?: string;
uid?: number;
gid?: number;
onStart?: (params: { pid: number }) => void;
onExit?: (params: SupervisedExit) => void;
};
export type Supervised = {
pid: () => number | undefined;
stop: (params: { grace_ms: number }) => Promise<void>;
};
const TailBytes = 4000;
/**
* Runs a long-lived child and starts it again whenever it exits, waiting
* longer each time it dies young (0.5s doubling to 10s, back to 0.5s after
* it ran for 30s). It runs in its own process group, so a stop reaches
* everything it started: TERM, then KILL after `grace_ms`.
*/
export default function superviseProcess({ name, command, args, env, cwd, uid, gid, onStart, onExit }: Params): Supervised {
let child: ChildProcess | undefined;
let stopped = false;
let delay_ms = 500;
let timer: NodeJS.Timeout | undefined;
const start = () => {
if (stopped) return;
const started_at = Date.now();
let tail = "";
const keep = (chunk: Buffer) => {
tail = (tail + chunk.toString("utf8")).slice(-TailBytes);
};
child = spawn(command, args(), {
cwd,
env: env(),
uid,
gid,
detached: true,
stdio: ["ignore", "pipe", "pipe"],
});
child.stdout?.on("data", keep);
child.stderr?.on("data", keep);
child.on("error", (error) => {
log({ name, message: `couldn't start: ${error.message}` });
});
child.on("exit", (code, signal) => {
const uptime_ms = Date.now() - started_at;
child = undefined;
onExit?.({ code, signal, uptime_ms, tail });
if (stopped) return;
delay_ms = uptime_ms > 30_000 ? 500 : Math.min(delay_ms * 2, 10_000);
log({ name, message: `exited (${signal || code}) after ${Math.round(uptime_ms / 1000)}s; starting again in ${delay_ms}ms` });
timer = setTimeout(start, delay_ms);
});
if (child.pid) onStart?.({ pid: child.pid });
};
start();
return {
pid: () => child?.pid,
stop: async ({ grace_ms }) => {
stopped = true;
clearTimeout(timer);
const running = child;
if (!running?.pid) return;
const exited = new Promise<void>((resolve) => running.once("exit", () => resolve()));
killGroup({ pid: running.pid, signal: "SIGTERM" });
const timeout = new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), grace_ms));
if ((await Promise.race([exited, timeout])) == "timeout") {
killGroup({ pid: running.pid, signal: "SIGKILL" });
await exited;
}
},
};
}
/**
* Signals a whole process group, ignoring one that's already gone.
*/
export function killGroup({ pid, signal }: { pid: number; signal: NodeJS.Signals }) {
try {
process.kill(-pid, signal);
} catch {
try {
process.kill(pid, signal);
} catch {}
}
}
+14
View File
@@ -0,0 +1,14 @@
import type { CdpConnection } from "./open-cdp-connection";
import type { ParkedTab } from "./park-browser-tabs";
/**
* Puts parked sites back in front and closes the blank tabs that covered
* them, last parked first, so the browser is as it was left. A tab that
* went away meanwhile is skipped.
*/
export default async function unparkBrowserTabs({ cdp, parked }: { cdp: CdpConnection; parked: ParkedTab[] }) {
for (const { page_id, blank_id } of [...parked].reverse()) {
await cdp.send({ method: "Target.activateTarget", params: { targetId: page_id } }).catch(() => {});
await cdp.send({ method: "Target.closeTarget", params: { targetId: blank_id } }).catch(() => {});
}
}
+23
View File
@@ -0,0 +1,23 @@
import { AgentConfig } from "./config";
/**
* The environment everything run as the computer's user gets: its own
* home and identity, the virtual screen and the session bus, and nothing
* of the agent's own (its token never reaches a command).
*/
export default function userEnv({ extra = {} }: { extra?: NodeJS.ProcessEnv } = {}): NodeJS.ProcessEnv {
return {
PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
HOME: AgentConfig.Home,
USER: AgentConfig.User,
LOGNAME: AgentConfig.User,
SHELL: "/bin/bash",
LANG: process.env.LANG || "C.UTF-8",
TZ: process.env.TZ || "UTC",
DISPLAY: AgentConfig.Display,
XDG_RUNTIME_DIR: `${AgentConfig.RunDir}/xdg`,
DBUS_SESSION_BUS_ADDRESS: `unix:path=${AgentConfig.RunDir}/bus`,
PIP_BREAK_SYSTEM_PACKAGES: "1",
...extra,
};
}
+13
View File
@@ -0,0 +1,13 @@
type Params = {
check: () => Promise<boolean>;
every_ms: number;
};
/**
* Resolves once `check` passes, trying every `every_ms`.
*/
export default async function waitUntil({ check, every_ms }: Params) {
while (!(await check())) {
await new Promise((resolve) => setTimeout(resolve, every_ms));
}
}
+6
View File
@@ -0,0 +1,6 @@
import { expect, test } from "bun:test";
import websocketAccept from "./websocket-accept";
test("answers the RFC 6455 example key", () => {
expect(websocketAccept({ key: "dGhlIHNhbXBsZSBub25jZQ==" })).toBe("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
});
+13
View File
@@ -0,0 +1,13 @@
import { createHash } from "node:crypto";
/**
* The GUID RFC 6455 joins to the client's key.
*/
const WebsocketGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
/**
* The `Sec-WebSocket-Accept` answer to a client's `Sec-WebSocket-Key`.
*/
export default function websocketAccept({ key }: { key: string }) {
return createHash("sha1").update(key + WebsocketGuid).digest("base64");
}
+65
View File
@@ -0,0 +1,65 @@
import { describe, expect, test } from "bun:test";
import encodeWebsocketFrame from "./encode-websocket-frame";
import readWebsocketFrames, { type WebsocketFrame } from "./read-websocket-frames";
/**
* A client frame as a browser sends it: masked.
*/
function clientFrame({ opcode, payload }: { opcode: number; payload: Buffer }) {
return encodeWebsocketFrame({ opcode, payload, mask: Buffer.from([1, 2, 3, 4]) });
}
function collect({ from }: { from?: "client" | "server" } = {}) {
const frames: WebsocketFrame[] = [];
const feed = readWebsocketFrames({ onFrame: (frame) => frames.push(frame), max_payload: 1 << 20, from });
return { frames, feed };
}
describe("websocket frames", () => {
test("reads short, 16-bit and 64-bit lengths, unmasked", () => {
const { frames, feed } = collect();
for (const size of [5, 300, 70_000]) feed(clientFrame({ opcode: 2, payload: Buffer.alloc(size, size % 251) }));
expect(frames.map((frame) => frame.payload.length)).toEqual([5, 300, 70_000]);
expect(frames.every((frame) => frame.fin && frame.opcode == 2)).toBe(true);
expect(frames[1]!.payload.every((byte) => byte == 300 % 251)).toBe(true);
});
test("waits for a frame split across chunks, and reads two in one chunk", () => {
const { frames, feed } = collect();
const one = clientFrame({ opcode: 2, payload: Buffer.from("hello") });
const two = clientFrame({ opcode: 9, payload: Buffer.from("ping") });
const both = Buffer.concat([one, two]);
for (let index = 0; index < both.length; index += 3) feed(both.subarray(index, index + 3));
expect(frames.map((frame) => [frame.opcode, frame.payload.toString()])).toEqual([
[2, "hello"],
[9, "ping"],
]);
});
test("refuses unmasked and oversized frames", () => {
const { feed } = collect();
expect(() => feed(encodeWebsocketFrame({ opcode: 2, payload: Buffer.from("x") }))).toThrow("unmasked");
expect(() => collect().feed(clientFrame({ opcode: 2, payload: Buffer.alloc((1 << 20) + 1) }))).toThrow("too large");
});
test("masks a client's frame as RFC 6455 says", () => {
const frame = clientFrame({ opcode: 1, payload: Buffer.from("abcd") });
expect([...frame]).toEqual([0x81, 0x84, 1, 2, 3, 4, 0x61 ^ 1, 0x62 ^ 2, 0x63 ^ 3, 0x64 ^ 4]);
});
test("reads a server's unmasked frames, and refuses masked ones from it", () => {
const { frames, feed } = collect({ from: "server" });
for (const size of [3, 300, 70_000]) feed(encodeWebsocketFrame({ opcode: 1, payload: Buffer.alloc(size, 7) }));
expect(frames.map((frame) => frame.payload.length)).toEqual([3, 300, 70_000]);
expect(() => collect({ from: "server" }).feed(clientFrame({ opcode: 1, payload: Buffer.from("x") }))).toThrow("masked");
});
});
+81
View File
@@ -0,0 +1,81 @@
// Clipboard sync for noVNC (added to its vnc.html when the image is built).
// noVNC 1.6 only syncs the clipboard through its side panel. Here Ctrl+V or
// Cmd+V on the screen first hands the user's clipboard to the computer, then
// sends Ctrl+V, so it pastes what the user copied; text copied on the
// computer is put on the user's clipboard. Reading the clipboard asks the
// browser's permission once (the frame allows clipboard-read).
import UI from "./app/ui.js";
const XK_Control_L = 0xffe3;
const XK_v = 0x0076;
let swallowing_v = false;
// Whether the user still holds Ctrl when the paste goes out: reading the
// clipboard takes a moment, and noVNC may have sent Ctrl's release by then.
let ctrl_held = false;
const sendPaste = async () => {
let text = "";
try {
text = await navigator.clipboard.readText();
} catch {
text = "";
}
const rfb = UI.rfb;
if (!rfb) return;
if (text) rfb.clipboardPasteFrom(text);
// The computer's Chrome pastes on Ctrl+V (a Mac's Cmd is sent as Ctrl).
// Ctrl is pressed again here, and left down if the user still holds it.
rfb.sendKey(XK_Control_L, "ControlLeft", true);
rfb.sendKey(XK_v, "KeyV", true);
rfb.sendKey(XK_v, "KeyV", false);
if (!ctrl_held) rfb.sendKey(XK_Control_L, "ControlLeft", false);
};
window.addEventListener(
"keydown",
(event) => {
if (event.key == "Control") ctrl_held = true;
if (!UI.rfb || event.code != "KeyV" || event.altKey || event.shiftKey) return;
if (!(event.ctrlKey || event.metaKey)) return;
if (event.target instanceof HTMLTextAreaElement || event.target instanceof HTMLInputElement) return;
event.preventDefault();
event.stopImmediatePropagation();
swallowing_v = true;
sendPaste();
},
true,
);
window.addEventListener(
"keyup",
(event) => {
if (event.key == "Control") ctrl_held = false;
if (!swallowing_v || event.code != "KeyV") return;
event.preventDefault();
event.stopImmediatePropagation();
swallowing_v = false;
},
true,
);
const watch = () => {
if (!UI.rfb || UI.rfb.__cobble_clipboard) return;
UI.rfb.__cobble_clipboard = true;
UI.rfb.addEventListener("clipboard", (event) => {
navigator.clipboard?.writeText(event.detail.text).catch(() => {});
});
};
setInterval(watch, 500);
window.addEventListener("blur", () => {
ctrl_held = false;
});
+5
View File
@@ -2377,6 +2377,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `Memory limit of the container in MB, set when the computer is created`,
dataType: "INTEGER",
},
{
fieldName: "browser_settings",
fieldDescription: `JSON: its browser's timezone, languages, screen, sandbox and extra Chrome and Playwright MCP flags (ComputerBrowserSettingsSchema), passed to its container as env; empty uses the defaults`,
dataType: "TEXT",
},
],
indexes: [
{
+4
View File
@@ -1466,6 +1466,10 @@ export type BUN_SQLITE_COBBLE_COMPUTERS = {
* Memory limit of the container in MB, set when the computer is created
*/
memory_mb?: number | "";
/**
* JSON: its browser's timezone, languages, screen, sandbox and extra Chrome and Playwright MCP flags (ComputerBrowserSettingsSchema), passed to its container as env; empty uses the defaults
*/
browser_settings?: string;
}
export type BUN_SQLITE_COBBLE_BOT_COMPUTERS = {
+4 -3
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.12.3",
"version": "0.13.2",
"module": "index.ts",
"type": "module",
"private": true,
@@ -17,6 +17,7 @@
"typecheck": "tsc --noEmit",
"test": "bun test",
"check:bundle": "bun src/scripts/check-bundle-size.ts",
"build:computer": "bun src/scripts/build-computer-image.ts",
"publish:github": "bash scripts/publish-github.sh",
"publish:gitea": "bash scripts/publish-gitea.sh",
"mirror:gitea": "bash scripts/mirror-gitea.sh"
@@ -43,8 +44,8 @@
"@floating-ui/dom": "1.8.0",
"@modelcontextprotocol/sdk": "^1.32.1",
"@moduletrace/bun-sqlite": "^1.3.0",
"@moduletrace/bunext": "^1.3.3",
"@moduletrace/twui": "^0.1.7",
"@moduletrace/bunext": "^1.3.5",
"@moduletrace/twui": "^0.1.9",
"@tiptap/extension-bubble-menu": "3.32.0",
"@tiptap/extension-mention": "3.32.0",
"@tiptap/extension-placeholder": "3.32.0",
+3 -3
View File
@@ -12,8 +12,8 @@ describe("describeJobStep", () => {
text: null,
candidate,
tool_calls: [
{ id: "a", name: "sandbox_execute_bash", arguments: '{"command":"cat secret"}' },
{ id: "b", name: "sandbox_execute_bash", arguments: "{}" },
{ id: "a", name: "computer_bash", arguments: '{"command":"cat secret"}' },
{ id: "b", name: "computer_bash", arguments: "{}" },
{ id: "c", name: "update_memory", arguments: "{}" },
],
}),
@@ -23,7 +23,7 @@ describe("describeJobStep", () => {
metadata: {
step: 2,
model: "deepseek/deepseek-chat:free",
tools: ["sandbox_execute_bash", "update_memory"],
tools: ["computer_bash", "update_memory"],
},
});
});
@@ -157,7 +157,7 @@ export default function BotSessionsModal({
))}
{sessions.loading ? (
<LoadingBlock className="w-full h-[300px]" />
) : sessions.sessions.length ? (
) : !sessions.sessions.length ? (
<Span className="px-3 py-6 text-[13px] leading-[18px] text-ink-secondary">
{sessions.query.trim()
? `No session matches "${sessions.query.trim()}".`
+60
View File
@@ -0,0 +1,60 @@
import type { BotFace } from "@/src/dict/bot-dict";
import { StoneEyes } from "@/src/data/stone-geometry";
import StoneEyeDot from "./stone-eye-dot";
import StoneEyeLidded from "./stone-eye-lidded";
import StoneEyeArc from "./stone-eye-arc";
import StoneEyeFlat from "./stone-eye-flat";
type Props = {
face: BotFace;
/**
* Fill class for solid eyes.
*/
fill_class: string;
/**
* Stroke class for arc eyes.
*/
stroke_class: string;
};
/**
* The eyes for each face. Geometry follows the handoff face states:
* idle dots, working half-lidded, done upward arcs, asleep one flattened
* dot, needs-you dot plus arc.
*/
export default function BotStoneEyes({ face, fill_class, stroke_class }: Props) {
const { left, right, centre } = StoneEyes;
switch (face) {
case "working":
return (
<>
<StoneEyeLidded {...left} className={fill_class} />
<StoneEyeLidded {...right} className={fill_class} />
</>
);
case "done":
return (
<>
<StoneEyeArc {...left} className={stroke_class} />
<StoneEyeArc {...right} className={stroke_class} />
</>
);
case "asleep":
return <StoneEyeFlat {...centre} className={fill_class} />;
case "needs-you":
return (
<>
<StoneEyeDot {...left} className={fill_class} />
<StoneEyeArc {...right} className={stroke_class} />
</>
);
default:
return (
<>
<StoneEyeDot {...left} className={fill_class} />
<StoneEyeDot {...right} className={fill_class} />
</>
);
}
}
+57 -42
View File
@@ -1,9 +1,24 @@
import { twMerge } from "tailwind-merge";
import type { BotFace } from "@/src/dict/bot-dict";
import { StoneEyes } from "@/src/data/stone-geometry";
import StoneEyeDot from "./stone-eye-dot";
import StoneEyeLidded from "./stone-eye-lidded";
import StoneEyeArc from "./stone-eye-arc";
import StoneEyeFlat from "./stone-eye-flat";
import BotStoneEyes from "./bot-stone-eyes";
/**
* Idle blinks at three paces (`--animate-stone-blink-*` in `main.css`), so
* stones side by side never blink in step. Literal class names, so Tailwind
* sees them.
*/
const BlinkClasses = [
"animate-stone-blink-a",
"animate-stone-blink-b",
"animate-stone-blink-c",
] as const;
const FaceMotionClasses: Record<Exclude<BotFace, "idle">, string> = {
working: "animate-stone-glance",
done: "animate-stone-hop",
asleep: "animate-stone-breathe",
"needs-you": "animate-stone-nudge",
};
type Props = {
face: BotFace;
@@ -15,46 +30,46 @@ type Props = {
* Stroke class for arc eyes.
*/
stroke_class: string;
/**
* Leave the eyes still (the logo, static marks).
*/
still?: boolean;
/**
* Any whole number, the same for the same bot: picks its blink pace.
*/
motion_seed?: number;
};
/**
* The face is the status. Geometry follows the handoff face states:
* idle dots, working half-lidded, done upward arcs, asleep one flattened
* dot, needs-you dot plus arc.
* The face is the status, and each face moves its own way: idle blinks,
* working glances side to side, done hops once, asleep breathes, needs-you
* nudges. Only the eyes move; reduced motion keeps them still.
*/
export default function BotStoneFace({ face, fill_class, stroke_class }: Props) {
const { left, right, centre } = StoneEyes;
export default function BotStoneFace({
face,
fill_class,
stroke_class,
still,
motion_seed = 0,
}: Props) {
const motion_class =
face === "idle" || !FaceMotionClasses[face]
? BlinkClasses[Math.abs(motion_seed) % BlinkClasses.length]
: FaceMotionClasses[face];
switch (face) {
case "working":
return (
<>
<StoneEyeLidded {...left} className={fill_class} />
<StoneEyeLidded {...right} className={fill_class} />
</>
);
case "done":
return (
<>
<StoneEyeArc {...left} className={stroke_class} />
<StoneEyeArc {...right} className={stroke_class} />
</>
);
case "asleep":
return <StoneEyeFlat {...centre} className={fill_class} />;
case "needs-you":
return (
<>
<StoneEyeDot {...left} className={fill_class} />
<StoneEyeArc {...right} className={stroke_class} />
</>
);
default:
return (
<>
<StoneEyeDot {...left} className={fill_class} />
<StoneEyeDot {...right} className={fill_class} />
</>
);
}
return (
<g
className={twMerge(
"origin-center transform-fill",
!still && motion_class,
"motion-reduce:animate-none",
)}
>
<BotStoneEyes
face={face}
fill_class={fill_class}
stroke_class={stroke_class}
/>
</g>
);
}
+54 -11
View File
@@ -8,6 +8,19 @@ import {
import { botColorNeedsPaperFace, resolveBotStone } from "@/src/utils/bot-color";
import BotStoneFace from "./bot-stone-face";
/**
* How the whole stone moves for each face (`--animate-stone-body-*` in
* `main.css`). Only transforms: the outline and its one flat cut are never
* redrawn. The eyes move on top of this (`BotStoneFace`).
*/
const BodyMotionClasses: Record<BotFace, string> = {
idle: "animate-stone-body-idle",
working: "animate-stone-body-working",
done: "animate-stone-body-done",
asleep: "animate-stone-body-asleep",
"needs-you": "animate-stone-body-needs-you",
};
type Props = {
/**
* The bot's identity colour (`#rrggbb`). Omit (or `null`) for the
@@ -37,6 +50,11 @@ type Props = {
* stone (the default), so the stone is decorative.
*/
label?: string;
/**
* Leave the eyes still. Every face moves by default (`BotStoneFace`);
* the logo and other static marks pass this.
*/
still?: boolean;
className?: string;
};
@@ -44,6 +62,8 @@ type Props = {
* # Bot Stone
* @description A Cobble bot avatar: a stone with exactly one flat cut and two
* eyes. Never put it in a circle, ring or badge, or add an outline or shadow.
* The stone and its eyes move with its face unless `still`; it may hop a
* little past its box, so it draws `overflow-visible`.
*/
export default function BotStone({
color,
@@ -52,6 +72,7 @@ export default function BotStone({
face = "idle",
size = 32,
label,
still,
className,
}: Props) {
const is_coordinator = !color;
@@ -65,6 +86,14 @@ export default function BotStone({
const paper_face = is_coordinator || botColorNeedsPaperFace({ color: color! });
const eye_fill = paper_face ? "fill-paper" : "fill-dark";
const eye_stroke = paper_face ? "stroke-paper" : "stroke-dark";
/**
* The same bot always blinks at the same pace; different bots rarely
* share one.
*/
const motion_seed = [...`${color || ""}${stone || hue || ""}`].reduce(
(sum, char) => sum + char.charCodeAt(0),
0,
);
return (
<svg
@@ -74,18 +103,32 @@ export default function BotStone({
role={label ? "img" : undefined}
aria-label={label || undefined}
aria-hidden={label ? undefined : true}
className={twMerge("shrink-0", className)}
className={twMerge(
"shrink-0",
!still && "overflow-visible",
className,
)}
>
<path
d={body_path}
fill={is_coordinator ? undefined : color!}
className={is_coordinator ? "fill-ink" : undefined}
/>
<BotStoneFace
face={face}
fill_class={eye_fill}
stroke_class={eye_stroke}
/>
<g
className={twMerge(
"origin-bottom transform-fill",
!still && BodyMotionClasses[face],
"motion-reduce:animate-none",
)}
>
<path
d={body_path}
fill={is_coordinator ? undefined : color!}
className={is_coordinator ? "fill-ink" : undefined}
/>
<BotStoneFace
face={face}
fill_class={eye_fill}
stroke_class={eye_stroke}
still={still}
motion_seed={motion_seed}
/>
</g>
</svg>
);
}
@@ -1,3 +1,4 @@
import { twMerge } from "tailwind-merge";
import { ComputerViewModes, type ComputerViewMode } from "@/src/dict/computer-dict";
import computerViewUrl from "@/src/utils/computer-view-url";
@@ -23,7 +24,7 @@ export default function ComputerViewFrame({ computer_id, name, mode, active }: P
src={computerViewUrl({ computer_id, mode })}
title={`${name}: ${title}`}
allow="clipboard-read; clipboard-write; fullscreen"
className={`absolute inset-0 w-full h-full border-0 bg-sunken ${active ? "" : "hidden"}`}
className={twMerge("absolute inset-0 w-full h-full border-0 bg-sunken", !active && "hidden")}
/>
);
}
@@ -7,7 +7,7 @@ type Props = {
};
/**
* One mode in a computer view's toolbar (Browser, Terminal, Code).
* One mode in a computer view's toolbar (`ComputerViewModes`).
*/
export default function ComputerViewModeButton({ title, active, onPick }: Props) {
return (
+29 -17
View File
@@ -1,9 +1,14 @@
import { useState } from "react";
import { useContext, useState } from "react";
import { twMerge } from "tailwind-merge";
import Link from "@moduletrace/twui/layout/Link";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { ExternalLink } from "lucide-react";
import { ComputerViewModes, type ComputerViewMode } from "@/src/dict/computer-dict";
import type { ComputerViewMode } from "@/src/dict/computer-dict";
import { AppContext } from "@/src/pages/__root";
import computerViewModesFor from "@/src/utils/computer-view-modes-for";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import computerViewUrl from "@/src/utils/computer-view-url";
import ComputerViewFrame from "./computer-view-frame";
import ComputerViewModeButton from "./computer-view-mode-button";
@@ -22,13 +27,16 @@ type Props = {
};
/**
* A computer the user can work on: its browser, terminal or code editor
* (`ComputerViewModes`), served through the app (`/computers/<id>/`).
* A mode stays open once visited, so switching back keeps its state.
* A computer the user can work on: its screen (Chrome as it is), and its
* shell for crew managers (`computerViewModesFor`), served through the app
* (`/computers/<id>/`). The mode tabs show once there's more than one
* mode; a mode stays open once visited, so switching back keeps its state.
*/
export default function ComputerView({ computer_id, name, default_mode, className }: Props) {
const { user_types } = useContext(AppContext);
const modes = computerViewModesFor({ can_manage_crew: canManageCrew({ user_types: user_types || [] }) });
const [mode, setMode] = useState<ComputerViewMode>(
default_mode || ComputerViewModes[0].value,
modes.find((m) => m.value == default_mode)?.value || modes[0]!.value,
);
const [visited, setVisited] = useState<ComputerViewMode[]>([mode]);
@@ -38,18 +46,22 @@ export default function ComputerView({ computer_id, name, default_mode, classNam
};
return (
<Stack className={`w-full min-h-0 gap-0! items-stretch ${className || ""}`}>
<Stack className={twMerge("w-full min-h-0 gap-0! items-stretch", className)}>
<Row className="w-full gap-1! flex-nowrap items-center px-3 py-2 border-0 border-b border-solid border-hairline">
<Row role="tablist" aria-label={`${name} modes`} className="gap-1! flex-nowrap">
{ComputerViewModes.map((item) => (
<ComputerViewModeButton
key={item.value}
title={item.title}
active={item.value == mode}
onPick={() => pick({ value: item.value })}
/>
))}
</Row>
{modes.length > 1 ? (
<Row role="tablist" aria-label={`${name} modes`} className="gap-1! flex-nowrap">
{modes.map((item) => (
<ComputerViewModeButton
key={item.value}
title={item.title}
active={item.value == mode}
onPick={() => pick({ value: item.value })}
/>
))}
</Row>
) : (
<Span className="px-2 text-[13px] leading-[18px] font-bold text-ink">{modes[0]!.title}</Span>
)}
<Link
href={computerViewUrl({ computer_id, mode })}
target="_blank"
@@ -31,8 +31,7 @@ type Props = {
};
/**
* A computer, large, in its browser, terminal or code editor, over the
* page. `ComputerOpenButton` opens it from lists; chat's viewer adds a
* A computer, large, its browser live, over the page. `ComputerOpenButton` opens it from lists; chat's viewer adds a
* note and the hand-back action after a take-over. A restart reconnects
* its frames.
*/
+1
View File
@@ -18,6 +18,7 @@ export default function LogoIcon({ icon_size = 40, img_props }: Props) {
stone={BotHues[0].value}
size={icon_size}
label="Logo Icon"
still
className={img_props?.className}
/>
);
+55 -22
View File
@@ -86,19 +86,25 @@ export const AppData = {
*/
DockerNetworkName: SiteData["SiteSlug"],
/**
* Port the AIO sandbox listens on inside its container.
* Port a computer's agent listens on inside its container: its shell
* and file API, Playwright MCP (`/mcp`), its screen (`/desktop/`) and
* its shell (`/terminal/`).
*/
ComputerPort: 8080,
/**
* Every computer the app creates runs this image, named
* `<ComputerContainerPrefix>-<computer id>` on `DockerNetworkName`.
* Every computer the app creates runs this image (built from
* `computer/`), unless the `COMPUTER_IMAGE` app setting names another,
* named `<ComputerContainerPrefix>-<computer id>` on `DockerNetworkName`.
* Its tag is the image's version: bump it with any change under
* `computer/` (the release workflow builds that tag), and bump
* `ComputerWorkspaceLayout` too when existing computers must move to it.
*/
ComputerImage: "ghcr.io/agent-infra/sandbox:latest",
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.1.0",
ComputerContainerPrefix: `${SiteData["SiteSlug"]}-computer`,
/**
* Only a computer's workspace (`ComputerWorkspaceDir` in its
* container) is kept, at `DATA_DIR/<ComputerDataDir>/<id>`, owned by
* the sandbox's user, plus its browser profile
* the computer's user, plus its browser profile
* (`ComputerBrowserDataDir`). Both stay when the computer is deleted.
* The rest of its home (`ComputerHomeDir`: dotfiles, the env files)
* lives in the container and goes with it. Every bot works in
@@ -113,18 +119,33 @@ export const AppData = {
* A computer's browser profile (cookies, logins, site permissions) is
* kept at `DATA_DIR/<ComputerBrowserDataDir>/<id>`, outside its
* workspace, and mounted at `ComputerBrowserProfileDir`, which Chrome
* is pointed at with `--user-data-dir`. The image's own profile
* (`~/.config/browser`) can't be kept: every boot resets its
* preferences to session-only cookies.
* is pointed at with `--user-data-dir`.
*/
ComputerBrowserDataDir: "computer-browsers",
ComputerBrowserProfileDir: "/home/gem/.cobble-browser",
/**
* The managed policy file a computer's Chrome reads (the image's
* Chrome looks in `/etc/chromium/policies/managed`), written into the
* container by `syncComputerBrowserPolicy`.
* The managed policy file a computer's browser reads (Chrome's folder;
* the image links Chromium's to it), written into the container by
* `syncComputerBrowserPolicy`.
*/
ComputerBrowserPolicyFile: "/etc/chromium/policies/managed/cobble.json",
ComputerBrowserPolicyFile: "/etc/opt/chrome/policies/managed/cobble.json",
/**
* Where a computer's Playwright MCP writes what a browser tool saves
* without a name (snapshots, console logs), outside every run's
* folders: `withBrowserOutputs` turns those links into the tool that
* reads them.
*/
ComputerBrowserOutputDir: "/home/gem/.cobble/playwright",
/**
* Chrome saves downloads here itself (the seed prefs), since Playwright
* attached over CDP leaves them to the browser. After each browser tool
* call `withBrowserOutputs` moves finished ones into the run's
* `ComputerDownloadsFolder`, so whichever run's call comes next on that
* computer gets them (a download the user starts in the live view
* included).
*/
ComputerBrowserDownloadsDir: "/home/gem/Downloads",
ComputerDownloadsFolder: "downloads",
/**
* Written at the root of a computer's workspace once it uses that
* layout, so an older computer's whole home is told apart and moved
@@ -137,11 +158,12 @@ export const AppData = {
*/
ComputerOldHomeSuffix: "-home-",
/**
* Recorded in a container's `metadata.layout` once it mounts only the
* workspace and the browser profile. A container with another value
* is recreated (`migrateComputerLayout`).
* Recorded in a container's `metadata.layout`: the image and mounts it
* was created with. A container with another value is recreated
* (`migrateComputerLayout`), keeping its workspace and browser profile.
* `cobble-computer` moved every computer off the AIO sandbox.
*/
ComputerWorkspaceLayout: "workspace-browser",
ComputerWorkspaceLayout: "cobble-computer",
ComputerUserUid: 1000,
ComputerUserGid: 1000,
/**
@@ -154,8 +176,8 @@ export const AppData = {
ComputerMaxCpus: 64,
ComputerMinMemoryMb: 512,
/**
* Docker's health check on every computer container: the sandbox's API
* on `ComputerPort` and its browser answer. A new computer stays
* Docker's health check on every computer container: its agent's
* `/health`, which passes once the browser and its tools answer. A new computer stays
* `creating` until it passes, for at most `ComputerHealthyTimeoutMs`,
* checked every `ComputerHealthPollMs`.
*/
@@ -386,12 +408,23 @@ export const AppData = {
*/
McpToolTimeoutMs: 5 * 60 * 1000,
/**
* A bash command on a computer is killed there after at most this long
* (`withCommandTimeout`), below `McpToolTimeoutMs`: the sandbox ignores
* its own `timeout` and runs every call in one shell session, so a
* command left running would hold up every later one on that computer.
* A bash command on a computer (`computer_bash`) is killed there, with
* everything it started, after at most this long, below
* `HarnessToolTimeoutMs`.
*/
ComputerCommandMaxSeconds: 270,
/**
* What a computer's command hands the bot back (its start and end), and
* what `computer_read_file` reads: lines at a time, each line cut
* past `ComputerReadFileMaxLineChars`, files up to
* `ComputerReadFileMaxBytes`. `computer_write_file` and
* `computer_edit_file` take files up to `ComputerWriteFileMaxChars`.
*/
ComputerCommandMaxOutputChars: 40_000,
ComputerReadFileMaxLines: 2000,
ComputerReadFileMaxLineChars: 2000,
ComputerReadFileMaxBytes: 10 * 1024 * 1024,
ComputerWriteFileMaxChars: 5 * 1024 * 1024,
/**
* MCP servers set up in Settings, under MCPs: a stdio server runs in
* `DATA_DIR/<McpDataDir>/<id>` (its setup installs there, so it
+4 -2
View File
@@ -3,7 +3,9 @@
* a managed policy (`computerBrowserPolicy`, written by
* `syncComputerBrowserPolicy`). They're installed as `normal_installed`:
* a user can turn one off in that browser, but not remove it.
* Cookie-Editor carries a sign-in over from the user's own browser (help:
* "Google won't let me sign in on a computer").
*/
export const ComputerBrowserExtensions = [
export const ComputerBrowserExtensions: ReadonlyArray<{ id: string; name: string }> = [
{ id: "hlkenndednhfkekhgcdicdfddnkalmdm", name: "Cookie-Editor" },
] as const;
];
+4 -2
View File
@@ -1,3 +1,5 @@
import { AppData } from "@/src/data/app-data";
/**
* Chrome preferences a computer's browser profile starts with, written
* only when the profile has none (`prepareComputerBrowserDir`) so whatever
@@ -43,9 +45,9 @@ export const ComputerBrowserPreferences = {
accept_languages: "en-US,en",
},
download: {
default_directory: "/home/gem/Downloads",
default_directory: AppData.ComputerBrowserDownloadsDir,
prompt_for_download: false,
directory_upgrade: true,
},
savefile: { default_directory: "/home/gem/Downloads" },
savefile: { default_directory: AppData.ComputerBrowserDownloadsDir },
};
+1 -1
View File
@@ -108,7 +108,7 @@ export const ComputerFilesNote = ({
can_import?: boolean;
}) => `# Files on the computer
You work only in your own folders on the computer, never elsewhere in it: every shell, code and file tool starts in ${dirs.cwd} (also ~), and a path outside your folders is refused.
You work only in your own folders on the computer, never elsewhere in it: every shell and file tool starts in ${dirs.cwd} (also ~), and a path outside your folders is refused.
- ${dirs.cwd}: this user's work. Everything for them goes here.
- ${dirs.bot_dir}: only what is the same for every user you work for (other users' folders in it are not yours).${
+1 -1
View File
@@ -6,7 +6,7 @@ export const NotifyWatchVersion = "1";
/**
* The browser-notification watcher the app runs on a computer
* (`syncComputerNotifyWatch`), as `gem`, with the sandbox's own Python
* (`syncComputerNotifyWatch`), as `gem`, with the computer's own Python
* and GLib. It owns `org.freedesktop.Notifications` on the session bus,
* so Chrome sends its notifications to it instead of its silent built-in
* message center (Chrome looks for the service only when it starts), and
+4 -5
View File
@@ -97,11 +97,10 @@ export const BotComputerBusyStatusLine = "Waiting for its computer";
* tool name. Tools not listed read "Using <name>".
*/
export const JobStepToolLabels: Record<string, string> = {
sandbox_execute_bash: "Running a command",
sandbox_execute_code: "Running code",
sandbox_read_file: "Reading a file",
sandbox_write_file: "Writing a file",
sandbox_file_operations: "Working with files",
computer_bash: "Running a command",
computer_read_file: "Reading a file",
computer_write_file: "Writing a file",
computer_edit_file: "Editing a file",
search_computers: "Searching the computers",
import_file: "Copying a file from the computer",
ask_user_to_take_over: "Asking you to take over",
+88 -32
View File
@@ -1,8 +1,8 @@
/**
* A computer is an AIO sandbox running in its own docker container on the
* cobble network, created by the app (`createComputer`), only its
* workspace (`AppData.ComputerWorkspaceDir`) kept under
* `DATA_DIR/computers/<id>`.
* A computer is a container of the app's own image (`computer/`: a real
* headful browser and a shell) on the cobble network, created by the app
* (`createComputer`), only its workspace (`AppData.ComputerWorkspaceDir`)
* and browser profile kept under `DATA_DIR`.
*/
export const ComputerKinds = [
{
@@ -93,50 +93,47 @@ export const ContainerPurposes = [
export type ContainerPurpose = (typeof ContainerPurposes)[number]["value"];
/**
* Path of the AIO sandbox's MCP endpoint, on the computer's address.
* Path of the computer's MCP server (Playwright MCP, driving its browser),
* on the computer's address.
*/
export const ComputerMcpPath = "/mcp";
/**
* Sandbox MCP tools bots don't get: noise (cdp urls), skills they have no
* use for, and raw display control that needs pixel coordinates (the page
* tools cover the same ground by element).
* Playwright MCP tools bots don't get on a computer: closing or resizing
* the shared browser (every run and the user's live view use it, and its
* window fills the screen like a real one), its config, and running code
* in the MCP server itself (computer_bash covers that, inside the run's
* folders).
*/
export const ComputerMcpExcludedTools = [
"browser_get_info",
"sandbox_load_skill",
"browser_gui_screenshot",
"browser_gui_execute_action",
"browser_close",
"browser_resize",
"browser_get_config",
"browser_run_code_unsafe",
] as const;
/**
* How the user can open a computer, each one of the AIO sandbox's own
* apps at `path` (relative to the computer's address; `{prefix}` is the
* computer's app address without its leading slash, e.g. `computers/3/`).
* Desktop is the whole screen over VNC: the only view with the browser's
* toolbar (extensions) and a clipboard panel. More of them (opencode,
* codex) can join later.
* How the user can open a computer, each one served by the computer at
* `path` (relative to its address), and the only paths the app's proxy
* passes on (`computerProxyPathAllowed`). Browser is the computer's
* screen (noVNC over its VNC server): Chrome's whole window, tabs, menu,
* extensions and prompts, for anyone who reaches the computer. Shell is a
* terminal as the computer's user, who has sudo and so reads every bot's
* and user's folder there: `crew_only`, for crew managers
* (`canManageCrew`).
*/
export const ComputerViewModes = [
{
title: "Browser",
value: "browser",
path: "browser-ui",
path: "desktop/",
crew_only: false,
},
{
title: "Terminal",
title: "Shell",
value: "terminal",
path: "terminal",
},
{
title: "Code",
value: "code",
path: "code-server/",
},
{
title: "Desktop",
value: "desktop",
path: "vnc/vnc.html?autoconnect=true&resize=scale&reconnect=true&path={prefix}websockify",
path: "terminal/",
crew_only: true,
},
] as const;
@@ -144,6 +141,65 @@ export type ComputerViewMode = (typeof ComputerViewModes)[number]["value"];
/**
* Where the app serves a computer to its owner's browser:
* `/computers/<id>/<path>`, proxied to the sandbox (`handleComputerProxy`).
* `/computers/<id>/<path>`, proxied to the computer (`handleComputerProxy`).
*/
export const ComputerProxyPrefix = "/computers";
/**
* Screen sizes a computer's browser can have (`browser_settings.screen`):
* common desktop ones, so the screen gives nothing away. The first is the
* default.
*/
export const ComputerScreenSizes = ["1920x1080", "1366x768", "1536x864", "1440x900", "1280x800", "1600x900", "2560x1440"] as const;
/**
* How large a computer's browser draws pages, in percent
* (`browser_settings.scale`, Chrome's device scale factor): above 100,
* text is larger in bots' screenshots and the page is laid out narrower
* (1920x1080 at 125 is 1536x864, the most common laptop).
*/
export const ComputerBrowserScales = ["100", "125", "150", "175", "200"] as const;
/**
* The scale a computer's browser has when its settings name none; the
* computer's agent has the same default (`computer/agent/browser-scale.ts`).
*/
export const ComputerDefaultBrowserScale = "125";
/**
* Chrome flags a computer's settings may not add (`browser_settings
* .browser_args`): they'd open its DevTools to the network around the
* token, move its profile, or break the agent's hold on it. The computer's
* agent drops the same ones (`computer/agent/blocked-args.ts`); keep them
* alike.
*/
export const ComputerBlockedBrowserArgs = [
"--remote-debugging-port",
"--remote-debugging-address",
"--remote-debugging-pipe",
"--remote-allow-origins",
"--user-data-dir",
"--headless",
] as const;
/**
* Playwright MCP flags a computer's settings may not add (`mcp_args`):
* where it listens and what browser it drives are the agent's.
*/
export const ComputerBlockedMcpArgs = [
"--host",
"--port",
"--allowed-hosts",
"--allowed-origins",
"--cdp-endpoint",
"--cdp-header",
"--extension",
"--config",
"--browser",
"--executable-path",
"--user-data-dir",
"--isolated",
"--shared-browser-context",
"--output-dir",
"--file-paths",
] as const;
+5 -1
View File
@@ -100,4 +100,8 @@ export const ReservedToolNames = [
"update_workspace",
] as const;
export const ReservedToolPrefixes = ["sandbox_", "browser_"] as const;
/**
* Name prefixes of a computer's own tools (`computer_*` shell and files,
* `browser_*` from Playwright MCP); `sandbox_` was the AIO sandbox's.
*/
export const ReservedToolPrefixes = ["computer_", "browser_", "sandbox_"] as const;
+7 -1
View File
@@ -71,6 +71,12 @@ export const EnvDict: readonly KnownEnv[] = [
required: false,
secret: false,
},
{
key: "COMPUTER_IMAGE",
description: `The image new and rebuilt computers run, e.g. a registry mirror or a local build. Empty uses the image this release was made with.`,
required: false,
secret: false,
},
{
key: "COMPUTER_APP_URL",
description: `Where computers reach this app, for hooks they call (browser notifications), e.g. http://172.17.0.1:7000 for a server running outside docker. Empty uses the app's container on the docker network.`,
@@ -79,7 +85,7 @@ export const EnvDict: readonly KnownEnv[] = [
},
{
key: "MAIN_COMPUTER_DATA_DIR",
description: `Where the main computer's workspace (/home/gem/workspace, the only folder bots work in) is on this server's disk, for a computer the app didn't create itself (see MAIN_COMPUTER_URL), e.g. the bind mount your sandbox's compose file uses. Empty reads DATA_DIR/computers/<id>.`,
description: `Where the main computer's workspace (/home/gem/workspace, the only folder bots work in) is on this server's disk, for a computer the app didn't create itself (see MAIN_COMPUTER_URL), e.g. the bind mount you started it with. Empty reads DATA_DIR/computers/<id>.`,
required: false,
secret: false,
},
+2 -1
View File
@@ -4,7 +4,8 @@
export const HelpPath = "/admin/help";
/**
* Signing in to Google and other strict sites with Cookie-Editor.
* Signing in to Google and other strict sites, with cookies brought over
* from the user's own browser when the site still refuses.
*/
export const HelpSignInTopicId = "sign-in-with-cookies";
@@ -0,0 +1,46 @@
import { AppData } from "@/src/data/app-data";
import parseCollectedDownloads from "@/src/utils/parse-collected-downloads";
import shellQuote from "@/src/utils/shell-quote";
import type { ComputerApi } from "./computer-fetch";
import runComputerCommand from "./run-computer-command";
type Params = {
computer: ComputerApi;
/**
* The run's folder to move them into (made when needed).
*/
dir: string;
signal?: AbortSignal;
};
/**
* Moves every finished download out of the browser's download folder
* (`AppData.ComputerBrowserDownloadsDir`) into a run's folder, under its
* own name, numbered (`1-name`, ...) when that's taken, and lists the ones
* Chrome is still writing (`.crdownload`), which a later call picks up.
*/
export default async function collectComputerDownloads({ computer, dir, signal }: Params) {
const command = [
`src=${shellQuote({ text: AppData.ComputerBrowserDownloadsDir })}`,
`dir=${shellQuote({ text: dir })}`,
`[ -d "$src" ] || exit 0`,
`for f in "$src"/* "$src"/.[!.]*; do`,
` [ -f "$f" ] || continue`,
` name=$(basename -- "$f")`,
` case "$name" in *.crdownload) printf 'pending\\t%s\\n' "\${name%.crdownload}"; continue;; esac`,
` mkdir -p "$dir" || exit 1`,
` to="$dir/$name"; n=1`,
` while [ -e "$to" ]; do to="$dir/$n-$name"; n=$((n+1)); done`,
` mv -- "$f" "$to" && printf 'moved\\t%s\\t%s\\n' "$name" "$to"`,
`done`,
].join("\n");
const { output } = await runComputerCommand({
computer,
command,
timeout_ms: AppData.McpConnectTimeoutMs,
signal,
});
return parseCollectedDownloads({ output });
}
@@ -0,0 +1,35 @@
/**
* A computer's agent: its address and the token it asks for
* (`computerToken`). `grabComputerMcpUrl`'s ready answer is one.
*/
export type ComputerApi = {
base_url: string;
token: string;
};
type Params = {
computer: ComputerApi;
/**
* From the agent's root, e.g. `/api/exec`.
*/
path: string;
init?: RequestInit;
timeout_ms: number;
signal?: AbortSignal;
};
/**
* One request to a computer's agent, with its token. Returns the response
* as it is; throws when the computer can't be reached in time.
*/
export default function computerFetch({ computer, path, init = {}, timeout_ms, signal }: Params) {
const headers = new Headers(init.headers);
headers.set("authorization", `Bearer ${computer.token}`);
return fetch(`${computer.base_url}${path}`, {
...init,
headers,
signal: AbortSignal.any([...(signal ? [signal] : []), AbortSignal.timeout(timeout_ms)]),
});
}
@@ -0,0 +1,33 @@
import computerFetch, { type ComputerApi } from "./computer-fetch";
type Params = {
computer: ComputerApi;
path: string;
/**
* A JSON body makes it a POST.
*/
body?: Record<string, unknown>;
timeout_ms: number;
signal?: AbortSignal;
};
/**
* One JSON call to a computer's agent. Returns its answer; throws with the
* agent's own error when it refuses.
*/
export default async function computerJson<T = any>({ computer, path, body, timeout_ms, signal }: Params): Promise<T> {
const res = await computerFetch({
computer,
path,
init: body
? { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }
: { method: "GET" },
timeout_ms,
signal,
});
const json: any = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(`The computer refused ${path}: ${json?.error || res.status}`);
return json as T;
}
@@ -0,0 +1,55 @@
import computerFetch, { type ComputerApi } from "./computer-fetch";
import statComputerFile from "./stat-computer-file";
type Params = {
computer: ComputerApi;
/**
* The file on the computer, absolute.
*/
path: string;
/**
* Refuse it above this many bytes.
*/
max_bytes: number;
signal?: AbortSignal;
};
export type ComputerDownload =
| { ok: true; bytes: Buffer; size: number }
| { ok: false; reason: "missing" | "too_big" | "cut_short"; size: number };
/**
* A computer's file, byte for byte, streamed by its agent
* (`/api/files/download`), never through a shell, whose output is capped
* and would silently cut a big file short. The size is read first so
* nothing over the limit is sent; the agent cuts the transfer when the
* file changes while it's sent, and the length is checked, so a short
* transfer is reported instead of being saved.
*/
export default async function downloadComputerFile({ computer, path, max_bytes, signal }: Params): Promise<ComputerDownload> {
const stat = await statComputerFile({ computer, path, signal });
if (!stat.exists || stat.type != "file") return { ok: false, reason: "missing", size: 0 };
if (stat.size > max_bytes) return { ok: false, reason: "too_big", size: stat.size };
const res = await computerFetch({
computer,
path: `/api/files/download?path=${encodeURIComponent(path)}`,
timeout_ms: stat.size > 5 * 1024 * 1024 ? 120_000 : 60_000,
signal,
});
if (res.status == 404) return { ok: false, reason: "missing", size: 0 };
if (!res.ok) throw new Error(`The computer refused to send ${path}: ${res.status}`);
const bytes = await res
.arrayBuffer()
.then((buffer) => Buffer.from(buffer))
.catch(() => null);
if (!bytes || bytes.byteLength != stat.size) {
return { ok: false, reason: "cut_short", size: bytes?.byteLength || 0 };
}
return { ok: true, bytes, size: stat.size };
}
@@ -0,0 +1,47 @@
import computerJson from "./computer-json";
import type { ComputerApi } from "./computer-fetch";
type Params = {
computer: ComputerApi;
command: string;
/**
* The command is stopped on the computer after this (whole seconds,
* rounded up), with its whole process group.
*/
timeout_ms: number;
signal?: AbortSignal;
};
export type ComputerCommandResult = {
output: string;
exit_code: number | null;
timed_out: boolean;
truncated: boolean;
};
/**
* Runs one bash command on a computer as its user (the agent's
* `/api/exec`): a fresh `bash -c` from its home, no input, stdout and
* stderr together. The agent stops it at the timeout, and when this call
* is aborted (a stopped run), so nothing is left blocking the computer.
* Throws when the computer can't be reached or refuses the command.
*/
export default async function runComputerCommand({ computer, command, timeout_ms, signal }: Params) {
const result = await computerJson<Partial<ComputerCommandResult>>({
computer,
path: "/api/exec",
body: { command, timeout_seconds: Math.max(1, Math.ceil(timeout_ms / 1000)) },
/**
* Room for the agent to stop it and answer.
*/
timeout_ms: timeout_ms + 15_000,
signal,
});
return {
output: String(result.output ?? ""),
exit_code: typeof result.exit_code == "number" ? result.exit_code : null,
timed_out: Boolean(result.timed_out),
truncated: Boolean(result.truncated),
} satisfies ComputerCommandResult;
}
@@ -0,0 +1,18 @@
import computerJson from "./computer-json";
import type { ComputerApi } from "./computer-fetch";
export type ComputerFileStat =
| { exists: false }
| { exists: true; type: "file" | "directory" | "other"; size: number; mtime_ms: number };
/**
* What's at an absolute path on a computer.
*/
export default function statComputerFile({ computer, path, signal }: { computer: ComputerApi; path: string; signal?: AbortSignal }) {
return computerJson<ComputerFileStat>({
computer,
path: `/api/files/stat?path=${encodeURIComponent(path)}`,
timeout_ms: 30_000,
signal,
});
}
@@ -0,0 +1,28 @@
import { AppData } from "@/src/data/app-data";
import composeComputerEnvFiles from "@/src/harness/tools/computer/compose-computer-env-files";
import type { ComputerApi } from "./computer-fetch";
import writeComputerFile from "./write-computer-file";
type Params = {
computer: ComputerApi;
envs: { key: string; value: string }[];
signal?: AbortSignal;
};
/**
* Writes the computer's env files (`~/.cobble/env` and `env.json`, owner
* only; the agent keeps `~/.cobble` private), replacing the last run's, so
* removed envs disappear too. Returns their paths, which the shell and
* script tools load.
*/
export default async function writeComputerEnv({ computer, envs, signal }: Params) {
const dir = `${AppData.ComputerHomeDir}/.cobble`;
const shell_path = `${dir}/env`;
const json_path = `${dir}/env.json`;
const files = composeComputerEnvFiles({ envs });
await writeComputerFile({ computer, path: shell_path, content: files.shell, mode: 0o600, signal });
await writeComputerFile({ computer, path: json_path, content: files.json, mode: 0o600, signal });
return { shell_path, json_path };
}
@@ -0,0 +1,33 @@
import computerJson from "./computer-json";
import type { ComputerApi } from "./computer-fetch";
type Params = {
computer: ComputerApi;
/**
* Absolute; missing folders are created.
*/
path: string;
content: string | Buffer;
/**
* Permission bits, e.g. `0o600`. Defaults to `0o644`.
*/
mode?: number;
signal?: AbortSignal;
};
/**
* Writes a whole file on a computer, owned by its user (the agent's
* `/api/files/write`, through a temporary file, so a reader never sees
* half of it).
*/
export default function writeComputerFile({ computer, path, content, mode, signal }: Params) {
const bytes = Buffer.isBuffer(content) ? content : Buffer.from(content, "utf8");
return computerJson<{ ok: boolean; size: number }>({
computer,
path: "/api/files/write",
body: { path, content: bytes.toString("base64"), encoding: "base64", ...(mode ? { mode } : {}) },
timeout_ms: 60_000,
signal,
});
}
@@ -1,39 +0,0 @@
import { AppData } from "@/src/data/app-data";
type Params = {
/**
* The sandbox's REST address (no `/mcp`).
*/
base_url: string;
path: string;
/**
* A JSON body makes it a POST.
*/
body?: Record<string, unknown>;
timeout_ms?: number;
};
/**
* One call to a computer's sandbox REST API (`/v1/...`). Returns its
* JSON; throws when the computer can't be reached or refuses.
*/
export default async function callComputerApi({
base_url,
path,
body,
timeout_ms = AppData.McpConnectTimeoutMs,
}: Params): Promise<any> {
const res = await fetch(`${base_url}${path}`, {
method: body ? "POST" : "GET",
headers: { "content-type": "application/json" },
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(timeout_ms),
});
const json: any = await res.json().catch(() => ({}));
if (!res.ok || json?.success === false) {
throw new Error(`The computer refused ${path}: ${json?.message || res.status}`);
}
return json;
}
@@ -1,6 +1,9 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import { AppData } from "@/src/data/app-data";
import { NotifyWatchScript, NotifyWatchVersion } from "@/src/data/notify-watch-script";
import { BotHookPath } from "@/src/dict/bot-hook-dict";
import runComputerCommand from "@/src/functions/backend/computers/run-computer-command";
import writeComputerFile from "@/src/functions/backend/computers/write-computer-file";
import grabComputerAppUrl from "@/src/functions/backend/docker/grab-computer-app-url";
import type { NotifyWatchSync } from "@/src/types";
import computerNotReadyMessage from "@/src/utils/computer-not-ready-message";
@@ -8,7 +11,6 @@ import { decrypt } from "@/src/utils/crypt";
import notifyWatchEnsureCommand from "@/src/utils/notify-watch-ensure-command";
import grabComputerMcpUrl from "../computers/grab-computer-mcp-url";
import isComputerBusy from "../computers/is-computer-busy";
import callComputerApi from "./call-computer-api";
type Params = {
computer_id: number | string;
@@ -47,15 +49,14 @@ export default async function syncComputerNotifyWatch({ computer_id }: Params):
return { ok: false, watching: false, hooks: hooks.length, error: computerNotReadyMessage(address) };
}
const base_url = address.base_url;
const context = await callComputerApi({ base_url, path: `/v1/sandbox` });
const dir = `${String(context.home_dir || "/home/gem").replace(/\/+$/, "")}/.cobble`;
const computer = address;
const dir = `${AppData.ComputerHomeDir}/.cobble`;
if (!hooks.length) {
await callComputerApi({
base_url,
path: `/v1/shell/exec`,
body: { command: `[ -f ${dir}/notify-hooks ] && : > ${dir}/notify-hooks; true` },
await runComputerCommand({
computer,
command: `[ -f ${dir}/notify-hooks ] && : > ${dir}/notify-hooks; true`,
timeout_ms: AppData.McpConnectTimeoutMs,
});
return { ok: true, watching: false, hooks: 0 };
@@ -78,34 +79,18 @@ export default async function syncComputerNotifyWatch({ computer_id }: Params):
.map(async (hook) => `${app_url}${BotHookPath}/${await decrypt(hook.watch_token!)}`),
);
await callComputerApi({
base_url,
path: `/v1/shell/exec`,
body: { command: `mkdir -p ${dir} && chmod 700 ${dir} && touch ${dir}/notify-hooks && chmod 600 ${dir}/notify-hooks` },
});
await callComputerApi({
base_url,
path: `/v1/file/write`,
body: { file: `${dir}/notify-watch.py`, content: NotifyWatchScript },
});
await callComputerApi({
base_url,
path: `/v1/file/write`,
body: { file: `${dir}/notify-hooks`, content: `${urls.join("\n")}\n` },
});
await writeComputerFile({ computer, path: `${dir}/notify-watch.py`, content: NotifyWatchScript, mode: 0o600 });
await writeComputerFile({ computer, path: `${dir}/notify-hooks`, content: `${urls.join("\n")}\n`, mode: 0o600 });
const busy = await isComputerBusy({ computer_id });
const res = await callComputerApi({
base_url,
path: `/v1/shell/exec`,
body: { command: notifyWatchEnsureCommand({ version: NotifyWatchVersion, restart_browser: !busy }) },
const res = await runComputerCommand({
computer,
command: notifyWatchEnsureCommand({ version: NotifyWatchVersion, restart_browser: !busy }),
timeout_ms: 30_000,
});
const output = String(res?.data?.output ?? "").trim();
const output = res.output.trim();
const result = JSON.parse(output.split("\n").filter(Boolean).pop() || "{}");
return {
@@ -6,6 +6,7 @@ import grabBots from "../bots/grab-bots";
import grabBotExtensionsOverview from "../extensions/grab-bot-extensions-overview";
import grabConversationFiles from "../bot-files/grab-conversation-files";
import grabBotComputers from "../computers/grab-bot-computers";
import userHasBrowsers from "../browsers/user-has-browsers";
import resolveHarnessCandidates from "@/src/harness/resolve/resolve-harness-candidates";
import grabUserWorkspaces from "../workspaces/grab-user-workspaces";
import grabUserConversation from "./grab-user-conversation";
@@ -24,8 +25,9 @@ type Params = {
* `/admin/workspaces/<id>/bots/<id>`): the rail's crew (the workspace's
* in a workspace) and workspaces, the bot, the text model it runs on, its
* computers, tools, MCP servers and files there, and whether its mic and
* read-aloud have a model to run on. The history (its session, messages
* and active task) is left to the client (`grabConversationHistory`,
* read-aloud have a model to run on, and whether the user has a browser
* of their own (the composer's Browser button). The history (its session,
* messages and active task) is left to the client (`grabConversationHistory`,
* `api/admin/bots/conversation-history`), so a page the back button
* restores never shows an old thread. The full model settings are left to
* the models modal: the install-wide catalog (`api/admin/harness/catalog`)
@@ -59,13 +61,14 @@ export default async function grabConversationProps({
/** Loading its history marks the open session read. */
bot.unread = 0;
const [bot_text_model, bot_computers, bot_extensions, bot_files, transcription, speech] = await Promise.all([
const [bot_text_model, bot_computers, bot_extensions, bot_files, transcription, speech, has_browsers] = await Promise.all([
grabTextModel({ bot_id: bot.id, workspace_id: scope }),
grabBotComputers({ bot_id: bot.id, workspace_id: scope }),
grabBotExtensionsOverview({ user_id, bot_id: bot.id, workspace_id: scope }),
grabConversationFiles({ bot_id: bot.id, workspace_id: scope }),
hasHarnessModel({ harness: "transcription", bot_id: bot.id, workspace_id: scope }),
hasHarnessModel({ harness: "speech", bot_id: bot.id, workspace_id: scope }),
userHasBrowsers({ user_id }).catch(() => false),
]);
return {
@@ -78,6 +81,7 @@ export default async function grabConversationProps({
bot_extensions,
bot_files,
bot_voice: { transcription, speech },
has_browsers,
};
}
@@ -0,0 +1,18 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
user_id: number | string;
};
/**
* Whether the user has added any browser of their own, so the composer
* shows its Browser button only when there is one to pick.
*/
export default async function userHasBrowsers({ user_id }: Params) {
const res = await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM browsers WHERE user_id = ? LIMIT 1`,
values: [Number(user_id)],
});
return Boolean(res.payload?.length);
}
@@ -5,6 +5,7 @@ import type {
} from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import { ComputerMcpPath, type ContainerStatus } from "@/src/dict/computer-dict";
import computerToken from "@/src/utils/computer-token";
import grabEnv from "../envs/grab-env";
import pickReachableAddress from "./pick-reachable-address";
import refreshComputerContainer from "./refresh-computer-container";
@@ -17,7 +18,7 @@ type ComputerRow = Pick<BUN_SQLITE_COBBLE_COMPUTERS, "name" | "kind"> &
Pick<BUN_SQLITE_COBBLE_CONTAINERS, "id" | "docker_id" | "status" | "hostname" | "ip_address" | "port">;
export type ComputerAddress =
| { ready: true; url: string; base_url: string; name: string }
| { ready: true; url: string; base_url: string; token: string; name: string }
| { ready: false; status: ContainerStatus; name: string };
/**
@@ -26,7 +27,8 @@ export type ComputerAddress =
* e.g. `http://localhost:8170`), else its docker hostname and port, or
* its IP address on the network when the hostname can't be reached (a
* dev server outside docker, `pickReachableAddress`). `base_url` is the
* same address without `/mcp`, for the sandbox's REST API. Only a
* same address without `/mcp`, for the agent's API, and `token` what the
* agent asks of every request (`computerToken`). Only a
* computer whose health check passed (`running`) is reached; any other
* state is read again from docker first, since it may have come back
* since the last sync, and returned as `ready: false`. Null when the
@@ -52,7 +54,7 @@ export default async function grabComputerMcpUrl({ computer_id }: Params): Promi
if (main_override) {
const base_url = main_override.replace(/\/+$/, "");
return { ready: true, url: `${base_url}${ComputerMcpPath}`, base_url, name };
return { ready: true, url: `${base_url}${ComputerMcpPath}`, base_url, token: computerToken({ computer_id }), name };
}
let status = (row.status || "unknown") as ContainerStatus;
@@ -76,5 +78,5 @@ export default async function grabComputerMcpUrl({ computer_id }: Params): Promi
],
});
return { ready: true, url: `${base_url}${ComputerMcpPath}`, base_url, name };
return { ready: true, url: `${base_url}${ComputerMcpPath}`, base_url, token: computerToken({ computer_id }), name };
}
@@ -14,8 +14,9 @@ type Params = {
/**
* Recreates a computer whose container was set up with an older layout
* (its whole home mounted, or its browser profile left in the container),
* so it mounts only its workspace and keeps its browser profile.
* (`AppData.ComputerWorkspaceLayout`: an older image, its whole home
* mounted, or its browser profile left in the container), so it runs the
* current image with only its workspace and browser profile mounted.
* `provisionComputer` moves an old home aside (`prepareComputerDataDir`)
* and records the layout, so this runs once per computer. Waits for a
* later sync while a job works on it. Returns whether it did.
@@ -29,9 +30,9 @@ export default async function migrateComputerLayout({ computer_id, metadata }: P
await provisionComputer({ computer_id });
await logEvent({
title: `Computer #${computer_id} now keeps its browser profile`,
title: `Computer #${computer_id} moved to the current computer image`,
category: "system",
plain_text: `Recreated computer #${computer_id} so only ${AppData.ComputerWorkspaceDir} and its browser profile (${AppData.ComputerBrowserProfileDir}) are kept; an old home, if any, was moved aside and kept on disk.`,
plain_text: `Recreated computer #${computer_id} on the current image (layout ${AppData.ComputerWorkspaceLayout}); ${AppData.ComputerWorkspaceDir} and its browser profile (${AppData.ComputerBrowserProfileDir}) were kept, and an old home, if any, was moved aside and kept on disk.`,
metadata: { computer_id },
});
@@ -6,6 +6,8 @@ import createComputerContainer from "@/src/functions/backend/docker/create-compu
import { logError } from "@/src/functions/backend/logger";
import prepareComputerBrowserDir from "./prepare-computer-browser-dir";
import prepareComputerDataDir from "./prepare-computer-data-dir";
import computerBrowserEnv from "@/src/utils/computer-browser-env";
import parseComputerBrowserSettings from "@/src/utils/parse-computer-browser-settings";
import pushComputerUpdate from "./push-computer-update";
import syncComputerBrowserPolicy from "./sync-computer-browser-policy";
@@ -15,25 +17,31 @@ type Params = {
* A brand new computer: start from an empty workspace.
*/
fresh?: boolean;
/**
* Pull the image again first (a rebuild), for a newer build under the
* same tag.
*/
pull?: boolean;
};
/**
* Sets up a computer's container: prepares its workspace and browser profile directories, pulls the
* sandbox image and starts the container with the computer's resources
* (`cpus`, `memory_mb`, else the `AppData` defaults), then records it (`containers`:
* computer image and starts the container with the computer's resources
* (`cpus`, `memory_mb`, else the `AppData` defaults) and its browser
* settings (`browser_settings`, `computerBrowserEnv`), then records it (`containers`:
* docker id, state, and its IP address on the network). A failure is
* recorded as `failed` with its reason, which the computer lists show. The
* owner's tabs hear about it either way. Its browser gets its policy
* (`syncComputerBrowserPolicy`). The metadata's `layout` says the
* container mounts only the workspace and the browser profile (`syncComputers` recreates one that
* doesn't). Never throws.
* container runs the current image and mounts (`syncComputers` recreates
* one that doesn't). Never throws.
*/
export default async function provisionComputer({ computer_id, fresh }: Params) {
export default async function provisionComputer({ computer_id, fresh, pull }: Params) {
const row = (
await BunSQLite.sql<
BUN_SQLITE_COBBLE_CONTAINERS & Pick<BUN_SQLITE_COBBLE_COMPUTERS, "cpus" | "memory_mb">
BUN_SQLITE_COBBLE_CONTAINERS & Pick<BUN_SQLITE_COBBLE_COMPUTERS, "cpus" | "memory_mb" | "browser_settings">
>({
sql: `SELECT co.*, c.cpus, c.memory_mb FROM containers co JOIN computers c ON c.container_id = co.id WHERE c.id = ? LIMIT 1`,
sql: `SELECT co.*, c.cpus, c.memory_mb, c.browser_settings FROM containers co JOIN computers c ON c.container_id = co.id WHERE c.id = ? LIMIT 1`,
values: [computer_id],
})
).payload?.[0];
@@ -57,6 +65,11 @@ export default async function provisionComputer({ computer_id, fresh }: Params)
browser_dir,
cpus: Number(row.cpus) || AppData.ComputerDefaultCpus,
memory_mb: Number(row.memory_mb) || AppData.ComputerDefaultMemoryMb,
browser_env: computerBrowserEnv({
settings: parseComputerBrowserSettings({ text: row.browser_settings }),
fallback_timezone: process.env.TZ,
}),
pull,
});
const { error: _error, mcp_url: _mcp_url, ...kept } = metadata;
@@ -66,7 +79,7 @@ export default async function provisionComputer({ computer_id, fresh }: Params)
port = ?, status = ?, metadata = ?, last_seen_at = ?, updated_at = ? WHERE id = ?`,
values: [
created.docker_id,
AppData.ComputerImage,
created.image,
created.network,
row.name,
created.ip_address,
@@ -3,7 +3,9 @@ import type {
BUN_SQLITE_COBBLE_COMPUTERS,
BunSQLiteTables,
} from "@/db/types/db";
import type { ComputerBrowserSettings } from "@/src/schemas/computer-schema";
import AppError from "@/src/utils/app-error";
import parseComputerBrowserSettings from "@/src/utils/parse-computer-browser-settings";
import _ from "lodash";
import grabEnv from "../envs/grab-env";
import grabUserComputers from "./grab-user-computers";
@@ -16,12 +18,18 @@ type Params = {
/**
* Only the fields given are changed.
*/
data: Pick<BUN_SQLITE_COBBLE_COMPUTERS, "name" | "description" | "cpus" | "memory_mb">;
data: Pick<BUN_SQLITE_COBBLE_COMPUTERS, "name" | "description" | "cpus" | "memory_mb"> & {
/**
* The whole of its browser's settings (already checked by
* `ComputerBrowserSettingsSchema`), replacing what's stored.
*/
browser_settings?: ComputerBrowserSettings;
};
};
/**
* Updates one of the user's computers. When its container's settings
* change (`cpus`, `memory_mb`), the container is stopped, removed and
* change (`cpus`, `memory_mb`, `browser_settings`), the container is stopped, removed and
* run again with them in the background (`provisionComputer`); its home
* directory is bind-mounted, so its files stay. A name or description
* alone leaves the container running. The main computer of a server that
@@ -34,9 +42,13 @@ export default async function updateComputer({ user_id, computer_id, data }: Par
throw new AppError(`Computer not found.`);
}
const browser_settings = data.browser_settings ? JSON.stringify(data.browser_settings) : undefined;
const stored_browser_settings = JSON.stringify(parseComputerBrowserSettings({ text: computer.browser_settings }));
const recreate =
(data.cpus !== undefined && Number(data.cpus) != Number(computer.cpus)) ||
(data.memory_mb !== undefined && Number(data.memory_mb) != Number(computer.memory_mb));
(data.memory_mb !== undefined && Number(data.memory_mb) != Number(computer.memory_mb)) ||
(browser_settings !== undefined && browser_settings != stored_browser_settings);
if (recreate && (await grabUserComputers({ computer_id: computer.id }))[0]?.status == "creating") {
throw new AppError(`${computer.name || "The computer"} is still being set up. Try again once it's ready.`);
@@ -58,6 +70,7 @@ export default async function updateComputer({ user_id, computer_id, data }: Par
description: data.description,
cpus: data.cpus,
memory_mb: data.memory_mb,
browser_settings,
},
_.isUndefined,
),
@@ -1,6 +1,8 @@
import { AppData } from "@/src/data/app-data";
import computerToken from "@/src/utils/computer-token";
import dockerRequest from "./docker-request";
import ensureDockerNetwork from "./ensure-docker-network";
import grabComputerImage from "./grab-computer-image";
import pullDockerImage from "./pull-docker-image";
import removeDockerContainer from "./remove-docker-container";
@@ -34,20 +36,32 @@ type Params = {
* The container's memory limit in MB.
*/
memory_mb: number;
/**
* Its browser's settings as env (`computerBrowserEnv`).
*/
browser_env?: string[];
/**
* Pull the image again even when docker has it (a rebuild), keeping
* the local one when the registry can't be reached.
*/
pull?: boolean;
};
/**
* Creates and starts (the API's `docker run`) an AIO sandbox container
* for a computer (`AppData.ComputerImage`), attached to the computers'
* network (created first when missing), with its home directory
* bind-mounted from `data_dir` (only its workspace, `AppData.ComputerWorkspaceDir`: the rest of its home lives and dies with the container), its browser profile from
* `browser_dir` (at `AppData.ComputerBrowserProfileDir`, which Chrome is
* pointed at, so logins outlive restarts and recreates; the basic password
* store keeps the cookies' key the same in every container), limited to `cpus` and `memory_mb`, with a
* health check (`AppData.ComputerHealthcheck`), and restarted with
* docker. A container left by an earlier try is stopped and replaced.
* Resolves once the health check passes, with its IP address on the network, which a dev
* server outside docker reaches it at, since it can't resolve the
* Creates and starts (the API's `docker run`) a computer's container
* (`grabComputerImage`, built from `computer/`), attached to the
* computers' network (created first when missing), with its workspace
* bind-mounted from `data_dir` (at `AppData.ComputerWorkspaceDir`: the
* rest of its home lives and dies with the container) and its browser
* profile from `browser_dir` (at `AppData.ComputerBrowserProfileDir`, so
* logins outlive restarts and recreates), limited to `cpus` and
* `memory_mb`, with a health check (`AppData.ComputerHealthcheck`), and
* restarted with docker. Its agent asks every request for the computer's
* token (`computerToken`), and the browser gets its settings
* (`browser_env`: timezone, languages, screen, flags). A
* container left by an earlier try is stopped and replaced. Resolves once
* the health check passes, with its IP address on the network, which a
* dev server outside docker reaches it at, since it can't resolve the
* hostname.
*/
export default async function createComputerContainer({
@@ -57,12 +71,16 @@ export default async function createComputerContainer({
browser_dir,
cpus,
memory_mb,
browser_env = [],
pull,
}: Params) {
const network = await ensureDockerNetwork();
const host_dir = await resolveHostPath({ local_path: data_dir });
const browser_host_dir = await resolveHostPath({ local_path: browser_dir });
await pullDockerImage({ image: AppData.ComputerImage });
const image = await grabComputerImage();
await pullDockerImage({ image, force: pull });
await removeDockerContainer({ container: name });
const created = await dockerRequest<{ Id: string }>({
@@ -70,20 +88,19 @@ export default async function createComputerContainer({
path: `/containers/create`,
query: { name },
body: {
Image: AppData.ComputerImage,
Image: image,
Hostname: name,
Labels: {
[`${AppData.DockerNetworkName}.computer_id`]: String(computer_id),
},
Env: [
`BROWSER_EXTRA_ARGS=--user-data-dir=${AppData.ComputerBrowserProfileDir} --password-store=basic`,
`COBBLE_COMPUTER_TOKEN=${computerToken({ computer_id })}`,
`COBBLE_BROWSER_PROFILE_DIR=${AppData.ComputerBrowserProfileDir}`,
...browser_env,
],
ExposedPorts: { [`${AppData.ComputerPort}/tcp`]: {} },
Healthcheck: {
Test: [
"CMD-SHELL",
`curl -fs -o /dev/null http://localhost:${AppData.ComputerPort}/v1/sandbox && ([ "$DISABLE_BROWSER" = "true" ] || nc -z localhost "$BROWSER_REMOTE_DEBUGGING_PORT") || exit 1`,
],
Test: ["CMD-SHELL", `curl -fsS -o /dev/null http://127.0.0.1:${AppData.ComputerPort}/health || exit 1`],
Interval: seconds(AppData.ComputerHealthcheck.IntervalSeconds),
Timeout: seconds(AppData.ComputerHealthcheck.TimeoutSeconds),
StartPeriod: seconds(AppData.ComputerHealthcheck.StartPeriodSeconds),
@@ -96,6 +113,10 @@ export default async function createComputerContainer({
],
NetworkMode: network,
RestartPolicy: { Name: "unless-stopped" },
/**
* Chrome's own sandbox needs user namespaces, which
* docker's default seccomp profile blocks.
*/
SecurityOpt: ["seccomp=unconfined"],
ShmSize: AppData.ComputerShmBytes,
Memory: memory_mb * 1024 * 1024,
@@ -124,6 +145,7 @@ export default async function createComputerContainer({
return {
docker_id: created.data.Id,
image,
network,
status: state.status,
host_dir,
@@ -0,0 +1,10 @@
import { AppData } from "@/src/data/app-data";
import grabEnv from "../db/envs/grab-env";
/**
* The image computers are created with: the `COMPUTER_IMAGE` app setting
* (a registry mirror, a local build), else `AppData.ComputerImage`.
*/
export default async function grabComputerImage() {
return (await grabEnv({ key: "COMPUTER_IMAGE" }))?.trim() || AppData.ComputerImage;
}
@@ -2,19 +2,24 @@ import dockerRequest from "./docker-request";
type Params = {
/**
* e.g. `ghcr.io/agent-infra/sandbox:latest`.
* e.g. `ghcr.io/moduletrace/cobble-computer:1.0.0`.
*/
image: string;
/**
* Pull even when docker has it, for a newer build under the same tag;
* the image docker has is kept when the pull fails.
*/
force?: boolean;
};
/**
* Pulls an image unless docker already has it. Waits for the whole pull,
* which can take minutes for a large image.
* Pulls an image unless docker already has it (or `force`). Waits for the
* whole pull, which can take minutes for a large image.
*/
export default async function pullDockerImage({ image }: Params) {
export default async function pullDockerImage({ image, force }: Params) {
const present = await dockerRequest({ path: `/images/${encodeURIComponent(image)}/json` });
if (present.ok) return;
if (present.ok && !force) return;
const slash = image.lastIndexOf("/");
const colon = image.lastIndexOf(":");
@@ -45,7 +50,7 @@ export default async function pullDockerImage({ image }: Params) {
})
.find((line) => line?.error);
if (!res.ok || failed) {
if ((!res.ok || failed) && !present.ok) {
throw new Error(`Couldn't pull ${image}: ${failed?.error || res.message}`);
}
}

Some files were not shown because too many files have changed in this diff Show More