# How Cloudflare OS Agents Are Executed Using Code Mode

> Learn how Cloudflare OS agents use Code Mode to execute user JavaScript or TypeScript in sandboxed Workers via pipelined Cap'n Proto RPC for immediate edge processing.

- Repository: [Cloudflare/cloudflare-os](https://github.com/cloudflare/cloudflare-os)
- Tags: internals
- Published: 2026-09-05

---

**Cloudflare OS agents are executed using Code Mode by evaluating user-supplied JavaScript or TypeScript inside sandboxed Cloudflare Workers, invoked via pipelined Cap'n Web RPC stubs that bypass intermediate promise awaiting for immediate edge execution.**

The `cloudflare/cloudflare-os` repository (internally referred to as the **Workshop**) provides the runtime for these agents. Code Mode is a lightweight execution path designed for on-demand, stateless computation, distinct from long-lived persistent deployments. It enables agents packaged as **gadgets**—self-contained bundles of source files—to run securely within ephemeral Worker environments governed by strict capability-based access controls.

## Code Mode Execution Architecture

### Capability-Based Sandboxing

When a workspace requests an agent, the orchestrator defined in [`packages/workshop-backend/src/overseer.ts`](https://github.com/cloudflare/cloudflare-os/blob/main/packages/workshop-backend/src/overseer.ts) instantiates a fresh **capability-based execution context**. This context restricts the running code to only explicitly granted bindings: gatekeeper resources, ambient capabilities, and the agent-catalog reference. The Cloudflare Worker runtime enforces these constraints at the binding level, ensuring isolated execution without container overhead.

### Cap'n Web RPC Pipeline

Agent invocation traverses the **Cap'n Web RPC** layer implemented in [`packages/workshop-shared/src/api.ts`](https://github.com/cloudflare/cloudflare-os/blob/main/packages/workshop-shared/src/api.ts). Rather than awaiting connection establishment, the system pipelines the RPC stub directly to the worker. This pattern eliminates network round-trips between the caller and the edge node, allowing the agent's `run` method to begin execution immediately upon receipt of the request.

## Agent Lifecycle and Resource Management

### Gadget-Based Agent Definition

In Cloudflare OS, an agent is a code module contained within a **gadget**. As documented in [`AGENTS.md`](https://github.com/cloudflare/cloudflare-os/blob/main/AGENTS.md), the gadget exports a default object exposing a `run` method that accepts structured input and returns results. Code Mode specifically targets these gadgets for direct evaluation inside the Worker runtime, treating the source as an ephemeral function rather than a continuously running service.

### Explicit Resource Disposal

To prevent resource leaks on the server side, the RPC stub implements the explicit resource management protocol via `Symbol.dispose`. Backend code should utilize the `using` keyword or explicitly invoke `stub[Symbol.dispose]()` once execution completes. This deterministic cleanup immediately terminates the Cap'n Web RPC connection and releases the Worker instance, critical for high-throughput scenarios where agents spawn frequently.

## Observability and Error Handling

All Code Mode executions are instrumented through `@gadgets/backend-utils/logger`, which emits structured logs capturing agent identifiers, input parameters, and execution results. Unexpected failures are captured by `@gadgets/backend-utils/error-reporting`, aggregating stack traces and runtime context for debugging while maintaining isolation between tenant boundaries. Frontend-facing agent documentation resides in [`packages/workshop-frontend/AGENTS.md`](https://github.com/cloudflare/cloudflare-os/blob/main/packages/workshop-frontend/AGENTS.md), providing a discoverability layer for available agent capabilities.

## Practical Code Examples

### Defining a Simple Agent

```typescript
// A simple agent that echoes a string – Code Mode
export default {
  async run({ input }: { input: string }) {
    // No await needed for the RPC stub – pipeline directly
    return `Echo: ${input}`;
  },
};

```

### Invoking the Agent from the Backend

```typescript
// Invoking the agent from the backend (Code Mode)
import { createRpcClient } from "@gadgets/workshop-shared";
import { logger } from "@gadgets/backend-utils/logger";

async function executeAgent(agentId: string, payload: any) {
  const client = createRpcClient();               // Cap’n Web RPC client
  const agent = client.getAgent(agentId);          // RPC stub, pipelined
  const result = await agent.run(payload);        // Execution in the worker
  logger.info("Agent executed", { agentId, result });
  return result;
}

```

### Proper Stub Disposal

```typescript
// Proper disposal of a stub (recommended pattern)
using const session = client.getSession(); // Session stub
// …use session…
// Automatically disposed when block exits via Symbol.dispose

```

## Summary

- **Code Mode** executes Cloudflare OS agents inside ephemeral Cloudflare Workers using capability-based sandboxing configured in [`packages/workshop-backend/src/overseer.ts`](https://github.com/cloudflare/cloudflare-os/blob/main/packages/workshop-backend/src/overseer.ts).
- **Cap'n Web RPC** pipelines method calls directly to the edge Worker without awaiting connection handshakes, minimizing latency for agent invocations defined in [`packages/workshop-shared/src/api.ts`](https://github.com/cloudflare/cloudflare-os/blob/main/packages/workshop-shared/src/api.ts).
- Agents are packaged as **gadgets** containing standard JavaScript/TypeScript modules with exported `run` methods, enabling straightforward code deployment.
- Resource safety relies on explicit disposal via `Symbol.dispose` and `using` blocks to prevent RPC stub leaks under load.
- Execution telemetry flows through `@gadgets/backend-utils/logger` and `@gadgets/backend-utils/error-reporting` for operational visibility.

## Frequently Asked Questions

### What distinguishes Code Mode from persistent agent deployments in Cloudflare OS?

Code Mode provisions transient, stateless execution environments for immediate task processing, whereas persistent deployments maintain long-running processes. According to the Workshop architecture described in [`AGENTS.md`](https://github.com/cloudflare/cloudflare-os/blob/main/AGENTS.md), Code Mode is optimized for cold-start performance and rapid teardown, making it ideal for event-driven automation that does not require maintained state between invocations.

### How does Cap'n Web RPC achieve low-latency agent execution?

The implementation in [`packages/workshop-shared/src/api.ts`](https://github.com/cloudflare/cloudflare-os/blob/main/packages/workshop-shared/src/api.ts) utilizes **pipeline** semantics, allowing the client to send invocation parameters immediately without blocking on connection establishment promises. This eliminates the round-trip latency typically associated with HTTP request-response cycles, delivering sub-millisecond overhead for agent execution initiation at the edge.

### What security mechanisms isolate Code Mode executions?

Security is enforced through **capability-based access control** where the orchestrator explicitly grants only necessary bindings to each execution context. As implemented in [`packages/workshop-backend/src/overseer.ts`](https://github.com/cloudflare/cloudflare-os/blob/main/packages/workshop-backend/src/overseer.ts), agents receive no ambient authority beyond their declared gatekeeper resources and catalog references, preventing unauthorized access to system internals or cross-tenant data.

### How should developers dispose of agent RPC stubs to prevent resource leaks?

Always wrap stub usage in a `using` declaration or explicitly call `stub[Symbol.dispose]()` upon completion. The Workshop's RPC client conforms to the explicit resource management standard, ensuring that underlying Cap'n Web RPC connections terminate immediately when disposal is triggered, rather than awaiting garbage collection cycles that could exhaust connection pools under high concurrency.