# Canonical Platform Architecture
**Status:** Approved implementation baseline
**Date:** 2026-09-02
**Scope:** Cloudflare-centric coding and research agent platform
**Execution design:** [Canonical Run and Execution Model](./RUN_EXECUTION_MODEL.md)
## 1. Purpose and Decision Summary
This document is the canonical architecture baseline for the platform. It consolidates the decisions made during architecture review and incorporates the agreed production hardening without moving away from the intentional Cloudflare-centric design.
The platform is organized into four logical planes:
1. **Control Plane** — trusted request handling, identity, authorization, live agent coordination, durable orchestration, policy, and routing.
2. **Execution Plane** — isolated code, shell, Git, browser, build, test, and heavy-compute execution.
3. **Data Plane** — authoritative relational data, agent-local operational state, workflow state, artifacts, and restorable workspaces.
4. **Intelligence + Tooling Plane** — model inference, model routing, evaluations, web retrieval, browser automation, and agent-facing tools.
Cloudflare is the platform foundation and the inference control point:
- Cloudflare Workers host the web application, canonical API, trusted control services, and tool adapters.
- Cloudflare Agents and Durable Objects own active agent identity, realtime coordination, and agent-local operational state.
- Agent Fibers provide durable, I/O-oriented coordination owned by an Agent.
- Cloudflare Workflows run independent, multi-step, retryable processes and approval-bearing operations.
- Cloudflare Sandbox is the primary untrusted execution provider.
- Cloudflare AI Gateway is the single runtime entry point for model inference and benchmark-driven model routing.
- Cloudflare R2 stores immutable artifacts and sandbox workspace backups in separate logical stores.
- Cloudflare Browser Run supplies deterministic Worker-native browser automation.
The intentional non-Cloudflare components remain where they provide a clear, bounded capability:
- **Neon Postgres + Drizzle ORM** for the globally accessible relational system of record, reached from Workers through Hyperdrive where appropriate.
- **Better Auth** for authentication and session management.
- **E2B** as the ordinary-execution fallback when Cloudflare Sandbox cannot meet a workload or availability requirement.
- **Modal** for GPU, high-memory, high-CPU, or specialized compute rather than ordinary agent execution.
- **Langfuse** as the authoritative system for LLM traces, evaluation datasets, experiments, annotations, and quality scores.
- **Parallel CLI and Firecrawl CLI** for progressively escalated web research and extraction.
- **Playwright CLI** inside a sandbox when the browser must share a filesystem and process environment with agent-generated code.
- **GitHub Actions** for CI/CD and standard Playwright Test for deployed-application E2E tests.
PartyKit is not part of v1. Cloudflare Agents already provides the Durable Object and WebSocket runtime needed for active agent coordination. PartyServer, Yjs, or a similar collaboration layer may be introduced later only for a distinct non-agent collaborative editing use case.
## 2. Core Principles
### 2.1 Cloudflare-centric, not Cloudflare-exclusive
Cloudflare owns the edge, control, policy, orchestration, primary execution, browser, artifact, and inference-gateway paths. External providers sit behind internal interfaces and are selected only when measured capability, resilience, or workload requirements justify them.
### 2.2 One authoritative owner per kind of state
Every durable fact has one authoritative system. Other stores may contain projections, caches, live views, or recovery data, but never competing authoritative copies.
### 2.3 Trusted control is separate from untrusted execution
Workers, Agents, policy services, and credential brokers are trusted. Sandboxes execute model-written or user-supplied code and are always untrusted. A sandbox cannot grant itself permissions, relax its network policy, select a more privileged provider, or obtain raw platform credentials.
### 2.4 Policy is data, not scattered conditionals
Execution, model selection, tool access, budget, workspace retention, network reachability, and credential grants are expressed through versioned policy objects. The policy version used for a run is retained for audit and replay analysis.
### 2.5 Runtime validation at every trust boundary
TypeScript supplies compile-time safety. Zod schemas, database constraints, authorization checks, output limits, and protocol adapters supply runtime safety. Model output, tool arguments, browser content, sandbox output, webhooks, RPC payloads, and database JSON are all untrusted until validated.
### 2.6 Durable coordination is not general compute
Agent Fibers coordinate I/O-oriented work, checkpoint progress, dispatch execution, and await results. They do not perform large parsing, AST transformation, compression, diffing, compilation, or other CPU-heavy work. Heavy work is sent to Cloudflare Sandbox or Modal.
### 2.7 Idempotency precedes retries
Every externally accepted run and every retryable side effect has a stable idempotency identity. Retries return or resume the same logical operation rather than creating duplicate runs, deployments, commits, messages, or charges.
### 2.8 Cancellation is cooperative, durable, and auditable
Cancellation is a durable intent propagated to every active layer. It revokes future capability, stops new work, attempts to interrupt current work, and records any side effects that could not be reversed.
### 2.9 Measured quality controls model selection
No model provider is the universal default. Langfuse evaluations and production quality signals feed versioned routing policy. Workers AI is preferred wherever it satisfies measured quality, capability, latency, and cost thresholds; external models remain available through Cloudflare AI Gateway.
### 2.10 Progressive capability discovery conserves context
Agent-facing CLI capabilities are discovered on demand through concise tool descriptions and commands such as `--help`. Large, rarely used API schemas are not injected into every model turn.
## 3. Platform Foundation
### 3.1 Language and repository
- **Language:** TypeScript across Workers, SvelteKit, Hono, agents, contracts, orchestration, policies, and provider adapters.
- **Runtime schemas:** Zod at every external and cross-component boundary.
- **Database access:** Drizzle ORM, migrations committed with application code, and database constraints for durable invariants.
- **Repository shape:** a TypeScript monorepo with independently deployable applications and shared packages.
Recommended top-level structure:
```text
apps/
├── web/ # SvelteKit Worker + Static Assets
├── api/ # Hono canonical API Worker
├── agents/ # Cloudflare Agents / Durable Object classes
├── workflows/ # Cloudflare Workflow definitions
├── execution/ # execution router, Sandbox classes, broker handlers
└── docs/ # documentation site deployed to Pages
packages/
├── contracts/ # shared Zod input, output, event, and RPC schemas
├── auth/ # Better Auth configuration and AuthContext helpers
├── db/ # Drizzle schema, queries, migrations, repositories
├── policy/ # ExecutionPolicy, routing policy, authorization rules
├── agents/ # agent domain logic independent of transport
├── execution/ # provider-neutral execution interfaces
├── models/ # normalized model protocol and AI Gateway adapters
├── tools/ # tool registry, routing, schemas, result normalization
├── observability/ # trace context, Langfuse, OTel, audit helpers
└── test-support/ # provider fakes, fixtures, conformance suites
```
The exact package boundaries may evolve, but dependencies must flow inward toward shared contracts and domain policy rather than from domain logic into provider-specific SDKs.
### 3.2 Application surfaces
| Surface | Runtime | Responsibility |
|---|---|---|
| `app.example.com` | SvelteKit on Cloudflare Workers + Static Assets | SSR, UI, dashboard, page loading, frontend composition, session bootstrap |
| `api.example.com` | Hono on a Cloudflare Worker | Canonical `/v1/*` application API, webhooks, machine API, agent/run API, integrations |
| Better Auth endpoint | Narrow SvelteKit/Better Auth handler | Authentication protocol routes and session cookies only |
| `docs.example.com` | Cloudflare Pages | Product and developer documentation |
SvelteKit does not duplicate domain endpoints owned by Hono. Server-side SvelteKit code calls the Hono Worker through a Cloudflare Service Binding/RPC interface. Browser and external clients use the public Hono API. Both paths share the same Zod contracts from `packages/contracts`.
The Better Auth handler is a deliberate narrow exception to the Hono domain API boundary because it owns authentication protocol mechanics and cookie integration. Once authenticated, all domain authorization remains enforced at the Hono/API and service layers.
### 3.3 Cloudflare bindings over public internal networking
Cloudflare Service Bindings and Worker RPC are preferred for Worker-to-Worker calls. Internal services are not exposed as public URLs merely to allow another Worker to call them.
An internal binding is not an authorization bypass. The callee still receives a normalized `AuthContext`, validates the contract, enforces tenant/resource permissions, and records audit context.
## 4. Four-Plane Architecture
### 4.1 Control Plane
The Control Plane is trusted and owns request admission, identity, authorization, policy evaluation, active agent coordination, durable orchestration, and routing decisions.
#### 4.1.1 SvelteKit web Worker
The SvelteKit Worker owns:
- server-side rendering and frontend delivery;
- dashboard and interactive UI;
- frontend-specific data composition;
- Better Auth session bootstrap and cookie integration;
- connection setup to Agent WebSockets;
- calls to the canonical Hono API through Service Bindings/RPC.
It does not own duplicate resource, run, execution, or integration APIs.
#### 4.1.2 Hono canonical API Worker
Hono owns:
- `/v1/*` public and first-party application APIs;
- run submission, inspection, cancellation, and artifact APIs;
- agent control and configuration APIs;
- webhook intake and deduplication;
- external integration endpoints;
- authorization and tenant/resource enforcement;
- construction of immutable, versioned policy inputs;
- normalized error and idempotency responses.
All requests and responses use schemas from `packages/contracts`. The same contracts govern public HTTP, Service Binding calls, RPC, webhook normalization, and internal events where applicable.
#### 4.1.3 Better Auth
Better Auth remains the authentication system.
- Better Auth owns identity authentication, sessions, supported sign-in methods, and its schema.
- Better Auth data is stored in Neon through the platform's database integration.
- SvelteKit integrates the Better Auth handler and populates the server request's session context.
- Hono independently validates or resolves the caller's session and builds an `AuthContext` containing subject, tenant, roles, grants, session, and request metadata.
- Authorization is application-owned. Authentication success alone never grants project, repository, execution, artifact, model, or deployment access.
#### 4.1.4 Cloudflare Agents and Durable Objects
Cloudflare Agents are the center of the live agent runtime. An Agent/Durable Object instance owns:
- durable agent or conversation identity;
- WebSocket connections, hibernation-aware realtime delivery, and reconnect state;
- live turn and run coordination;
- current tool-loop progress and stream cursors;
- agent-local schedules and short lifecycle callbacks;
- Agent SQLite operational state;
- starting and observing Agent Fibers;
- dispatching independent work to Cloudflare Workflows;
- broadcasting normalized run events to connected clients.
Agent SQLite state should be reconstructible from Neon, R2, and external operation status wherever practical. Globally queried business facts do not live only inside a Durable Object.
#### 4.1.5 Agent Fibers
Agent Fibers own durable work that belongs to one Agent and benefits from checkpoint/recovery semantics.
Appropriate Fiber work:
- calling a model and awaiting the response;
- invoking a trusted API or tool adapter;
- dispatching a sandbox operation and awaiting status;
- checkpointing a tool loop with `stash()`;
- polling or reconciling an Agent-owned external handle;
- updating agent-local progress;
- producing realtime events;
- accepting idempotent background Agent work with retained status.
Inappropriate Fiber work:
- compilation or package installation;
- large diff, AST, archive, compression, or dataset transformations;
- tight CPU loops or large synchronous parsing;
- GPU or high-memory workloads;
- an independent business process whose lifecycle should outlive the Agent.
Fibers are **I/O-oriented durable coordination, not compute workers**.
#### 4.1.6 Cloudflare Workflows
Cloudflare Workflows own independently durable, multi-step operations that require retries, waiting, recovery, or approval. Examples include:
- multi-stage research jobs;
- deployments and releases;
- human approval gates;
- long-running external operations;
- artifact promotion;
- repository import or export pipelines;
- tenant-level maintenance;
- multi-stage sandbox execution whose lifecycle is independent of a connected Agent turn.
Workflows own their execution graph and step state. Neon stores queryable workflow metadata and the relationship to the logical run, but it does not reimplement Workflow step state.
#### 4.1.7 Control-plane routers
The Control Plane contains three separate routers:
| Router | Input | Output |
|---|---|---|
| **Model Router** | capability, context, modality, quality target, budget, tenant policy | versioned AI Gateway dynamic route and protocol |
| **Execution Router** | authorized `ExecutionPolicy`, provider health, workload requirements | Cloudflare Sandbox, E2B, or Modal |
| **Tool Router** | task semantics, data sensitivity, interactivity, cost | API tool, CLI tool, Browser Run, or sandbox-local tool |
The model never directly chooses a provider, network profile, credential, or privilege level. It requests a capability; trusted policy and routing code selects the permitted implementation.
### 4.2 Execution Plane
The Execution Plane runs untrusted or resource-intensive work. It receives a fully authorized `ExecutionPolicy` and exposes a provider-neutral execution contract to the Control Plane.
#### 4.2.1 Provider hierarchy
| Provider | Role | Typical use |
|---|---|---|
| **Cloudflare Sandbox** | Primary | Shell, Git, package installation, builds, tests, coding workspaces, sandbox-local browser |
| **E2B** | Fallback | Ordinary execution when Cloudflare Sandbox is unavailable or lacks a required capability |
| **Modal** | Heavy/specialized | GPU, high CPU, high memory, specialized images, large data or ML workloads |
Providers are not randomly load-balanced. They are selected by policy, measured reliability, required capability, data classification, region, budget, and health.
All providers implement an internal contract with equivalent lifecycle concepts:
```ts
interface ExecutionProvider {
create(request: CreateExecutionRequest): Promise<ExecutionHandle>;
restore(request: RestoreWorkspaceRequest): Promise<ExecutionHandle>;
exec(request: ExecRequest): Promise<ProcessHandle>;
inspect(handle: ExecutionHandle): Promise<ExecutionStatus>;
signal(request: SignalProcessRequest): Promise<void>;
checkpoint(request: CheckpointWorkspaceRequest): Promise<WorkspaceSnapshot>;
download(request: DownloadArtifactRequest): Promise<ArtifactStream>;
terminate(handle: ExecutionHandle): Promise<void>;
}
```
Provider-specific behavior is normalized at the adapter boundary. Provider identifiers may appear in telemetry and audit records but do not leak into domain contracts.
#### 4.2.2 First-class `ExecutionPolicy`
Every execution is governed by an immutable policy created and authorized in the Control Plane. At minimum, it contains:
```ts
type ExecutionPolicy = {
version: string;
tenantId: string;
projectId: string;
runId: string;
requestedBy: string;
workload:
| "research"
| "coding"
| "build"
| "test"
| "browser"
| "deploy"
| "ml";
dataClass: "public" | "internal" | "confidential";
provider: {
preferred: "cloudflare" | "e2b" | "modal";
allowed: Array<"cloudflare" | "e2b" | "modal">;
allowFallback: boolean;
};
network: {
profile:
| "none"
| "packages"
| "repository"
| "research"
| "privileged-deploy";
allowedHosts: string[];
deniedHosts: string[];
};
repository: {
access: "none" | "read" | "write";
allowedRepositories: string[];
};
credentialGrants: Array<{
capability: string;
resource: string;
actions: string[];
expiresAt: string;
}>;
resources: {
cpuClass: "standard" | "heavy";
memoryClass: "standard" | "heavy";
gpu: boolean;
};
limits: {
maxWallTimeMs: number;
maxOutputBytes: number;
maxArtifactBytes: number;
maxProcesses: number;
maxCostUsd?: number;
};
workspace: {
mode: "ephemeral" | "restore" | "checkpoint";
snapshotId?: string;
retentionTtlSeconds?: number;
};
approval: {
required: boolean;
approvalId?: string;
};
};
```
Rules:
- The model may request a capability but cannot construct or modify the authoritative policy.
- The Hono/service layer resolves tenant, project, role, budget, and approval constraints before execution begins.
- Policy is validated again by the execution service and provider adapter.
- The effective policy can only become stricter as it crosses layers.
- The policy version and a canonical policy hash are stored with the run and execution record.
- A fallback provider must satisfy the same effective security policy; fail closed if it cannot.
#### 4.2.3 Deny-by-default network profiles
| Profile | Sensitive workspace | Internet | Credentials | Intended use |
|---|---:|---|---|---|
| `none` | Allowed | None | None | Offline analysis and deterministic transforms |
| `packages` | Allowed | Package registries only | Broker only if required | Builds and dependency installation |
| `repository` | Allowed | Explicit source/package/API allowlist | Broker only | Coding agents with private repositories |
| `research` | **Not combined with private repository data** | Broad web subject to filtering and limits | None by default | Open-web research |
| `privileged-deploy` | Selected artifacts only | Strict deployment destinations | Broker only + approval | Release and deployment operations |
Cloudflare Sandbox starts with public internet disabled for protected workloads. Allowed hosts and outbound handlers then open only the destinations required by the selected profile.
The platform must never create the combination of private repository data, unrestricted internet, arbitrary code, and raw credentials. If a task needs both private code analysis and broad research, it uses separate execution contexts and passes only reviewed or sanitized artifacts through R2.
#### 4.2.4 Credential and egress broker
Raw credentials are never injected into an untrusted sandbox as environment variables, files, command arguments, or tool output.
For Cloudflare Sandbox, outbound handlers implement the native enforcement point:
```text
Untrusted sandbox
-> credential-free request to approved virtual host
-> Sandbox outbound handler in trusted Worker runtime
-> resolve container/run identity
-> load immutable ExecutionPolicy and active grant
-> authorize host, method, path, resource, action, size, rate, and budget
-> attach credential or call a Workers binding outside the sandbox
-> forward request
-> strip sensitive response headers and sanitize/limit the body
-> emit audit and usage event
-> return bounded response to sandbox
```
Examples of broker capabilities include repository read/write, pull-request creation, selected Cloudflare deployment actions, artifact access, and calls to approved third-party APIs.
Broker invariants:
- The handler identifies the execution from trusted provider/container context, not from a sandbox-asserted tenant ID.
- Grants are capability-, resource-, action-, run-, and time-scoped.
- Cancellation immediately revokes active grants before best-effort process termination.
- The broker never returns authorization headers, access tokens, database credentials, signing keys, or upstream cookies.
- Request bodies and responses are size-limited and logged by metadata, with sensitive values redacted.
- Direct destinations and DNS behavior remain restricted by the network profile.
- Binding-backed access to R2, Durable Objects, or other Cloudflare resources is mediated by a dedicated handler rather than exposed as a general binding.
E2B and Modal adapters must preserve the same logical broker contract using provider-specific egress restrictions and a trusted broker channel. If an alternate provider cannot enforce the effective policy, the Execution Router must not use it.
#### 4.2.5 Workspace lifecycle and persistence
The active filesystem is execution-local and ephemeral. Persistent coding workspaces use Cloudflare Sandbox backup/restore with R2:
```text
Neon workspace metadata
-> authorized R2 backup handle
-> restore into fresh Cloudflare Sandbox workspace
-> execute
-> create meaningful point-in-time backup
-> store immutable backup in dedicated R2 workspace bucket
-> commit new metadata and lineage in Neon
```
Workspace snapshot metadata in Neon includes:
- snapshot ID and provider;
- tenant, project, repository, run, and execution IDs;
- R2 bucket/key or opaque backup handle;
- source Git commit and dirty-state indicator;
- parent snapshot ID and lineage;
- content checksum and size;
- creating policy version/hash;
- toolchain/image version;
- creation and expiry timestamps;
- restore compatibility and quarantine state.
Workspace backups and canonical artifacts are separate:
- **Workspace backup bucket:** restorable filesystem snapshots, lifecycle TTLs, project scoping, and lineage.
- **Artifact bucket:** immutable, content-addressed user/run outputs such as archives, reports, screenshots, traces, and generated files.
For cross-provider recovery, a logical workspace checkpoint also includes a portable, provider-neutral reconstruction manifest: repository/base commit, tracked patch or changed-file digests, authorized untracked artifacts, lockfiles, modes, and toolchain version. Cloudflare's native backup remains the fast primary restore path; the portable checkpoint is the safe boundary for E2B fallback. Neither representation contains credentials or historical grants.
A restore never restores credentials or expands policy. Restored workspaces receive a newly authorized execution identity and current effective policy. Snapshot integrity, tenant ownership, project ownership, retention, and compatibility are verified before restore.
#### 4.2.6 Run idempotency
The public API accepts an `Idempotency-Key` for run-creating operations. The key is scoped to the authenticated tenant, operation, and relevant resource. Neon enforces uniqueness and stores the request fingerprint and response receipt.
Semantics:
1. The first valid request creates one `run_id` and durable receipt.
2. A byte-for-byte or semantically equivalent retry returns the same run and receipt.
3. Reuse of the same key with a conflicting request fingerprint is rejected.
4. The Agent uses stable Fiber keys derived from the run and logical phase.
5. A Workflow uses a deterministic instance identity derived from the run and workflow purpose.
6. Execution attempts and external side effects use their own stable action keys beneath the run.
7. Retries may create new physical attempts, but they do not create a new logical run or repeat an already committed side effect.
Every side effect that cannot rely on an upstream provider's native idempotency is protected by an application action ledger and reconciliation before retry.
#### 4.2.7 Cancellation
Cancellation is an idempotent API operation. A cancellation request:
1. durably records cancellation intent and reason against the run;
2. changes the run to a non-admitting `cancelling` condition unless it is already terminal;
3. revokes credential broker grants and prevents new model, tool, workflow, or execution dispatch;
4. notifies the owning Agent and connected clients;
5. requests cancellation of active Fibers and signals application cancellation to Workflow steps;
6. sends interrupt/termination to active sandbox processes and execution providers;
7. attempts a final safe workspace checkpoint only when policy permits and doing so does not prolong unsafe side effects;
8. reconciles provider and external-operation status;
9. records `cancelled` only when active work is stopped or accounted for.
Cancellation is cooperative. A side effect already accepted by an external system may be irreversible. Such effects are recorded in the action ledger and surfaced in the final run result.
Terminal transitions are immutable. If success commits before the cancellation compare-and-swap, success remains terminal; if `cancelling` commits first, later success is forbidden and the run proceeds to `cancelled` after reconciliation. The complete transition, lease, fencing, and recovery rules are defined in the [Canonical Run and Execution Model](./RUN_EXECUTION_MODEL.md).
### 4.3 Data Plane
#### 4.3.1 Neon Postgres + Drizzle + Hyperdrive
Neon is the globally accessible relational system of record. It is not treated as a globally distributed multi-primary write database. Database round-trip time to the Neon primary is therefore an explicit design constraint.
Hyperdrive is used for supported Worker database paths where connection pooling, protocol compatibility, and latency characteristics benefit the workload. One-shot or provider-specific Neon access patterns may use the appropriate serverless driver behind the same repository interface. The choice is benchmarked; domain code does not depend on the driver.
Neon owns durable, globally queryable business facts:
- users, identities, sessions, organizations, memberships, and Better Auth records;
- projects, repositories, agents, and configurations;
- logical runs, attempts, status summaries, idempotency receipts, and cancellation intent;
- workflow and execution metadata, provider handles, and reconciliation state;
- `ExecutionPolicy` versions, hashes, approvals, and credential-grant metadata;
- model-routing policy versions and deployment approvals;
- artifact and workspace snapshot metadata;
- permissions, billing/usage records, quotas, and budgets;
- audit events and externally visible side-effect ledger entries;
- run summaries and durable references to large results.
High-frequency token deltas, live heartbeats, and every streamed event do not produce synchronous Neon writes. They are aggregated in the live runtime and periodically or terminally reconciled into durable summaries.
#### 4.3.2 Agent SQLite
Agent SQLite owns agent-local operational state:
- current live step and tool-loop cursor;
- active connection and stream cursors;
- recent operational messages needed for the live loop;
- Fiber metadata, retained status, and `stash()` snapshots;
- temporary approval wait state;
- execution handles and local polling state;
- outbound realtime event sequence;
- short-lived recovery information.
Agent SQLite does not own globally queried billing, authorization, project, run-history, or artifact facts. Important local state is either reconstructible or reconciled into Neon/R2 at defined boundaries.
#### 4.3.3 Cloudflare Workflows state
Cloudflare Workflows owns the authoritative durable step graph, retry/wait state, and progression of each Workflow instance. Neon contains the queryable business projection and workflow identifiers, not a second implementation of the step engine.
#### 4.3.4 Cloudflare R2
R2 owns large immutable objects:
- content-addressed artifacts;
- generated source bundles and release candidates;
- uploaded documents and datasets;
- screenshots, browser traces, and test reports;
- large tool and model outputs retained by policy;
- sandbox workspace backups in a dedicated logical bucket.
Canonical artifact keys should be content-addressed where practical:
```text
artifacts/sha256/{digest}
```
Neon stores the artifact ID, digest, R2 key, media type, size, tenant/project/run ownership, provenance, retention class, encryption metadata, and timestamps. R2 is not used as a transactional run state machine.
#### 4.3.5 State propagation and reconciliation
- Durable facts are written first to their authoritative owner.
- Projections and notifications are updated through idempotent events or an outbox/reconciliation mechanism.
- Consumers carry an event ID and ignore duplicates.
- Reconciliation jobs repair incomplete projections using authoritative records and provider inspection.
- UI live state may be fresher than the Neon projection; terminal and historical views reconcile to Neon.
- No distributed transaction is assumed across Agent SQLite, Workflows, Neon, R2, Langfuse, or providers.
### 4.4 Intelligence + Tooling Plane
#### 4.4.1 Cloudflare AI Gateway as the inference control point
All runtime model inference goes through Cloudflare AI Gateway. Application code requests a capability, not a provider model name.
Canonical capabilities include:
```text
fast
classify
extract
embedding
coding
reasoning
research
vision
multimodal
```
Initial routing posture:
| Capability | Policy posture |
|---|---|
| `fast`, `classify`, `extract`, `embedding` | Prefer Workers AI when capability and measured quality thresholds are met |
| `coding`, `reasoning`, `research` | Select the benchmark winner within tenant, budget, latency, and data-policy constraints; retain tested fallback routes |
| `vision`, `multimodal` | Select by required modality, context, tool/protocol support, and measured quality |
Workers AI is not assumed to be either universally sufficient or universally inferior. It is preferred where evidence supports it. External models remain behind AI Gateway for capability, quality, or resilience.
#### 4.4.2 Benchmark-driven routing loop
Langfuse owns evaluation datasets, experiment runs, human annotations, evaluator outputs, production trace scores, and quality analysis.
The routing feedback loop is:
```text
Production traces and curated failures
-> Langfuse datasets
-> offline experiments across candidate models/routes/prompts
-> deterministic, model-judge, human, latency, reliability, and cost scores
-> policy compiler applies minimum quality and safety constraints
-> reviewed routing-policy candidate
-> approved version stored in Neon
-> deployment to versioned AI Gateway dynamic routes
-> canary traffic and online Langfuse evaluation
-> promote, hold, or rollback
```
Automated scoring may propose a route change but cannot silently promote it when the change crosses a configured risk, cost, provider, or data-handling boundary. High-risk changes require approval.
Every model call records:
- logical capability;
- routing-policy and prompt versions;
- selected gateway route, provider, and model;
- protocol adapter;
- input/output token or unit usage where available;
- latency, retry, fallback, and cache status;
- tenant, project, agent, run, and trace identifiers;
- evaluation cohort and sampled online scores.
#### 4.4.3 Protocol flexibility
The agent runtime uses normalized internal contracts such as `ModelRequest`, `ModelEvent`, `ToolCall`, `ModelUsage`, and `ModelResult`. Protocol adapters translate between those contracts and the AI Gateway endpoint best suited to the selected model:
- `/ai/v1/responses` where the route/model supports the Responses schema;
- `/ai/v1/chat/completions` for compatible chat-completion routes;
- `/ai/v1/messages` where the Anthropic Messages schema is appropriate;
- `/ai/run` for universal or non-LLM/modal model calls.
The architecture is not coupled only to `/ai/v1/responses`. A route is eligible only if its adapter supports the required streaming, tool calling, structured output, modality, usage accounting, and error semantics.
Fallback is semantic, not merely transport-level. The router must not silently fall back to a model that lacks a required tool, modality, context size, structured-output guarantee, data policy, or minimum quality tier.
#### 4.4.4 Tool registry and routing
Tools are registered by capability with explicit Zod input/output schemas, authorization requirements, cost class, data classification, timeout, idempotency behavior, and execution location.
The web-research escalation path is:
1. **Parallel CLI** for search, discovery, and structured research where it is the cheapest sufficient capability.
2. **Firecrawl CLI** for page extraction, rendering, crawl, or structured scraping when search output is insufficient.
3. **Cloudflare Browser Run + `@cloudflare/playwright`** for deterministic Worker-native navigation, forms, screenshots, PDFs, and browser sessions.
4. **Cloudflare Sandbox + Playwright CLI** when the browser must share localhost, files, cookies, generated applications, or arbitrary shell processes with the execution workspace.
The model is given the smallest useful tool surface. It can inspect CLI help on demand rather than receiving every option and schema in its prompt.
#### 4.4.5 Browser boundary
Runtime browser roles are intentionally distinct:
| Need | Runtime |
|---|---|
| Worker-native browser automation | Cloudflare Browser Run + `@cloudflare/playwright` |
| Browser sharing sandbox files/processes/local app | Playwright CLI inside Cloudflare Sandbox; E2B fallback if selected by policy |
| CI verification of a deployed application | Standard `playwright` + `@playwright/test` in GitHub Actions |
Cloudflare's Worker-compatible Playwright package is not treated as a replacement for the standard Playwright Test runner in CI.
Browser content is untrusted input. Downloads, extracted text, scripts, cookies, and navigation targets are constrained by the active policy and never gain control-plane credentials.
## 5. State Ownership Matrix
| State or capability | Authoritative owner | Non-authoritative copies/projections |
|---|---|---|
| Identity and sessions | Better Auth records in Neon | SvelteKit request locals, validated API `AuthContext` |
| Organizations, projects, permissions | Neon | request-scoped authorization cache |
| Logical run and idempotency receipt | Neon | Agent live view, client state |
| Live agent/turn state | Agent/Durable Object + Agent SQLite | reconciled run summary in Neon |
| Fiber checkpoint/status | Agent SQLite/Fiber runtime | run progress projection in Neon |
| Independent orchestration graph | Cloudflare Workflows | workflow metadata/status projection in Neon |
| Execution policy and approval | Neon | immutable copy/hash on execution record and provider context |
| Active sandbox filesystem | Selected execution provider | none |
| Restorable workspace bytes | R2 workspace backup bucket | metadata and lineage in Neon |
| Canonical large artifacts | R2 artifact bucket | metadata and provenance in Neon |
| Relational application and billing data | Neon | analytics/observability projections |
| LLM traces, datasets, experiments, scores | Langfuse | selected run/model summary in Neon |
| Runtime AI route enforcement | Cloudflare AI Gateway | approved route version and audit metadata in Neon |
| Infrastructure telemetry | Cloudflare observability | correlated references in Langfuse/Neon |
| CI/CD workflow and deployment history | GitHub Actions + Cloudflare deployment history | release record in Neon or repository metadata |
Ownership rules:
- A cache or projection never becomes authoritative because it is newer.
- Cross-store updates are idempotent and reconciled; they are not assumed atomic.
- Large payloads go to R2 and are referenced by digest rather than copied through Neon or Agent SQLite.
- Historical/global queries use Neon; live interaction uses the owning Agent.
- Langfuse owns quality evidence; Neon owns the approved business decision derived from it; AI Gateway owns enforcement of the deployed route.
## 6. Security Architecture
### 6.1 Trust zones
1. **Public/untrusted:** browsers, webhook senders, uploaded content, websites, model output.
2. **Trusted edge/control:** SvelteKit Worker, Hono Worker, Better Auth integration, Agents, Workflows, policy, routers, credential broker.
3. **Untrusted execution:** Cloudflare Sandbox, E2B, Modal job/container, sandbox-local browser and processes.
4. **Controlled data services:** Neon, R2, Langfuse, AI Gateway, and approved external APIs.
Every zone crossing is authenticated where applicable, authorized, schema-validated, size-limited, traced, and audited according to risk.
### 6.2 Identity and authorization
- Better Auth authenticates the user/session.
- Hono and service methods enforce resource authorization on every operation.
- Tenant and project IDs are derived from authenticated context and resolved resources, not trusted from request bodies.
- Service Bindings prove call path, not end-user permission.
- Agent, Workflow, execution, artifact, and broker access use scoped internal identities tied to run and policy.
- Sensitive or irreversible operations require explicit approval according to policy.
### 6.3 Secrets
- Platform/provider secrets exist only in trusted Worker/Cloudflare secret storage or equivalent trusted provider configuration.
- Sandboxes receive no raw GitHub, Cloudflare, database, deployment, model-provider, or production credentials.
- Model prompts and tool results never contain raw secrets.
- Brokered responses strip sensitive headers, cookies, signed URLs where inappropriate, and diagnostic leakage.
- Logs use structured redaction before export.
### 6.4 Egress and prompt-injection containment
- Protected sandbox profiles start deny-by-default.
- Host allowlists are necessary but not sufficient; the broker also checks method, path, resource, action, content type, size, rate, and budget.
- Private code and broad open-web research do not share one untrusted environment.
- Web content and repository instructions are treated as data, not authority to change policy.
- Redirects, DNS rebinding, alternate IP forms, and proxy/tunnel attempts are included in egress tests.
- Tool outputs cannot grant new tools or credential capabilities.
### 6.5 Artifact and workspace security
- Every R2 access is authorized using Neon metadata; an object key alone is not authorization.
- Artifact downloads use short-lived delivery mechanisms or trusted streaming after authorization.
- Uploads and restored backups are checked for tenant/project ownership, size, checksum, provenance, and retention.
- Executable or active content is quarantined or served with safe content disposition where appropriate.
- Backup restore never carries execution identity, credentials, or a historical policy grant.
### 6.6 Auditability
Security-relevant events include actor, tenant, project, run, policy version, resource, action, result, reason, trace ID, and timestamp. At minimum, audit:
- sign-in/session and material authorization decisions;
- run creation, deduplication, cancellation, and terminal transition;
- policy creation/evaluation and approval;
- provider selection and fallback;
- broker request and upstream side effect;
- workspace backup/restore and artifact access;
- model-route version change and promotion;
- deployment and privileged operation.
## 7. Routing Architecture
### 7.1 API routing
- Public and programmatic domain requests terminate at Hono `/v1/*`.
- SvelteKit server code calls Hono through a Service Binding/RPC.
- Better Auth protocol routes terminate at the Better Auth/SvelteKit integration.
- Agent WebSocket/RPC traffic terminates at the owning Agent/Durable Object.
- No domain endpoint is implemented independently in both SvelteKit and Hono.
### 7.2 Model routing
The Model Router evaluates:
- requested capability and modality;
- context length, tool calling, streaming, and structured-output requirements;
- tenant/provider allowlists and data-handling constraints;
- minimum evaluation score and safety tier;
- latency SLO and availability;
- remaining run/tenant budget;
- route health, retry class, and fallback compatibility;
- experiment cohort and routing-policy version.
Cloudflare AI Gateway performs the deployed dynamic route, provider selection/fallback allowed by that route, rate limiting, gateway logging, and other configured gateway controls. The application retains final responsibility for semantic eligibility and policy.
### 7.3 Execution routing
The Execution Router first filters providers that cannot satisfy `ExecutionPolicy`, then selects among eligible providers using:
- workload and required image/toolchain;
- CPU, memory, GPU, browser, and filesystem requirements;
- data class and network/broker enforcement capability;
- workspace snapshot compatibility;
- provider health and regional availability;
- latency, cost, quota, and historical reliability.
Normal preference is Cloudflare Sandbox, then E2B for eligible ordinary workloads. Modal is chosen explicitly for heavy/specialized compute. Security equivalence is mandatory for fallback.
### 7.4 Tool routing
The Tool Router selects the least costly sufficient capability and escalates only when necessary. It records why escalation occurred, enforces tool-specific policy, and normalizes citations, artifacts, errors, and usage.
## 8. Observability, Evaluations, and Usage Signals
### 8.1 Correlation
The same identifiers propagate through all planes:
```text
trace_id
request_id
tenant_id
user_id
project_id
agent_id
run_id
attempt_id
fiber_id
workflow_id
execution_id
sandbox_id
model_call_id
tool_call_id
artifact_id
policy_version
```
### 8.2 Responsibility split
**Langfuse answers:**
- What did the agent/model do?
- Which prompt, route, provider, and model ran?
- What tools were called and in what trace?
- What were latency, token usage, cost, output, and evaluation scores?
- Which dataset item or production cohort failed?
**Cloudflare observability answers:**
- Which Worker, Agent/Durable Object, Workflow, Sandbox, binding, or request failed?
- What were CPU, wall-time, network, exception, deployment, and platform signals?
- Which AI Gateway route/provider was selected and how did it perform?
**Neon answers:**
- Which durable business run, policy, user, tenant, budget, approval, artifact, and side effect correspond to those signals?
### 8.3 Telemetry model
- Use OpenTelemetry-compatible trace context where supported.
- Emit structured events rather than unbounded logs.
- Redact before export; do not rely only on downstream redaction.
- Large logs and traces retained as artifacts go to R2 with metadata in Neon.
- Sampling is policy-aware: errors, security events, fallbacks, cancellations, and privileged runs receive higher retention.
- Metrics cover request latency/error rate, Agent/Fiber recovery, Workflow retries, sandbox startup/restore, broker denials, provider failure, model quality, tool success, token/unit use, and cost.
### 8.4 Evaluation ownership and gates
Langfuse is the evaluation source of truth. Evaluation suites include:
- coding correctness and test pass rate;
- patch relevance and unnecessary-change rate;
- research factuality, citation quality, and source coverage;
- tool-selection accuracy and escalation efficiency;
- structured-output/schema conformance;
- safety, prompt-injection resistance, and secret leakage;
- latency, reliability, token use, and total cost;
- cancellation responsiveness and duplicate-side-effect rate.
Offline evaluation gates model/prompt/tool/router changes in CI. Online sampled evaluation detects regressions and contributes new cases to curated datasets. Route promotion uses both quality constraints and operational metrics; cost never overrides a minimum quality or safety threshold.
### 8.5 Usage accounting foundation
Each plane emits normalized usage events with stable event IDs so ingestion is idempotent. Events carry run, attempt, tenant, capability, provider, unit, quantity, price-version reference, and timestamps. Neon owns billable aggregates and audit records; Langfuse retains model-centric usage with traces; Cloudflare/provider usage is reconciled against internal events.
The precise usage ledger, reservation, quota, refund, and reconciliation contracts are specified in the [Canonical Run and Execution Model](./RUN_EXECUTION_MODEL.md).
## 9. Testing Strategy
### 9.1 Unit and schema tests
- domain logic, policy merging, authorization, and router decisions;
- every Zod contract and normalized error;
- request fingerprints and idempotency keys;
- run terminal-transition and cancellation invariants;
- redaction and response sanitization;
- model protocol adapters and usage normalization.
### 9.2 Contract and conformance tests
- SvelteKit-to-Hono Service Binding/RPC contracts;
- public HTTP and internal RPC behavioral equivalence;
- every `ExecutionProvider` implementation against one conformance suite;
- model adapters for Responses, Chat Completions, Messages, and `/ai/run`;
- tool input/output contracts and error taxonomy;
- artifact and workspace backup metadata contracts.
### 9.3 Integration tests
- Better Auth session establishment and Hono authorization;
- Agent/Durable Object reconnect and live event replay;
- Fiber checkpoint, eviction/recovery, retained status, idempotent acceptance, and cancellation;
- Workflow retries, waits, approvals, and run reconciliation;
- Cloudflare Sandbox creation, command execution, backup, restore, and teardown;
- R2 artifact integrity and Neon metadata consistency;
- AI Gateway route selection, protocol compatibility, retry, and fallback;
- brokered repository/API calls without raw sandbox credentials.
### 9.4 Security tests
- arbitrary environment/file inspection cannot reveal credentials;
- denied egress, alternate IPs, redirects, DNS rebinding, tunneling, and proxy attempts;
- virtual broker host method/path/resource bypass attempts;
- prompt-injected attempts to expand policy or access another tenant;
- oversized and malicious tool/browser/sandbox outputs;
- artifact ownership and signed-delivery expiry;
- cross-tenant Agent, snapshot, run, and R2 reference access;
- cancellation revokes broker grants before further side effects.
### 9.5 Failure and recovery tests
- duplicate API/webhook delivery;
- completion-versus-cancellation races;
- Agent/Durable Object eviction during model and execution waits;
- Workflow retry after partial external success;
- sandbox crash and provider timeout;
- provider fallback under a strict policy;
- corrupt, expired, incompatible, and cross-tenant workspace backup;
- Neon, R2, Langfuse, AI Gateway, and external API partial outages;
- lost projection event followed by reconciliation.
### 9.6 Performance and load tests
- Service Binding/RPC and public API latency;
- WebSocket connection, reconnect, and event fan-out behavior;
- Agent/Durable Object contention and hot-key distribution;
- Fiber concurrency with I/O-heavy workloads;
- sandbox cold start versus backup restore;
- Hyperdrive/Neon query count, latency, and pool behavior;
- AI Gateway route latency and fallback overhead;
- Browser Run session reuse and concurrency;
- multi-tenant quotas and noisy-neighbor resistance.
### 9.7 E2E and evaluation tests
- GitHub Actions deploys an isolated preview environment.
- Standard Playwright Test exercises the real deployed web/API application.
- Browser Run is tested as a runtime tool, not substituted for the CI test runner.
- Langfuse experiments compare prompts, models, and route candidates against versioned datasets.
- Release gates require no statistically or operationally material regression in protected evaluation dimensions.
## 10. CI/CD
GitHub Actions is the CI/CD orchestrator; Cloudflare is the deployment target.
### 10.1 Pull-request pipeline
1. Install from the lockfile and verify generated files are current.
2. Lint, format-check, type-check, and run unit tests.
3. Run Zod contract compatibility and provider conformance suites.
4. Run database migration validation against an isolated Neon branch/database.
5. Run integration tests with local/emulated services where faithful and remote test resources where required.
6. Run security policy, egress, idempotency, cancellation, and recovery tests.
7. Run protected Langfuse offline evaluation suites for model/prompt/tool/router changes.
8. Deploy versioned preview Workers, Workflows, Sandbox definitions, Static Assets, and docs.
9. Run standard Playwright E2E against the preview deployment.
10. Publish test, trace, browser, and evaluation artifacts.
### 10.2 Production promotion
- Use isolated development, preview, staging, and production bindings, secrets, R2 buckets, Neon resources, Better Auth configuration, Langfuse projects, and AI Gateway routes.
- Apply backward-compatible database migrations using expand/migrate/contract sequencing.
- Deploy shared contracts and backward-compatible service implementations before dependent callers.
- Promote Workers and Workflows through staged traffic where supported.
- Change model routes independently through versioned AI Gateway route promotion and canaries.
- Use scoped, short-lived deployment identity where available; avoid broad long-lived CI credentials.
- Require approval for database-destructive, privilege-expanding, or high-risk model-route changes.
### 10.3 Rollback
- Worker and application rollback selects a previously known-good immutable deployment.
- AI routing rollback reactivates the prior approved route version.
- Database changes maintain backward compatibility across the rollback window; destructive contraction occurs only after verification.
- Artifacts and workspace snapshots are immutable and referenced by version/digest.
- Rollback does not erase audit, usage, or side-effect records.
## 11. Operational Invariants
The implementation is conformant only if all of the following remain true:
1. Hono is the canonical domain API boundary; SvelteKit does not duplicate it.
2. SvelteKit calls Hono through Service Bindings/RPC and both use shared Zod contracts.
3. Better Auth remains the authentication/session system; authorization remains application-owned.
4. Cloudflare Agents/Durable Objects own live agent coordination and realtime WebSockets.
5. PartyKit is absent from v1 unless a separate collaborative-document requirement is approved.
6. Fibers coordinate durable I/O and offload CPU-heavy work.
7. Workflows own independent multi-step orchestration, retry, wait, and approval state.
8. Cloudflare Sandbox is primary, E2B is fallback, and Modal is specialized heavy compute.
9. Every execution has a versioned, immutable `ExecutionPolicy` enforced outside the sandbox.
10. Protected execution uses deny-by-default egress.
11. No raw platform credential enters untrusted execution.
12. Credentialed access passes through an audited, capability-scoped broker.
13. Workspace backups live in a dedicated R2 store with authoritative metadata and lineage in Neon.
14. Cross-provider recovery uses a credential-free portable checkpoint; native Sandbox backup is not assumed portable to E2B.
15. Canonical artifacts are immutable/content-addressed in R2 with metadata in Neon.
16. Neon, Agent SQLite, Workflows, R2, Langfuse, and AI Gateway do not compete for authority.
17. Run admission and retryable actions are idempotent; non-replayable external effects are never retried automatically.
18. Cancellation durably revokes new capability and propagates to every active layer.
19. Cloudflare AI Gateway is the sole runtime inference gateway.
20. Model selection is capability- and benchmark-driven, with Langfuse-owned evaluation evidence.
21. The model layer supports multiple AI Gateway protocols and is not coupled only to `/ai/v1/responses`.
22. Playwright CLI remains available inside sandboxes; Browser Run + `@cloudflare/playwright` handles Worker-native browser operations.
23. Standard Playwright Test remains the deployed-application E2E runner in CI.
24. Trace, run, policy, execution, model, tool, and artifact identities correlate across every plane.
## 12. Completed Execution Design
The companion [Canonical Run and Execution Model](./RUN_EXECUTION_MODEL.md) completes the platform design with:
- the root run, task, attempt, operation, lease, fencing, transition, and recovery model;
- provider-neutral execution and Agent-to-sandbox contracts;
- credential-broker grants, egress enforcement, revocation, and side-effect reconciliation;
- native and portable workspace checkpoint semantics;
- context acquisition, compaction, memory, caching, and provenance;
- usage meters, budget reservations, cost/billing separation, and reconciliation;
- bounded multi-agent delegation, isolated workspaces, cancellation, and merge ownership.
Implementation may tune operational limits, pricing, retention, and product-specific policies without reopening the component ownership and security invariants in these two canonical documents.
## 13. Implementation Reference Anchors
- [Cloudflare Agents: durable execution with Fibers](https://developers.cloudflare.com/agents/runtime/execution/durable-execution/)
- [Cloudflare Agents: sub-agents](https://developers.cloudflare.com/agents/runtime/execution/sub-agents/)
- [Cloudflare Agents: Agents as tools](https://developers.cloudflare.com/agents/runtime/execution/agent-tools/)
- [Cloudflare Agents: Workflows boundary](https://developers.cloudflare.com/agents/harnesses/think/workflows/)
- [Cloudflare Sandbox: outbound traffic and trusted handlers](https://developers.cloudflare.com/sandbox/guides/outbound-traffic/)
- [Cloudflare Sandbox: Worker binding connections](https://developers.cloudflare.com/sandbox/guides/workers-connections/)
- [Cloudflare Sandbox: backup and restore with R2](https://developers.cloudflare.com/sandbox/guides/backup-restore/)
- [Cloudflare Sandbox: process execution](https://developers.cloudflare.com/sandbox/1-0-preview/processes/)
- [Cloudflare AI Gateway: REST API protocols](https://developers.cloudflare.com/ai-gateway/usage/rest-api/)
- [Cloudflare AI Gateway: dynamic routing](https://developers.cloudflare.com/ai-gateway/features/dynamic-routing/usage/)
- [Cloudflare AI Gateway: spend limits](https://developers.cloudflare.com/ai-gateway/features/spend-limits/)
- [Cloudflare Workers: Service Binding RPC](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/)
- [Cloudflare Browser Run: Playwright](https://developers.cloudflare.com/browser-run/playwright/)
- [Cloudflare SvelteKit on Workers](https://developers.cloudflare.com/workers/framework-guides/web-apps/sveltekit/)
- [Better Auth: SvelteKit integration](https://better-auth.com/docs/integrations/svelte-kit)
- [Langfuse: evaluation concepts](https://langfuse.com/docs/evaluation/core-concepts)
- [Langfuse: scores data model](https://langfuse.com/docs/evaluation/scores/data-model)
## 14. Final Architecture Diagram
```mermaid
flowchart TB
User[Users and API clients]
Webhook[Webhook senders]
ExternalAPI[Approved external APIs]
subgraph Foundation[Cloudflare-Centric Platform]
direction TB
subgraph Control[1. Control Plane - trusted]
Web[SvelteKit Worker + Static Assets<br/>UI, SSR, session bootstrap]
Auth[Better Auth<br/>authentication and sessions]
API[Hono API Worker<br/>canonical /v1 API + Zod]
Agent[Cloudflare Agents + Durable Objects<br/>identity, WebSockets, live coordination]
Fiber[Agent Fibers<br/>durable I/O coordination + checkpoints]
Workflow[Cloudflare Workflows<br/>independent steps, retries, waits, approvals]
Policy[Policy Services<br/>authorization + ExecutionPolicy]
Routers[Model, Execution, and Tool Routers]
Broker[Credential and Egress Broker<br/>Sandbox outbound handlers]
end
subgraph Execution[2. Execution Plane - untrusted or resource intensive]
CFS[Cloudflare Sandbox<br/>primary shell, Git, build, test]
E2B[E2B<br/>ordinary fallback]
Modal[Modal<br/>GPU / heavy CPU / memory]
PWCLI[Playwright CLI<br/>sandbox-local browser]
end
subgraph Data[3. Data Plane]
Hyperdrive[Cloudflare Hyperdrive]
Neon[(Neon Postgres + Drizzle<br/>relational system of record)]
SQLite[(Agent SQLite<br/>live operational state + Fiber stash)]
WFState[(Workflow-managed step state)]
R2Artifacts[(R2 Artifact Bucket<br/>immutable / content-addressed)]
R2Workspaces[(R2 Workspace Backup Bucket<br/>restorable snapshots)]
end
subgraph Intelligence[4. Intelligence + Tooling Plane]
ModelRouter[Capability Model Router<br/>approved policy version]
AIG[Cloudflare AI Gateway<br/>dynamic routes + protocol adapters]
WAI[Workers AI]
ExternalModels[External model providers]
ToolRouter[Tool Registry and Router]
Parallel[Parallel CLI]
Firecrawl[Firecrawl CLI]
BrowserRun[Browser Run + @cloudflare/playwright]
Langfuse[Langfuse<br/>traces, datasets, experiments, eval scores]
end
CFTelemetry[Cloudflare Observability]
end
GitHub[GitHub Actions<br/>CI/CD + Playwright Test]
Docs[Cloudflare Pages<br/>documentation]
User --> Web
User --> API
Webhook --> API
Web <--> Auth
Auth --> Neon
Web -->|Service Binding / RPC| API
API --> Policy
API --> Agent
Agent <--> User
Agent --> Fiber
Agent --> Workflow
Agent <--> SQLite
Fiber <--> SQLite
Workflow <--> WFState
Policy --> Routers
Fiber --> Routers
Workflow --> Routers
Routers --> ModelRouter
ModelRouter --> AIG
AIG --> WAI
AIG --> ExternalModels
AIG --> Langfuse
Langfuse -.evaluation scores and experiments.-> ModelRouter
Routers --> ToolRouter
ToolRouter --> Parallel
ToolRouter --> Firecrawl
ToolRouter --> BrowserRun
ToolRouter --> PWCLI
Routers --> CFS
Routers --> E2B
Routers --> Modal
CFS --> PWCLI
CFS -->|credential-free egress| Broker
E2B -->|policy-equivalent broker channel| Broker
Modal -->|policy-equivalent broker channel| Broker
Broker -->|authorized, credentialed call| ExternalAPI
CFS <--> R2Workspaces
Broker -->|authorized artifact access| R2Artifacts
API --> Hyperdrive
Hyperdrive <--> Neon
Policy <--> Neon
R2Artifacts -.metadata and provenance.-> Neon
R2Workspaces -.metadata and lineage.-> Neon
Agent -.run projection.-> Neon
Workflow -.workflow projection.-> Neon
Web -.telemetry.-> CFTelemetry
API -.telemetry.-> CFTelemetry
Agent -.telemetry.-> CFTelemetry
Fiber -.telemetry.-> CFTelemetry
Workflow -.telemetry.-> CFTelemetry
CFS -.telemetry.-> CFTelemetry
AIG -.gateway telemetry.-> CFTelemetry
GitHub --> Foundation
GitHub --> Docs
```