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]>
This commit is contained in:
@@ -16,3 +16,5 @@ coverage
|
||||
logs
|
||||
*.log
|
||||
assets
|
||||
# The computer image builds on its own (computer/Dockerfile).
|
||||
computer
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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. 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.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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=="],
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
**/*.test.ts
|
||||
**/node_modules
|
||||
@@ -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"]
|
||||
@@ -0,0 +1,114 @@
|
||||
# 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.
|
||||
- **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_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.0.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
|
||||
```
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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",
|
||||
];
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
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);
|
||||
upstream.on("close", () => {
|
||||
if (!closed) close();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
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",
|
||||
/**
|
||||
* 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,
|
||||
];
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { BrowserBlockedArgs, McpBlockedArgs } from "./blocked-args";
|
||||
import safeExtraArgs from "./safe-extra-args";
|
||||
import browserScale from "./browser-scale";
|
||||
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 }),
|
||||
/**
|
||||
* 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,
|
||||
};
|
||||
@@ -0,0 +1,129 @@
|
||||
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 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.
|
||||
*/
|
||||
export default function createAgentServer() {
|
||||
const server = createServer((req, res) => {
|
||||
route({ req, res }).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") {
|
||||
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 }: { req: IncomingMessage; res: ServerResponse }) {
|
||||
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/")) {
|
||||
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" } });
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* One whole, unmasked server frame (RFC 6455) around a payload.
|
||||
*/
|
||||
export default function encodeWebsocketFrame({ opcode, payload }: { opcode: number; payload: Buffer }) {
|
||||
const length = payload.length;
|
||||
let header: Buffer;
|
||||
|
||||
if (length < 126) {
|
||||
header = Buffer.from([0x80 | opcode, length]);
|
||||
} else if (length < 65536) {
|
||||
header = Buffer.alloc(4);
|
||||
header[0] = 0x80 | opcode;
|
||||
header[1] = 126;
|
||||
header.writeUInt16BE(length, 2);
|
||||
} else {
|
||||
header = Buffer.alloc(10);
|
||||
header[0] = 0x80 | opcode;
|
||||
header[1] = 127;
|
||||
header.writeBigUInt64BE(BigInt(length), 2);
|
||||
}
|
||||
|
||||
return Buffer.concat([header, payload]);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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`);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { AgentConfig } from "./config";
|
||||
import createAgentServer from "./create-agent-server";
|
||||
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);
|
||||
|
||||
createAgentServer().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();
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
log({ name: "agent", message: `couldn't start: ${error?.stack || error}` });
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
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;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads a browser's 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 an unmasked or oversized
|
||||
* frame (a browser always masks).
|
||||
*/
|
||||
export default function readWebsocketFrames({ onFrame, max_payload }: 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]!;
|
||||
let length = second & 0x7f;
|
||||
let offset = 2;
|
||||
|
||||
if (!(second & 0x80)) throw new Error("A client frame came unmasked.");
|
||||
|
||||
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.");
|
||||
if (buffer.length < offset + 4 + length) return;
|
||||
|
||||
const mask = buffer.subarray(offset, offset + 4);
|
||||
const payload = Buffer.from(buffer.subarray(offset + 4, offset + 4 + length));
|
||||
|
||||
for (let index = 0; index < payload.length; index++) payload[index]! ^= mask[index & 3]!;
|
||||
|
||||
buffer = buffer.subarray(offset + 4 + length);
|
||||
onFrame({ fin: Boolean(first & 0x80), opcode: first & 0x0f, payload });
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
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 { 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. Returns them in the order they stop.
|
||||
*/
|
||||
export default async function startServices(): 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 }) => 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 },
|
||||
);
|
||||
}
|
||||
@@ -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 {}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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=");
|
||||
});
|
||||
@@ -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");
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
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 }) {
|
||||
const server = encodeWebsocketFrame({ opcode, payload });
|
||||
const header_length = server.length - payload.length;
|
||||
const mask = Buffer.from([1, 2, 3, 4]);
|
||||
const masked = Buffer.from(payload.map((byte, index) => byte ^ mask[index & 3]!));
|
||||
const header = Buffer.from(server.subarray(0, header_length));
|
||||
|
||||
header[1]! |= 0x80;
|
||||
|
||||
return Buffer.concat([header, mask, masked]);
|
||||
}
|
||||
|
||||
function collect() {
|
||||
const frames: WebsocketFrame[] = [];
|
||||
const feed = readWebsocketFrames({ onFrame: (frame) => frames.push(frame), max_payload: 1 << 20 });
|
||||
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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: [
|
||||
{
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
+3
-2
@@ -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",
|
||||
|
||||
@@ -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"],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
+55
-22
@@ -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.0.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
|
||||
|
||||
@@ -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;
|
||||
];
|
||||
|
||||
@@ -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 },
|
||||
};
|
||||
|
||||
@@ -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).${
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ type Socket = ServerWebSocket<WebSocketSession>;
|
||||
|
||||
/**
|
||||
* Bridges a user's websocket on `/computers/<id>/...` to the same path on
|
||||
* the computer (a terminal shell, the browser's CDP, the code editor).
|
||||
* the computer (the screen's VNC line, the shell's terminal).
|
||||
* Messages sent before the computer's side opens are held, and either
|
||||
* side closing closes the other.
|
||||
*/
|
||||
|
||||
@@ -2,7 +2,9 @@ import grabComputerMcpUrl from "@/src/functions/backend/db/computers/grab-comput
|
||||
import grabUserComputer from "@/src/functions/backend/db/computers/grab-user-computer";
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import computerNotReadyMessage from "@/src/utils/computer-not-ready-message";
|
||||
import computerProxyPathAllowed from "@/src/utils/computer-proxy-path-allowed";
|
||||
import parseComputerProxyPath from "@/src/utils/parse-computer-proxy-path";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
|
||||
type Params = {
|
||||
req: Request;
|
||||
@@ -10,9 +12,11 @@ type Params = {
|
||||
|
||||
/**
|
||||
* Where a `/computers/<id>/...` request goes: the computer's own address
|
||||
* for that path, only for the computer's owner. An error response when
|
||||
* the user isn't logged in, the computer isn't theirs, it has no
|
||||
* container, or it isn't ready.
|
||||
* for that path, only for a user who reaches the computer and only for a
|
||||
* view they may open (`computerProxyPathAllowed`: the live view, and the
|
||||
* shell for crew managers; never the agent's API or Playwright MCP). An
|
||||
* error response when the user isn't logged in, the computer or path
|
||||
* isn't theirs, it has no container, or it isn't ready.
|
||||
*/
|
||||
export default async function computerProxyTarget({ req }: Params) {
|
||||
const url = new URL(req.url);
|
||||
@@ -24,6 +28,10 @@ export default async function computerProxyTarget({ req }: Params) {
|
||||
|
||||
if (!session.user?.id) return { error: new Response("Unauthorized", { status: 401 }) };
|
||||
|
||||
if (!computerProxyPathAllowed({ rest: parsed.rest, can_manage_crew: canManageCrew({ user_types: session.user_types || [] }) })) {
|
||||
return { error: new Response("Not Found", { status: 404 }) };
|
||||
}
|
||||
|
||||
const computer = await grabUserComputer({
|
||||
computer_id: parsed.computer_id,
|
||||
user_id: session.user.id,
|
||||
@@ -46,6 +54,7 @@ export default async function computerProxyTarget({ req }: Params) {
|
||||
url,
|
||||
prefix: parsed.prefix,
|
||||
base_url: address.base_url,
|
||||
token: address.token,
|
||||
target: `${address.base_url}/${parsed.rest}${url.search}`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -11,9 +11,10 @@ type Params = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Serves a computer's own apps (browser, terminal, code) to its owner
|
||||
* Serves a computer's own pages (its screen and shell) to its owner
|
||||
* under `/computers/<id>/`, so the chat can show them in a frame without
|
||||
* the sandbox being reachable from the user's browser. Plain requests are
|
||||
* the computer being reachable from the user's browser. Requests carry
|
||||
* the computer's token, which never reaches the user. Plain requests are
|
||||
* fetched and streamed back; websockets are bridged
|
||||
* (`computerProxySocket`).
|
||||
*/
|
||||
@@ -22,9 +23,11 @@ export default async function handleComputerProxy({ req, server }: Params) {
|
||||
|
||||
if (resolved.error) return resolved.error;
|
||||
|
||||
const { session, url, prefix, base_url, target } = resolved;
|
||||
const { session, url, prefix, base_url, token, target } = resolved;
|
||||
const headers = computerProxyRequestHeaders({ headers: req.headers, url, prefix });
|
||||
|
||||
headers.set("authorization", `Bearer ${token}`);
|
||||
|
||||
if (req.headers.get("upgrade")?.toLowerCase() == "websocket") {
|
||||
if (!isSameOriginUpgrade({ req })) return new Response("Forbidden", { status: 403 });
|
||||
|
||||
|
||||
@@ -6,11 +6,11 @@ const big = "x".repeat(30000);
|
||||
|
||||
const run = (): HarnessMessage[] => [
|
||||
{ role: "user", content: "Do the thing." },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "sandbox_execute_bash", arguments: "{}" }] },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "1", content: big },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "sandbox_execute_bash", arguments: "{}" }] },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "2", content: big },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "sandbox_execute_bash", arguments: "{}" }] },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "3", content: "recent" },
|
||||
];
|
||||
|
||||
|
||||
@@ -23,15 +23,18 @@ type Params = {
|
||||
|
||||
type Args = {
|
||||
computer_id?: number;
|
||||
mode: ComputerViewMode;
|
||||
mode?: ComputerViewMode;
|
||||
};
|
||||
|
||||
const Modes = ComputerViewModes.map((m) => m.value) as [ComputerViewMode, ...ComputerViewMode[]];
|
||||
/**
|
||||
* The views the user is sure to be able to open (not the crew-only shell).
|
||||
*/
|
||||
const Modes = ComputerViewModes.filter((m) => !m.crew_only).map((m) => m.value) as [ComputerViewMode, ...ComputerViewMode[]];
|
||||
|
||||
/**
|
||||
* Lets a bot ask the user to take over one of its computers, for what
|
||||
* only they can do there (a login, a captcha, a code). Their message
|
||||
* gets a button that opens the computer in that mode, and the bot shows
|
||||
* gets a button that opens the computer (its browser's live view), and the bot shows
|
||||
* needs-you until they hand it back in chat.
|
||||
*/
|
||||
export default function askToTakeOverTool({ computers, in_task, onAsk }: Params): HarnessTool<Args> {
|
||||
@@ -41,10 +44,10 @@ export default function askToTakeOverTool({ computers, in_task, onAsk }: Params)
|
||||
|
||||
return {
|
||||
name: "ask_user_to_take_over",
|
||||
description: `Ask the user to take over one of your computers when only they can do something on it: log in, solve a captcha, enter a code, approve a prompt, or show you something. They get a button that opens it in the mode you pick: browser (the web browser), terminal (a shell), code (the code editor) or desktop (the whole screen, with the browser's toolbar and extensions). When a site refuses to sign in on the computer (Google often does: "This browser or app may not be secure"), pick desktop and point the user to the guide at ${HelpPath}#${HelpSignInTopicId}: they bring their session over with the Cookie-Editor extension. Computers: ${listed}. Defaults to ${computers[0]?.id}.`,
|
||||
description: `Ask the user to take over one of your computers when only they can do something on it: log in, solve a captcha, enter a code, approve a prompt, or show you something. They get a button that opens the computer's browser live, the tab you're on in front, where they can click, type and paste. Leave the page they need open. When a site still refuses to sign in on the computer, point the user to the guide at ${HelpPath}#${HelpSignInTopicId}: they bring their session over from their own browser with the view's Import cookies. Computers: ${listed}. Defaults to ${computers[0]?.id}.`,
|
||||
schema: z.object({
|
||||
computer_id: z.number().int().optional(),
|
||||
mode: z.enum(Modes),
|
||||
mode: z.enum(Modes).optional(),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const computer =
|
||||
@@ -54,7 +57,7 @@ export default function askToTakeOverTool({ computers, in_task, onAsk }: Params)
|
||||
throw new Error(`You have no computer with id ${args.computer_id}. Computers: ${listed}.`);
|
||||
}
|
||||
|
||||
const ref = takeOverRef({ id: computer.id, mode: args.mode });
|
||||
const ref = takeOverRef({ id: computer.id, mode: args.mode || Modes[0] });
|
||||
|
||||
onAsk({ ref });
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import capToolOutput from "./cap-tool-output";
|
||||
|
||||
describe("capToolOutput", () => {
|
||||
test("leaves short text alone", () => {
|
||||
expect(capToolOutput({ text: "abc", max_chars: 10 })).toBe("abc");
|
||||
});
|
||||
|
||||
test("keeps the start and the end of long text", () => {
|
||||
const out = capToolOutput({ text: `${"a".repeat(50)}${"b".repeat(50)}`, max_chars: 20 });
|
||||
|
||||
expect(out.startsWith("a".repeat(8))).toBe(true);
|
||||
expect(out.endsWith("b".repeat(12))).toBe(true);
|
||||
expect(out).toContain("80 characters left out");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
type Params = {
|
||||
text: string;
|
||||
max_chars: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Text kept to `max_chars`: its start and its end, which is where a
|
||||
* command's answer and its error usually are, with what was left out
|
||||
* said in between.
|
||||
*/
|
||||
export default function capToolOutput({ text, max_chars }: Params) {
|
||||
if (text.length <= max_chars) return text;
|
||||
|
||||
const head = Math.floor(max_chars * 0.4);
|
||||
const tail = max_chars - head;
|
||||
|
||||
return `${text.slice(0, head)}\n\n[... ${text.length - max_chars} characters left out ...]\n\n${text.slice(-tail)}`;
|
||||
}
|
||||
@@ -1,18 +1,16 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { ComputerApi } from "@/src/functions/backend/computers/computer-fetch";
|
||||
import downloadComputerFile from "@/src/functions/backend/computers/download-computer-file";
|
||||
import runComputerCommand from "@/src/functions/backend/computers/run-computer-command";
|
||||
import saveUserSecret from "@/src/functions/backend/db/envs/save-user-secret";
|
||||
import { resolveComputerPath, type ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import secretRef from "@/src/utils/secret-ref";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import computerDirsShell from "./computer-dirs-shell";
|
||||
import downloadComputerFile from "./download-computer-file";
|
||||
import runComputerCommand from "./run-computer-command";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The sandbox's REST address (no `/mcp`).
|
||||
*/
|
||||
base_url: string;
|
||||
computer: ComputerApi;
|
||||
/**
|
||||
* The computer's env file, sourced before a command.
|
||||
*/
|
||||
@@ -41,13 +39,13 @@ type Args = {
|
||||
/**
|
||||
* Saves a secret that's on the computer (a generated password, a token a
|
||||
* CLI printed, a key file) as the user's personal secret for this bot,
|
||||
* without the bot ever reading it: the file comes over the sandbox's
|
||||
* download endpoint, a command's output over its REST shell, and neither
|
||||
* without the bot ever reading it: the file comes over the computer's
|
||||
* download endpoint, a command's output over its shell API, and neither
|
||||
* is returned. The bot gets a `[secret:ID]` ref to show the user, and the
|
||||
* value is redacted from everything it reads afterwards.
|
||||
*/
|
||||
export default function captureSecretTool({
|
||||
base_url,
|
||||
computer,
|
||||
shell_path,
|
||||
dirs,
|
||||
user_id,
|
||||
@@ -65,7 +63,7 @@ export default function captureSecretTool({
|
||||
command: z.string().trim().min(1).max(4000).optional().describe("For from command"),
|
||||
}),
|
||||
run: async ({ args, signal }) => {
|
||||
const value = await readValue({ args, base_url, shell_path, dirs, signal });
|
||||
const value = await readValue({ args, computer, shell_path, dirs, signal });
|
||||
|
||||
if (value.text === undefined) return value.error;
|
||||
|
||||
@@ -87,13 +85,13 @@ export default function captureSecretTool({
|
||||
|
||||
async function readValue({
|
||||
args,
|
||||
base_url,
|
||||
computer,
|
||||
shell_path,
|
||||
dirs,
|
||||
signal,
|
||||
}: {
|
||||
args: Args;
|
||||
base_url: string;
|
||||
computer: ComputerApi;
|
||||
shell_path: string;
|
||||
dirs: ComputerRunDirs;
|
||||
signal?: AbortSignal;
|
||||
@@ -104,7 +102,7 @@ async function readValue({
|
||||
if (!args.path) return { error: `Give the file's path.` };
|
||||
|
||||
const download = await downloadComputerFile({
|
||||
base_url,
|
||||
computer,
|
||||
path: resolveComputerPath({ path: args.path, dirs }),
|
||||
max_bytes: AppData.CapturedSecretMaxChars * 4,
|
||||
signal,
|
||||
@@ -126,7 +124,7 @@ async function readValue({
|
||||
if (!args.command) return { error: `Give the command.` };
|
||||
|
||||
const result = await runComputerCommand({
|
||||
base_url,
|
||||
computer,
|
||||
command: `(${computerDirsShell({ dirs })}[ -f ${shell_path} ] && . ${shell_path}; ${args.command}) 2>/dev/null`,
|
||||
timeout_ms: AppData.CaptureSecretTimeoutMs,
|
||||
signal,
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import runComputerCommand from "@/src/functions/backend/computers/run-computer-command";
|
||||
import { resolveComputerPath } from "@/src/utils/computer-work-dirs";
|
||||
import shellQuote from "@/src/utils/shell-quote";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import capToolOutput from "./cap-tool-output";
|
||||
import computerDirsShell from "./computer-dirs-shell";
|
||||
import type { ComputerToolContext } from "./computer-tool-context";
|
||||
|
||||
type Args = {
|
||||
command: string;
|
||||
cwd?: string;
|
||||
timeout?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* A bash command on the run's computer, from the run's folder (its
|
||||
* `HOME`), with the computer's envs loaded. Each call is its own shell,
|
||||
* stopped on the computer at its timeout (at most
|
||||
* `AppData.ComputerCommandMaxSeconds`) or when the run is stopped, so a
|
||||
* command that never ends can't block the computer.
|
||||
*/
|
||||
export default function computerBashTool({ computer, dirs, shell_path, redact }: ComputerToolContext): HarnessTool<Args> {
|
||||
const max = AppData.ComputerCommandMaxSeconds;
|
||||
|
||||
return {
|
||||
name: "computer_bash",
|
||||
description: `Run a bash command on this computer (Debian, as the user gem, with passwordless sudo: install what you need with sudo apt-get update && sudo apt-get install -y ..., or pip install). It starts in your folder (${dirs.cwd}, also ~ and $HOME) with your envs set. Every call is a fresh shell (cd and export don't carry over), reads no input (anything waiting for a prompt fails at once: pass -y, a password through its env, and so on) and is stopped after timeout seconds (at most ${max}, ${max} when not given). Start longer work in the background (nohup ... > log 2>&1 &) and check its log in later calls. Output past ${Math.round(AppData.ComputerCommandMaxOutputChars / 1000)}k characters is cut in the middle, so filter it.`,
|
||||
schema: z.object({
|
||||
command: z.string().min(1).max(100_000),
|
||||
cwd: z.string().max(AppData.BotFilePathMaxChars).optional().describe("Where to start, inside your folders"),
|
||||
timeout: z.number().positive().optional().describe(`Seconds, at most ${max}`),
|
||||
}),
|
||||
run: async ({ args, signal }) => {
|
||||
const cwd = args.cwd ? resolveComputerPath({ path: args.cwd, dirs }) : null;
|
||||
const seconds = Math.min(max, Math.max(1, Math.ceil(args.timeout || max)));
|
||||
|
||||
const result = await runComputerCommand({
|
||||
computer,
|
||||
command: [
|
||||
computerDirsShell({ dirs }),
|
||||
`[ -f ${shell_path} ] && . ${shell_path}; `,
|
||||
cwd ? `cd ${shellQuote({ text: cwd })} && ` : "",
|
||||
args.command,
|
||||
].join(""),
|
||||
timeout_ms: seconds * 1000,
|
||||
signal,
|
||||
});
|
||||
|
||||
const output = capToolOutput({ text: redact(result.output.replace(/\s+$/, "")), max_chars: AppData.ComputerCommandMaxOutputChars });
|
||||
|
||||
return [
|
||||
`Exit code: ${result.exit_code ?? "unknown"}`,
|
||||
output || "(no output)",
|
||||
result.timed_out ? `[Stopped after ${seconds}s: the command timed out. Run long work in the background and check its log.]` : "",
|
||||
result.truncated ? `[The computer kept only the first part of a very long output.]` : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import { shellQuote } from "./download-computer-file";
|
||||
import shellQuote from "@/src/utils/shell-quote";
|
||||
|
||||
/**
|
||||
* The shell that puts a command in the run's folder on the computer:
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import downloadComputerFile from "@/src/functions/backend/computers/download-computer-file";
|
||||
import writeComputerFile from "@/src/functions/backend/computers/write-computer-file";
|
||||
import { resolveComputerPath } from "@/src/utils/computer-work-dirs";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import type { ComputerToolContext } from "./computer-tool-context";
|
||||
import replaceInText from "./replace-in-text";
|
||||
|
||||
type Args = {
|
||||
path: string;
|
||||
old_text: string;
|
||||
new_text: string;
|
||||
replace_all?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Replaces exact text in a file on the run's computer: once, where it
|
||||
* appears exactly once, or everywhere with `replace_all`.
|
||||
*/
|
||||
export default function computerEditFileTool({ computer, dirs }: ComputerToolContext): HarnessTool<Args> {
|
||||
return {
|
||||
name: "computer_edit_file",
|
||||
description: `Change part of a text file on this computer: old_text (copied exactly, with its whitespace) becomes new_text. It must appear exactly once, unless replace_all is true; include more of the lines around it to make it unique.`,
|
||||
schema: z.object({
|
||||
path: z.string().min(1).max(AppData.BotFilePathMaxChars),
|
||||
old_text: z.string().min(1),
|
||||
new_text: z.string(),
|
||||
replace_all: z.boolean().optional(),
|
||||
}),
|
||||
run: async ({ args, signal }) => {
|
||||
const path = resolveComputerPath({ path: args.path, dirs });
|
||||
const download = await downloadComputerFile({ computer, path, max_bytes: AppData.ComputerWriteFileMaxChars, signal });
|
||||
|
||||
if (!download.ok) {
|
||||
return download.reason == "missing"
|
||||
? `There's no file at ${path}.`
|
||||
: download.reason == "too_big"
|
||||
? `${path} is too big to edit this way; use computer_bash (sed, python).`
|
||||
: `${path} changed while it was read. Try again.`;
|
||||
}
|
||||
|
||||
const edit = replaceInText({
|
||||
text: download.bytes.toString("utf8"),
|
||||
old_text: args.old_text,
|
||||
new_text: args.new_text,
|
||||
replace_all: Boolean(args.replace_all),
|
||||
});
|
||||
|
||||
if (!edit.ok) {
|
||||
return edit.count == 0
|
||||
? `old_text isn't in ${path}. Read the file again and copy the text exactly.`
|
||||
: `old_text is in ${path} ${edit.count} times. Include more of the lines around it, or pass replace_all.`;
|
||||
}
|
||||
|
||||
await writeComputerFile({ computer, path, content: edit.text, signal });
|
||||
|
||||
return `Edited ${path} (${edit.count} replacement${edit.count == 1 ? "" : "s"}).`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import downloadComputerFile from "@/src/functions/backend/computers/download-computer-file";
|
||||
import { resolveComputerPath } from "@/src/utils/computer-work-dirs";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import type { ComputerToolContext } from "./computer-tool-context";
|
||||
|
||||
type Args = {
|
||||
path: string;
|
||||
offset?: number;
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Images a model takes as they are, by their first bytes.
|
||||
*/
|
||||
const ImageSignatures: { type: string; test: (bytes: Buffer) => boolean }[] = [
|
||||
{ type: "image/png", test: (b) => b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) },
|
||||
{ type: "image/jpeg", test: (b) => b[0] == 0xff && b[1] == 0xd8 && b[2] == 0xff },
|
||||
{ type: "image/gif", test: (b) => b.subarray(0, 4).toString("latin1") == "GIF8" },
|
||||
{ type: "image/webp", test: (b) => b.subarray(0, 4).toString("latin1") == "RIFF" && b.subarray(8, 12).toString("latin1") == "WEBP" },
|
||||
];
|
||||
|
||||
/**
|
||||
* Reads a file on the run's computer: text as numbered lines, a window at
|
||||
* a time, and a PNG, JPEG, GIF or WebP image for the bot to look at.
|
||||
* Inside the run's folders only; secret values are redacted.
|
||||
*/
|
||||
export default function computerReadFileTool({ computer, dirs, redact }: ComputerToolContext): HarnessTool<Args> {
|
||||
const lines_max = AppData.ComputerReadFileMaxLines;
|
||||
|
||||
return {
|
||||
name: "computer_read_file",
|
||||
description: `Read a file on this computer (a path in your folders; relative ones start in ${dirs.cwd}). Text comes back as numbered lines, ${lines_max} at a time: pass offset (the first line, from 1) and limit for another part. PNG, JPEG, GIF and WebP images come back for you to look at. For anything else (PDFs, archives), use computer_bash, or import_file it into your files.`,
|
||||
schema: z.object({
|
||||
path: z.string().min(1).max(AppData.BotFilePathMaxChars),
|
||||
offset: z.number().int().min(1).optional(),
|
||||
limit: z.number().int().min(1).max(lines_max).optional(),
|
||||
}),
|
||||
run: async ({ args, signal }) => {
|
||||
const path = resolveComputerPath({ path: args.path, dirs });
|
||||
const download = await downloadComputerFile({ computer, path, max_bytes: AppData.ComputerReadFileMaxBytes, signal });
|
||||
|
||||
if (!download.ok) {
|
||||
return download.reason == "missing"
|
||||
? `There's no file at ${path}.`
|
||||
: download.reason == "too_big"
|
||||
? `${path} is ${download.size} bytes, over the ${AppData.ComputerReadFileMaxBytes} this reads. Look at part of it with computer_bash (head, sed -n, grep).`
|
||||
: `${path} changed while it was read. Try again.`;
|
||||
}
|
||||
|
||||
const image = ImageSignatures.find((signature) => signature.test(download.bytes));
|
||||
|
||||
if (image) {
|
||||
return {
|
||||
text: `${path} (${image.type}, ${download.size} bytes)\n\n[Image: shown after the tool results]`,
|
||||
images: [{ url: `data:${image.type};base64,${download.bytes.toString("base64")}`, redact }],
|
||||
};
|
||||
}
|
||||
|
||||
if (download.bytes.subarray(0, 8000).includes(0)) {
|
||||
return `${path} is a binary file (${download.size} bytes). Use computer_bash to look into it (file, xxd, unzip -l ...).`;
|
||||
}
|
||||
|
||||
const lines = download.bytes.toString("utf8").split("\n");
|
||||
|
||||
if (lines[lines.length - 1] == "") lines.pop();
|
||||
|
||||
const start = (args.offset || 1) - 1;
|
||||
const shown = lines.slice(start, start + (args.limit || lines_max));
|
||||
const end = start + shown.length;
|
||||
const width = String(end).length;
|
||||
const body = shown
|
||||
.map((line, index) => {
|
||||
const cut = line.length > AppData.ComputerReadFileMaxLineChars;
|
||||
|
||||
return `${String(start + index + 1).padStart(width)}\t${cut ? `${line.slice(0, AppData.ComputerReadFileMaxLineChars)} [line cut]` : line}`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
return [
|
||||
`${path} (${lines.length} lines)`,
|
||||
redact(body) || "(empty)",
|
||||
end < lines.length ? `[Lines ${start + 1}-${end} of ${lines.length}. Pass offset ${end + 1} for more.]` : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { ComputerApi } from "@/src/functions/backend/computers/computer-fetch";
|
||||
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
|
||||
/**
|
||||
* What a run's own computer tools share: the computer, the run's folders
|
||||
* on it (every path is kept inside them), the env file its commands load,
|
||||
* and the redaction its secret values go through.
|
||||
*/
|
||||
export type ComputerToolContext = {
|
||||
computer: ComputerApi;
|
||||
dirs: ComputerRunDirs;
|
||||
shell_path: string;
|
||||
redact: (text: string) => string;
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import writeComputerFile from "@/src/functions/backend/computers/write-computer-file";
|
||||
import { resolveComputerPath } from "@/src/utils/computer-work-dirs";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import type { ComputerToolContext } from "./computer-tool-context";
|
||||
|
||||
type Args = {
|
||||
path: string;
|
||||
content: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Writes a whole text file on the run's computer, in the run's folders,
|
||||
* creating its folders.
|
||||
*/
|
||||
export default function computerWriteFileTool({ computer, dirs }: ComputerToolContext): HarnessTool<Args> {
|
||||
return {
|
||||
name: "computer_write_file",
|
||||
description: `Write a whole text file on this computer (a path in your folders; relative ones start in ${dirs.cwd}), replacing what's there and creating missing folders. To change part of a file, use computer_edit_file.`,
|
||||
schema: z.object({
|
||||
path: z.string().min(1).max(AppData.BotFilePathMaxChars),
|
||||
content: z.string().max(AppData.ComputerWriteFileMaxChars),
|
||||
}),
|
||||
run: async ({ args, signal }) => {
|
||||
const path = resolveComputerPath({ path: args.path, dirs });
|
||||
const written = await writeComputerFile({ computer, path, content: args.content, signal });
|
||||
|
||||
return `Wrote ${path} (${written.size} bytes).`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
type Params = {
|
||||
/**
|
||||
* The sandbox's REST address (no `/mcp`).
|
||||
*/
|
||||
base_url: string;
|
||||
/**
|
||||
* 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. It goes through the sandbox's own
|
||||
* download endpoint (`/v1/file/download`), which streams the file as it
|
||||
* is, rather than its shell: a shell's output is capped (30,000
|
||||
* characters) and would silently cut a big file short, which is exactly
|
||||
* how a 1.12 MiB archive once arrived as 22 KB.
|
||||
*
|
||||
* The size is read first so nothing over the limit is transferred, and the
|
||||
* download asks the sandbox to abort if the file changes while it is sent
|
||||
* (`change_policy=abort`); the length is also checked, so a cut-short
|
||||
* transfer is reported instead of being saved.
|
||||
*/
|
||||
export default async function downloadComputerFile({
|
||||
base_url,
|
||||
path,
|
||||
max_bytes,
|
||||
signal,
|
||||
}: Params): Promise<ComputerDownload> {
|
||||
const size = await fileSize({ base_url, path, signal });
|
||||
|
||||
if (size == null) return { ok: false, reason: "missing", size: 0 };
|
||||
if (size > max_bytes) return { ok: false, reason: "too_big", size };
|
||||
|
||||
const res = await fetch(
|
||||
`${base_url}/v1/file/download?path=${encodeURIComponent(path)}&change_policy=abort`,
|
||||
{
|
||||
signal: AbortSignal.any([
|
||||
...(signal ? [signal] : []),
|
||||
AbortSignal.timeout(size > 5 * 1024 * 1024 ? 120_000 : 60_000),
|
||||
]),
|
||||
},
|
||||
);
|
||||
|
||||
if (res.status == 409) return { ok: false, reason: "cut_short", size };
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`The computer refused to send ${path}: ${res.status}`);
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(await res.arrayBuffer());
|
||||
|
||||
if (bytes.byteLength != size) {
|
||||
return { ok: false, reason: "cut_short", size: bytes.byteLength };
|
||||
}
|
||||
|
||||
return { ok: true, bytes, size };
|
||||
}
|
||||
|
||||
/**
|
||||
* A file's size on the computer, or null when it isn't there.
|
||||
*/
|
||||
async function fileSize({
|
||||
base_url,
|
||||
path,
|
||||
signal,
|
||||
}: {
|
||||
base_url: string;
|
||||
path: string;
|
||||
signal?: AbortSignal;
|
||||
}) {
|
||||
const { output } = await import("./run-computer-command").then((mod) =>
|
||||
mod.default({
|
||||
base_url,
|
||||
command: `f=${shellQuote({ text: path })}; if [ -f "$f" ]; then wc -c < "$f"; fi`,
|
||||
timeout_ms: 30_000,
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
|
||||
const digits = output.trim().match(/^\d+/)?.[0];
|
||||
|
||||
return digits ? Number(digits) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A path as one shell word, so a name with spaces or quotes is still one
|
||||
* argument.
|
||||
*/
|
||||
export function shellQuote({ text }: { text: string }) {
|
||||
return `'${text.split("'").join(`'\\''`)}'`;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user