Skip to content

Latest commit

 

History

History
2131 lines (1818 loc) · 119 KB

executor-protocol.md

File metadata and controls

2131 lines (1818 loc) · 119 KB

Executor protocol

The daemon dispatches filesystem and shell tool calls to an executor process (rafiki executor serve) over Connect RPC. This document describes the wire protocol: the executor RPCs, their message shapes, the four failure codes, the background-handle lifecycle, the workspace lifecycle, and the mtime contract.

There are three transports for the same protocol, and they differ only in what carries the bytes:

Transport Command Used when
Reverse-dialled TLS rafiki executor serve --connect the daemon cannot reach the executor's host (NAT, a laptop), or a launcher installed the executor on another machine with mode=direct — see "Installing over ssh"
Unix socket (reverse) rafiki executor serve --connect-socket executor and daemon on one host, enrolling as a fully rowed member of the pool
ssh stdio relay rafiki executor serve --stdio a launcher installed the executor on another machine with mode=tunnel — see "Installing over ssh"

There was once another form: the executor listened on a unix socket and the daemon dialled it with rafiki create --executor-socket. It is gone. It produced an executor with no database row — no labels, no admits, no isolation, no workspace_mode, invisible to selectors and never inherited by a child — which made it the direct cause of two separate confinement defects. --connect-socket reverses the direction so the executor enrolls, and the row is again the only authority on what an executor is.

A fourth transport is the client-run executor: rafiki create and rafiki attach start an executor in-process and reverse-dial the daemon, so the operator's own machine becomes the workspace by default. It is not a new wire path — it uses --connect's TLS transport when RAFIKI_URL names a remote daemon, and --connect-socket's unix path when the daemon is local.

Transient executors

A client-run executor is transient: it has no database row at all. The daemon mints a one-shot session ticket over the already-authenticated control connection, the client connects with the ticket (Authorization: Ticket <ticket> on the upgrade request), and the executor lives exactly as long as the control connection that asked for it. Closing the connection revokes the ticket and evicts the executor from the pool.

This confronts a documented invariant — "the row is the only authority on what an executor is" — so the resolution is explicit rather than an exception. The row is authority because an operator wrote it and the machine it describes cannot assert it. For a transient executor, every such fact comes from the authenticated control connection, which is a stronger source, not a weaker one:

Fact Durable Transient
owner operator label authenticated user on the connection
admits operator owner=<that user>, daemon-written
isolation operator none — it is the operator's own terminal
workspace_mode operator pinned
roots operator claim the cwd the client reported
machine trust label at mint the operator-written name the client read back, validated

Nothing is self-reported, so SelfReported's rule is not bent. The invariant generalises to: every access-gating fact is written by the daemon from something it verified — a row an operator wrote, or a connection it authenticated.

Consequences:

  • refreshRow must skip transient executors: store.Get answers ErrNotFound for a row that never existed, and refreshRow correctly treats that as "this row was deleted, evict now", killing a healthy executor on its first health tick.
  • liveConn.transient marks an executor with no row. Live() returns it like any other; selection, admission and narrowing are unchanged.
  • Because the ticket is per-connection, two concurrent TUIs on one machine get two distinct executors rather than colliding on one per-machine credential.

The selector returned by ctrl_executor_session is owner=<user>,machine=<name> in BOTH the durable and transient cases, so a child can move between the two without its stored selector — the thing its whole subtree inherits — ever being rewritten. The durable executor is preferred (durable before session in sortCandidates), and the transient one is a zero-config fallback.

Sandbox launchers

The daemon never touches a container runtime. A sandbox is a container, created by the daemon through a launcher executor's declared docker proxy; the launcher is the only process that speaks to Docker. It is an ordinary durable executor whose operator declared three things:

  • --proxy docker=unix:///var/run/docker.sock — a proxy named exactly docker (sandbox.DockerProxyName), whose base is a unix:// socket. A unix:// base names a socket to DIAL, not an HTTP origin: pkg/executor accepts it only in the authority-less absolute form (unix:///path/to.sock), builds the target against the fixed http://docker origin and swaps in a transport that dials that socket. http/https bases join as any other proxy. The daemon finds a launcher by looking for this proxy name in the creator's effective executor set — a launcher is never chosen by default.
  • --sandbox-mount-root <dir> (repeatable) — every host directory a sandbox may bind-mount. Reported as DescribeResponse.sandboxMountRoots. A root is a read grant of EVERYTHING under it, to every child of the owner, so it must not contain a socket or a credential file: the launcher's guard refuses a bind source that is not a regular file or a directory (see "The create-body guard" below).
  • --relay-dir <dir> — the host directory the daemon bind-mounts into the container so its rafiki executor serve can reach the daemon. Reported as DescribeResponse.sandboxRelayDir.
  • --relay-foothold-image <ref> — the image for foothold mode, which replaces --relay-dir (the two are mutually exclusive) and is the default, with ghcr.io/graveland/rafiki-sandbox:latest, on a non-Linux host with a unix:// docker proxy and no --relay-dir (resolveFootholdImage): the launcher runs one foothold container per docker host, inside the docker host's own kernel, whose relay socket lives in a named volume the sandbox mounts. Works only where the docker runtime maps host.docker.internal to this host's loopback (Docker Desktop, OrbStack), since the foothold's bridge dials its OWN host's loopback — not a plain lima VM or a remote docker context. Reported as DescribeResponse.sandboxRelayVolume. Requires a unix:// docker proxy and a daemon address, and is replaced by foothold.Ensure when the create body or the resolved image id drifts.

Accepted residuals of foothold mode, not protections: the foothold→launcher loopback TCP hop is plaintext and carries each sandbox's durable executor credential, and the foothold keeps running while the launcher is down, still dialing its ephemeral port — a local process that binds that port would receive those credentials. The foothold's key is the host name, so a rename orphans its volume, stranding sandboxes already created on it.

The relay. --relay-dir makes rafiki executor serve also bind <relay-dir>/daemon.sock (sandboxrelay.Serve) and splice every accepted sandbox connection to a fresh dial of the daemon the launcher itself is connected to (TLS and pin applied when the daemon is remote; nothing authenticates the LAUNCHER on the relayed connection). The relay never reads or writes the bytes it carries: the sandbox speaks the daemon's own protocol end to end, so the credential the create body put in the container's environment is what the daemon authenticates — the relay only carries it, untouched. The socket is chmodded world-connectable because the container user differs from the host user; the daemon-side credential, not the socket, is the gate. The relay directory is mounted read-only at /run/rafiki-relay in the container, and the container's executor runs --connect-socket /run/rafiki-relay/daemon.sock. A dead relay is not a degraded mode: a launcher started with --relay-dir but no daemon address to dial refuses to start (relayDirNeedsDaemon), and a serve command whose relay exits ends the process nonzero. --relay-dir therefore requires --connect or --connect-socket (or a remote RAFIKI_URL).

The create-body guard. Every proxied request whose proxy is docker and whose method is POST and whose path routes to Docker's containers/create (behind at most one Docker API version segment, matched case-insensitively, and any path carrying a % or # treated as a create) is buffered and inspected before it is forwarded (pkg/executor/dockerguard.go). The guard is a fail-closed allowlist, not a denylist: the top level, HostConfig, each mount and RestartPolicy are decoded and every key outside the exact set the daemon's create body emits (pkg/sandbox.CreateBody) is refused, so a privilege field nobody enumerated (Binds, Privileged, Devices, VolumeOptions, DeviceCgroupRules, a host namespace, …) is refused by construction rather than by a remembered list. A key repeated at any object level is refused too — a map decode keeps only the LAST value, while the engine MERGES repeated object keys, so the two views of the same document must agree. Each bind mount's source is symlink-resolved and must sit at or under a declared --sandbox-mount-root (or equal the resolved relay dir), and must be a regular file or a directory — a socket, device or fifo is refused, because an ro bind of a unix socket still permits connect(); volume and tmpfs mounts pass (the daemon owns their contents), except the launcher's relay volume (a foothold's sandboxRelayVolume), which is admitted only as a volume mount, read-only, at the fixed relay target /run/rafiki-relay — any other target, or a writable mount, is refused, because a writable relay volume lets a sandbox replace daemon.sock and capture the executor credential of every other sandbox sharing it; NetworkMode is limited to "", bridge or none. A named volume's source is rafiki-<ownerKey>-<name>: ownerKey is derived from the owner's user id by stripping every non-alphanumeric character, taking the LAST 12 characters of what remains (uuidv7's random tail, not the shared millisecond timestamp prefix), or the literal local for the empty anonymous owner (sandboxOwnerVolumeKey, cmd/rafikid/sandbox.go; CreateBody requires the key to match ^[A-Za-z0-9]{1,32}$). Named volumes are never removed.

Two residuals, both accepted. The guard covers POST /containers/create ONLY — every other Docker route proxies uninspected, which is safe because the proxy is driven only by the daemon and the design already accepts root-equivalent Docker access through the relay. And the check and the container start are separate calls, so the TOCTOU window is create→start (wider than check→create); the accepted posture is that the daemon is trusted on this link.

Reaching several executors

A child's workspace tools can reach the executors in its executor set: ids fixed on its row at spawn, or all. The set is chosen by the spawner from its own (SpawnRequest.executors, field 37; executor_ref and executor_selector are placement inputs that resolve into it) and is evaluated on every call, never cached, so an executor that connects after the child started is usable on the next call if the set names it (always for all) and one that has gone is not usable on this one.

Spawn shape Stored set executor argument
executors exactly those, each inside the spawner's set (["all"] only from an all spawner) optional with one, required with 2+
A name (ExecutorRef) exactly that executor, if it is in the spawner's set optional
A label selector every member of the spawner's set it matches, frozen at spawn; none matching refuses the spawn optional with one, required with 2+
Empty, a parent the spawner's home when it can launch the kind, else a copy of its set as above
Empty, top level all required when 2+ are live
A sandbox its own sandbox only optional

Reach is the set, narrowed again by owner and by the executor's Admits evaluated against the CHILD's labels. workspace_mode filters which executors a selector or ephemeral spawn may freeze into the set. A parent's set shrinking later changes no descendant, and a resumed child keeps the set stored on its row. Installs, uninstalls, deletes, sandbox removals and new executors change stored sets and notify live agents (see the executor-sets section of docs/guide/executors.md). None of this is a security boundary: within one owner an executor with a shell can reach the owner's other machines.

Admits, on the executor's row, is how an operator keeps a special-purpose machine away from some agents: an executor declared admits=env=lab serves only a child whose labels match it, whatever set names it. That steers; it does not isolate.

Every TierWorkspace tool takes an optional executor property — a machine name or executor id — added once by the registry (pkg/fundi/tools/executor_target.go) and identical for every child, because the tool schema sits in the cached prompt prefix and must not vary. The wrapper strips the key before the tool or the executor sees the input. It applies to the background-job tools too: bash_start, bash_output and bash_kill all take it, so bash_output names the executor that started the job.

A call that names no executor when the child can reach 2+ is refused, listing them:

this agent can reach 2 executors (build-1, ci-runner-7); pass executor: "<name>"

Home is not a default: with 2+ reachable a call still names a machine, its home included. When the child can reach 2+ executors every result is prefixed [<machine>] (and so is an error), so a multi-machine transcript says which one acted. The first call on a NON-home binding is prefixed [<machine>] working from <workdir>: a non-home workspace starts at the executor's own --root, never the child's cwd, and the model is told before it writes into a tree it assumed.

Losing an executor never fails a child. The daemon releases what it held there, marks the child rafiki/executor-state: unbound, forgets the binding and steers it with EXECUTOR LOST: … naming the machine from its durable row (HandleExecutorLost, cmd/rafikid/workspace_wiring.go; executorLostSteer, cmd/rafikid/executor_lost.go). Workspace mode is then purely a rebinding rule: pinned re-provisions only on that same executor when it returns, ephemeral may rebind an implicit call on the single reachable executor. Calls to the lost machine fail until it reconnects, which is what the steer says — it is not a sentence about the child ending.

The home executor itself is chosen by the daemon at spawn, and the probe that picks it has two bounds: it SKIPS sandboxes (a sandbox provisions at its own workdir, so a probe there can never answer "does this child's cwd exist here"), and a probe workspace whose id is lost to the probe deadline is a known orphan of bounded size — pkg/executor has no reaper, so it stays in that executor's in-memory registry until the process exits, holding no files and no daemon reference.

Reaching the daemon

The reverse-dial transports are reached at a path on the daemon's shared listener, upgraded out of HTTP/1.1 — the TLS listener and the unix executor socket mount the same handler:

GET /executor/connect HTTP/1.1
Upgrade: rafiki-executor
Connection: Upgrade
Authorization: Bearer <credential>
Rafiki-Protocol: 4
        ↓
HTTP/1.1 101 Switching Protocols
Rafiki-Executor-Id: …
Rafiki-Protocol: 4
        ↓
HTTP/2, roles inverted

One port and one certificate therefore serve the control plane (/control) and the executor link (/executor/connect). When the daemon and executor are on one host, the executor socket (executor.sock in the runtime directory) is the same handler without TLS. Enable either with RAFIKI_EXECUTORS_ENABLED=1; the executor link has no listener of its own.

Two consequences worth knowing:

  • ALPN is no longer load-bearing. The outer connection negotiates http/1.1 — net/http can only hijack an HTTP/1.1 connection — and the inverted HTTP/2 begins after the 101, directly on the byte stream, where ALPN is not consulted. Agreement is the Upgrade header's job now, and a mismatch fails with a readable HTTP status instead of a TLS alert.
  • An HTTP proxy can carry it. An Upgrade tunnel is the same machinery as WebSocket, so an ingress may terminate TLS and forward rather than requiring TCP passthrough. Terminating means the daemon↔executor hop is no longer end-to-end encrypted and --pin-cert pins the proxy's certificate, so that is a deployment choice rather than a default.

Transport

  • Protocol: Connect (gRPC-compatible) over HTTP/2 cleartext (h2c).
  • Socket: Unix domain socket, filesystem mode 0600 — no authentication beyond filesystem permissions in this phase.
  • Roles: rafikid (the daemon) is the RPC client; the executor is the server. On the reverse-dialled transport the executor DIALS and then serves on what it dialled, so the TLS roles and the HTTP roles are inverted relative to each other — see pkg/execpool's package comment.
  • Codec: Binary protobuf by default; JSON also supported (Connect's auto-negotiation).
  • Streams: one inverted HTTP/2 connection carries up to maxExecutorStreams (250) concurrent streams. The daemon's client sets StrictMaxConcurrentStreams, so a call past the limit WAITS for a free stream rather than failing (pkg/execpool/transport.go); pkg/execpool/inflight.go logs one warning per upward crossing of inFlightWarnAt (200) — below the limit, so pressure is visible before callers start queueing.

Authentication on the upgrade request

There is no hello frame and nothing is negotiated in-band. Authentication rides the HTTP Upgrade request itself, as a single Authorization header, and upgradeconn.Handler runs authorize BEFORE the connection is hijacked. A refusal is therefore an ordinary HTTP response — a status the peer can classify and a body it can log — rather than an authenticated connection that closes under it. A refused upgrade is never hijacked: no HTTP/2 begins, no side effect of the exchange (a spent token, a rotated credential) has happened or needs undoing, and the socket closes after the response.

The epoch gate runs before authorize. The dialing side sets Rafiki-Protocol: 4 on the Upgrade request (upgradeconn.Dial sets it and callers cannot override it), and upgradeconn.Handler refuses a missing or different value with a plain 400 whose body names both epochs, BEFORE any credential is touched. That ordering is what stops a stale peer from spending a one-shot Enroll token or ticket on an exchange the far side cannot finish; the 400 is terminal by the 400/401/403 rule below, so a mismatched executor fails at once rather than retrying forever. The 101 carries Rafiki-Protocol: 3, and the dialer reports a 101 without it (an old peer) or with another value as a 400 Refused, terminal the same way. See control-protocol.md "The protocol epoch" for the full rule.

The scheme selects what the secret is:

Scheme Secret Used when
Bearer the executor's durable credential, or the daraja's in-memory reconnect credential every connection after the first
Enroll a one-time enrollment token minted by EnrollExecutor an executor's first join
Ticket a one-shot session ticket (transient executor), a launch ticket (daraja), or an installed executor's per-launch ticket (row-bound) the first connection for something with no durable identity, and the first connection of every installed executor's launch

A missing, repeated, schemeless, unknown-scheme or empty-secret header is refused 401 with a body that names the header form, so a peer still speaking the pre-header-auth JSON hello learns that it predates header auth and must be upgraded.

Auxiliary headers

  • Rafiki-Self-Reported (sent by the executor on every connection, read on Enroll only) carries capability facts — os, arch, version — url.Values-encoded. They are recorded on the row but are NEVER merged into the trust labels: lying about arch only earns work the executor cannot run, but a label that gates access cannot be asserted by the thing it gates. A header that does not parse as url.Values is refused 400, not silently dropped — enrollment is one-shot, so a discarded self-report could not be corrected by retrying.
  • Rafiki-Child-Id (sent by daraja on every connection, read on Bearer only — a ticket already names its child) names the child the reconnect credential claims; the credential must match it or the connection is refused 401.
  • On the 101 response, Rafiki-Executor-Id names the row that answered, and Rafiki-Credential carries a credential minted during the exchange — an executor's durable identity on first enrollment, a daraja's reconnect credential on every connection, so the newest connection is the only one that can come back. Riding the 101 costs no extra round trip.

Statuses

Status Meaning Peer behaviour
401 A decision about the credential — unknown, consumed, expired, disabled, no such row, or a machine name already claimed by another executor of the same owner. Also a missing or malformed Authorization header. Stop. Retrying cannot un-revoke a row, nor free a taken name. Connect returns ErrEnrollmentRejected (daraja: ErrRejected).
400 Malformed Rafiki-Self-Reported, or a missing/wrong Rafiki-Protocol epoch header (the gate runs before authorize). Stop — terminal.
503 The store could not be reached or read. Keep reconnecting with backoff.
409 Another connection for this executor is already live and answering. Retry shortly; if this machine is not sharing its credential with another, the incumbent is healthy and should be yielded to.

The client treats 400, 401 and 403 as terminal and retries anything else (503, 409, a plain 500) — the classification the retired retryable field used to carry, now expressed in the status itself. 403 is in the terminal set defensively; nothing currently mints one. The failure directions are not symmetric: quitting on a genuinely dead credential costs a log line, while quitting on a transient one takes the machine out of service permanently — and because executors reconnect together, one database restart would otherwise take the entire fleet down. That is why a store blip must answer 503 rather than down the fleet, and why a 409 — an incumbent still answering, so the row is healthy — is retried rather than fought.

The 503 body is deliberately generic — "rafikid could not verify the credential right now; retry". The peer has by definition not proved who it is, and a store error routinely carries a DSN, a hostname or a query; the real error goes to rafikid's log.

A terminal refusal does forward its text verbatim, so every terminal answer must be a sentinel whose own message is written for the operator reading the executor's log. The name collision is the one that carries real advice — the enrollment token was minted with a --name another executor already holds, and the fix is a token with a different name, or relabelling the existing row — and it must never be the store's own text for the same DSN reason.

RPCs

All RPCs documented below belong to the rafiki.executor.v1.ExecutorService service. rafiki.admin.v1.AdminService adds three more (Launch, Reap, Status) on the same connection — see AdminService: Launch, Reap and Status.

Describe

Describe() → { executorId, platform, roots[], concurrency, isolation,
               workspaceMode, tools[], version, selfReportedLabels,
               proxies[], launchKinds[], skillsSync, pymodulesSync,
               sandboxMountRoots[], sandboxRelayDir, sandboxRelayVolume,
               mcpCommands[] }

Unary. Called at startup and periodically to discover the executor's capabilities. tools[] is the executor's actual served set — the names its registry materialized, not a static list — and it is what the parent builds the child's tools[] from (at spawn, and again on each MCP request for a claude child in workspace-tools mode), so a name that isn't here never reaches the child's envelope. It includes the lsp_* verbs only when a language server is installed (or --lsp-config names one), and never the parent-side bash_start/bash_output/bash_kill RPCs, which the daemon implements itself.

proxies[], launchKinds[] and mcpCommands[] are the things an executor self-reports, and all are safe to self-report for the same reason: each only ever NARROWS what the executor will do. proxies[] names the LLM endpoints its operator declared with --proxy and the relay enforces on this side — a name that is not declared never reaches the network. launchKinds[] names the child protocols its operator declared with --launch that the daemon may host here via AdminService.Launch; the daemon still requires the child's ordinary executor selector to match, so a wrong entry costs a failed launch rather than admitting anyone. mcpCommands[] names the MCP server processes its operator declared with --mcp-command — the NAMES only; the argv lives on this machine and never travels (see "MCPStdio"). All of them default to EMPTY: with no flag the executor forwards nothing, hosts nothing and serves no MCP server. A machine volunteering to host other people's children because someone forgot a flag is the self-report-gates-placement shape the isolation and workspace_mode rules exist to forbid — unlike those two fields, which the executor does not report at all. skillsSync and pymodulesSync self-report the same way (see their Sync sections): each only narrows whether the daemon may push that corpus here, and both default to off.

sandboxMountRoots[], sandboxRelayDir and sandboxRelayVolume self-report the launcher's --sandbox-mount-root directories and its relay — --relay-dir or the foothold's --relay-foothold-image (see "Sandbox launchers"). Exactly one of sandboxRelayDir and sandboxRelayVolume is set on a launcher: an empty sandboxRelayVolume means no volume relay, and the daemon refuses a launcher that declares both or neither. They are safe to self-report for the same narrowing reason: the daemon uses the roots only to PRE-CHECK a requested host path, and the launcher re-checks every bind source itself, so a wrong entry costs a refusal, never access. A launcher that declares neither is simply not a sandbox launcher.

Health

Health() → { load, runningHandles[], diskFree, draining }

Unary. Liveness and load snapshot. runningHandles names every non-exited background job. It is a point-in-time snapshot of what is running, NOT how the daemon learns an exit happened: exits are pushed over WatchJobs (below), never polled.

Execute

Execute(callId, tool, inputJSON, timeout, expectMtime, background, workspaceId,
        autoBackground, owner)
  → stream { Output(chunk) | Result(content[], isError, observedMtime)
            | Failed(code, msg) | handle }

Server-streaming. Dispatches a single tool call. timeout (a Duration) bounds one tool call — unset or zero means no timeout, exactly as the old timeout_ms=0 did. workspaceId selects the workspace this call runs in — empty means the executor's own root, the pre-phase-08 behaviour kept as a compatibility path so an executor and a daemon of different vintages still interoperate.

timeout bounds a NON-auto call only. autoBackground (set for bash calls) makes the bash tool own the call's lifetime: a command still running at tools.BashPromoteAfter (60s, fixed) becomes a background job and the call returns the handoff, so the call ends there whatever the tool's own timeout argument says (the executor does not wrap the call in timeout when autoBackground is set). That argument, milliseconds, is instead a KILL deadline for the whole command, background time included (default 1h, capped at 24h; a call without autoBackground blocks and keeps the old bounds, 120s and 600s). The job registry arms it when the command starts and kills the process group when it expires: the job exits with code 124 (the GNU timeout convention), its output ends with [job killed: still running after its <d> timeout], and the exit is published like any other, so a stuck job always ends in a WatchJobs event. A deadline at or below 60s kills the command inside the call, which answers command timed out after <d> and was killed. A job started by background=true / bash_start has no deadline. A caller's timeout need only STRICTLY exceed tools.MaxBashTimeout: pkg/execpool's executorCallTimeout (tools.MaxBashTimeout + 30s) is the enforcement, and the 60s promote is always inside it.

owner is the daemon's id for the agent making the call, opaque here. It is stored on any job the call creates and rides every WatchJobs event for that job, so the daemon routes an event to the right child with no handle bookkeeping of its own.

The normal path is:

  1. The server checks expectMtime — if any path's current on-disk mtime does not match, it immediately streams Failed(CODE_DENIED, …).
  2. If background=true and tool=bash, the server starts the command as a background job and streams only the handle.
  3. Otherwise, the tool runs synchronously; the server streams Result{content[], observedMtime} on success or Failed{…} on error. An autoBackground bash call still running after 60s takes this same path with a handoff Result naming the promoted job's handle.

Result carries typed content, not a bare string. content[] holds ContentBlock entries that may be text or images — a read of a PNG on the executor returns an ImageBlock here, and the parent reconstructs it as image content rather than dropping it.

WatchJobs and AckJobExits

WatchJobs() → stream { JobRunning(handle, workspaceId, owner, command)
                   | JobExited(handle, workspaceId, owner, command, exitCode, finishedAt)
                   | ReplayComplete }
AckJobExits(handles[]) → {}

WatchJobs is the push channel for background-job lifecycle events — the notification path, where a poll used to be. ONE stream per daemon connection covers every job on the executor, and the executor carries each job's owner on its events so the daemon routes an event to its child with no handle bookkeeping of its own. On subscribe the executor first sends a JobRunning for every running job and a JobExited for every finished, retained, UNACKED one, then ReplayComplete, then live events. A subscriber that cannot keep up is ended with CodeUnavailable rather than silently skipped, and its resubscribe replays everything unacked.

AckJobExits (unary) tells the executor these finished jobs' exits have been delivered, so they stop being replayed and become eligible for byte-budget eviction. The daemon calls it only AFTER the exit's fragment has been handed to the event buffer, which persists it to the durable inbox — push before ack, never the reverse. An unacked finished job is replayed on every subscribe and is NEVER evicted, so a crash between the two costs a duplicate event (which the inbox coalesces while the first fragment is still pending), never a lost notification. A job the agent killed is acked at kill time by the executor itself (jobRegistry.kill), so its exit publishes no event to ack.

Undeliverable owners. The daemon pushes an exit only to an owner that can still receive it (jobDeliverable, cmd/rafikid/jobwatch.go: a known child whose status is not exited); an exit for any other owner is acked and dropped, because nobody is left to tell. That includes a recovered child during the window between daemon recovery and its asynchronous resume, when the store still reads exited: a replayed exit that lands in that window is dropped and acked, not held. The watch stream's first open waits for the recovery walk (Pool.HoldJobEventsUntil), which closes the earlier window in which no owner was loaded at all, but it does not wait for resumes.

Provision

Provision(childId, workspaceMode, mounts[], workdir, network, memoryBytes, cpus, env)
  → { workspaceId, roots[], workdir, isolation }

Provision prepares a workspace and returns the handle later Execute calls carry. A workspace is a handle bound to the filesystem the executor can see. The executor builds no container, so this call has no container spec to build from.

mounts, network and workspaceMode are therefore never sent by the daemon and ignored by the executor. A container is a sandbox, created by a launcher executor through its docker proxy (see "Sandbox launchers"), and it runs rafiki executor serve itself — so by the time the daemon calls Provision the filesystem already exists and the call only has to name a workdir. workdir is that exception. It is where this workspace's tools START, in the executor's own filesystem vocabulary, and the daemon sends the child's cwd. An empty workdir means the executor's root. A requested workdir must exist and be a directory in the executor's filesystem view; anything else is refused with CodeInvalidArgument rather than silently starting somewhere the child cannot write. Existence is the whole check — the workdir is NOT required to sit under the executor's root, because a native executor has no path confinement (bash reaches the whole machine, so an under-root check is not a boundary) and the git worktrees coordinators create beside a repository to isolate workers must keep working. For a container executor the same check is the proto's mount rule: a path that is not one of the container's mounts does not exist in the container's view, so it is refused here too.

The executor materializes one tool registry per workspace, with that registry's cwd set to the workdir: foreground bash starts there, the file tools resolve relative paths against it, background jobs start there, and the workspace's language servers (if any) root there. ProjectContext and ProjectSkills read the same workdir. What does NOT change with it: roots in the response stay the executor's own view of what the machine exposes, and isolation stays empty.

isolation in the response is deliberately empty, as it is in Describe. An executor does not know whether it is running in a container and must not guess: the answer gates where other people's children may run, so the authoritative copy is the isolation column on the executor's row, written by the operator at token-mint time. A daemon that reads it from here gets "none" for every child on every machine.

Release

Release(workspaceId) → {}

Unary. Tears a workspace down. Idempotent: a daemon restart that lost track of a workspace must be able to release it again without error. A released workspace kills its own background jobs — a job in a released workspace is not a job, and reporting it as running is worse than reporting it gone. It must not touch any other workspace's jobs.

ProjectContext

ProjectContext(workspaceId) → { contextFiles }

Unary. Returns the instruction files belonging to a workspace: CLAUDE.md and AGENTS.md at the git root and at the workdir, concatenated with a blank line between sections. An @include reference in any of them is expanded on the executor — it names a path on that filesystem, which the daemon cannot resolve — so the returned text is fully inlined, never a dangling @ line.

It takes a workspaceId, not a path, for the same reason Execute does: a request naming a directory would let the daemon — or anything that reached the executor — read instruction files anywhere on the machine. The workspace handle already scopes it. An unknown handle is CodeNotFound, answered rather than resolved against the executor's root, or the handle is a formality.

Empty contextFiles is the ordinary answer — most workspaces have neither file — and is not an error. It is a separate call rather than a field on ProvisionResponse because it returns content, and content is unbounded where a workspace handle is not: a large CLAUDE.md would make every provision pay for it. It is separate from Describe for a different reason — Describe is per-executor and this is per-workspace.

ProjectSkills and SkillBody

ProjectSkills(workspaceId) → { skills: [{name, description, dir}] }
SkillBody(workspaceId, name) → { body, dir }

Two calls rather than one, because an inventory is a handful of lines per skill while a body is a document — returning every body at spawn would put the whole project's skill text into every child. ProjectSkills is called at spawn; SkillBody on the turn the model actually asks for one.

Only the project tier is served. paths.SkillsDirs() is the daemon operator's own skill library, not the workspace's; discovering it on the executor would give a child two copies of every operator skill and let an executor's local library shadow the operator's. The two directories scanned are <cwd>/.claude/skills and <cwd>/.rafiki/skills.

SkillBody resolves by name, not by path. A path parameter would let anything reaching this executor read an arbitrary file — the same reason ProjectContext takes a workspaceId rather than a path. An unknown name is NotFound, not an empty body (which a model would read as a skill that exists and says nothing).

An empty inventory is the ordinary answer for a workspace with no project skills, and is not an error.

SyncSkills

SyncSkills(namespaces[{name, version,
            skills[{name, description, body, files[{path, mode, content}]}]}])
  → { written, pruned, skillsDir }

Unary. Delivers the daemon's skill corpus to the executor's Claude skills directory. Each namespace becomes one plugin-style directory holding skills/<name>/SKILL.md for every skill plus a generated .claude-plugin/plugin.json at the plugin root — Claude Code adopts the directory as a plugin, looks for that plugin's skills only under its skills/ subdirectory, and derives the <namespace>:<name> qualified name from the directory layout; nothing on disk is prefixed. The skill body has already had its frontmatter stripped by the daemon; the executor re-renders a frontmatter block from name and description when it writes SKILL.md. files are the skill's supporting files, written under the skill's own directory beside SKILL.md (path relative to that directory, /-separated, mode 0644 or 0755); the executor validates the whole set with the same rules the store applies — no absolute or .. paths, no path a directory of another, no symlinks, 1 MiB per file and 8 MiB per skill — before touching the filesystem, and a namespace whose staged tree is byte-identical to the live one is left alone. The response counts the namespaces written and pruned, and skillsDir echoes the directory the corpus actually landed in so the daemon can log it rather than guess.

The whole corpus, every time. namespaces is the COMPLETE set of rafiki-managed namespaces, and a namespace absent from it has its directory removed — whole-tree replacement rather than per-path bookkeeping, so there is no partial state to reconcile after a crash. Each namespace tree is staged in a sibling directory and renamed into place, so a claude child launching mid-sync never observes a half-written corpus; a tree whose staged content is byte-identical to the live one is left alone, so file watching stays quiet across a converged fleet's restarts.

The executor owns one directory per namespace and marks each with .rafiki-managed. The marker is what distinguishes "a tree we own and may replace" from "the operator's own skill directory" — ownership by marker rather than by a central manifest, because a manifest is state that can disagree with the filesystem and the disagreement is always discovered at the moment of an rm. An unmarked directory is never touched: replacing one is refused and pruning skips it. The existence check runs Lstat, not Stat, so a symlink planted in the skills dir is judged as itself and cannot redirect a RemoveAll anywhere.

Names are validated as path segments at BOTH the write and the delete site. A namespace or skill name becomes a directory on someone's machine: empty, ./.., anything containing /, \, : or NUL, and anything over 64 bytes is refused with CodeInvalidArgument before the filesystem is touched at all. The prune path re-validates names that came off the local filesystem — the delete call site does its own checking, always, because a check written once and far from the RemoveAll is the shape every directory-traversal bug in this class has taken.

The target is $CLAUDE_CONFIG_DIR/skills, else ~/.claude/skills. The resolution reads the executor's own process environment, which is exactly what a launched claude child inherits: executor.env/executor-overrides.env are applied to this process at startup, and AdminService.Launch passes the environment through to daraja — so pointing the corpus where this process looks is correct by construction rather than by agreement between components. It must not be a private directory: ~/.claude is where Claude Code keeps the OAuth credential --passthrough-auth depends on.

Opt-in per machine, and skills_sync on DescribeResponse is self-reported for the same narrowing reason as proxies and launchKinds: it only ever NARROWS what the executor will do. An executor answers CodePermissionDenied when the option is off, and a daemon reading false from Describe never sends a corpus to it. The option is on when the operator passed --skills-sync or set RAFIKI_EXECUTOR_SKILLS_SYNC, and it is also implied by --launch claude: an executor that hosts claude children needs the corpus, and a claude host with the sync off launches children that quietly see no rafiki skills — a failure the daemon cannot see and the operator reads as "skills are broken". --skills-sync=false still refuses explicitly, overriding the implication; the enforcement on the RPC remains regardless, because a daemon that ignored a false here would cost an unexpected write to the operator's machine, which is a worse failure than the failed launch a wrong launchKinds entry buys.

MaterializeSkill

MaterializeSkill(treeHash, files[{path, mode, content}]) → { dir }

Unary. Writes ONE stored skill's supporting-file tree into a content-addressed cache directory on this executor and returns its absolute path. treeHash is skills.TreeHash(files); the executor recomputes the hash from the bytes it was sent and refuses a mismatch with CodeInvalidArgument, which makes the returned directory name a proof of its own contents rather than a claim the daemon has to trust. The file set is validated with the same rules as SyncSkills (relative, /-separated paths, mode 0644/0755, no path a directory of another, 1 MiB per file, 8 MiB per skill) before anything is written, and a treeHash that is not exactly 64 lowercase hex characters is refused rather than cleaned.

The target is <paths.CacheDir()>/skill-cache/<treeHash>/. Cache and not Data: every tree there is reconstructible from the daemon's store. The root is marked with .rafiki-managed before first use; an existing root without the marker — or one that is not a directory — is refused CodeFailedPrecondition rather than adopted, because materialize and the sweep both RemoveAll beneath it. A tree is staged under a .rafiki-staging-* sibling and renamed into place, so a concurrent reader never observes a half-written directory; a rename that loses to a concurrent materialization of the same hash is success, since the target is content-addressed.

An already-present tree is reused with only its mtime bumped, so a warm cache costs a stat rather than a rewrite. Each call then sweeps trees and abandoned staging directories older than skillCacheMaxAge (7 days), keeping the tree just asked for; sweep errors are logged and never fail the call.

No opt-in flag, unlike SyncSkills: this writes only under the executor's own disposable cache, never into anything an operator owns. The daemon calls it when a fundi child invokes a database-backed skill that has supporting files — the same machine the child's workspace tools read — and the returned directory becomes the skill body's "Base directory". A child with no bound executor gets the body plus a note that the files are unavailable, never a directory that does not exist.

SyncPyModules

SyncPyModules(version, modules[{name, code}])
  → { written, pruned, venvResults[{name, ready, error}] }

Unary. Delivers ONE owner's pymodule corpus to the executor's disposable cache directory. Unlike SyncSkills this is owner-scoped at the source: the daemon resolves the executor's own Labels["owner"] username to a user id and sends only that owner's latest version of each saved module — an executor with no owner label, or one whose username does not resolve, receives nothing at all. Each module name is a bare Python identifier and lands at <name>/<name>.py inside the cache root — one directory per module, no per-namespace subtree, no plugin manifest, no frontmatter rendering; the payload has no namespace concept because a pymodule is a single file a script imports by name. The per-module directory exists so pymodule_run can execute the entry script — itself a synced module, run as <name>/<name>.py, never a workspace copy — and put the named modules' directories on PYTHONPATH for a run instead of copying files into the workspace. A module that declares a # pymodule-requirements: block has its per-module .venv's site-packages directory on PYTHONPATH too, and the entry script runs under its own .venv/bin/python3 when it has one; a module whose dependencies are not ready (requirements declared, venv absent — build in progress or failed) refuses the run with a clear error rather than executing against missing imports. The process's working directory is the calling agent's own workspace — or the call's own cwd, resolved like the file tools' paths (~, relative, absolute) — so a script sees the same relative world a bash call would, while which copy of the script runs is decided solely by the synced cache. Bytecode from imports lands inside the modules' own cache directories (__pycache__/): the prune sweeps at root level only, so it survives between runs — part of why the cache is the right home for the scripts.

pymodule_run's repo argument selects the source, and only local means this corpus. repo is required on the tool; repo="local" (the reserved sentinel for the blob store everywhere on the pymodule surface) runs a saved module exactly as described above. Any other value names a repo synced by SyncRepo (below): the script resolves to scripts/<script>.py in that source's checkout under <paths.CacheDir()>/repos/<repo>/commits/<sha> — a scripts/ layout, not the per-module directories above — where <sha> is whatever the repo's current symlink named when the call started, held for the duration (below); while each modules entry resolves to a top-level package directory of the same checkout, and the checkout ROOT itself always joins PYTHONPATH first, so a script's own intra-repo imports resolve without naming its packages. The interpreter is the repo's shared .venv/bin/python3 when that checkout has one, else the plain fallback — a repo whose venv build failed runs and fails visibly at import time rather than refusing. A repo's name never collides with local: registration refuses it.

The whole owner's corpus, every time. modules is the complete set for this owner, and a synced entry absent from it is pruned — same wholesale replacement reasoning as SyncSkills. Zero modules is a legitimate sync (an owner who has saved nothing yet): it empties the owner's cache directory, which is correct, not data loss. Each module is written to a sibling temp file inside its directory and renamed into place, and a module whose content is byte-identical to the synced corpus is left alone, so repeated syncs stay quiet.

**The target is <paths.CacheDir()>/pymodules, and the root is marked with a .rafiki-managed file before first use; an existing unmarked directory is refused with CodeFailedPrecondition rather than adopted, so rafiki never writes into — and its prune never sweeps — a directory it did not create. Names are validated as path segments before anything is written. The prune sweep adds no per-entry re-validation, unlike the skills prune: it runs against a root already verified managed and removes every entry absent from the corpus — a module directory via os.RemoveAll (which is also how a legacy flat <name>.py from the pre-directory layout migrates, and how a stray staging temp disappears), while a symlink entry is unlinked with os.Remove, never followed, so the sweep cannot reach outside the root. The skills prune re-validates per entry because its root is the operator's own ~/.claude/skills and a planted name matters there.

Each module's dependencies install into a per-module venv, and the response reports how that went. A module's requirements ride inside the code itself — a # pymodule-requirements: comment block parsed executor-side — so nothing about a module's dependencies travels outside its own source. The executor always builds and blocks on every sync; there is no wait flag. Each module directory's .venv is hash-gated with a .rafiki-requirements-hash file inside it: an unchanged hash skips the build entirely, and a changed one is rebuilt staged in a sibling temp directory and renamed into place only once it succeeded, so a failed rebuild leaves the previous working venv untouched. The response carries venvResults (repeated PyModuleVenvResult{name, ready, error}), one per module: ready is true when the module declares no requirements, built successfully, or was already up to date, and false only when requirements were declared and the build failed, with error naming why.

Two properties of that reporting are inherent rather than configurable. A build continues to completion even if the daemon's client times out — the timeout bounds the daemon's wait, not the executor's build, so the venv still lands and the next sync reports it. And results are reported only when the RPC itself succeeds: a failed or timed-out call carries no per-module outcomes at all, the same way written and pruned are absent from it.

Opt-in per machine, and pymodules_sync on DescribeResponse is self-reported exactly like skills_sync: it only ever narrows what the executor will do, an executor answers CodePermissionDenied when the option is off, and a daemon reading false from Describe never sends a corpus. The option is on when the operator passed --pymodules-sync or set RAFIKI_EXECUTOR_PYMODULES_SYNC. There is NO launch-kind implication — unlike skills there is no single launch kind pymodules correlate with, so an operator opts in explicitly; --pymodules-sync=false still refuses explicitly. The enforcement on the RPC remains regardless, for the same reason as skills: a daemon that ignored a false here would cost an unexpected write to the operator's machine.

ResolveRepoRef

ResolveRepoRef(name, url, ref) → { commit, error }

Unary. Resolves ref to a commit SHA on this executor, fetching url at ref into the source's bare repo first. The daemon asks ONE executor and fans the SHA out to the rest, so git runs only on executors, with their owner's own credentials, and two executors can never land different commits for one refresh.

Same gates as SyncRepo: the repo_sync option, validSegment(name), and refuseLeadingDash on both url and ref (a leading dash would make git parse the value as an option — git fetch --upload-pack=<cmd> executes <cmd> locally). The fetch names the URL explicitly rather than a configured remote, so a source whose url was repointed resolves the NEW repository's commit; the bare repo is created (git init --bare) if it does not exist yet, and git rev-parse --verify FETCH_HEAD^{commit} reads the answer back.

A git failure is REPORTED, never raised: error carries git's capped output and commit is empty, so the daemon can tell a bad ref from an unreachable executor. Resolutions of one source are serialised on the executor, like refreshes, because both write the same bare repo.

SyncRepo

SyncRepo(name, url, ref, commit)
  → { commit, checkoutError, scripts[{name, description}],
      packages[{name, description}], skills[{namespace, name, description,
      body, from, files[{path, mode, content}]}], skillErrors[],
      venvReady, venvError }

Unary. Refreshes ONE named repo onto the commit the daemon resolved, into <cache>/repos/<name>/:

<name>/git/             bare repo; every fetch lands here
<name>/commits/<sha>/   detached worktree per commit, own .venv
<name>/current          symlink -> commits/<sha> (relative)

Per-source, not whole-corpus: a repo's own history is already the versioning and pruning mechanism, so there is no "prune what's absent" model to replicate. One checkout PER COMMIT is what lets a running job keep its commit: a job resolves current to its real path when it starts and holds a shared flock on <dir>/.rafiki-inuse for as long as it runs out of that directory, so a refresh that moves current on cannot pull the sources or the venv out from under it. The hold is inherited by the launched child process, so it outlives the executor that opened it.

commit must be the 40-hex SHA ResolveRepoRef returned (CodeInvalidArgument otherwise — it becomes a path segment). The steps, in order: if current already resolves to commits/<commit>, skip straight to discovery (no fetch, no uv sync); otherwise fetch url at ref, verify commit arrived (git cat-file -e), create commits/<commit> as a detached worktree if it is absent (git worktree add --detach), build that checkout's venv, discover scripts/packages/skills, and only THEN flip current by renaming a freshly created relative symlink over it. current moving last is the contract: everything above can still fail, and a current naming a half-built checkout would hand the next job a broken tree.

A failed checkout is NOT an RPC error: the response carries checkoutError with the reason, commit names whatever is still current, and nothing changed on this executor. A commit the fetch did not bring reports commit <sha> not found after fetching <ref> rather than checking out nothing. Because a leading dash would make git parse the argument as an option rather than a value, both url and ref beginning with a dash are refused with CodeInvalidArgument before any subprocess runs, re-checked at the executor's own boundary. Git runs as an ordinary subprocess and inherits whatever ambient credentials the executor's environment already has; rafiki configures none.

Refreshes of one source are serialised per repo name on the executor: two concurrent ones would race on the bare repo's FETCH_HEAD and on the worktree they both want to create.

After the flip, a sweep removes every OTHER commit checkout that is both unheld (an exclusive non-blocking flock on its .rafiki-inuse succeeds) and older than 7 days (the directory's mtime, which every hold stamps). Removal is git worktree remove --force followed by git worktree prune; sweep errors are logged, never returned.

On a successful refresh, discovery is a plain walk (no manifest parsing): each scripts/*.py is one callable script and each top-level directory containing __init__.py is one importable package, each described by its first #-prefixed comment line. The scripts[]/packages[] in the response carry names and descriptions only, never the executor's own filesystem paths.

Skills are discovered against the SAME commit checkout, with that checkout's venv when it has one: the repo's own skill directories plus any [tool.rafiki] skill-sources distributions installed there. A skill is reported with its namespace, bare name, description, frontmatter-stripped body, where it was found (from), and its supporting files. Per-skill and per-source failures ride skillErrors and are never fatal — to the refresh or to the scripts.

The commit gets exactly ONE shared venv, <commits/<sha>>/.venv, built with uv sync run with the checkout root as its working directory — rafiki parses no manifest and lets uv figure out its own input. The manifest gate is file existence only, three-way: a checkout with neither pyproject.toml nor requirements.txt declares no dependencies at all, the build is skipped entirely and venvReady=true is reported with nothing invoked; a checkout carrying ONLY a bare requirements.txt — which uv sync cannot consume — reports venvReady=false with one clear sentence in venvError rather than promising a venv that was never built, its inventory still riding the same response as with any failed build. Otherwise the build runs staged in a sibling temp directory (via UV_PROJECT_ENVIRONMENT) using the same RAFIKI_PYMODULE_UV resolution and interpreter as blob-sourced venvs, and is renamed into place only once it succeeded; a failed build discards the staging tree, leaves any previous venv untouched, and reports venvReady=false with the capped output — while STILL returning the discovered inventory, because a broken dependency must not hide what exists (a broken build only fails the runs that actually need it). The unchanged-commit path does NOT re-run uv sync on a venv that is already there — "already there" meaning the interpreter exists — so a refresh of the same commit never pays for a rebuild. It does complete a build that never finished: with no interpreter, the same manifest gate and build run, so one transient failure cannot leave a commit venv-less until a new commit lands.

Opt-in per machine, and repo_sync on DescribeResponse is self-reported exactly like pymodules_sync: it only ever narrows what the executor will do, an executor answers CodePermissionDenied when the option is off, and a daemon reading false from Describe never sends a refresh. The option is on when the operator passed --repo-sync or set RAFIKI_EXECUTOR_REPO_SYNC. There is NO launch-kind implication — an operator opts in explicitly; --repo-sync=false still refuses explicitly.

Cancel

Cancel(callId) → {}

Unary. Terminates the background job named by callId. Does not wait for the process to reap.

JobOutput

One-shot poll of a background job. Never blocks.

Field Direction Meaning
handle → the handle returned by a background Execute
since → byte offset into lifetime output; pass back the previous total
data ← bytes from since to total, capped at 100 KB from the end
total ← bytes the job has ever written, including any not returned
exited ← whether the process has been reaped
exit_code ← meaningful only when exited
found ← false when the handle is unknown, or its output was evicted by the workspace's byte budget

WatchJobs tells you a job exited; JobOutput (the bash_output tool) returns what it printed. Use JobOutput for a snapshot read.

Tree and git sync

Five RPCs move files and git branches between executors. They are the data path behind the daemon's SyncPath/SyncRepo verbs (docs/reference/control-protocol.md → "Verbs"): the daemon resolves which executors a caller may name and relays between two of them, so on this side they are ordinary typed RPCs that carry no caller identity.

DescribeResponse.tree_sync (field 18) reports that this executor accepts ReadTree/WriteTree and the three Git* RPCs. It is a capability SELF-REPORT, safe for the same reason as skills_sync: it only ever narrows what the executor will do, so a wrong value costs a refused sync, never an admitted one.

ReadTree

ReadTree(ReadTreeRequest{path}) → stream ReadTreeResponse{oneof msg { TreeHeader header; bytes chunk }}
TreeHeader{is_dir}

Server-streaming. path must be absolute and clean and must name a regular file or a directory — a symlink path, or anything else, is refused InvalidArgument. The stream starts with exactly one TreeHeader, then carries a tar stream in 256 KiB chunks: a file is one entry named filepath.Base(path); a directory's entries follow, relative to it, and the root itself is not emitted. Symlinks are emitted verbatim (their targets are never resolved), and sockets, devices and fifos are skipped — they cannot be transferred and their contents would be meaningless on the far side.

WriteTree

WriteTree(stream WriteTreeRequest{oneof msg { WriteTreeStart start; bytes chunk }}) → WriteTreeResponse{files, bytes}
WriteTreeStart{path, is_dir, overwrite, optional max_bytes}

Client-streaming. The first frame must be a WriteTreeStart; path must be absolute and clean. max_bytes, when present, must be greater than zero — the field is optional precisely so an explicit zero is refused rather than read as "unlimited".

The tar is UNTRUSTED in this direction too: the caller may be a compromised sandbox and this side writes to a filesystem the daemon cares about. Every entry is validated before anything is created, and the transfer is extracted into a staging directory (os.MkdirTemp(parent, ".rafiki-sync-"), made 0755 and removed on every failure path) beside the destination, then renamed into place, so a failed transfer leaves the destination untouched.

Entry rules:

  • Absolute names, the empty name, a name resolving to the destination root, and any .. component are refused.
  • Only regular files, directories and symlinks are accepted. A hard link and every other type (device, fifo, socket, …) are refused.
  • safeJoin Lstats every ancestor component of an entry's path and refuses any entry whose parent traverses an EXISTING symlink — a symlink planted by an earlier entry must not become a way out of the staging directory. Symlinks are created verbatim and never followed while extracting.
  • Special mode bits are stripped: a regular file's mode goes to the kernel through unix.Open masked to 0o777, so a setuid/setgid/sticky tar mode never becomes a setuid/setgid/sticky file on disk. The executable bit is kept.
  • Directories are created 0o700 and chmodded to their header mode at the end, deepest first, so the deepest chmod is never locked out by a parent.

Resource guards count STREAM bytes — headers and padding included — not file content, so a flood of empty files, directories or symlinks cannot do unbounded disk work while the file counters never move. max_bytes caps that stream total, and the free-space floor is re-checked every 8 MiB of stream bytes.

Free-space floor. 256 MiB must be free on the destination's filesystem before extraction starts, and again every 8 MiB of stream bytes consumed; below it the transfer is refused ResourceExhausted.

A file transfer (is_dir false) must carry exactly one entry, and that entry must be a regular file.

Publish. Without overwrite, an existing destination is refused (FailedPrecondition) unless it is an EMPTY directory and the transfer is a directory. A file is published with a hard link — which cannot clobber — falling back to rename only after re-checking that the destination is still absent. With overwrite, the old tree is renamed aside (<parent>/.rafiki-old-<random>), the staged tree is renamed in, and the old tree is then removed; a failure before the final rename restores the old tree (and, if even that fails, the error names the stranded path).

The overwrite path guard (checkOverwritePath, pkg/executor/tree.go) runs only when overwrite is set. Every rule is applied to the symlink-RESOLVED path — the longest existing ancestor is EvalSymlinks'd and the non-existent tail re-joined — so a link pointing into /etc is judged as /etc, not by the link's own name. A path whose longest existing ancestor is a symlink with a missing target (a dangling symlink) is refused outright rather than judged unresolved.

  • At least two components. A destination with fewer than two path components is refused. Two is the floor, not three: /work/repo is a legitimate sandbox target, while /work and / are not targets at all.
  • Deny list. A path that IS, or is under, one of these top-level trees is refused: /bin, /boot, /dev, /etc, /lib, /lib32, /lib64, /proc, /root, /sbin, /sys, /usr, /var, /System, /Library, /Applications, /private, /Volumes, /Users, /home, /opt. The comparison is component-wise and case-INSENSITIVE, so a case variant on a case-sensitive filesystem cannot slip past.
  • Exemptions. A path strictly under the executor's own --root, strictly under the user's home, or strictly under the process temp directory (os.TempDir()) is exempt from the deny list — a denied prefix would otherwise cover /home, macOS's /private/var/folders, or an executor rooted under /usr. An exemption base must be a real subtree: / itself, and a base that IS one of the denied trees, do not exempt. The HOME base is stricter than the other two: homes legitimately live under /home, /Users and /root, so a home must be a STRICT descendant of one of them — /Users/<name> or /home/<name>, never /Users or /home themselves — while /root is also valid as root's own home. A home reached through any OTHER denied tree (macOS's /etc → /private/etc) is not a usable base, and a home strictly under the process temp directory is.
  • Root and home ancestry. The resolved path must not be the executor's root or the home directory, nor an ANCESTOR of either. Equality and ancestry are decided with os.SameFile where both paths exist — a case-insensitive filesystem or an alias cannot slip a path past — falling back to a string comparison when the protected path does not exist yet (a synthetic or uncreated executor root is still protected).

GitRefs

GitRefs(GitRefsRequest{repo}) → GitRefsResponse{exists, heads[{name, oid}], scratch_dir}

Unary. Reports whether repo is a git repository on this executor and, if so, its branch heads (git for-each-ref refs/heads) plus the executor's scratch_dir. An absent path, or one that is not a directory (Lstat, so a symlink is not followed), answers exists=false without an error — "there is nothing there" is a normal answer for a destination that is about to be seeded.

GitBundle

GitBundle(GitBundleRequest{repo, branch, exclude_oids}) → GitBundleResponse{up_to_date, bundle_path, bytes, tip_oid}

Unary. Writes one branch to a bundle file in the executor's scratch directory, skipping the objects named by exclude_oids (the objects the caller already has). If the branch tip is itself in the exclude set, or git refuses an otherwise empty bundle because every object it would carry is already a prerequisite, the reply is up_to_date=true with tip_oid set and no file. Prerequisites this repository cannot resolve are dropped before the bundle is created, so a caller may offer tips of a destination that is ahead of or unrelated to this source.

GitFetchBundle

GitFetchBundle(GitFetchBundleRequest{repo, bundle_path, branch, force}) → GitFetchBundleResponse{old_oid, new_oid, created_repo}

Unary. Fetches a bundle file into repo, creating it when absent. It is git's own fetch semantics: a checked-out branch is refused, and a non-fast-forward update is refused unless force. A fetch never touches the working tree of an EXISTING repository; a repository that does not exist is created with the branch checked out, with attribute filters disabled (info/attributes, below). It never reads the source's .git/config or hooks, and a bundle carries objects and refs only — every git call the executor makes runs under gitHardening and a fixed environment. The bundle is verified (git bundle verify, against a throwaway bare repository in the scratch directory, with the destination's object store attached as an alternate when there is one) BEFORE anything is created, so a corrupt bundle cannot leave a half-created destination behind. A non-empty directory that is not a repository is refused, never initialized over. The bundle file is consumed exactly once and removed whatever the outcome.

Git hardening and scratch handling

Every git operation is a typed RPC invoked with an ARGV array — never a shell and never a string concatenated into one argument. Values are validated before any subprocess runs: a leading-dash branch/url/ref is refused (git would parse it as an option), a branch name must be accepted by git check-ref-format --branch (and may not be empty, HEAD, or contain the reflog syntax @{), an object id must be 40 or 64 lowercase hex characters, and a repo must be an absolute, clean path whose final component is not a symlink (GitFetchBundle may create an absent one).

Every invocation is prefixed with gitHardening — -c core.fsmonitor=false, -c core.hooksPath=/dev/null, -c protocol.allow=never, -c protocol.file.allow=always (the bundle is a local file), -c protocol.ext.allow=never, -c core.sshCommand=false, -c core.alternateRefsCommand=true — as defense in depth against a hostile .git/config in a repository the executor did not create: a repository's own configuration must not run a hook, an fsmonitor program, or a remote transport helper. Each option is pinned by a test that fails when it is removed (pkg/executor/git_sync_test.go).

The subprocess environment forces LC_ALL=C (locale-independent messages) and GIT_TERMINAL_PROMPT=0 (git can never block on a terminal that does not exist), and nulls the receiver's own git configuration with GIT_CONFIG_GLOBAL=/dev/null, GIT_CONFIG_SYSTEM=/dev/null and GIT_CONFIG_NOSYSTEM=1, so a filter driver or rewrite defined there cannot be selected by content the sandbox prepared. Any conflicting entry for these names and GIT_CEILING_DIRECTORIES is dropped from the pinned base first.

A repository GitFetchBundle creates gets info/attributes containing * -filter -ident -working-tree-encoding before the checkout. It outranks the .gitattributes that arrives with the checkout, so the source cannot select a filter driver, and the bundled bytes are written unchanged. Line-ending attributes (text, eol) are left to the source.

Repository discovery is fenced by GIT_CEILING_DIRECTORIES=<dir of repo>, so a SUBDIRECTORY of a repository cannot be mistaken for one. The ceiling is defense in depth; the authoritative guard is the ownership check: the discovered git directory (via --absolute-git-dir) must be <repo>/.git or <repo> itself, or the working-tree root (--show-toplevel) must BE repo — which is how a LINKED WORKTREE, a git SUBMODULE or a separate-git-dir checkout counts as a repository. Objects for such a checkout are resolved through --git-common-dir, since the worktree's own git dir has no objects/.

Fetches run with -c transfer.fsckObjects=true, so a bundle whose objects fail git's own fsck is refused.

Scratch directory. Bundle files live only in <os.TempDir()>/rafiki-sync, created 0700 and swept on every call. It refuses to adopt anything it did not create: Mkdir (not MkdirAll) makes a pre-created path visible, a symlink or non-directory is refused, and the directory must be owned by this executor's effective uid, so a shared /tmp cannot have another user plant the path. Every call sweeps regular *.bundle/*.bundle.lock files and .verify-* directories older than one hour; other names are left alone, so a caller's own bookkeeping survives.

AdminService: Launch, Reap and Status

rafiki.admin.v1.AdminService is the machine-admin surface: starting and ending daraja hosts. It is deliberately NOT part of ExecutorService — the executor is a data path for one child's filesystem and shell tools, with its own lifecycle hazards, while a daraja outlives both the turn and the connection that asked for it. The two services share the executor's process and its reverse-dialled connection and nothing else: AdminService mounts on the SAME mux as ExecutorService, so one connection reaches both. Like the capability it serves it is opt-in — an executor started without --launch mounts no AdminService at all, and neither do the short-lived enroll and session-executor surfaces, which host nothing by construction.

Launch

Launch(childId, cwd, spec: rafiki.daraja.v1.ChildSpec, dialAddr, ticket string)
  → { pid, pgid }

Starts one rafiki daraja serve, re-executed from the executor's own binary, hosting one child. spec is typed rather than raw argv because the executor and daraja would otherwise each need an argv builder on opposite sides of an RPC; both call pkg/claudeargv instead.

dialAddr is a host:port or Unix socket path that daraja dials back to the rafikid that asked for it — the reverse-dial pattern replaces the 1b-i direct connect where the caller dialled a socket path returned by the response.

The executor does NOT simply trust dialAddr. It is the daemon's own guess at an address reachable from the executor's machine, derived from whatever the daemon binds its control listener on (RAFIKI_CONTROL_LISTEN) — a BIND address, not necessarily a reachable one. Behind a reverse proxy, a k8s Service, or anywhere the daemon's public address differs from its bind spec, that guess is wrong (a daemon bound on bare :8036 sends :8036 as dialAddr, which resolves on the EXECUTOR's own machine, not the daemon's). The executor is, at the moment it handles a Launch, already connected to the daemon via its own --connect/--connect-socket — an address proven reachable, needing no new configuration — so it tells the daraja it spawns to dial THAT instead (AdminOptions.ConnectAddr/ConnectSocket), falling back to dialAddr only for an executor built before this existed.

ticket is a one-shot credential delivered via environment variable (RAFIKI_DARAJA_TICKET, never argv — ps visibility is why). It is replaced by a durable credential on first successful connection.

ChildSpec.ClaudeParams also carries Phase 2's passthrough-billing fields — proxy_url, proxy_token, passthrough_auth, auto_compact_window, record_requests — all LAUNCH-ONLY (daraja reads them once, at its own process startup, to build the environment proxyenv.ClaudeEnv produces; a later Restart's spec may leave them unset and daraja ignores them there, since env is fixed for a daraja process while only argv is rebuilt per restart). The executor forwards the four non-secret ones as daraja serve flags (--proxy-url, --passthrough, --auto-compact-window, --record-requests) and, for proxy_token alone, via environment (RAFIKI_DARAJA_PROXY_TOKEN) — the same ps-visibility treatment the ticket gets, and for the same reason.

workspace_tools ("rafiki", or empty/"native" — the daemon resolves the mode before the spec is built, so the empty spelling only reaches here when the child kept its built-ins) is the opposite: it is ARGV-shaped, so the executor forwards it as --workspace-tools and daraja re-reads it from every Restart's spec. It disallows Claude Code's local-effect built-ins — Bash, Read, Write, Edit, NotebookEdit, LSP, EnterWorktree, ExitWorktree — inside the same single --disallowedTools element that already carries AskUserQuestion, and joins the workspace paragraph to the coordination prompt (claudeargv.RafikiWorkspaceDisallowed, claudeargv.RafikiWorkspacePrompt). A restart that dropped it would hand the built-ins back to a child whose MCP replacements are still served, with nothing reporting the swap. Its one ENVIRONMENT half is ENABLE_TOOL_SEARCH=false, forced by proxyenv.ClaudeOptions.EagerTools at daraja's own startup and REPLACING any inherited value: a rafiki-mode child must never be offered deferred tool search, or the tools it must now call are the ones omitted from tools[].

Setpgid makes daraja a group leader and claude joins the group (daraja spawns its child with SpawnSpec.InheritProcessGroup, opting out of the runner's default own-group). pgid is therefore the one handle that reaches the whole child for its whole life: restarts stay in the group, and one kill(-pgid) still reaches a claude orphaned by a SIGKILLed daraja — darwin has no subreaper, so the orphan reparents to launchd and the group is what covers it, not any wait by this executor.

Refusals:

Condition Code
empty childId InvalidArgument
kind other than claude or script InvalidArgument
kind not declared with --launch FailedPrecondition — the operator's declaration wins
childId already hosted here AlreadyExists

A script kind is hosted like a claude with a different payload: the spec carries the pymodule names, not resolved argv — the EXECUTOR resolves them against its own synced corpus before daraja starts, and the resolved interpreter and script path arrive as the daraja process's binary and positional args (there is no claude-style argv builder to reconcile). The host's drain differs by kind, and the difference is a script's last output: claude's stderr is drained and discarded (its protocol is stdout), but a script's stderr is relayed — its tail is what a failed settle carries — and the host waits (bounded by pumpDrainGrace, 500 ms, the same bounded-drain shape as the executor's stderrDrainGrace) for BOTH stdout and stderr pumps to reach EOF after the process is reaped BEFORE emitting Exited. Without the wait the host would emit Exited while the pumps still hold unread pipe data, and a relay consumer that stops reading on Exited would lose a hosted script's final output — typically a failure's traceback — and with it the settle's stderr tail. The bound keeps a wedged pump from delaying the exit forever.

pgid is NEVER taken from the request: a process group id is recycled once its group empties, so signalling a number a peer handed over could reach an unrelated group. Reap resolves the pgid from this executor's own launch table, and drops the entry when daraja exits — which is what makes a later Reap against a recycled pgid answer reaped=false instead of signalling a stranger.

Reap

Reap(childId, grace) → { reaped }

Ends one launched daraja and its child: SIGTERM to the process group, wait out grace (a Duration; unset or zero means the server default, 3s — matching daraja's own stopLocked rather than inventing a second escalation policy), then SIGKILL the group. An unknown childId returns reaped=false, NOT an error — reaping something already gone is the normal case, so Reap is idempotent.

Status

Status(childId) → { known, running, exit_code?, stderr_tail }

Unary. Reports whether this executor launched a daraja for childId and — once that daraja has exited — how: an unknown childId answers known=false (NOT an error, like Reap), a live one answers known=true, running=true with exit_code unset, and an exited one answers known=true, running=false with exit_code set (negative when it was killed by a signal) and stderr_tail carrying the last 4 KiB of the daraja process's stderr — the connection-failure diagnostics it logged on the way out.

The record outlives the process on purpose. The launch entry is dropped when daraja exits so a recycled pgid is never signalled, but the Status record survives, because the daemon's launch wait (darajapool.Launch) polls Status every second alongside the connect signal: a daraja that died before its reverse dial arrived ends the wait at once with exited (code N) before connecting: <stderr_tail> instead of burning the full launch timeout on a machine that will never dial back. A later Launch of the same childId replaces the record; a refused Status poll (an old executor answers Unimplemented) is logged once and the wait continues on the connect signal and the timeout as before.

The wait's timeout arm may overshoot by up to statusCallTimeout (2 s): the select blocks for the whole Status call, so a connect signal that lands (or the timeout itself) is only serviced once the in-flight poll returns. An already-landed dial can therefore be observed up to 2 s late; the launch timeout itself can run the same 2 s over. The tail errs the other way on purpose: the executor stamps running=false only after its stderr relay has drained the pipe (bounded — the daraja's claude can inherit the write end and hold EOF off), so the first exited answer already carries the daraja's last lines.

The socket field is retired

1b-i returned LaunchResponse.socket — a Unix path for the caller to dial directly into DarajaService. 1b-ii replaces that with a reverse-dial pattern: the caller passes its own address as dialAddr on the request, and daraja dials back. The socket field (number 3) is reserved and no longer served.

Wire break in 1b: RestartRequest

RestartRequest.spec (typed ChildSpec) replaced RestartRequest.argv in 1b. A 1a client speaking raw argv is incompatible with a 1b daraja.

MCPStdio

MCPStdio() ⇄ stream { start{name} | stdin(bytes) }
                 → stream { started{pid, program} | stdout(bytes)
                          | stderr(bytes) | exit{code, signal, stderr_tail} }

Bidirectional streaming. Hosts ONE declared MCP server process for ONE client session and relays its stdio. This is how an MCP server that only exists on a workstation reaches a child of a cluster daemon: no TCP listener, no new credential, no new allowlist on the network — just the connection the executor already holds.

The executor relays BYTES and never speaks MCP. stdout is opaque and the caller frames it; stderr is opaque and is never parsed as protocol. Same principle as the HTTP relay: rafiki does not care what protocol an endpoint speaks, only that it can reach it.

The argv lives on the executor. The request carries a NAME, and the name is checked against Options.MCPCommands — the operator's --mcp-command name=argv… declarations — BEFORE anything is spawned or even stat'd. The matched process runs under the executor's own environment and --root working directory (which IS the executor's process working directory unless the operator passed --root), never the daemon's: credentials live on the machine that holds them, and nothing secret travels to the daemon. A compromised daemon gains the ability to name a declared command, and nothing more — no argv, no env, no cwd, and no way to run an undeclared binary.

The declared grammar is whitespace-separated words with a backslash escaping a space, a backslash or a quote. No shell is involved, so a glob or $(…) in an argument is literal text.

Framing rules.

  • start is exactly once, first. A stream whose first frame is not start, or whose start arrives twice, is a protocol violation and ends with an error — the daemon is the only caller, so it is a bug loud enough to name.
  • started is exactly once, first in the response. A dial that cannot spawn fails on the stream instead, so the caller learns why BEFORE it begins its handshake.
  • stdout chunks are flushed as they arrive (32 KiB reads); the executor never buffers to a line, because it does not know where lines are.
  • stderr is a first-class channel rather than a debugging afterthought, and it never backpressures stdout: a stderr frame whose send would stall is DROPPED rather than queued behind it, so a chatty server cannot deadlock a tool call. A 4 KiB ring buffer (the same cap as Status's stderr tail) is the record that survives, and it is what exit.stderr_tail carries.
  • Half-closing the request stream closes the process's stdin.
  • exit{code, signal, stderr_tail} is last when the process ends while the stream is open; code is −1 when a signal killed it.

Lifetime: one process per stream, killed on stream end. The process leads its own process group (Setpgid), so a server that forks (npx, a shell wrapper) dies whole; stream end — the daemon disconnecting, the child being killed, a pod rolling — is SIGTERM, wait out child.TermGrace, then SIGKILL to the group, the same escalation AdminService.Reap uses. No MCP server outlives the session that asked for it, and nothing is restarted inside an open stream: a fresh process has no MCP session (the initialize handshake and any session id belong to the process that died), so a restart is always a new stream.

The group is swept when the leader exits, not only when the stream ends: a server that forks a helper and then exits would otherwise leave the helper holding the pipes for the rest of the session. The sweep is SIGTERM, a short grace, SIGKILL, and an empty group costs one ESRCH.

No signal is ever sent after the process is reaped. A pgid belongs to this executor only while the group's leader is unreaped — once it is reaped the kernel may hand that pid to a new process, whose group is somebody else's. Every kill therefore happens either before Wait returns or immediately after it, and the stream-end watcher is stopped the instant the wait completes rather than being left able to fire during the exit drain.

Spawn budget (crash-loop guard), per declared NAME across the whole machine — a shared laptop can have ten children retrying at once:

  • a spawn that fails to start, or whose process dies within 5 s, counts as a failure;
  • a process that ran longer than that and then died resets the record (an hourly crash is not a crash loop);
  • 3 failures within 60 s refuse new spawns for 60 s, answering with the last stderr tail;
  • at most 8 concurrent streams per name;
  • a kill this executor performed is neither a failure nor a success — it leaves the record exactly as it was. Otherwise three ordinary child shutdowns inside a minute would quarantine a perfectly healthy server for the whole machine.

This is the half of supervision the daemon cannot do: it sees one child's dials, the executor sees the machine's.

A url server needs no new machinery. It is dialled through the executor's existing HTTP relay (--proxy), whose meaning is deliberately protocol-agnostic: "an HTTP endpoint this executor will forward to". A request for / is served by the base URL as declared, path and all, so --proxy codescan=http://host:8080/mcp reaches /mcp rather than /mcp/.

Credentials. A stdio MCP server takes its credential from its process environment, and here that environment is the executor's own — readable at /proc/<pid>/environ by any same-uid process on that machine, including the agent's own bash. That is accepted: an executor holding the workspace already holds the source, .git/config, .env, and on a laptop the operator's SSH keys. A url server's headers travel over the relay instead, because the entry's Authorization is the server's own credential and the daemon is what holds it.

What a reconnect cannot change. MCP discovers tools at initialize, but a child's tools[] is fixed at build because the tool block sits inside the prompt-cache breakpoint. A redial that returns a different tool list therefore cannot add to it: tools that vanished return is_error, tools that appeared are ignored until the child restarts.

Keepalive is for legacy handshakes only. The daemon pings a server every 30 s and tolerates one miss, which is the one failure neither side can otherwise see: a process that is alive and holding its pipe. MCP removed ping in protocol 2026-07-28, and the SDK starts keepalive only on the legacy initialize handshake, so against a modern peer no pings are sent and a wedged server is caught by the call's own deadline instead. The option stays set: it is exactly right for an older server, which is the population most likely to wedge.

Failures are not retried when the process exit was OBSERVED DURING THE CALL. The daemon's session retries once on an ambiguous transport death, but an exit frame means the executor saw the process end, and replaying a possibly non-idempotent tool against a server that just died is a side effect the model must see rather than a hiccup to paper over. The call fails with the exit status and the stderr tail, the session is dropped, and the next call redials.

"A server that died while its session sat idle" is NOT that case: the exit record was already there before the call began, so the call redials silently and the agent never learns of it. The record is read before the call and consulted on the same transport afterwards, which is also what keeps a concurrent redial from answering for a failure on a different session.

An executor too old to serve it says so. An Unimplemented answer to MCPStdio is reported as a version gap naming the executor — not as a broken MCP server — so an operator upgrades the laptop rather than debugging a config.

Installing over ssh

An executor can be put on a machine that has never enrolled, through a machine that already has. The daemon never runs ssh: it asks a LAUNCHER executor it already trusts, over the executor connection it already holds (pkg/executor/remote_ssh.go, cmd/rafikid/executor_install.go). The launcher is trusted with the target's traffic exactly as far as it is already trusted with the ssh keys to it.

An installed executor is a durable row — an ordinary conversations.executors row, written by the daemon with isolation=none, workspace_mode=pinned, the --root it was given, and the daemon-written rafiki/installed-via / rafiki/installed-target labels — plus one row in conversations.executor_install (migration 0070): the launch RECIPE, holding the launcher, the ssh destination, the target's executor instance, the root and the remote platform. Executor rows hard-delete, so the recipe is what is TOMBSTONED (removed_at); one live recipe per executor id is a unique index. Nothing the target reports gates access: the probe chooses a binary and refuses a clobber, and decides nothing about who may use the result.

A relaunch always needs the launcher; the mode decides whether the RUNNING executor does. The relaunch is lazy — no fleet of idle ssh sessions is kept — so a down installed executor is still a name a caller may pass, and the first call that needs it opens the ssh session, records a one-time note on that call, and waits for the connection to ARRIVE (the pool's on-connect hook, never a poll). In tunnel mode that ssh session IS the executor's lifetime, so a launcher that sleeps takes the executor with it; in direct mode the ssh has ended long before and the detached process keeps dialling the daemon on its own.

Direct or tunnel: the transport is chosen once

An installed executor reaches the daemon one of two ways, and the RECIPE stores which (conversations.executor_install.mode, migration 0072; a row written before the column existed reads as tunnel, because that is how it behaves):

Mode What runs on the target Lifetime
direct a detached executor serve --ticket-stdin --detach that dials the daemon over TLS itself, with the credential its first ticket minted its own: a launcher that sleeps, restarts or disconnects leaves it running. A reboot or VM reset kills it, and the next call's lazy relaunch starts a fresh one
tunnel executor serve --stdio, whose stdio RemoteServe relays into Pool.ServeConn that ssh session, and no longer — the launcher is in every byte's path

direct also answers a diagnostic question: a detached process leaves only a file, so a failed launch is reported with the target's own executor.log tail instead of the relay's silence.

auto is a request spelling, never a stored value. InstallExecutor's mode is ""/auto, direct or tunnel, resolved once at install by one decision function (chooseInstallMode, cmd/rafikid/executor_install.go): only reach=yes from the probe chooses direct; reach=no and reach=unavailable fall back to tunnel; a requested direct the target cannot satisfy is refused with the probe's own detail, naming mode=tunnel as the alternative; a requested tunnel is always accepted. The choice is written to the recipe, and a RELAUNCH reads it rather than re-probing — a changed network is an operator's reinstall, and a reinstall does re-probe.

A launcher built before these RPCs answers Unimplemented. Under auto the install falls back to the relay and records tunnel; under a requested direct it refuses and names the machine that has to be upgraded.

A direct launch's ticket mints the credential the process will reconnect with. Pool.authorize's Ticket branch, for a row-bound grant flagged MintCredential (set only by the install path), rotates the row's credential and returns the new one on the 101's Rafiki-Credential, exactly as enrollment does. The ticket is CLAIMED atomically, never consumed up front, and committed only once the connection is admissible AND the credential is minted. The claim is what makes a replay harmless — two connections presenting one ticket cannot both get past it, so exactly one can rotate the credential, and a second rotation can never invalidate the plaintext the winner was just handed. The claim is BOOKED, not spent: a refusal anywhere before the commit either hands it back for a retry (a store outage resolving the row, a failed rotation, a 409 against a healthy incumbent) or drops it when retrying cannot help (the row is gone or disabled), so no retryable failure can strand an executor. Three consequences to keep: every relaunch mints a new credential and invalidates the previous one, so a credential found on the target belongs to the current launch and is never a durable identity (the ROW is that); a spent ticket is a terminal 401, never a retry; and a ticket REVOKED while a connection holds it is refused at the commit — revocation wins over an in-flight claim, or a launch the daemon abandoned would connect anyway.

Who may launch

Any NATIVE executor — one whose row's isolation is not container — by default: the capability equals what bash on that machine can already do. A container-isolated executor is never a launcher (it has no ssh keys of its own), and a disabled executor is refused (disabling is a revocation). Those two are one gate, run at install time AND on every relaunch, because the facts are live.

A child credential may install only through a launcher in its own reachable set (the child's own executor set) and its default launcher is its home executor, else its launch host, else the single native executor it can reach. A user credential (or the local socket) names one with via, and otherwise takes the single native executor it owns. Several candidates and no via is an error listing them: a launcher is never guessed.

The ssh itself

The option set is fixed, always and only:

-T -o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=15 -o ServerAliveCountMax=3

There is no host-key option, ever. ProxyJump, User, keys, Include and host-key policy all come from the launcher's own ssh config, because that is the operator's trust decision, not the daemon's. A refusal returns ssh's stderr verbatim (bounded): an agent reading Host key verification failed knows the fix, and an invented summary would replace that knowledge with nothing.

Every remote command is built from TYPED request fields and quoted for a POSIX shell; no caller-supplied text becomes shell syntax. The one exception is the $HOME prefix of binary_path, which the remote shell expands and whose remainder is quoted like any other value. Validation refuses what could not be meant: a destination starting with - (it would be read as an ssh option), whitespace or control characters in a destination, a binary_path outside the content-addressed cache, an install_id outside [A-Za-z0-9_-]{1,64}, a non-absolute root, and an instance name that fails paths.ValidateInstance.

The target's login shell must be POSIX sh. The remote scripts use ${XDG_DATA_HOME:-$HOME/.local/share}, [ -f … ] and uname -sm; under a csh or fish login shell they fail opaquely — the probe's output is parsed, so a syntax error surfaces as a malformed answer rather than as a shell problem.

The six RPCs

RemoteProbe(RemoteTarget{destination, instance}, binary_path) →
    { uname, binary_present, credential_present, marker, reach, reach_detail }

RemoteInstall(stream { header{target, binary_path, sha256} | chunk(bytes) }) → {}

RemoteServe(stream { start{target, binary_path, root, install_id} | stdin(bytes) }) →
    stream { started{pid} | stdout(bytes) | stderr(bytes)
             | exit{code, signal, stderr_tail} }

RemoteClean(RemoteTarget{destination, instance}, install_id, stop_process) →
    { removed, stopped }

RemoteLaunch(stream { start{target, binary_path, root, install_id}
                    | stdin(bytes) }) → { state, pid }

RemoteLogTail(RemoteTarget{destination, instance}, lines) → { tail }

RemoteProbe is ONE ssh whose script prints exactly four lines (uname=, binary=, cred=, marker=), or those four plus two reach lines; any other shape is refused with the raw output rather than half-parsed. marker is the first line of <data dir>/installed-executor, empty when absent.

reach is the target's own answer to "can I dial the daemon?" — yes, no, or unavailable — and reach_detail is one line: the tool that answered (via curl, via bash, via nc), that tool's first stderr line when it could not, or why the question was never asked. The address is the LAUNCHER's own (executor.Options.ConnectAddr, its --connect): it is never a request field and never travels through the daemon. A launcher with no dialable address answers unavailable from the four-line shape; one whose address is not a plain host:port answers unavailable with the address named, because nothing about that address is rendered into a remote script.

On the target the probe tries the first of curl (5s bound, no -k: a remote executor dials with the system roots only, so a certificate curl cannot verify is one the executor cannot use either — and any HTTP answer counts), bash's /dev/tcp under timeout (it has no connect timeout of its own), and nc -z -w 5, reporting which one answered.

RemoteInstall pipes the binary to the target over the SAME ssh channel: no scp, no sftp, no internet on the target, and no copy kept by the launcher. The first frame is the header and every later frame is a chunk of the binary on ssh's stdin; the remote writes a temp file, verifies the sha256 it was given, chmod 0755s it and renames it into place, removing the temp file on any failure. A torn or corrupted stream therefore leaves no file at binary_path.

RemoteServe runs executor serve --stdio on the target and relays its stdio unparsed — stdout is opaque protocol bytes, stderr is opaque diagnostics. started{pid} is first in the response; stdout is flushed as it arrives; stderr never backpressures stdout (a frame that would stall is dropped, a 4 KiB ring is the record that survives and it is what exit.stderr_tail carries); exit{code, signal, stderr_tail} is last, and code is −1 when a signal killed it. Half-closing the request stream closes the remote process's stdin. One process per stream, in its own process group, swept the instant the leader is reaped, so nothing it forked outlives the session.

RemoteLaunch starts a detached, self-dialling executor. The frames are one start, then exactly ONE stdin carrying the install ticket line — the only place the ticket travels, which is why a second stdin frame is refused before any ssh runs (two tickets would mean two remote executors and one spent credential). One ssh runs <binary> executor serve --connect <addr> -P <instance> [--root R] --install-id ID --ticket-stdin --detach, with addr again the launcher's own ConnectAddr; a launcher that has none refuses FailedPrecondition, because it has nothing to hand a self-dialling executor. That command's stdout must be exactly one line — started pid=<n> or running pid=<n> — and anything else is refused with the raw output. Every byte of text this call returns is scrubbed of the ticket first (ssh's stderr, and any raw output quoted in a parse error), since a target's shell can echo what it read.

RemoteLogTail returns the last lines of <data dir>/executor.log — lines 0 means 40, the request is clamped to 1..200, and the answer keeps the log's END (16 KiB at most), which is where the failure is. A target with no log answers the sentinel (no executor.log) rather than an error: the launch that produced it may be exactly the one that failed before writing anything.

RemoteClean removes <data dir>/installed-executor iff its first line is this install's id, and answers removed=false otherwise; a marker naming another install leaves that install's process, pid file and credential alone and prints neither word. The shared binary cache is content-addressed and is left alone.

With stop_process it stops that same install's detached executor FIRST, under the same marker match, and answers stopped. The rule, as implemented (remoteStopScript, pkg/executor/remote_ssh.go):

  • A pid is not an identity. Before anything is signalled, ps -o command= -p <pid> must show THIS install's id, which the detached child carries in its --install-id argv; a ps that cannot answer, prints nothing, or prints somebody else's command line is no evidence at all. Nothing is signalled, no file is touched and neither word is printed.
  • The pid comes from <data dir>/executor.pid and must be 2..9999999 — a 0-leading or non-numeric value, 0 or 1 is no pid at all, because kill -TERM -0 would signal the remote shell's OWN process group and kill -TERM -1 every process the remote user may signal, this ssh session included.
  • The signal goes to -pid (the whole group) only when ps -o pgid= says that pid IS its group's leader — which a detached executor, setsid'd, always is. Everything else is signalled as a plain pid, and a ps that cannot answer is no evidence of a group: nothing here guesses.
  • TERM, then up to 10 polls 0.5s apart, then KILL and the same again. A process that is already gone — one kill -0 cannot find, or one ps -o stat= calls a zombie — needs neither: a defunct process holds a pid without doing work, and waiting one out would leave the target unreinstallable.
  • stopped is printed, and executor.pid/executor.cred/executor.lock removed, only once the process is confirmed gone. A stop that is not achieved removes NOTHING — not the credential, not the lock, and not the marker, whose first line is the only file that names which install the leftovers belong to — and the target reports neither word. Telling the daemon an executor stopped while it is still running is worse than saying nothing, and an orphaned credential beside a removed marker leaves the next install's clobber guard with nothing to name.

Residual, recorded rather than eliminated: the identity is checked before the signal rather than atomically with it, so a pid that exits and is reused in the moment between those two ps calls can still be signalled. That window is what the identity check narrows the problem to; a stale pid file is no longer sufficient on its own.

executor serve --stdio

The launcher starts the installed binary on the target as

exec <binary> executor serve --stdio -P <instance> [--root <root>] --install-id <id>
  • The ticket is the FIRST LINE of stdin, at most 256 bytes, and never in argv: argv is visible in ps on the target, and a ticket is a credential for as long as it is unused. A ticket is minted per launch, is bound to the executor's durable ROW (the pool reads the row for every gating fact, so a disabled row is refused 401 even with a valid ticket), and is revoked on every way out of a launch that is not a connection.
  • stdout carries only the protocol. The logger is pinned to stderr before anything can log, because a log line on stdout is read as a frame and kills the session.
  • --install-id is required (the remote records it in the marker) and --stdio refuses --connect, --connect-socket, --credential, --credential-file and --enroll-token by name: a stdio executor has no daemon address and no durable credential of its own. Skills, pymodules and repo sync are off — being installed is not a grant to rewrite the machine's Claude corpus or its caches.
  • The marker (<data dir>/installed-executor, mode 0600, written through a temp file and a rename) is written from the request handler, so it appears only once a request has been served — i.e. only after the upgrade succeeded. A process that never connects leaves the target looking empty, which is the truth.

executor serve --ticket-stdin --detach

exec <binary> executor serve --connect <addr> -P <instance> [--root <root>] \
    --install-id <id> --ticket-stdin --detach
  • It reads ONE ticket line from stdin (at most 4096 bytes) and presents it as Authorization: Ticket on the FIRST connect only; every later connect is Bearer, with the credential the daemon returned on the 101, persisted to --credential-file (default <data dir>/executor.cred — deliberately NOT under --root, where the executor's own file tools could read it).
  • --connect and --install-id are required, and it refuses --stdio, --connect-socket, --enroll-token and --credential by name: a ticket authenticates a TCP dial, and enrollment creates a row while a ticket redeems one that already exists.
  • --detach takes a non-blocking flock on an open descriptor of <data dir>/executor.lock BEFORE it reads stdin. Held ⇒ an executor is already running here: it prints running pid=<n>, reads no stdin (so no ticket is spent), and exits 0. Otherwise it reads the one ticket line, re-execs itself (setsid, stdin /dev/null, stdout and stderr appended to <data dir>/executor.log, rotated to executor.log.1 at 4 MiB), handing the child the ticket on an inherited pipe (fd 3) and the locked descriptor (fd 4) — never argv, never the environment, both of which are world-readable on the target — records <data dir>/executor.pid atomically, prints started pid=<n>, and exits without waiting.
  • The lock is a flock on an OPEN DESCRIPTOR, not the existence of a file: a lock file left behind by a crashed executor is inert, so a relaunch after a crash is not refused. The child holds it for life and marks it close-on-exec, so nothing the executor spawns can keep the instance "running".
  • stdout is exactly one line — started pid=<n> or running pid=<n> — and that line is the whole contract the daemon parses.
  • The child writes <data dir>/installed-executor once its credential is on disk, which is what marks the target as this install's.

Everything it keeps lives in the target's data directory (paths.DataDir(), per instance via -P), so two instances on one machine never collide:

File What it is
executor.lock the flock holder for "an executor is running in this instance"
executor.pid the detached executor's pid, which uninstall signals
executor.log its stdout and stderr, rotated to executor.log.1 at 4 MiB
executor.cred its durable credential (the default --credential-file)
installed-executor the install marker: this install's id, as the first line

Inside --detach the parent reshapes its own argv for the child: --detach and --ticket-stdin are dropped and --ticket-fd=3/--lock-fd=4 added, so the child never detaches twice and reads its ticket from the inherited pipe. Both of those descriptor flags are hidden from help: offering them to an operator would invite passing a ticket in argv, which is the one place fd 3 exists to keep it out of.

The binary depot

A remote executor runs exactly the daemon's version: the daemon is the epoch authority (protocol.Epoch), so a binary built from anything else could fail the epoch check on every connection — or pass it while behaving differently. The depot therefore never resolves "latest": its tag is this process's own version.String(), fixed at construction.

Two sources, in order:

  1. $RAFIKI_EXECUTOR_BINARIES/<goos>-<goarch>/rafiki — an operator's own build (RAFIKI_EXECUTOR_BINARIES, .env.example). It is the ONLY source for an untagged (dev) daemon, and it is hashed before use.
  2. The signed release for that tag: checksums.txt.sig is verified against relsign.TrustedKeys before the archive is requested (release.Client.StageBinary), and the rafiki member is then staged into <cache dir>/executor-binaries/<tag>/<goos>-<goarch>/rafiki beside its .sha256. Every later use re-hashes the cached bytes and treats a mismatch as a cache miss, so a truncated file is never shipped as the daemon's version.

An untagged (dev) daemon with no override REFUSES, naming the command that would fill the directory: GOOS=<os> GOARCH=<arch> go build -o <dir>/<os>-<arch>/rafiki ./cmd/rafiki.

On the target the binary lives at $HOME/.cache/rafiki/bin/rafiki-<tag>-<sha256[:12]> — content-addressed, shared by every executor instance and every daemon that installs there — so a target that already has those bytes is pushed nothing. The platform comes from the target's own uname -sm, and only the exact spellings those unames print are accepted (Linux x86_64/aarch64, Darwin x86_64/arm64, OpenBSD amd64/arm64); a guess would install a binary that cannot exec.

The clobber guard

An install proceeds only onto a target that is empty for its namespace, or that carries this executor's own install. There is no --force. Three refusals, each naming its fix:

Target state Refusal Fix
A durable executor credential exists (<data dir>/executor.cred) the machine already has an enrolled executor use it, or remove that file on the target first
The marker names a DIFFERENT install the target carries executor state from another install ssh <target> rm -f <data dir>/installed-executor
This (owner, machine) already has an executor row that was not installed over ssh the name is taken pick another --name, or rafiki executor delete that one

The first two are the probe's answers; the third is the daemon's own row lookup. None is bypassable by a client, because every one of them runs on the daemon side of the ssh.

Reinstall and uninstall

Reinstalling the same name reuses the executor: the same row and the same id, so anything pinned to executor: <name> keeps meaning that machine. A reinstall IGNORES the request's labels, root and admits — change those with rafiki executor label — and it keeps the instance the recipe recorded, not the launcher's current one, so a launcher whose profile changed cannot silently move the executor to a fresh namespace.

Uninstall removes what the caller's LINEAGE installed — the caller itself, or an ANCESTOR of it; authority flows down the tree, so a worker may tidy up a machine its coordinator provisioned for it, while a sibling's install is not its to remove. A row a human installed has no installer child, so no child may uninstall it. Uninstall ends the ssh session FIRST (a still-running remote rewrites its marker), then removes the target's marker through the launcher when it holds this install's id and the launcher is live, then tombstones the recipe, deletes the executor row and evicts the executor's connection — the pool's row refresh would otherwise keep serving it for about half a minute after the row went. A failure to clean the marker does NOT fail the uninstall: the leftover is named by the next install's clobber guard, with the command that clears it.

A direct stop that is asked for and not achieved is reported the same way, because the response has no field for it: the daemon logs a warning naming the target, the install id and the consequence, and the target keeps every file — marker, credential and lock — so the next install's clobber guard can name who they belong to. An operator who reads neither can believe the remote process is gone until it reconnects.

Deleting the row is what ends a direct executor whose launcher could not be reached at uninstall. Its next reconnect presents a credential for a row that no longer exists, is refused a terminal 401, and the process exits. RemoteClean's stop_process is how a reachable launcher stops it sooner than that.

Failure codes

Failures are typed, never collapsed into a bare string. The parent makes a different retry decision for each code:

Code Meaning Retry?
CODE_TOOL_FAILED (3) The tool itself errored (missing file, unknown tool name, bash exit ≠ 0 in a synchronous call). Yes — the error is tool-specific.
CODE_DENIED (1) Structural refusal (stale mtime, sandbox violation, tool not permitted). Never. The condition is permanent for this request.
CODE_EXECUTOR_LOST (2) The executor disappeared mid-call. Yes — a different executor may still serve the request.
CODE_TIMEOUT (4) The tool call exceeded timeout. Yes — a longer timeout may succeed.

bash exit ≠ 0 in a synchronous call is a Result (with is_error=true), not a Failure. That is existing behaviour and the protocol preserves it. A non-zero exit inside a background job is reported via the exit code in the JobExited WatchJobs event.

Background-handle lifecycle

Start:    Execute(background=true, tool=bash) → stream { handle }
Notified: WatchJobs → JobExited(handle, exitCode)   (pushed, never polled)
Read:     JobOutput(handle, since) → { data, total, exited, exit_code }
Kill:     Cancel(callId) → {}
  • A handle is the callId from ExecuteRequest. The parent picks it.
  • A job's output goes to a FILE on the executor, retained with drop-oldest at 8 MB, and a single reply returns at most 100 KB of it from the end. Byte offsets are tracked against a monotonic total, so a re-read after data has been dropped can tell the caller it missed output rather than silently replaying or skipping bytes — and unlike the in-memory ring this replaces, what it missed usually still exists, at a path the reply names. That is the same "spill, never destroy" rule foreground tool results follow; background output was the one place output was both unbounded and thrown away.
  • Retention has no time limit. A finished job's output lives until its workspace is released, which is exactly as long as the agent that might ask for it. A wall-clock window cannot work here: an async agent's turn can end and resume hours later, so a 10-minute timer expired output while the agent that started the job was still alive and idle. Memory is bounded instead by a per-workspace BYTE budget (256 MB by default, --job-output-budget-mb), evicting the oldest FINISHED job first. Running jobs are never evicted: their output is a live stream, not an archive. An UNACKED finished job is never evicted either — its exit has not been delivered yet.
  • Background commands are never rewritten through rtk, whatever --rtk says. The rewrite is only safe because the foreground path can watch stderr after the command exits and re-run the original when rtk itself refused; a long-running job offers no exit to inspect and no output it could take back.
  • A job survives a dropped WatchJobs connection — the daemon re-subscribes and the replay covers it; its output is read at any time with JobOutput.
  • Health().runningHandles lists every handle whose process has not yet exited.

Mtime (TOCTOU) contract

The FileTracker splits state from check: the parent holds the map (conversation state that survives executor respawn), and the executor verifies at the moment of the write.

  1. After a successful read (or write/edit), the executor populates Result.observedMtime with the on-disk mtime of each file touched.
  2. The parent stores these in its own FileTracker.
  3. On a subsequent write or edit, the parent sets ExecuteRequest.expectMtime to the values it previously recorded.
  4. The executor stats each path before dispatching the tool. If any mtime differs, it streams Failed(CODE_DENIED, …) and the write does not proceed.

The stat happens in the executor process, which is the only place the file is visible: if that process is in a container, the path it stats is the container's.

Parent-side checking alone would be a TOCTOU — the file can change between the parent's check and the executor's write. The executor-side check at the last possible moment closes that window.

Not built: a presence tier

A third tool tier was reserved and deleted without ever carrying a tool. This section records why, because the design that proposed it is persuasive and its absence otherwise reads as an oversight.

What was proposed. Verbs a deployed executor structurally cannot serve, because they need the operator's own machine and their presence: read the system clipboard, open a file in their editor, open a URL in their browser, resolve a path they just dragged in, pick a file interactively. A client-run executor (kind=client, interactive=true) would serve them, and a child would somehow hold two executors at once — a workspace one and a presence one.

Why it was rejected. One test settles every verb on the list: who initiates, and does the answer have to arrive inside the turn?

Initiator Correct home
The human a message, not a tool
The daemon, on a state change a notification, not a tool
The model, mid-turn, blocking on the result a tool
  • Clipboard read — the human can paste.
  • Clipboard write — a TUI keybinding does it better, and it is a capability an injected prompt would enjoy having.
  • Browser open — print the URL; terminals make it clickable. Also exfiltration-shaped: a URL with data in the query string, opened on the operator's machine.
  • Editor open — print file.go:42, which is clickable, and which this repo's own conventions already prefer.
  • File picker — "which file did you mean?" is a sentence.

None of them is model-initiated-and-blocking. Claude Code, the most mature build of this architecture, ships none of them either; what it ships is one verb where the model does initiate and does need the answer, AskUserQuestion.

And that verb is not a presence tool. The agent emits a question; whatever is subscribed to its event stream decides who is present and how to render it — a desktop notification, a phone push with the choices as buttons, a coordinating parent agent, or nobody. Presence is a property of subscribers, not a tier of tools. That is why no second executor binding, no ToolOpts.PresenceExecutor, and no child-to-attached-client link were needed: the problem the tier existed to solve dissolves once the question is an event rather than a routed call.

Two consequences, both load-bearing.

tools[] is immutable for a child's lifetime, not merely monotonic. The earlier rule allowed one growth, on first human attach, purely to admit this tier. Nothing else would ever have exercised it.

The genuinely useful items on the list are TUI-local affordances — paste, drag-and-drop, @file completion over the executor's tree, clickable file:line. They need no tier and no wire protocol, and they are blocked on a real rafiki TUI existing rather than on anything here.

What is still open, and must not be smuggled back in under this name. A child that needs its container for the checkout and its operator's laptop for browser-based auth or secrets is a second workspace binding — read and bash on two machines. That is a real, undesigned problem. It is not presence, and reviving TierPresence is not how to solve it.