Part of the runner protocol. docs/protocol.md has the rules for all of it and which file each section is in.
A box on a virtual runner (docs/virtual-runners.md, convex/boxes.ts) runs
one thread as an ordinary runner, on a box key (tbb_ and 64 hex
characters): a third kind of key, beside the owner key and runner keys,
for one runnerId and one thread. It isn't a runnerKeys row and
doesn't count toward their three: the thread's boxes row keeps its
SHA-256 (boxKeyHash).
- Getting one. The provider starts the box with a boot token (
tbt_and 64 hex characters) in its environment and nothing else reusable.boxes:exchange({ bootToken, machineId?, boxKeyHash? })trades it, once and within 10 minutes of its minting, for{ boxKey, runnerId, threadId, claudeToken, threadKey, repo, save, login }: the box key, the login's cloud token, the thread's key for sealing its saves (base64, 32 bytes), the repo the owner fixed (originwithout credentials,subfolder,baseBranch), the last save's URL, or null, and the login the box runs on (as its cloud token is kept, an email), which a token login can't read from.claude.json. WithboxKeyHash(the SHA-256, in hex, of a box key the box made itself, as the runner's box mode does) that hash is the box's key and noboxKeycomes back, so the key never crosses the network. The exchange then records the token's hash and when it would have expired (boxes.exchanged), and the samebootToken,machineIdandboxKeyHashasked again, while that key is still the thread's (not replaced, revoked or dead) and within the token's 10 minutes, get the same answer and change nothing: a box whose answer was lost tries again. Anything else with a spent token (another machine, another hash, no machine or no hash) is refused (auth). It unseals first, from a read that uses nothing up, so a deployment that can't unseal (kind: "config") leaves the boot token and the box as they were. Then, in one mutation that checks the token again, it's used up, the box's machine goes toawake(READY), and the new key's hash replaces the last box's, so the last box's key is refused from that moment. A login with no cloud token refuses withkind: "noCloudToken"and leaves the boot token as it was.machineIdis the provider's id for the machine the box runs on, which each provider says how a box learns (BoxProvider.machineIdEnv: Fly'sFLY_MACHINE_ID); letters, digits,_and-, at most 64. The exchange records it as the key holder's machine (boxes.keyMachineId), so where a provider made two machines for one attempt, only that one is the row's: the reaper takes it in and deletes the other, and aCREATED,LOSTorPAUSEDnaming the other changes nothing. The box runner sends it from slice 3; an exchange without it is taken, its machine unknown, and then no machine of that attempt is reported lost, taken in or deleted for the key while another of it is listed. A box's heartbeat may send it too (runner.machineId, kept on the box row, never the runner's): it names the key holder's machine if nothing has yet, and changes nothing once one is known. Before a wake, a lease check or the reconciler decides anything, the service makes sure of the key holder's machine: one the row never took in is taken in, or, once the provider confirms it gone (asked by its id), reported lost, which ends its key and its attempt's protection together. Not known: the row's machine gone with one of its attempt left, that one is taken in as a guess (it deletes nothing and refuses no report, and a box's own word replaces it); several left, each is tried in turn. A machine resumed while it's unsure is a trial: the thread stayswaking(noRESUMED) until a key heartbeat 30 seconds or more after that resume names it, and one that stops, or sends none within 3 minutes, is paused and the next tried. A failed trial, or a wake that gives up with it still unsure, is shown on the thread (RemoteRunner.box.unsure). A create's lateFAILEDfor an attempt that has traded its token (or may hold work) changes nothing, nor does a lateCREATEDnaming another machine for an attempt the row already names one for, unless it names the key holder's machine, which the row then takes as its own. A refusedCREATEDdeletes its machine only if the reaper's plan and fence would delete it then. A machine a delete fence decides to delete is condemned in that same step (aboxCondemnedrow, with when, no cap) until its delete succeeds or a listing asked for after that no longer has it: an exchange naming it is refused, as is one naming no machine while any of its attempt is condemned (the boot token stays for the kept machine), and a heartbeat naming it never makes it the key holder's. A newer boot token for the thread replaces an older one. Each is for one attempt at a box (mintBootTokenreturns itsattempt, numbered from 1), which the service'sCREATEDandLOSTname: a loss ends the key, unused boot token and provider id of that attempt and older ones, and leaves a newer attempt's alone (aLOSTnaming none ends them all). An event naming an older attempt than the newest the thread has changes neither its state nor its provider box: a lateCREATEDis refused (boxMachine.tsstale, one rule for every event).CREATED,IDLE,RESUMEDandLOSTeach name their attempt. The newest attempt'sCREATEDrecords its provider id in any state, and only starts a box that hasn't traded its token yet;RESUMEDis only the key holder's, while no newer attempt has been minted. Box keys and boot tokens (tbb_,tbt_) are redacted from transcripts like runner keys, and so is a value under a name likethreadKey,boxKeyorsealed; a message'sturn(or a picture's name, a claim's holder, a move's digest) with a credential's prefix is stored as[REDACTED]. A message'sturnmust be a turn id's first characters (1 to 8 letters, digits,-or_, from any key) and a runner or box key'satan ISO time, asshare:viewhands both out unscrubbed; anything else is dropped (turn) or made now (at). A box can't put a share link another thread had under its runner id on its own thread. - What it reaches. Only what running its one thread needs (the list
below,
BOX_CALLSinconvex/runnerAccess.ts), each for its own runner as a runner key's is, and each row checked against its thread too (ownThreadOnly): a thread row only under its own thread id, never a new thread. Every list and write by runner id (threadsOf,sharedThreads,messageHeads,setThreadIndex'sremovedandkeep, its requests, making room under its caps, removing its thread) leaves out any other thread the owner key put under its runner id. Messages, tool output and pictures of that thread; its runner's commands for that thread or for no thread (another thread's are hidden frompendingCommandsand refused); its thread's moves only. Everything else is refused asforbidden: everything owner-only, schedules, Pocket, projects, logins and usage readings (the service sets a box's login), pools, shared memory, presence,pruneand machine figures. A new thread from a box goes throughfileRequest, which asks Mike with a card, as from any runner key. An upload URL it asks for dies when its key is replaced. - When it stops working. The box's state machine (
convex/boxMachine.ts) clears the hash when the box is lost (no heartbeat for 5 minutes, or the provider says so, in any state, waking included), when the provider makes a new box for the thread, and when it fails, is archived or deleted; a key whose row isdestroying,goneorfailedis refused whatever the row holds. A box that sleeps on a paused machine keeps its key, so it can resume. - Heartbeats. A box's
heartbeatmarks itsrunnersrowbox: { serviceId }, renews the box's lease (boxes.lastHeartbeatAt) and drops anyrpcUrl: no Mac app dials a box. Its answer carriesbox: { state }, the box's state as the heartbeat found it (a box stopped by its save runs again onawake, Box mode). - The Machines page (
convex/viewer.ts) leaves out a box'sbootTokenHash,boxKeyHashandsealedThreadKey, and anysealed. - Internal.
boxes:authorize(an action's gate),storeCloudToken,newBoxandinsertBox(a thread's box row),storeBootToken,peekBoot(the exchange's read),claimBoot(its one step) andreport(what the service saw of the provider, as the machine'sserverevents;FAILEDnames its attempt too, and one for an older attempt changes nothing).
A box key may call:
heartbeat, bye, upsertThreads, removeThreads, threadsOf,
sharedThreads, appendMessages, messageHeads, appendBodies,
replyImages, addReplyImage, shareImages, addShareImage,
dropShareImages, addHeldPicture, iconUploadUrl, setThreadIndex,
pendingCommands, takeCommand, finishCommand, fileRequest,
runnerRequest, closeRequest, moves, moveInfo, moveReady,
moveFrozen, moveChunkUrl, movePacked, moveChunks, moveClaim,
moveDone, moveFailed, boxSaved, tokenRefused, boxCloudToken
The runner in a box (runner/src/box-mode.ts, box-save.ts): an ordinary
runner for one thread, started by the image with THREADBEAR_BOX_BOOT set.
The box image (runner/box/Dockerfile) is Node 24 on Debian with git,
Claude Code at a pinned version (~/.local/bin/claude) and the runner from
the commit it was built from. Its entrypoint (runner/box/entrypoint.sh)
runs the runner as root, in box mode, with IS_SANDBOX=1,
DISABLE_AUTOUPDATER=1, THREADBEAR_BOX_WORK=/work and the runner's log on
stderr as well (THREADBEAR_LOG_STDERR=1); with no THREADBEAR_BOX_BOOT, or
no THREADBEAR_SYNC_URL, it exits 64 at once, saying why, rather than start
an ordinary runner. Nothing restarts the runner in the box: when it exits,
the machine stops.
- Starting. Before anything else it reads the boot token and takes it
out of its own environment, so nothing it starts (Claude Code, its
shells, a worktree's setup) inherits it. It makes its own box key and
sends only its hash (
boxKeyHash). Thenboxes:exchangeatTHREADBEAR_SYNC_URL, withmachineIdfrom the variableTHREADBEAR_MACHINE_ID_ENVnames (FLY_MACHINE_IDwhen it names none; left out if it isn't an id the backend takes). A network failure, orconfig,noCloudTokenorconflict(each leaves the token as it was), is tried again, 2 s doubling to 15 s, for up to the token's 10 minutes, with the same key hash (so an answer lost after the backend took the token comes back as a replay);auth(used, expired, unknown) stops the box at once, as does an answer it can't use. What it got is kept in the data dir's secrets, 0600:box.json(the box key, runner id, thread id, thread key, repo, login, machine id, the save's URL and the boot token's SHA-256, never the token) andconvex-key(the box key, the sync key as any runner's is); the login's token goes to claude-main'sthreadbear-token.json(0600), which the runner already passes to that login's CLI as a year-long token. A runner that starts again on the same machine under the same boot token usesbox.jsonrather than exchange again. - The thread's folder. The repo is cloned (
origin, https or ssh only) intoTHREADBEAR_BOX_WORK(default~/work) under its own name, onbaseBranch. With no save, that's all: the thread'screatecommand makes the thread under the id the backend named, insubfolder, on claude-main, and its first turn makes a worktree as a new thread in that repo would, its patch trusted as the runner's own checkout is. With a save, it's restored on top of the clone (below), and the thread's next turn resumes the same Claude session. Done once per box (box.json'sprepared), only by the start that traded the token and only into an empty place; nothing is ever deleted to make room. A box whose folder has gone, or whose first start died before its folder was made, stops and says so rather than clone or restore over what's there (the exchange's save may be older than its work). It doesn't exit, either: on Fly an exited machine's disk is reset. It stays up degraded, heartbeating on its key, running nothing (no turn, nocreate, nosave), with a note on its thread saying what's wrong and what of the thread it found, so the billing guard pauses it with its disk and a person can see to it. The same goes for any failure at the start of a box that has run. Only a fresh box with nothing to lose exits. Only the box's own thread is loaded from the data dir: any other record there is left alone and logged, and none is taken in by a handover or a move. - What box mode turns off (decision 1): self-update and following
main, CLI updates, keep-awake,
followOrigin, the reinstaller and upstream releases, Sentry, the Mac screen watch, schedules, the librarian, spare-week threads and the borrow sweep; the sync sends no presence, logins, projects or their pictures, schedules, pools, shared memory or machine figures, and never callsprune(its key can't do any of them; a fresh box's first full write goes without it). It keeps no schedules:schedule_message,tb scheduleand the backend'sschedulecommand are refused with a note that the Mac schedules it (a schedule there sends to the thread and wakes it), and nothing in the box arms a schedule's timer, runs its check or readsschedules.json. Its key isn't the owner's (ownerKey()is false fortbb_, as fortbr_), socreate_threadnaming another runner files a request the main Mac asks the user about. A repo's patch code never runs in the box's runner process: each patch file is imported in a short-lived child process (runner/src/patch-child.ts) that sends back what's static in it as one line of JSON on a channel of its own (fd 3; what the patch prints on stdout or stderr is thrown away) and exits. The loader runs in a process group of its own: the read ends on that line, the loader's exit or 30 seconds, never on its pipes closing, and then the whole group is killed, so nothing the patch starts holds the read up. A process the patch starts in a group of its own (detached, setsid) can outlive the read, but it stays in the box, and a stopping save's sweep kills it. Its functions aren't run at all: an action or panel with awhen,badge,labelorsummary, and a list panel (items), aren't shown on a box's thread; its static actions, panels, hooks (commands, gated like any process) andworktreesetup are. It runs one thread: any othercreate, from anywhere, is refused (create_threadasks the main Mac, as from any runner key). Claude Code runs as root there, soIS_SANDBOX=1is set for everything the runner starts. The app port listens on 127.0.0.1 only, as every runner's does; nothing dials a box. - Heartbeats carry
runner.machineId, the same id as the exchange. - A refused token (API 94). The exchange also gives
tokenSetAt, when the login's token was set, kept inbox.json.claude auth statuscalls any token signed in, so a dead one only shows when a turn is refused (errorKindauth). In box mode that turn sendsboxes:tokenRefused({ key, setAt }), says so once in the thread (system.note), and the thread waits (waitingForTokenon its record, kept across restarts, withrefusedSetAt, the version refused, andreportedonce the backend has heard; no pool move, as a box has one login). A refusal not yet heard is sent again on the next start or poll, always withrefusedSetAt, never a version installed since. While it waits the runner asksboxes:boxCloudToken({ key })(an action, box key only: the login's token andsetAtwhile it'svalid, else null) every 30 seconds. Any token newer than the refused one lifts the hold: one the box already has (a box restored from a save whose exchange installed a newer token goes at once, telling nobody), or one set later, which is written over claude-main'sthreadbear-token.json(0600) and intobox.json, the thread's CLI is closed so the next turn starts on it, and the thread carries on by itself with the runner's carry-on message, as after a sign-in. A message from Mike meanwhile waits behind it. - Superseded. Any call refused with
kind: "auth"(the box key unknown: a newer box for the thread has traded its boot token, or the box was lost, failed or archived) means this box no longer has the thread. It sends nothing more, stops its CLIs and exits with nobye, so the provider's machine stops for the service to clean up. - The
savecommand (only the backend sends it, for the box's own thread). Every save the backend asks for is a stopping one (to sleep, at its day's hours, or to be archived), and once it's acknowledged the box may be deleted, so the box stops first, categorically: turns are held, a running turn is interrupted (30 s to end) and the CLI closed, then every other process in the box is killed (all but the runner, its ancestors, PID 1 and the provider's own:runner/src/box-procs.ts, from/proc). The provider's are a baseline the first start after the exchange takes, before anything of the thread runs, kept inbox.json(baseline: pid, start time, command) and used by every start after, so an agent's process that outlived a restart of the runner is never spared. A process is alive while any of its threads is (a zombie leader can have live ones), and its whole thread group is killed. The runner's own work waited for (a minute at most, or the command fails), and it looks again that nothing new started. A worktree cleanup or teardown an archive would start meanwhile is owed instead (cleanupOwed). And from the save's start, no process starts in the runner at all: in box mode,node:child_processis gated (runner/src/spawn-gate.ts: every function of it that starts a process, andChildProcess.prototype.spawn, for the runner and its libraries alike), and only the save's own git and packing are let by. A patch's live functions aren't read while it's held, and a read already going is waited for. From the moment a save starts, the thread runs nothing until the backend says it may: a command other thansavetaken after the save's outcome is known, or a heartbeat sent after that whose answer finds the boxawake. Nothing in the box lets it go: not a clock jump, a timeout or an error, nor a restart: the hold is written tobox.json(saveHold) before the thread is touched, and a start that finds it holds the thread before loading it. While it's held, the box's heartbeats and its save'sfinishCommandsendheld: true, and don't mark the box as holding work (runnerAuth's housekeeping; only asavecommand's finish counts), and a finish of any other command taken while the save goes waits until its outcome is known. A command's finish goes once at a time (a retry waits for one on its way), and the backend takes a finish that changes nothing (its command already ended) as housekeeping too. Then it's packed: the thread's folder in the data dir (its record and events, notpanels), its Claude session's transcript and the folder beside it, and its git work as a move packs it (move-git.ts packGit: the commits origin doesn't have and one more of every uncommitted and untracked file, in a git bundle; ignored files stay behind, and so do files under anode_modulesfolder that the checkout's own index doesn't have, which a restore refuses: the worktree's setup makes them again; a change there to a tracked or staged file fails the command, saying so. Its index is built from HEAD, with no stat data to trust, and every file hashed afresh (core.checkStatdefault,core.trustctimeon, whatever the repo says), plus the paths the checkout's own index has staged that HEAD hasn't (force-added, so an ignored one comes too): what's saved is the files as they really are), in a move's archive (move-pack.ts) with abox.jsonnaming the thread. At most 100,000 files and 128 MB unpacked, the limits a restore holds it to, checked from the sizes on disk before anything is read, and it's read back as a restore will read it before anything is uploaded: over a limit or unreadable, the command fails and the thread carries on. Sealed AES-256-GCM under the thread key: a 12-byte IV, the ciphertext, the 16-byte tag, bound tothreadbear box save v1 <threadId>as associated data. Uploaded to the URLsync:iconUploadUrlgives the box key, thenboxes:boxSaved({ key, storageId, bytes }), but only once every change of the runner's has gone up (the mirror's flush waited for, then one run to the end with nothing left, the sidebar index's writer the same, and any command's finish still to send from before the save; if it can't, the command fails and the box stays held), so no write after the save marks the box as working; the command finishes with{ bytes }(andleftOut, up to 20 paths left out). A sealed save over 10 MB (one upload) fails the command saying so; saves in parts are a TODO. AboxSavedwhose answer is lost (not a refusal) is sent again with the same file, which the backend takes as the same save, for up to 10 minutes; past that its outcome is unknown, and the thread stays held until the backend asks for another save. Messages wait in the queue while it's held. - Restoring. The save is downloaded (https, no redirects, 10 MB at
most), gunzipped to 128 MB at most, opened (one that doesn't open with the thread's key, or isn't
that thread's, stops the box), the thread's folder written into the data
dir, its git work put back on the clone (
unpackGit), in a worktree at<clone>-threads/<the folder name it had>onthread/<id8>if it had one, and its transcript put where Claude Code looks for the folder it now runs in. Once the runner is up, the worktree's setup runs again (installed packages weren't saved), and no turn starts in the thread (recovery, a carry-on or a message) until it's done; one that fails says so in the thread, and the turns go ahead. That it has run is kept apart (box.json'ssetUp): a runner that stops before it has runs it again, holding the turns again, on its next start.