Skip to content

Latest commit

 

History

History
340 lines (192 loc) · 101 KB

ARCHITECTURE.md

File metadata and controls

340 lines (192 loc) · 101 KB

Flyco architecture

The product-level spec is proposal.md. This document records the technical design and the facts it rests on.

Two planes

  • Control plane — crates/api, a skyzen app on Cloudflare Workers (wasm32). REST API + auth, session store, budget accounting, approvals, skills/MCP registry, provisioning orchestration. Services: D1 (relational metadata), KV (caches, auth tokens), R2 (transcripts, repo snapshots, skill zips), Queues (provisioning jobs), Durable Objects (live session rooms).
  • Execution plane — flycod (crates/daemon), a native Rust daemon installed on every session VM. It supervises the harness process, enforces takeovers, serves the terminal, streams events to the control plane, and handles spot-eviction notices and budget pauses.

The Worker is wasm32: no processes, no listening sockets, no tokio. Anything long-running or process-shaped lives in the daemon.

Crates

Crate Runs on Purpose
flyco-core wasm32 + native Domain types, DTOs, wire protocol, budget engine. Pure logic, no I/O.
flyco-api Cloudflare Workers Control plane.
flyco-provider wasm32 + native CloudProvider trait + implementations (Azure, AWS, GCP, Codespaces) over signed HTTP via zenwave, and the container-job planner for a machine the user owns.
flyco-daemon Linux VMs & containers (native) flycod: unified ACP harness drivers, terminal, local MCP broker/server, dual-UID enforcement.
flyco-cli native flyco: terminal client — interactive ACP/SSE sessions (claude, codex, devin, antigravity, resume), run, session …, handoff, and discovery commands.
xtask native (dev/CI) Workspace automation: cargo xtask publish-flycod cross-compilation, OCI image build/push, and R2 release upload.

frontend/ is the SolidJS PWA (Bun + Vite), hosted on Cloudflare Pages in production (with EmbeddedStaticDir still available in flyco-api for embedded/local serving).

Session relay

One Durable Object per session, addressed by the session id (SESSION_ROOMS.get_by_name(session)), so a session and its room are one identity with no mapping table to go stale. The transport is REST in, SSE out — no WebSockets anywhere: the daemon attaches with POST /v1/sessions/{id}/relay/attach, receives commands on GET /v1/sessions/{id}/relay/commands?epoch=N (an SSE stream the room serves), and posts outbound frames with POST /v1/sessions/{id}/relay/frames. The attach returns an epoch that names the attachment; every frames POST and every streamed command carries it, a stale epoch is a 409 relay-epoch-stale, and a frames POST whose sequence is not contiguous is a 409 relay-frames-gap. Commands the daemon has not acknowledged are replayed from the room's own daemon_commands table on the next attach — ack_through in each frames POST is what deletes them — so a user message typed while the daemon is reconnecting is held, not lost.

Browsers never reach a room at all. Every client command is an authenticated REST call (/messages, /shell, /terminal/input, /terminal/resize, /interrupt, /compact, /context), and every event arrives over one global SSE stream per user: GET /v1/events, backed by a per-user UserEvents Durable Object (schema v3 with a (session, seq) index), with session to filter and after/Last-Event-ID to resume its reconnect buffer. Both SessionRoom (schema v4, including the turns projection table), UserEvents, and HostRoom (schema v3) are &self Durable Objects (skyzen 0.6.1) using in-memory Signal wakeups (crates/api/src/sse.rs) rather than polling loops. The room is still the writer — a Durable Object cannot call another Durable Object, so the Worker is the courier that publishes each room's emissions to the owning user's stream as SessionEvent { session, seq, event } envelopes. The stream's rows are a reconnect buffer, not the record: the authoritative per-session history stays in the room's SQLite (events) and is replayed through GET /v1/sessions/{id}/events?after=…, which is what a browser uses to heal gaps the buffer cannot. That events table is the only normalized, harness-neutral record of a session, so GET /v1/sessions/{id}/turns reads the turns projection table populated as events land (flyco_api::turns) rather than out of R2, which holds the harness's own store: opaque Agent SDK entries for Claude Code (R2TranscriptSync) and nothing at all for Codex. The room also keeps the last working-tree status the daemon reported per checkout, which is what repo-status serves; no report is a 404, because an unexamined tree is not a clean one. D1 keeps durable metadata and the append-only spend ledger.

The wire protocol is flyco_core::wire, versioned by WIRE_PROTOCOL_VERSION (currently 20); a mismatch is refused at attach (fast fail). Three enums, one per direction: DaemonToControl, ControlToDaemon, and ClientEvent (what browsers receive, including ClientEvent::SwarmUpdated for read-only Swarm observation). Every variant is a struct variant, including single-payload ones — an internally-tagged newtype variant wrapping another internally-tagged enum emits type twice, which serde_json writes happily and then refuses to read back.

A composer message beginning with ! is a shell command, not a prompt (docs/ux.md §9.3), and it is the one client command the room rewrites. A browser sends ShellCommand { command }, which carries no identity because a browser has no authority to name a run; the room mints a ShellRunId, records the command as a ClientEvent::ShellCommand and reissues it to the daemon as RunShell { run, command }, and every ShellOutput chunk and the single ShellExited are keyed by that run. flycod runs it as bash -c in the session's workdir, as the user the daemon runs as, one command at a time, bounded in wall-clock and in bytes (crates/daemon/src/shell.rs); Stop cancels it along with the turn. The harness is never told any of it. Every way it can end is a typed ShellOutcome, including the three where it never ran — no daemon connected, one already running, a paused or reclaiming session — because a command the user typed must never simply produce nothing. Unlike the web terminal's bytes, the output is appended to the room's stream: it belongs to a transcript row, and a replay of the command with nothing under it would be worse than no replay at all.

A Durable Object cannot reach D1 or the Worker's KV, so every check that needs them happens in the Worker before it addresses a room: credential validity, session ownership, and the durable half of any state change. What arrives at the room is already authenticated and says so in internal headers (x-flyco-internal, x-flyco-session, x-flyco-role) that only a same-Worker call can set.

How each side authenticates. The daemon presents Authorization: Bearer fd_…, a per-session token minted by POST /v1/sessions/{id}/daemon-token and stored as a SHA-256 in sessions.daemon_token_hash. It resolves to a session, never to a user, and is checked against the session id in the path — so the scope check is the lookup itself, and attach, commands and frames all carry it. A browser sends its own bearer on every REST call and on GET /v1/events — SSE is fetched with the Authorization header set, which is why the stream is opened with fetch rather than EventSource.

Transcripts never ride the relay. A transcript is unbounded while an event row is not, so flycod writes batches over ordinary authenticated REST to R2 at transcripts/{session}/{stream}/{seq:08}.jsonl. The zero-padded sequence makes lexicographic order equal numeric order, so a read is a prefix list with no index to keep consistent, and batches are immutable — rewriting one would silently reorder the transcript, so it is a 409.

Request budgets

The control plane runs on Cloudflare's free plan, whose ceilings are account-wide and daily: 100k Worker requests, 100k Durable Object requests, 5M Durable Object row reads, 100k D1 row writes. One client looping at line rate spends the whole account's day (issues #174, #288, #336, #342), so the Worker charges every request to a principal and refuses a principal that has spent its share, before that share becomes everyone's (crates/api/src/request_budget.rs).

Two bounds, one middleware, outermost of the route layers so a refused request costs nothing further. The per-minute bound is a Cloudflare Rate Limiting binding per credential class (LIMIT_USERS, LIMIT_DAEMONS, LIMIT_HOSTS, LIMIT_PUBLIC in Skyzen.toml), keyed by the SHA-256 of the bearer or by the connecting address, and checked before any credential is resolved — a per-colo in-memory counter that costs no storage. The daily ceiling is charged after the route ran, once the request's principal is known: a signed-in user (user:<id>, every credential the user holds shares it), a session daemon (session:<id>), a host (host:<id>), or the connecting address for everything else. The tally is a per-isolate ledger flushed to D1's request_budgets table (one row per principal per UTC day) on first sighting, on reaching the ceiling and every FLUSH_EVERY requests, so the ledger costs one D1 write per few dozen requests rather than one per request. A principal at its ceiling has its credentials put on the isolate's block list and is refused until UTC midnight without a storage read.

Every refusal is a 429 problem document with a Retry-After: rate-limited names the window (60 s), request-budget-exhausted and row-budget-exceeded name the seconds to midnight. Clients treat that header as the floor of their next wait — the daemon's relay ladders, the PWA's SSE feeds, and the CLI's retries all read it — and request-budget-exhausted is surfaced, never worked around by switching credentials. The ceilings are request_budget::Limits::PRODUCTION, pinned to the manifest by a test; the rules for raising one, and for every loop that talks to the control plane, are in AGENTS.md.

Provisioning

A machine takes minutes to appear — Azure took over five in a live test — and a Worker request cannot wait on one, so provisioning is a queue and POST /v1/sessions answers 201 before any machine exists.

The choice of machine is part of creating the session. CreateSession carries a MachineChoice: which linked provider account, machine type, region, spot preference and disk. It is validated against that account's own catalog before any row is written, so a machine the account cannot deploy is refused where the user made the choice rather than two minutes later inside a consumer nobody is watching. For Azure the check is region_report rather than the merged catalog, because the report keeps why a machine type is missing — not sold here, no quota, region forbidden by the subscription's policy — and those are three different things to fix. Creating a session without a machine is what forced the frontend into a best-effort resize immediately afterwards, which is a real window in which a session runs on the wrong machine at the wrong price.

Creation then writes the session, its budget, and an empty machines row, and enqueues one job. The consumer (flyco_api::provisioning_queue) prices the machine from the cached catalog document the choice was validated against — the same catalog:{account} document the picker reads, so a provision pays no provider call for it — mints the session's fd_ daemon token, unseals the harness credential from harness_accounts, builds the DaemonBootstrap, calls the driver's provision, and records what came back — including whether spot was actually obtained, which can differ from what was asked and is what the price follows. A document that cannot price the machine is the one case the queue asks the provider itself: the read is just the region the machine is in (or the whole catalog for a provider that answers in one pass), and what it learns is written back so the next leg and the picker both see it.

The bootstrap also carries the checkouts, because a machine with no repository on it is an agent with nothing to do. A session's repositories are the session_repos rows — CreateSession.repos, one to sixteen, first is primary — and DaemonBootstrap::repos is a SessionCheckout per row: the slug, the branch, and the dir it clones into under the workdir. The GitHub access is hoisted into one DaemonBootstrap::github: the user's own OAuth token unsealed from users.github_token_enc, and the user.name / user.email the session's commits are authored under — one table because the authorization is the workspace's, not the repository's. That is the behave-as-the-user default made concrete — every clone and any push are the user's, not a flyco bot's, and the address is GitHub's own id+login@users.noreply.github.com form. A stored token that does not grant repo cannot clone a private repository or push anything, so the queue checks the token's scopes (X-OAuth-Scopes on GET /user) and fails the session with problems/github-token-insufficient, which tells the user to sign in again; POST /v1/sessions makes the same check while somebody is still watching the form. Every repository's branch is settled at creation — the one the caller named, or the repository's default read from GitHub — so nothing downstream has to guess.

flycod clones before it starts the harness. It announces ProvisioningStage::Cloning over POST /v1/sessions/{id}/provisioning-stage — the one stage of the timeline that cannot be a relay frame, because the daemon does not attach until there is a harness session behind it — clones each [[repos]] entry into workdir/<dir>/, applies the workdir patch an automatic archive may have stored (one patch per checkout), and only then starts the agent. A resume onto a new machine is therefore fresh clones plus those patches rather than anything carried over from the machine that is gone. The GitHub token reaches git through a one-line credential helper installed with -c that reads it from the environment of that one child process: it is never written into a remote URL, into .git/config, into a credential store, or into a log line.

The workspace root is the agent's cwd, and the checkouts live inside it as workdir/<dir>/ — the repository's name, owner--name on a collision, owner--name-2 after that, all computed by flyco_core::checkout_dir and recorded on the session_repos row so the daemon, the browser and the stored patches name the same directory. One cwd holding every checkout is the only arrangement that works identically across the harnesses: ACP's session/new takes exactly one working directory with no additional-roots concept, and a checkout that were a sibling of the cwd would sit outside Codex's workspace-write sandbox. A developer machine is the degenerate case: no [[repos]], the workdir itself is the one checkout, and the daemon reports it under no dir at all. flycod writes a root AGENTS.md/CLAUDE.md naming the checkouts when none exists, so the agent learns the layout and each repository's own instruction file still governs inside its checkout.

A repository can join a running session, and who asks decides how. The user's POST /v1/sessions/{id}/repos validates the slug and branch against GitHub while somebody is watching, writes the session_repos row, and the daemon is told through ControlToDaemon::AddRepo — a durable room command, so a detached daemon clones it on reattach. The agent's repo_add tool takes the same ride through the approval system as anything else consequential: it raises ApprovalPayload::RepoAdd, approval records the row as added_by = 'agent' and sends the same AddRepo, and denial lands as a user-origin message saying so. The daemon announces a successful clone as RepoAdded, which the transcript shows as a notice; an AddRepo that finds the dir already on disk announces nothing, because a replayed command is not news.

Running twice is normal, because Cloudflare Queues delivers at least once and a second machine for one session is a cloud resource nobody is billing anybody for. Three things make that safe: machines.session_id is UNIQUE, so a session has exactly one machine row for its whole life; the job names that row's id, and every provider-native resource name is derived from it, so a second call to the provider updates the same machine (an Azure PUT over the names it already made, a podman script that removes the container before recreating it) rather than making another; and a job whose row is already running with a native id is acknowledged without touching the provider at all.

A session goes active when its daemon attaches, not when the provider's call returns: a machine that exists is not an agent that is ready. A Durable Object cannot reach D1, so the durable half of that arrival happens in the Worker, on the authenticated relay/attach POST the daemon opens the relationship with.

A build that outlives one invocation is handed back and carried on. A Worker invocation has a subrequest budget (fifty on the free plan), and every poll of a provider operation is one of them: a Container Apps job whose image was cold on the node took six minutes to come up, and the consumer that started it died on Too many subrequests by single Worker invocation at the fortieth poll (issue #257). So CloudProvider::provision answers Provisioning::Ready(machine) or Provisioning::Pending { machine, continuation }: a driver polls for flyco_provider::polling::POLLS_PER_INVOCATION and then hands back where it got to — for Azure, the job and the Follow it was polling — as an opaque Continuation the driver alone reads. The queue records the pending machine by what exists of it (machines::record_pending writes the provider-native id and leaves the row provisioning, so a redelivered Provision sees a build already owned and drops itself) and enqueues ProvisioningJob::Continue after ten seconds; the next leg calls CloudProvider::resume under its own budget and either records the machine or hands it back again. Every leg notes progress, so the fifteen-minute stall sweep bounds the whole build and not each leg; a build it gives up on is destroyed by the id it has, and the Azure driver stops every live execution of a job-only id before deleting the job, so a machine that came up after the control plane stopped waiting does not run on unattended.

A provision that fails ends as SessionState::Failed, carrying why. Only a genuinely transient failure is retried — ProviderError::is_transient, which is transport-level failures and nothing else — and the attempt count travels in the job, because the queue's own redelivery counter is not visible to the handler and a message Cloudflare quietly stops redelivering would leave the session in provisioning for ever. After MAX_ATTEMPTS the session fails with the provider's own words. A failed session occupies no slot against the user's concurrent-session cap: it holds no execution environment.

POST /v1/sessions/{id}/resume is the same path. It moves the session back to provisioning, resets its existing machine row, and enqueues a job naming that same machine — there is one implementation of provisioning and this is not a second one. Archived is therefore not terminal in flyco_core::session, and that is the History feature rather than a loophole: archiving releases the execution environment and keeps the turns precisely so the session can come back.

A session on a machine the user owns is provisioned by asking the machine: the queue plans a ContainerJob and posts it to that host's Durable Object, which holds it in the mailbox the machine's own command stream drains. The Worker never dials anybody's hardware, because it has no sockets to dial with — see "Hosts" below.

Spot reclamation

Spot is the default capacity, so being reclaimed is an ordinary event rather than a failure. Flyco migrates the session itself and the agent takes no part in it: the notice is thirty seconds on Azure and GCP, an LLM is slow and unpredictable, and the whole window is spent by flycod. What the agent gets is one sentence afterwards, once it is running again.

Reclaim releases the machine and never the disk. Every driver configures it that way — Azure deallocates, an AWS persistent spot request's interruption behaviour is stop, and a Compute Engine spot instance is created with instanceTerminationAction: STOP — so there is no working-tree snapshot on a reclaim: the checkouts, the uncommitted work and the caches are on a disk that survives. workdir-patch stays what it always was, the safety net before an archive releases the disk.

flycod watches the endpoint its bootstrap named (flyco_daemon::spot). DaemonBootstrap::provider is written into the daemon's configuration as spot_provider, and only on machines a notice can arrive for — interruptible capacity on a cloud provider — because probing three link-local addresses to discover whose machine you are on is not a thing a daemon should do. One trait, three implementations, and the cadence each provider documents: Azure Scheduled Events (/metadata/scheduledevents?api-version=2020-07-01, Metadata: true, event type Preempt, polled every second, deadline read from NotBefore); EC2 IMDSv2 (a PUT-minted session token, then /latest/meta-data/spot/instance-action every five seconds, which is 404 until it is a document with an RFC 3339 time); and GCP's instance/preempted (Metadata-Flavor: Google), which is the one that offers a hanging read — wait_for_change=true answers the moment Google decides, and the notice carries the thirty seconds Google documents because no deadline is published with the flag.

On a notice the daemon does four things in this order, and the order is the feature: it interrupts the turn, so what is flushed has stopped moving; it flushes — every transcript batch the harness has handed it, then the harness-native session id, both awaited, because the daemon is about to stop existing and "the control plane knows" has to be true before it does; it syncs the filesystems, since the page cache is the only part of the working tree a reclamation could lose; and only then reports, over REST (POST /v1/sessions/{id}/spot-notice) and then as the relay frame the UI counts down from. Between the notice and the machine going it refuses anything that would open a turn — a user message that arrives is not lost, it waits in the room's mailbox for the daemon on the machine that comes back.

A machine with no disk answers SIGTERM with the same sequence, and spends it differently. A managed container is stopped by the platform sending SIGTERM and killing the execution about thirty seconds later — that is how ACA, Cloud Run and Fargate all announce a stop, a spot eviction and a run that reached its timeout. flyco_daemon::stop installs the handler on exactly the machines whose filesystem is about to disappear (runtime = container) and on no others: a VM's SIGTERM is systemd stopping a unit on a disk that will still be there, and spending thirty seconds saving something that was never at risk would be work for nothing. The sequence shares its first two steps with a reclamation — interrupt, flush — and replaces the sync with the step that matters here: the working trees leave the machine, as the same per-checkout workdir-patch an automatic archive stores. Then, and only then, POST /v1/sessions/{id}/stopping with { reason: "sigterm" }, and the process exits 0, so the platform records an execution that did what it was asked rather than one that failed. The whole of it is bounded at 25 seconds by flyco, under the shortest documented grace period, so a sequence that runs long is cut off with a log line rather than by a SIGKILL that leaves no trace.

The patch is applied at every start of such a session, not only after an archive. check_out clones each checkout and then replays whatever GET /v1/sessions/{id}/workdir-patch?repo=<dir> holds for it; on a container the filesystem went with the last execution, so the clones are always fresh and the patches are always where the work is. A patch that will not apply is fatal, with the git error in the reason the control plane records — an agent that came up on a clean tree and carried on would be the user's uncommitted work silently discarded.

The durable half is a REST route rather than a room frame because a Durable Object can reach neither D1 nor the queue. It marks the session interrupted with interrupted_reason = spot_reclaimed and enqueues a ProvisioningJob::Recover delayed by the provider's own countdown: the machine holds its disk for those seconds, and a start issued against a running instance is not a restart.

Recovering is a start, never a provision. The job moves the session back to provisioning — keeping the reason, which is the only thing that tells a migration apart from a first build and is what the UI renders as Migrating — announces reserving and booting, starts the same machine row through its own account, records the replacement in the budget ledger, and sends the agent one message: The machine was reclaimed and restarted on <type>; continue. It does not announce installing or cloning, because neither happens: the image already has flycod (its unit is enabled, so the boot that follows a start runs it), and the daemon that comes up finds the checkouts already on the disk and keeps them. The one thing that machine cannot get from its own disk is which conversation to continue — the configuration there was written when the machine was created — so it asks GET /v1/sessions/{id}/harness-session and resumes what the control plane recorded.

The budget keeps accruing storage across the gap, because the disk was kept and is therefore billed; only the compute meter stops and restarts. The ledger records a zero-amount compute line naming the reclamation, keyed on the machine and the instant it was announced, so an at-least-once redelivery writes one line and a session reclaimed twice writes two.

Plan usage limits

A subscription plan stops the agent at a window it also resets by itself, so flyco waits the window out for the user instead of failing the session (docs/ux.md §9.8). crates/api/src/usage_limits.rs is the whole mechanism and the module's own documentation is the reference; what belongs here is why it is shaped this way.

One fact, three signals. Both harnesses announce a spent window three ways — an explicit rate-limit event, the refusal of the turn that hit it, and a plan window the vendor reports at 100 % — and the drivers normalize all of them to one HarnessEvent::UsageLimited { window }, deduplicated per window inside the driver's normalizer so a limit announced by an event and again by a refusal is one pause. The daemon reports it over POST /v1/sessions/{id}/usage-limit and does nothing else about it: the wait outlives the machine, and a daemon that is about to be stopped is the wrong place to keep a timer. A window the vendor gave no reset for is refused with 422 usage-limit-without-reset — there is nothing to wait for, and a timer over an invented instant is worse than the failure it replaces.

The pause releases the machine only when the wait pays for it. More than thirty minutes to the reset and the machine is stopped, which is a deallocation that keeps the disk, exactly as a spot reclamation's is; less and it is kept, because a stop and a start cost more provisioning time than the wait saves in cents. Whether it was released is not a column: usage_limit_resume_at_unix is present if and only if there is a machine to start, so one field answers both "when does flyco start it again" and "is this costing anything", and the two cannot disagree.

The clock is the minute cron, not a delayed queue message. Cloudflare Queues cap a delay at twelve hours and a weekly window resets further out than that, so the sweep in crates/api/src/metering.rs — already running every minute to price machine time — reads the waiting sessions from an index on usage_limit_resets_at_unix and decides what each one is owed. The wake runs ten minutes before the reset so the agent is up and ready when the window turns over rather than provisioning through it, and it goes through the same ProvisioningJob::Recover a reclamation uses, distinguished by a RecoveryCause: a wake announces no replacement and writes no ledger line, because no machine was replaced.

Every step is idempotent from the session row alone, which is what makes an at-least-once cron safe: a pause is refused for a session already waiting, a release skips a machine that is already off, a wake moves the row out of its own query's predicate, and the continuation clears all five columns under a compare-and-swap on the state. At the reset the session is told usage limit reset, please continue — or whatever the user typed into the composer meanwhile, which the handler holds against the pause instead — carried as ControlToDaemon::UserMessage with origin: flyco so the transcript can mark a sentence the user never typed. The origin stops at the room: what reaches the harness is the text, because a model told that its next instruction came from a program would reason about the framing instead of the work.

GitHub webhooks

POST /v1/webhooks/github carries no flyco credential and is reachable by anyone who knows the URL, so the X-Hub-Signature-256 HMAC over the raw body is the entire boundary — which makes the order of operations part of it. The handler resolves the shared secret, verifies the signature with Mac::verify_slice (constant-time; a byte-by-byte == on a tag leaks through timing how much of a guess was right), and only then reads the event header and parses the payload. Nothing else in the module touches the body, so there is no path in which an unverified one is looked at.

The secret is FLYCO_GITHUB_WEBHOOK_SECRET and it is required at startup: there is no valid running deployment with a webhook route but no way to authenticate it. Reading a missing environment variable as "verification is off" would put the whole boundary behind a typo. Web Push is not optional either: FLYCO_VAPID_PRIVATE_KEY is required at startup, and the public subscription key is derived from it.

A check_run or workflow_run that concluded failure, timed_out or action_required is the CI-autofix trigger: every active session on that repository is woken with a goal-shaped notice — rendered from crates/api/templates/github/ci_failure.txt — sent as a ControlToDaemon::UserMessage through Rooms::command, which is the one command path to a session's daemon. Every one of them, not the first: two sessions may legitimately be open on one repository. cancelled, neutral and skipped are not failures and wake nobody.

Everything that is not a failure flyco can act on answers 204: a ping, an event flyco does not model, a green run, a repository nobody is working on. GitHub retries anything that is not a success, so an error is reserved for the two cases where a retry would help — an unverifiable delivery, and one whose sessions all failed to reach their rooms.

Harness drivers

Every harness is driven through the unified aither-acp v0.31.0 layer (crates/daemon/src/harness/acp/mod.rs), with the Bun/TS sidecar completely removed:

  • Claude Code: May-Agent/claude-acp running in-process via aither-acp's direct lane (ClaudeAgent::into_server), spawning the native claude CLI under AgentUser privilege isolation, with R2TranscriptSync (claude_acp_sdk::TranscriptSync backed by R2) for cross-host history. Feature detection via capabilities, never version strings.
  • Codex: May-Agent/codex-acp running in-process via aither-acp (CodexAgent::into_server + drive_background()), spawning codex under AgentUser privilege isolation.
  • Devin & Antigravity: external ACP child processes (devin acp and agy acp) over newline-delimited JSON-RPC.

All four are normalized to flyco_core::harness::HarnessEvent. Feature parity is tracked in feature-matrix.md — "ALL features" is a matrix with per-release gaps, not an untracked promise.

What a session can be told to do is the harness's own list, not flyco's. The unified ACP driver collects available commands from the harness (AvailableCommandsUpdate / commands_update) and forwards them as DaemonToControl::Commands → ClientEvent::Commands, appended to the room's stream so a browser opening later still finds it. That is the one place it differs from the model list beside it, which is filed over REST against the account: a command set carries the repository's own skills, so it belongs to this session and there is no account row to write it to — HarnessAccountView never sees it.

Nothing is plumbed per command. A command the user picks is sent as the ordinary message /name args, which the harness executes itself, so /goal, /effort, /context and every skill work with no flyco code that knows what any of them is.

Read-only Swarm observation

When an Antigravity (agy acp) session orchestrates a swarm, crates/daemon/src/swarm.rs watches <app_data_dir>/brain/<session_id>/.system_generated/swarm/ (swarm.json, members.json, plan.json, board.jsonl) strictly read-only — it never creates, modifies, or deletes any file there. Updates are coalesced over a debounce window and emitted as bounded ClientEvent::SwarmUpdated frames (WIRE_PROTOCOL_VERSION 20). The Web PWA (frontend/src/components/SwarmPanel.tsx) and flyco CLI (crates/cli/src/out.rs, crates/cli/src/interactive/render.rs) render the live snapshot (goal, thread groups, member roster) and ordered @ message board; user intervention stays on the session's normal message composer.

Auth has two shapes, and they are one decision: inherit (no CLAUDE_CONFIG_DIR, no credential injection — the developer-machine mode, which reads the host's own ~/.claude), or an injected credential that always carries its own isolated config tree and project key.

flycod run picks its driver from the configuration (harness = "claude_code" or harness = "acp" with [acp]) and logs which it chose. With a [control_plane] section it opens the relay and keeps its transcript in R2; without one it drives the session from a line-oriented stdin REPL, printing SessionOutput values as JSON lines, and keeps the transcript in transcript_dir. The REPL stays as the dev tool for reproducing a harness bug without provisioning a VM.

The relay client

Two directions, two halves. The collector owns the harness's output stream and turns each SessionOutput into a wire frame; the pump owns the harness's control handle and dispatches commands inward. Outbound frames are batched onto POST /v1/sessions/{id}/relay/frames — every POST carries the attach's epoch, the sequence range it covers, and the daemon's ack_through cursor over the command log — and inbound commands arrive on the attach's SSE stream. Between the two sits one bounded queue: the room is not always reachable, and the queue is what absorbs a reconnect — bounded at 1024 frames, because a queue that grows without limit trades a visible outage for an OOM kill. Overflow is fatal, never a silent drop: losing part of a session's transcript is worse than stopping. A frame whose POST fails is handed back and retried under the next epoch, and the room's per-epoch watermark plus the daemon's persisted applied cursor make the retry safe rather than double-applied.

Reconnection is capped exponential backoff with full jitter (1s→60s): re-attach, re-open the command stream, re-flush. The stream itself carries the room's own pings, so a daemon that has heard nothing — not a command, not a ping — for long enough abandons the flow and attaches again rather than waiting on a stream it cannot prove is alive.

A budget threshold below 100% is told to the agent, as a [flyco budget notice] … message in the conversation — the agent decides how to spend its budget, so a threshold is information rather than a limit. Pause is the exception: it interrupts the turn immediately and the daemon stops accepting work.

An approval is recorded over REST before its frame is announced, so the id a browser sees is one the API can settle, and a decision that arrives while the daemon is detached still finds a pending row.

Takeover enforcement and dual-UID isolation (strongest first)

Across VMs, containers, and Codespaces, flycod enforces dual-UID isolation (crates/daemon/src/privilege.rs): the privileged root daemon exclusively owns 0600 /etc/flycod/config.toml and root-owned managed policy directories (0755/0644, unwritable by the agent), while every agent-controlled child process (coding harnesses, ! shells, interactive PTYs, virtual desktop) drops privileges to the unprivileged flyco user (DEFAULT_AGENT_USER), clearing supplementary groups and stripping daemon secrets (FLYCO_*, GITHUB_TOKEN, GH_TOKEN, cloud credentials) from the environment. On developer machines (euid != 0), AgentUser::resolve returns None to keep local workflows unchanged.

  • Claude Code: /etc/claude-code/managed-settings.json + managed-mcp.json (root-owned, outrank everything) with allowManagedPermissionRulesOnly, allowManagedMcpServersOnly, disableSideloadFlags, autoMemoryEnabled: false, absolute-path deny rules (bind even in bypass mode), and a PreToolUse command hook backstop (flycod hook pre-tool-use, exiting 2 to block); managed policy CLAUDE.md carries the shared AGENTS.md.
  • Codex & ACP agents: MCP allowlist (id + identity) + root-owned $CODEX_HOME/config.toml (via [acp.files]) + hooks.

Sanctioned mutations go through flycod's local stdio MCP server: memory_* (tree), agentsmd_change_request (→ user approval), repo_add (→ user approval; cloning a repository the user did not pick is consequential), machine_status, machine_resize, budget_status. A skill arrives by upload on Settings → Tools or installed from a plugin marketplace — either way it is stored in R2 and indexed in skills, and reaches a machine the next time its daemon starts: the daemon reads the owner's registry from GET /v1/sessions/{id}/skills and each bundle from GET /v1/sessions/{id}/skills/{skill}/bundle, then unpacks them into every harness's global skills directory on the machine before the agent launches, because a skill belongs to the user rather than to the harness that happens to be running (crates/daemon/src/skills.rs).

The MCP server and Unix-socket broker (crates/daemon/src/mcp.rs, crates/daemon/src/mcp_broker.rs). flycod mcp is a second process the harness launches over stdio under the unprivileged flyco UID — it never reads /etc/flycod/config.toml and never holds daemon_token. Instead, it connects over a local Unix-domain socket to mcp_broker inside flycod run to retrieve non-secret session metadata and proxy AgentApi / ApprovalRaiser calls to the control plane, which is the only answer that survives a resize (resizing restarts the machine, so the config on disk describes the machine the session booted on). RateLimitGuard on the broker enforces 429 Retry-After and request-budget-exhausted / row-budget-exceeded cooldowns locally so repeated tool calls cannot hammer the control plane. Every sentence handed to the model — tool descriptions, results, refusals, and the notices the relay injects — is an askama template under crates/daemon/templates/ (crates/daemon/src/notice.rs), because those sentences are the contract: an agent not told that a resize restarts the machine will lose a build to one. Two rules are enforced rather than described. The dirty-tree refusal lives in the daemon, because the working tree is on that machine and the Worker cannot see it. The licence gate lives in the control plane, which refuses a license-bound resize on a daemon's authority (409 license-bound-resize-needs-approval) so the agent raises an ApprovalPayload::MachineResizeLicenseBound instead — and approving that is what performs the resize, since nothing on the daemon's side is waiting for it.

Where a registered server comes from (crates/api/src/mcp_catalog.rs). The registry is the user's, and typing a transport by hand is not the way a browser-only user fills it, so GET /v1/catalog/mcp-servers is a search over the official MCP Registry — one page of its /v0/servers per request, kept in KV for an hour under its query. It is read on the request path rather than mirrored the way a cloud catalog is: the registry holds around thirty-four thousand servers, a page is one bounded call, and a full mirror would be a multi-megabyte document parsed on every keystroke. The translation from the registry's server.json to flyco's McpServerConfig lives there too — streamable-http remotes become http, npm packages npx -y <pkg>, PyPI packages uvx <pkg>, and an entry offering only an OCI image, a NuGet package or an .mcpb bundle is left out because a session machine cannot run it — so the browser never carries the registry's schema, and POST /v1/catalog/mcp-servers re-reads the entry, fills it with the values the user typed (headers, environment, arguments, and the {placeholders} inside them) and registers it exactly as POST /v1/mcp-servers would.

Where an installed skill comes from (crates/api/src/skill_catalog.rs, crates/api/src/marketplaces.rs). A skill arrives as a zip today, which a browser-only user has no way to produce, so a second door reads one straight out of a plugin marketplace: a GitHub repository whose .claude-plugin/marketplace.json names its plugins, each carrying skills/<name>/SKILL.md under its own root. anthropics/skills is built in and is not a row; every other marketplace is one, in marketplaces, unique per user and repository. A manifest may point a plugin at another repository — the format's github, url and git-subdir sources — and flyco follows those to GitHub, one extra tree read per plugin, so the skill is listed as the marketplace's own and installed out of the repository that actually holds it. A plugin published as an npm package, a zip, a command, or a repository on another Git host is not something flyco can open, so it contributes no skills. Reading one is a tree walk plus a file read per skill, which is not work a request does, so it happens on the provisioning queue and lands in KV as a document per repo@ref — the same claim-key pattern the machine catalog uses, and the reason GET /v1/catalog/skills answers with pending beside skills and failed rather than pretending a repository it has not read yet is empty. POST /v1/catalog/skills re-reads the entry, downloads the skill's files through the user's own GitHub token, builds the bundle in the Worker — a stored zip, because a compression backend is one more thing to link into wasm and a SKILL.md tree is a few kilobytes — and stores it through the same path POST /v1/skills uses, as the one row a skill is per user and name. Nothing about a skill's storage, mounting or delivery changes: this is where the bytes come from, not what happens to them.

Mounting it (crates/daemon/src/mount.rs) is a separate job from serving it, and it is done twice on purpose. A session's MCP surface is one set — flyco's own server plus the user's enabled registry, provisioned into flycod's config from GET /v1/mcp-servers — rendered from one structure into two places. The harness's start options (the Agent SDK's mcpServers with strictMcpConfig, Codex's thread/start.config) mount the set: they travel with the session, need no privilege, and work on a developer's machine. The root-owned files (/etc/claude-code/managed-{settings,mcp}.json, $CODEX_HOME/config.toml) make it exclusive: an managed-mcp.json gives Claude Code's enterprise scope exclusive control over auto-discovery, allowManagedMcpServersOnly pins allowedMcpServers to managed settings so a stdio server is admitted only against its exact command line, and Codex's [mcp_servers.<id>] is the identity, --strict-config rejects anything else, and the workspace sandbox keeps a project's own .codex/ read-only. Both documents are serde structures rather than templates, because a server name or a bearer token is whatever the user typed and escaping is the serializer's problem; crates/daemon/fixtures/mount/ pins the rendered bytes.

What is left of the plan is read from the vendor by the control plane, on the request that draws it, and is never stored. GET /v1/harness-accounts asks api.anthropic.com/api/oauth/usage with the account's own OAuth token — one subrequest, crates/api/src/anthropic.rs — and turns its five_hour, seven_day, seven_day_opus and seven_day_sonnet readings into flyco_core::wire::UsageWindow, whose label (5-hour, Weekly, Weekly (Opus)) is derived in Rust from the window's own length. A window whose resets_at has passed is not drawn: it describes an interval that has ended. The answer is a PlanUsage — the windows, unmetered for a credential with no plan behind it, or unavailable with the vendor's reason — because an empty set of windows and a vendor that would not answer are different facts and only one of them means "nothing is spent". A snapshot column used to hold this (harness_accounts.usage_json, filled by the daemon over PUT /v1/sessions/{id}/usage); nothing expired it, so an account with no session running was served a reading days old and every window in it read "resets now" (#381). Both are gone.

The daemon still reads the plan — the Agent SDK's usage_…() control request after each result frame, Codex's account/rateLimits/read at handshake and after every turn — but only for the limit it may announce: a window the vendor reports at 100% is one of the three signals of a spent plan, normalized to HarnessEvent::UsageLimited above. Neither read can end a session, so a refusal is a warning and nothing is drawn from it.

The mount is proved, not assumed. After the harness starts, each driver asks it what it actually mounted — the Agent SDK's mcpServerStatus(), Codex's mcpServerStatus/list — waits out anything still connecting, and fails the session unless flyco is connected and advertising machine_status, budget_status and machine_resize. An agent that cannot read its budget will spend past it, so that session does not run. Codex is asked inside the handshake, so start refuses and no session exists; Claude Code reports it just after the CLI's initialize, so a session that is already identified ends on a Fatal.

Budget engine

flyco_core::budget, pure and exhaustively tested. Thresholds: notice 50%, warn 80%, final warn 90%, pause 100%; budgets under $5 signal only at 90%+pause. Budgets cover compute + storage, never LLM tokens. Money is integer microdollars (Usd) — floats never enter the domain. A scheduled Worker cron prices machine time from provider catalogs and posts spend to each live session's DO.

Providers

flyco_provider::CloudProvider: catalog (typed pricing, including minimum-billing flags like EC2 Mac's 24-hour Apple-license minimum), provision, resize (disk-preserving), deallocate, start, destroy. Every method takes &mut self, because a driver caches state it must be able to replace — an Azure access token, refreshed at 80% of its lifetime and on any 401 — and modelling that with &self would mean interior mutability, which on a Send future means a lock.

No driver touches zenwave directly. They build a flyco_provider::http::HttpRequest and hand it to an HttpTransport, which is ZenwaveTransport in production (Fetch on the Worker, hyper natively) and a table of recorded exchanges under test. That indirection is what makes the wire assertable: crates/provider/fixtures/ holds the recorded provider responses, and the tests pin the exact URL, query, headers and body each operation produces — down to the AWS signature, which is reproducible because the signing instant is injected rather than read. Spot by default; eviction notices are watched by flycod on the VM metadata endpoint (Azure Scheduled Events Preempt, EC2 IMDSv2).

A machine is a virtual machine or a managed container, and that is one axis on the machine rather than a second set of providers (issue #235). flyco_core::Runtime is Vm | Container; it sits on MachineSpec, on every MachineCatalogEntry, and — written by flyco_provider::flycod — in the flycod configuration the machine boots. The same subscription sells both: an Azure account offers Standard_D4s_v6 as a virtual machine and a Container Apps job as aca-4x8, and the driver that reaches them is the same driver. Curation never compares across the axis, for the reason it never compares across architecture or OS — a container that loses its filesystem when it stops is not a cheap VM, it is a different bargain.

What the axis decides is whether the filesystem survives a stop, and every operation follows from that. deallocate on a VM keeps a disk; on a container there is no disk to keep, and what makes the session resumable is the workdir-patch its daemon wrote on the way out. start on a container is a new execution on a fresh filesystem: clone, then replay that patch. resize on a container is stop, then start at the new size — a job's size belongs to the execution, so there is nothing to modify in between, which makes it cheaper than a VM resize and not a degraded one. A driver with no size to change refuses with ProviderError::Unsupported; host::Host is the one such driver, because hardware the user owns has the cores it has.

A container entry may carry a free_grant, the allowance its provider gives away each month before it bills anything: Azure Container Apps publishes 180,000 vCPU-seconds and 360,000 GiB-seconds per subscription per month, Cloud Run 240,000 and 450,000. It is stated in the provider's own two meters rather than in hours or dollars, because that is how it is spent, and the constants live beside the driver that publishes them (azure::CONTAINER_APPS_FREE_GRANT, gcp::CLOUD_RUN_FREE_GRANT). auto_linux_choice prefers a granted container over everything else, hardware the user owns included: the grant expires unspent at the end of the month and the machine at home does not.

A Machine carries its own region. Every operation after provisioning needs it — an EC2 call is addressed to a regional endpoint, an ARM resize re-checks the region's quota — and the alternatives are worse: reading it back off a public DNS name works until a provider spells a region differently in one (us-east-1 is compute-1 in an EC2 hostname), and a machine with no address yet would have nowhere to keep it.

Every provisioned machine boots the same flycod configuration, rendered once by flyco_provider::flycod as a serde document — not a template, because the daemon's loader is deny_unknown_fields and escaping and layout have to be the serializer's problem. crates/daemon/tests/provisioned_config.rs renders it and parses it back with the daemon's own loader, so a field renamed on either side fails a test rather than producing a machine that boots and never phones home.

Azure

Every step is an HTTPS call, so the whole driver runs in the Worker. Written against azure-arm.md, which measured a real subscription — where that document contradicts an assumption, the document wins; where a later live test contradicted the document, the test wins and the document carries the correction.

Auth is client-credentials OAuth2 against login.microsoftonline.com/{tenant}/oauth2/v2.0/token, scope https://management.azure.com/.default. The token is cached against a monotonic clock (not wall-clock, which an NTP correction can move backwards) and refreshed at 80% of the stated expires_in, or on any 401 — the service is the authority on its own tokens and the clock is only an optimisation.

Per session it is three PUTs: public IP → network interface → virtual machine. The resource group, virtual network and security group are one-time workspace infrastructure, one set per region because a network's location is immutable. The resource group is created out of band: creating one is a subscription-scope write and no resource-group-scoped role can create the group it is scoped to. The security group is not optional — Basic public IPs were retired 2025-09-30 and Standard ones are closed to inbound traffic by default, so skipping it yields a machine that provisions cleanly and answers nothing. zones is never sent, and is not modelled at all: zone-restricted-but-usable is the dominant SKU pattern and a regional deployment is what succeeds.

Whether a machine can actually be created is the intersection of three independent gates, and each is invisible from the others:

  1. SKU restrictions — read from the SKUs REST endpoint, never az vm list-skus, which silently hides every Location-restricted SKU (532 visible of 1366 real in one measured region). Location means unusable there; Zone means usable, regionally.
  2. Quota — on-demand spends the machine type's family (keyed by the SKU's own family field, which matches the usage list exactly) and the region's cores; spot spends only lowPriorityCores and no family quota at all. Checking spot against a family quota would refuse machines the subscription can genuinely run.
  3. The subscription's own policy — an allowed-regions policy assignment refuses every PUT into a region outside its list, including the virtual network, and neither the SKU list nor the CLI mentions it. Measured: the region with the most deployable machine types on the reference subscription is forbidden outright. flyco reads Microsoft.Authorization/policyAssignments and keys on the parameter name listOfAllowedLocations rather than a policy definition id, because the parameter is what has the effect and another account will not have the same assignment. No assignment means every region, never no region.

Metered spend is Azure's own number. GET /v1/usage/cloud asks Cost Management (POST …/providers/Microsoft.CostManagement/query, type: ActualCost, timeframe: MonthToDate, granularity: None) rather than summing flyco's own machine records, which would miss the storage, egress and support charges on the same invoice. BillingMonthToDate is a billing-account concept and is refused at subscription scope — the only scope a flyco service principal is granted — so the window reported beside the amount is exactly the window Azure summed: midnight UTC on the first of the calendar month, to the instant of the query. Columns are read by name out of the result's own columns list, never by position, because the column set moves with the request. A subscription metered in another currency is refused rather than converted, and remaining_credit stays None: the balance API is EA-only, and a Some(0) would tell a user their free credit is spent. The instant is passed in rather than read — flyco_provider has a monotonic clock for token expiry and deliberately no wall clock.

AzureProvider::region_report is that computation with its workings shown: it returns what is offered plus an ExclusionReason per machine type, so a user can be told which of the three problems they have — "your subscription's policy forbids this region" is a different thing to fix from "no quota" and from "not sold here". The catalog's region set is the policy's own list; a caller's named regions narrow it.

Spot is requested by default and usually works. On AzureSpotFeatureNotEnabledForSubscription or AzureSpotIsNotSupportedForThisVMSize — from the PUT or from the async operation's terminal error — the identical body is re-sent with the three spot fields removed, after re-checking the on-demand pools, and the capacity actually obtained is recorded on the machine because that, not the request, is what the price follows.

Async operations: Azure-AsyncOperation in preference to Location (never both), Retry-After honoured per response, terminal set exactly {Succeeded, Failed, Canceled} — anything else means keep polling, including in-flight values a resource provider invents. The operation's status is trusted, never the resource body: a failed resize leaves the machine reporting the size it was asked for while still running on the old one. Resize is therefore always deallocate → PATCH vmSize → start.

Pricing comes from the unauthenticated retail-prices API, cached with a TTL because spot meters are republished monthly. Rows are discriminated by productName containing Windows (there is no Linux marker — Linux is the row without one), skuName ending Spot, and Low Priority, which is the older scale-set meter and is not spot.

Cloud-init installs flycod through osProfile.customData, rendered from an askama template with the daemon configuration base64'd into a write_files entry — so the session's daemon token never appears as a legible substring of the request.

The same subscription also runs containers (azure::containers, api-version 2025-07-01). A Runtime::Container session is one execution of an Azure Container Apps job: PUT …/Microsoft.App/managedEnvironments/flyco-<region>-env creates the environment a region's jobs share — lazily and idempotently, exactly as ensure_workspace creates its network — then PUT …/Microsoft.App/jobs/flyco-<machine> defines the job, and POST …/jobs/{job}/start runs it. The execution's name is Azure's to choose and changes with every start, so the machine's native_id is the pair job/execution; the job is the half that survives a stop, which is what makes a start a start. Stop is POST …/jobs/{job}/executions/{execution}/stop, destroy is that plus DELETE …/jobs/{job}, and resize is stop → PATCH the job's template at the new size → start. The PATCH is not a second PUT, because a PUT replaces the job and the driver does not hold the session's flycod configuration at resize time — re-sending the job without its secrets would delete the one the container reads its configuration from.

The environment declares exactly one workload profile, Consumption: serverless, so nothing is billed between executions and the free grant applies, where every other profile is reserved instances billed by the hour whether a session runs or not. Its appLogsConfiguration.destination is azure-monitor, the only destination needing no Log Analytics workspace — log-analytics carries a workspace's customer id and its shared key, a second credential flyco would have to create a workspace to obtain. The job carries triggerType: Manual, parallelism: 1, replicaRetryLimit: 0 (a retried replica would be a second daemon on one session) and a seven-day replicaTimeout, which a job must state and which exists only for the case where the budget, the idle timeout and the user all fail to stop it. The daemon's configuration reaches the container as a job secret referenced by FLYCO_DAEMON_CONFIG — the same variable, the same base64, the same image a machine the user owns runs, pinned to :wire-<version> rather than :latest because a container flyco starts on the user's behalf has to speak the wire this control plane speaks.

Container Apps publishes no SKU list and no per-subscription vCPU quota a credential can read, so the only gate a container passes is the region policy — which does apply, since it refuses the environment's PUT exactly as it refuses a virtual network's. The catalog's sizes are therefore flyco's own short table (aca-1x2, aca-2x4, aca-4x8; the platform pairs 2 GiB with every core), priced from the retail API's Standard vCPU Active Usage and Standard Memory Active Usage meters — quoted per vCPU-second and per GiB-second, multiplied out to the hour before rounding to microdollars, and active rather than idle because a job replica runs the whole time it exists. A region publishing neither meter offers no containers rather than an unpriced one.

AWS

Every step is an HTTPS call, so the whole driver runs in the Worker. There is no SDK: a request is the same HttpRequest every other driver builds, signed with SigV4 by aws-sigv4 (the vendor's own crate, verified on wasm32) and sent through the same transport. host is signed but never sent — it is a forbidden header for the Worker's fetch, and the value the service sees is the URL's own authority, which is exactly what was signed.

Signing needs civil time, which is the one thing the crate's monotonic clock cannot supply, so flyco_provider::clock::WallClock exists for this and for GCP's assertion claims and nothing else. It is a trait rather than a call to the host because that is what makes a signature assertable: with the instant supplied, crates/provider/src/aws/tests.rs pins the exact X-Amz-Date, the exact credential scope and the exact SignedHeaders list.

EC2 speaks the Query protocol — form-encoded requests, XML answers, no JSON dialect — so requests are #[derive(Serialize)] structs run through a serde serializer (aws::query) that knows the protocol's flattening rules, including that lists are one-based. Names are never assembled with format! at a call site. Answers are read by quick-xml, the one XML reader in the workspace.

The three gates again, in AWS's vocabulary:

  1. Region access — every region introduced since 2019 is disabled until the account opts in, and a disabled region's endpoint answers AuthFailure naming neither the region nor the reason. DescribeRegions with AllRegions is what makes it readable. This is the exact counterpart of Azure's deployment policy: a property of the account the catalog says nothing about.
  2. Availability — DescribeInstanceTypeOfferings for the region, which is a strict subset of what EC2 sells; DescribeInstanceTypes supplies the shape, the instruction set that picks the AMI, and whether the type is on the spot market at all.
  3. Quota — and spot draws on a different pool, exactly as on Azure: All Standard … Spot Instance Requests is a separate limit from Running On-Demand Standard … instances. Which quota binds an instance type is read out of the quota's own name (Standard (A, C, D, H, I, M, R, T, Z), P, Dedicated mac2) rather than from a table that would be wrong the week AWS adds a family. Service Quotas publishes only the ceiling, so what is under it is counted from the account's own running instances — Azure publishes both halves in one list, and this split is what AWS offers rather than a design choice.

Spot is a persistent request whose interruption behaviour is stop. Both halves matter: stop keeps the EBS root volume, where the default terminate would delete the session's work, and persistent lets the request bring the machine back rather than expiring with it. On a refusal that is about the spot market (aws::SPOT_UNSUPPORTED_CODES) the identical body is re-sent without its market options, after re-checking the on-demand pool, and the capacity actually obtained is read off the instance's instanceLifecycle — not off the request.

There is no operation resource. EC2 answers a mutating call with the instance's previous state (StopInstances says stopping), so every call is followed by reading the instance state until it settles, and the settled state is what is trusted. Never a read-back of the attribute that was set: a ModifyInstanceAttribute that failed leaves the instance running on the old type with nothing to distinguish it. Resize is therefore always stop → ModifyInstanceAttribute → start.

Nothing is orphaned. The root volume carries DeleteOnTermination: false — this driver's Detach — and the address is an elastic IP, because an auto-assigned one is lost on stop and a session that comes back from an interruption at a different address is a session nothing can find. Both outlive the instance, so destroy reads the volume id and the address before terminating (an elastic IP's association is gone the moment its instance is, which is why the address is tagged at allocation and found by tag), then terminates, waits, releases the address, waits for the volume to actually detach, and deletes it. A launch that fails releases the address it had already allocated: an unattached elastic IP is still billed by the hour.

The AMI is read, never hardcoded — an id is region- and architecture-specific and changes on every republication — from Canonical's public SSM parameter, with the architecture taken from the instance type's own answer (t4g is Arm, t3 is x86). The image's rootDeviceName is read too, because a block-device mapping naming the wrong device is silently ignored and the volume comes out the image's default size.

Pricing is two services. On-demand comes from the Price List Query API, filtered to Linux, shared tenancy, no pre-installed software and Used capacity — each filter removes a meter that prices the same hardware differently. Spot comes from EC2's own DescribeSpotPriceHistory, quoted at the cheapest availability zone, because a launch that names no zone lands wherever there is capacity. EC2 Mac carries minimum_billing_hours: 24: Apple's licence requires a 24-hour minimum allocation of the dedicated host, so an hour is billed as a day and a budget told the hourly rate alone would be wrong by about sixteen dollars. The entry is in the catalog for exactly that reason even though provision refuses it — flyco's session image is Ubuntu and there is no Ubuntu for a Mac, and the refusal says so.

The same account also sells containers, as standalone ECS tasks on Fargate (aws::fargate, issue #235). A spec whose runtime is Container names a shape on Fargate's grid — fargate-1x2 … fargate-16x64, two GiB a core and four at the top of the menu where a linker needs it, on either instruction set (fargate-arm64-4x8 is a different entry at a different rate) — and everything shared with the EC2 path is shared rather than repeated: the SigV4 signature, the JSON 1.1 envelope, the region-access gate, the workspace network, the flycod configuration, the flyco-<machine> naming. A task definition is the machine's shape and a task is the machine: RegisterTaskDefinition writes a revision and starts nothing, RunTask starts the task that holds the vCPU and the memory, and native_id is the task's ARN alone. The definition half is recovered rather than stored beside it — the family is the machine's name and the revision to run is whichever is ACTIVE, which is exactly what a resize changes — so a row written before a resize still names the shape the machine has now. One cluster per region, created lazily with both capacity providers associated, is the counterpart of the workspace security group: a Fargate cluster owns no instances and costs nothing.

Spot is a second call, because AWS states Fargate never falls back on its own. RunTask names one capacity provider — FARGATE_SPOT when the spec asked for interruptible capacity — and a strategy naming both would leave flyco unable to say which market it is paying for. What makes this refusal different from EC2's is where it is: RunTask answers HTTP 200 with an empty tasks and a failures entry reading Capacity is unavailable at this time…, so a driver reading only status codes would report a machine it never started. On that reason, and only on it, the identical body is re-sent naming FARGATE; the market actually obtained is read off the task's capacityProviderName rather than off the request. Stopping is StopTask, preceded by a read — a task that was evicted or reached its own end is already stopped, and one ECS has purged (it describes a stopped task for about an hour) is nothing left to stop — and waited on, because the next step is either another task of the same definition or the definition's deletion and both would race the container still writing its workdir-patch. A resize validates before it mutates: the one thing a machine-type name could silently change is the instruction set, and a working tree was built for the one it is on. destroy stops, then deregisters and then deletes every revision of the family, because deregistering alone leaves an INACTIVE revision in the account for ever. A redelivered provision or start adopts the family's live task, which is this driver's half of the at-least-once rule — ECS's own clientToken is not used, because it pins the first task ARN it saw and the obvious token (the machine id) would make every later start answer with the task it is replacing.

A container's price is the Price List again, under AmazonECS. Fargate has no offer code of its own: three queries per region read the per-vCPU-hour and per-GiB-hour meters (an x86-64 pair, a Graviton pair, and Windows pairs that are dropped) and the ephemeral-disk rate, and a region publishing no pair for an architecture offers no container of it rather than an unpriced one. Fargate Spot is the one price AWS publishes nowhere — no Spot meter under AmazonECS, no Fargate offer code beside it, and the pricing page says only that Spot rates are set by AWS and adjust gradually, at up to 70% off — so the catalog quotes the on-demand rate as what it is, the published ceiling: the session runs on Spot and is billed at less than flyco quoted, never more, and an entry with no spot price at all would be one flyco never asks Spot for. There is no free grant (Fargate gives away no task capacity), no execution role (the image is public and the logs go to the control plane over the relay) and no task role (an AWS identity inside the session is the one thing an agent must not be handed). The session's disk is the task's ephemeral one, sized from the spec above Fargate's free 20 GiB and refused above its 200 GiB ceiling; the free allowance is not expressible in StoragePricing, so the metered rate is quoted for every GiB — at most a fifth of a cent an hour above what AWS bills, never below. The flycod configuration travels base64 in FLYCO_DAEMON_CONFIG, the same variable the host path passes to Podman, and is readable by anyone the account grants ecs:DescribeTaskDefinition — the same exposure a VM's user-data has, bounded by deleting the definitions with the machine.

Metered spend is Cost Explorer's GetCostAndUsage, UnblendedCost, month to date. Its period end is exclusive, so the window flyco asks for ends tomorrow and today's spend is inside it.

GCP

Of the three cloud drivers this is the one closest in shape to Azure's: every mutating call answers with an operation resource that is polled to a terminal state, and the operation is what is trusted rather than a read-back of the resource.

Authentication is a signature, not a secret. A service account proves itself by minting a JWT, signing it RS256 with the account's private key, and exchanging that assertion for an OAuth2 token under the jwt-bearer grant. rsa + sha2, both pure Rust and both verified on wasm32; PKCS#1 v1.5 is deterministic, so signing takes no RNG — which is both why it compiles on a target with no random source and why a test can assert the assertion byte for byte. (rsa still reaches getrandom 0.2 transitively, which refuses to compile for wasm32 without its js feature, so flyco-provider declares that crate for the wasm32 target purely to turn the feature on.) The assertion's iat/exp are wall-clock claims Google checks against its own clock, which is the second reason WallClock exists; the token cache is keyed on elapsed time, for the reason Azure's is.

Two gates, not three, and flyco says so. Azure has a subscription policy and AWS a region opt-in, both readable by a provisioning credential. Google's equivalent — the gcp.resourceLocations org policy — is an Org Policy API read a project-scoped service account is not granted and cannot be, so the driver does not pretend to check it: a project under such a policy is refused at the insert with a code that names it. What is checked is what a compute credential can see: the zone offers the machine type and it is not OBSOLETE, and the project's quota covers it. Spot draws on a different pool here too — PREEMPTIBLE_CPUS against CPUS — and unlike AWS, a region's own answer publishes limit and usage together, so there is nothing to count.

Spot is provisioningModel: SPOT with onHostMaintenance: TERMINATE — required rather than inferred, because a spot instance may not be live-migrated and the API refuses the insert otherwise — and instanceTerminationAction: STOP, which is what keeps a preempted machine's boot disk instead of deleting it with the instance. On a capacity or quota refusal the identical body is re-sent as STANDARD, after re-checking the on-demand pool.

A DONE operation is not a successful one. Failure is reported inside the finished operation (error.errors[].code, httpErrorStatusCode), so reading the status alone would call a failed provision a success. The terminal set is exactly {DONE}; PENDING, RUNNING and anything the service invents mean keep polling.

The boot disk carries autoDelete: false — this driver's Detach — so destroy deletes the instance and then the disk, in that order, because a disk that is still attached cannot be deleted. Resize is stop → setMachineType → start, and the machine type is a full zonal URL: a bare name is refused. The external address is ephemeral and released on stop, so start reads the instance back for its new address; that read is only for the address, because whether the operation worked came from the operation.

A machine type has no price. Google publishes a rate per vCPU-hour and per GiB-hour, per family, per region, per market, so pricing folds the Cloud Billing SKU catalog into a (family, market) rate table and multiplies by each type's own shape. The family is not in any structured field — it is the first family-shaped word of the description (E2 Instance Core, but also N1 Predefined Instance Core and Spot Preemptible E2 Instance Core), so "the word before the marker" is wrong and the code looks for letters-then-digits. Prices are units + nanos, which converts to microdollars exactly rather than through a float. A catalog entry names the zone, not the region: a machine type offered in one zone of a region is routinely absent from another.

Metered spend is None, and that is a fact rather than a gap. Google publishes no spend-to-date API: billing data reaches a project through a BigQuery export the user configures, and a project-scoped service account cannot read a billing account's running total at all. So a GCP account contributes no row to the cloud usage panel, for a different reason than a machine the user owns and with the same answer — silence rather than a $0.00 that would read as "this costs nothing".

The same project also sells containers, as Cloud Run jobs (gcp::run, issue #235). A spec whose runtime is Container names a size on Cloud Run's own grid — cloudrun-1x4 … cloudrun-8x32, four GiB per vCPU, the top of which is exactly Cloud Run's ceiling — and everything shared with the compute path (the signed assertion, the 401 retry, the flycod configuration, the flyco-<machine> naming) is shared rather than repeated. A job is a definition and an execution is the machine: jobs.create writes the definition and starts nothing, jobs.run starts the execution that holds the vCPU and the memory, and a machine's native_id is therefore both halves, <job>/<execution>. That pair is also how a later operation tells the two runtimes apart without a field on Machine: a Compute Engine machine's native id is an absolute URL, and run::Handle::parse accepts only a name this driver derived followed by one path segment.

Nothing waits for the run operation. An instances.insert operation finishes when the machine exists; a Cloud Run run operation finishes when the task does, which for a session is up to its 168-hour timeout away — waiting on it would be waiting for the session to end. The execution's name is in the operation's metadata the moment Cloud Run accepts the call, which is all the caller needs. Every other operation — create, patch, cancel, delete — is administrative and is followed to done, and done alone is not success there either. maxRetries is 0: a retry would put a second flycod on one session token. Stopping is executions.cancel and is waited on, because the caller's next step is either another execution or the job's deletion and both would race the task still writing its workdir-patch; an execution that already finished is read first and left alone. A resize cancels, reads the job back for the one thing it cannot re-derive — the session's own configuration, which lives in the container's environment — patches the size, and runs again. destroy cancels and then deletes the job. A redelivered create or start adopts the execution that is already running rather than starting a second one, which is this driver's half of the at-least-once rule.

Cloud Run is priced from a published table rather than a SKU walk. Two rates in two regional tiers — Tier 1 $0.000018 per vCPU-second and $0.000002 per GiB-second, Tier 2 a fifth more — with the region lists cloud.google.com/run/pricing publishes beside them, held as nanodollars so an hour of any of them is an exact number of microdollars. They are the instance-based rates, which is what the page states a job is billed at for the entire lifetime of the instance it starts, not the request-based rates a service pays. A region in neither list is one flyco cannot price, so it publishes no container there and refuses a request for one rather than quoting the wrong tier. The entries carry CLOUD_RUN_FREE_GRANT, no spot price (Cloud Run sells no interruptible capacity) and no storage price (a job's filesystem is the in-memory one the memory rate already pays for; flyco requests no ephemeral disk). The session's flycod configuration travels base64 in FLYCO_DAEMON_CONFIG, the same environment variable the host path passes to Podman, so one image serves both — and, as with a VM's user-data, it is readable by anyone the project grants run.jobs.get, which the job's deletion with the machine is what bounds.

Hosts: a machine the user owns

The control plane runs on Cloudflare Workers, which have no TCP sockets, so flyco can never open a connection to somebody's machine. A host is therefore enrolled rather than dialled — the shape GitHub's self-hosted runners and Tailscale nodes have, and the only shape a Worker can drive (docs/host-enrollment.md).

browser ── REST ──▶ Worker ──▶ HostRoom (DO) ◀── REST attach + SSE commands + REST frames ── flycod host ── podman ── session container

Enrollment. POST /v1/hosts/enrollment-tokens mints a single-use fh_ token, ten minutes long, stored hashed like every other flyco credential, and renders the one line the wizard shows — from a template, against this deployment's origin, because a command assembled in the browser would point wherever the page happened to be served from. The machine runs it, POST /v1/hosts/enroll spends the token and creates two rows: the host, and a provider account of kind host carrying its id. That second row is what keeps a machine somebody owns from being a special case anywhere else — the compute chip, the curated catalog, session creation and the usage panel all speak provider_accounts.

Its catalog is one entry: itself, priced UserOwned, sized and architected from the facts the machine reported. Offered only while the host is online: an offline machine is not a cheaper machine, it is one that cannot be started, and putting it on the slider would be a choice that fails the moment it is taken.

Provisioning is a container job. flyco_provider::host::Host compiles on wasm32, performs no I/O, and plans: it turns a MachineOperation into a serializable ContainerJob — create (with a Podman volume for the checkout), stop, start, remove — which the Worker posts to the host's room. resize is ProviderError::Unsupported, never a silent no-op: the machine has the hardware it has. The rendered podman script lives beside the planner (host::script), with every interpolated value shell-quoted, because that text is the contract with Podman and flycod host runs exactly what it produces.

The room is the authority on liveness; D1 is the authority on identity. A Durable Object can reach neither D1 nor KV, so the split is not a preference:

  • The machine's HostAttach { facts } reaches its room, which records the facts and hands over whatever the mailbox is holding on the command stream that attach opens. The Worker sees the attach, and that is where hosts.state is written online.
  • Every read of a host asks its room whether the attachment is still live and writes back what it learned, so a machine that was unplugged reads offline on the next look — without a cron, a heartbeat route, or a second copy of the facts.
  • HostToControl::JobResult reaches the room, which forgets the job it was holding. The durable half — the container and volume names on the machine row — arrives at the Worker over REST as a ReportJobResult, authenticated by the host's own token. Two routes for one fact, exactly as a session daemon's spot notice travels twice and for the same reason.

The mailbox. A container job is written to the room's own SQLite before anything tries to deliver it, and stays there until the machine answers it: a Run lost while a machine reboots is a session that never gets its container, or a container nobody ever removes. Delivery is therefore at-least-once, which is what a job is written to survive — a redelivered create whose container is already there starts it rather than rebuilding it, a stop whose container is gone is already done, and a removal is podman rm --force --ignore.

The machine's end is flycod host, the same binary a session VM runs, in its other role (crates/daemon/src/host). flycod host enroll measures the machine — architecture, vCPUs, memory, free space where Podman keeps its storage, Podman's version, kernel, hostname — spends the enrollment token, and writes /etc/flyco/host.toml mode 0600: the host id, its long-lived token, its control plane, and the Podman layout. flycod host run is the unit: it attaches with HostAttach { facts }, holds the SSE command stream open, reports each job's outcome with POST …/relay/frames, and reconnects with the session relay's own backoff. The room's stream pings keep the flow honest — a machine that hears nothing abandons it and attaches again — and each job runs on its own task so a podman run pulling an image does not stall the stream. It runs as root — nothing else may read the token — and drops to the unprivileged flyco user with runuser for every podman command, so the containers themselves are rootless. A Revoked frame stops the loop and records the revocation in the configuration, so a restarted unit refuses rather than reconnecting against a credential that will never work again.

Removal drains. DELETE /v1/hosts/{id} refuses while sessions are still running there unless force; forced, it stops each container keeping its volume — the session's work is still on hardware the user owns — marks those machines deallocated, revokes the token, and tells the room, so the unit on the machine stops rather than reconnecting for ever against a credential that will never work again.

Version pins and platform notes (skyzen 0.6.1, zenwave 0.12.0)

Built against skyzen 0.6.1 (&self DurableObject::fetch activations) and zenwave 0.12.0 across a single main branch.

  • Production SPA hosted on Cloudflare Pages (wrangler pages deploy dist --project-name flyco --branch main in .github/workflows/deploy.yml); EmbeddedStaticDir remains in flyco-api for embedded/local serving.
  • openapi.json exported by a native debug run — cargo run -p flyco-api --bin openapi > openapi.json (linkme collection is debug+native only). The result is checked in at the repo root (134 paths, 158 operations, 223 schemas) and CI fails on a diff; the TS client is generated from that artifact. #[skyzen::openapi] cannot be applied to a generic handler (it emits module-level items naming every argument type), so auth/github/callback and github/repos export their paths without schemas, and their operation ids carry the type argument they were monomorphized with.
  • Response bodies derive themselves. Responder::openapi reaches the document, problem::Outcome forwards what it wraps, and respond::{Created, NoContent, Accepted, SeeOther} each report their own status — so an operation's status and payload come from its handler's return type. flyco_api::responses is down to two jobs: naming every returned DTO in components.schemas (a Json<Vec<T>> registers under utoipa's name for Vec<T>, which is the bare string Vec for every element type, so T itself would never get a name and the placeholder is dropped), and listing in BODILESS the operations that answer with a status and nothing else. crates/api/src/tests/responses.rs asserts the two are exhaustive against both the live router and the checked-in file. 101 of 158 operations carry a response schema; the other 57 are the 204/202 answers, redirects, the SSE streams (/v1/events, the two relay command feeds, session event replay), raw-byte transcript routes, and the generic github/repos handler.
  • D1 migrations via wrangler d1 migrations; KV/D1 resource IDs provisioned with wrangler and pasted into crates/api/Skyzen.toml (the manifest must sit next to the crate's Cargo.toml — that is where #[skyzen::main] looks for it). crates/api/src/testing.rs applies the same files statement by statement to an in-memory SQLite database rather than running skyzen's migration runner, so there is one opinion about which migrations a database has.
  • Logs are retained and are the first place to look. [cloudflare.raw.observability] in crates/api/Skyzen.toml turns on Workers Logs with full sampling, and the Worker installs a console-backed tracing subscriber at debug (crates/api/src/telemetry.rs), so every refused request (4xx, logged by ApiError::problem) and the full reason behind every opaque 5xx is stored, alongside the runtime's own request events and any panic (the panic hook writes it). Never ask a user to reproduce a failure; read it. Programmatically: POST https://api.cloudflare.com/client/v4/accounts/<account>/workers/observability/telemetry/query with an API token holding Workers Observability: Read (the wrangler login token does not; the dev deployment keeps one as CLOUDFLARE_LOGS_TOKEN in crates/api/.env), body {"queryId": "...", "timeframe": {"from": <ms>, "to": <ms>}, "parameters": {"datasets": ["cloudflare-workers"], "filters": [{"key": "$metadata.service", "operation": "eq", "value": "flyco", "type": "string"}], "needle": {"value": "..."}}, "view": "events", "limit": 100}. Request rows have $metadata.type == "cf-worker-event" (status under $workers.event.response.status, the Worker's outcome under $workers.outcome); tracing lines are cf-worker rows with the line in $metadata.message; $metadata.requestId joins the two. The dashboard's Logs page reads the same store.
  • D1 migrations are applied by the deploy workflow, ahead of the Worker: .github/workflows/deploy.yml runs skyzen migrate (which is wrangler d1 migrations apply flyco-main --remote against the generated crates/api/.skyzen/gen/wrangler.toml, from skyzen-cli 0.4; the manifest's [[database]] entry only moves the native path, so the D1 entry wrangler reads is restated in full under [[cloudflare.raw.d1_databases]] with migrations_dir = "../../../../migrations", resolved by wrangler against that generated file's own directory) and only then skyzen deploy, so a merge that adds a migration ships the schema first and a migration that fails leaves the previous code serving (issue #363 is what happened when the two were separate steps: three migrations behind, and the minute cron and every budget read failing). By hand, for recovery only: the same skyzen migrate from crates/api with the deploy .env present, or wrangler d1 migrations apply flyco-main --remote --config <file> with a config whose [[d1_databases]] entry names the repo-root migrations/. A migration's file name is part of the d1_migrations ledger once it has run: renumbering an applied file makes wrangler apply it again, so the ledger row is renamed with it. Publish flycod after the deploy if crates/daemon changed.
  • flycod is published by cargo xtask publish-flycod, and by nothing else. The daemon cannot ride in the Worker bundle, so everything a machine installs lives in the deployment's R2 bucket under releases/dev/, where flyco_api::releases serves it to the machine installer. One command produces all seven objects (flyco_core::release::OBJECT_COUNT): the two Linux binaries (flycod-linux-x86_64, flycod-linux-aarch64), a checksum for each (.sha256), the installer flycod.sh, and the two systemd units (flycod.service, flycod-host.service) — plus the session container image ghcr.io/may-agent/flyco-session (flyco_core::release::SESSION_IMAGE), built out of crates/xtask/image/ on the staging directory with the binaries just cross-compiled, tagged :<channel>, :wire-<version> and :latest, and pushed before any bucket object is uploaded so a refused push changes nothing under the machines already installing. Versioned daemon objects (the binaries and checksums) are stored under wire-<N>/ and also at content-addressed wire-<N>/<sha256>/<name> keys (flyco_api::releases::get_with_digest) so a re-publish never races edge-cache windows between a binary and its .sha256. The image is built in two cached layers from crates/xtask/image/Containerfile: flycod.sh image-runtime installs the same runtime the installer puts on a VM minus systemd (cached in GHCR under :buildcache-<arch> whenever flycod.sh is unchanged), and a second layer copies flycod and verifies flycod --version, followed by the flyco-session entrypoint that decodes FLYCO_DAEMON_CONFIG into the daemon's configuration and execs flycod run; a dry run builds the host's architecture, loads it, and asks the daemon inside its version. It links against glibc 2.31 via cargo zigbuild --release -p flyco-daemon --bin flycod — Ubuntu 20.04's baseline, so one binary runs on every image flyco provisions — writes each flycod-linux-<arch>.sha256 as the exact <hex> <name> line sha256sum --check reads, copies the installer and the units verbatim out of crates/xtask/install/, and uploads each with wrangler r2 object put flyco-transcripts/releases/<channel>/<key> --file … --content-type … --remote. The installer is part of the release, not a file someone uploads by hand, because an installer that drifts from the binaries it installs is a machine that provisions and does not connect; crates/xtask/install/ is its one copy, read by the publish and by nothing else — the PWA does not serve /install/, the Worker's allowlist does. The names are declared once, in flyco_core::release: the publisher builds its object set from that table and flyco_api::releases allowlists from the same one, so an eighth object the control plane would refuse cannot be uploaded and a name it serves that no publish writes cannot exist. Afterwards the publish reads back what https://dev.flyco.dev/install/ actually serves — every checksum and the installer assets, cache-busted with a nonce because the artifacts are served max-age=60 — and fails unless the bytes and the media type are the ones it just staged, because the build, the bucket and the Worker's allowlist are three places a release can be half-done. It refuses to upload a daemon the deployed control plane would refuse: GET /v1/healthz reports the Worker's flyco_core::WIRE_PROTOCOL_VERSION and a publish whose own version differs is stopped before it builds, since that pair provisions machines that are refused at attach and never connect — --allow-wire-mismatch is how an operator says the matching Worker deploy is following, and --dry-run stages all seven objects under target/flycod-release/<channel>/ and uploads none of them. .github/workflows/publish-flycod.yml runs the same command split across two parallel native runners (--arch x86_64 on ubuntu-latest and --arch aarch64 on ubuntu-24.04-arm, zero QEMU, pushing single-arch images by digest) followed by a --finalize job that merges the manifest list with docker buildx imagetools create, uploads to R2, verifies, and attests all seven objects.
  • [[database]] name = "main" default = true is declared in Skyzen.toml: #[skyzen::main] opens D1 on the Worker and a SQLite file (FLYCO_DATABASE_URL) natively, and injects it, so a handler's bare Db argument resolves to it and nothing in the crate names the binding. flyco_api::router still takes a Db explicitly — that is the seam the tests drive.
  • [native.service.auth_kv] backend = "memory" resolves to skyzen_test::mock::InMemoryKv, so skyzen-test is a dependency of flyco-api's native target — the Worker build never sees it.
  • skyzen-cloudflare pulls the official worker crate, which pulls tokio into the wasm dependency graph. Nothing in flyco uses it.
  • flyco_api::expiring keeps its own deadline inside every value and sets the store's. The logical deadline is the rule: Cloudflare KV's expiry has a sixty-second floor — once the life of a relay ticket, now of nothing flyco still issues — and eviction is the platform's schedule rather than a promise about the next read, so a read past the stored expires_at_unix is a miss whatever the namespace still holds. But a logical deadline alone deletes nothing, and single-use OAuth state keys were accumulating in the namespace for good, so the write goes through Kv::put_with_ttl with the life clamped up to that sixty-second floor. Unreadable at the real deadline, gone from the store shortly after.
  • SSE out of a Durable Object is a spawned pump, not a handler's stream. A DurableDb query future is Send but not Sync, so no Stream combinator can hold it inside Body::from_sse's Send + Sync bound. flyco_api::sse::serve instead opens Sse::channel_with_capacity and spawns the polling loop — executor_core's global executor natively, spawn_local on the isolate's microtask queue on wasm, where the task lives exactly as long as the response it feeds — which also makes the room's ping interval a first-class knob the tests turn down rather than sleep through. crates/api/src/tests/room.rs drives the whole thing against skyzen's SQLite-backed InMemoryDurableDb: attach and frames over fetch().go(), commands read out of the returned SSE body.
  • A Durable Object stub takes a skyzen request and answers a skyzen response on both targets, and its future is Send, so flyco_api::rooms has one call over a platform-resolved stub. No SendFuture, no web_sys request building.
  • #[skyzen::durable_object] on a struct T exports the JS class as TObject, so Skyzen.toml binds class_name = "SessionRoomObject" for struct SessionRoom.
  • No built-in sessions/OAuth/JWT on wasm: GitHub OAuth code flow via zenwave, opaque tokens in KV behind a custom Authenticator. The user arrives as State<CurrentUser> rather than skyzen's AuthUser<T>, because RequireAuth inserts it — and reports it through Middleware::provisions, so Route::try_build proves every handler behind it is wired.
  • flyco_api::middleware::RequireAuth replaces skyzen's AuthMiddleware: the stock one propagates the error to the runtime, which renders {"error": …} and cannot set WWW-Authenticate. Flyco's own errors likewise never propagate — handlers return problem::Outcome, which renders the RFC 9457 document itself — and an ErrorHandlingMiddleware at the router root converts framework errors to the same media type.
  • Stored domain types map themselves onto columns. #[derive(skyzen::Column)] on every enum kept as a text token, and on Usd, gives both directions of the conversion; Id<T> and RepoSlug are hand-written in flyco_core::sql because a phantom-typed id has no concrete newtype to derive on and a slug's parser is its invariant. Row structs derive skyzen::FromRow and name domain types, so a column is decoded by the field's own type and a missing or mistyped one is an error naming both. The mapping lives in flyco-core behind an optional sql feature — FromColumn is skyzen's trait and these are flyco's types, so the orphan rule leaves nowhere else — and the feature is what keeps flycod, which shares the crate and opens no database, from linking a web framework. ColumnEnum::TOKENS is what crates/api/src/tests/schema.rs checks every CHECK (… IN (…)) in migrations/ against, in both directions.

Auth

  • Authorization: Bearer only — no cookies. Two token kinds share one credential channel: fs_ browser session tokens (opaque, KV, 30 days) and fk_ API keys (D1, SHA-256 hashed). The prefix tells the authenticator which store owns the token, so a lookup never probes both. No cookie means no ambient authority and nothing for a cross-site request to ride on.
  • Cookie-less PKCE and fragment OAuth flow (crates/api/src/oauth.rs, crates/api/src/provider_oauth.rs):
    • GitHub sign-in: the SPA generates a per-tab PKCE verifier in sessionStorage and sends its S256 code_challenge to POST /v1/auth/github/start. GET /v1/auth/github/callback performs no exchange and sets no cookies — it forwards code and state in the URL fragment to /auth/complete, keeping them out of server logs and Referer headers. The SPA verifies state against sessionStorage and redeems the code via POST /v1/auth/github/exchange with its code_verifier, receiving the fs_ token.
    • Provider OAuth (Azure, GCP, Codespaces): /v1/providers/{azure,gcp}/oauth/callback (and /v1/auth/github/callback for Codespaces via disjoint cs_ state prefix) forwards provider, code, and state in the URL fragment to /connect/return. The authenticated SPA posts {attempt_id, code, state} with Authorization: Bearer to POST /v1/providers/{provider}/oauth/exchange (proving the signed-in user owns the attempt before redeeming the code, with PKCE for Azure and GCP), then polls and finishes.
  • Users: GitHub OAuth only.
  • Standards: 401s carry WWW-Authenticate: Bearer (RFC 6750), with error="invalid_token" when a credential was presented and rejected. Every error response is an RFC 9457 problem document (application/problem+json); flyco's own failures name a type under https://flyco.dev/problems/, framework-level failures use about:blank. Server-side detail is logged, never returned — the exceptions are the failures whose whole content is somebody else's answer, and ApiError::is_opaque names them one by one rather than by status class.
  • A failed sign-in says which GitHub call failed. Every GithubError carries a GithubCall — the code exchange, the account profile, the repository list, a repository lookup, a branch list — and the three failures become three problems rather than one blanket 502: a code GitHub refused is problems/github-code-rejected (400, quoting GitHub's own error and error_description, because the fix is to sign in again), a status GitHub answered with is problems/github-status (502, "GitHub answered HTTP 401 to the account profile request"), and only a transport failure — whose text is flyco's own client and deserializer — stays the opaque problems/github-unavailable, logged in full and never returned.
  • Harness accounts: flyco redirects to the provider's own auth page (the flow the official CLIs wrap); tokens stored encrypted, provisioned per-session to VMs. Anthropic's third-party-login policy approval is a hosted-launch prerequisite.
  • Usage panels are reactive: no remaining-quota API exists for either harness, so GET /v1/usage/llm reports what flyco observed. harness_observations (migration 0007) is one row per thing a session's daemon saw — the cost the harness reported for a turn, or the moment it hit its account limit — posted as it happens through a daemon-scoped POST /v1/sessions/{id}/harness-observations, because neither number can be asked for after the fact. Which account a row belongs to is a join from the session (its user, its harness) rather than something the daemon names, so a daemon token cannot file against somebody else's account. The panel sums cost over OBSERVATION_WINDOW_SECONDS — flyco's own rolling day, stated in the response as period_start_unix, because there is no billing period to key on — and reports the account's newest rate limit whenever it happened. An account with nothing observed reports null, never $0.00: one is a fact and the other is a claim flyco cannot support. A refused observation never fails a turn; a session on inherited developer credentials has no linked account and legitimately files none.