How Gadget Code Executions Are Harnessed in Cloudflare OS: Inside the Workshop Backend Kernel

Cloudflare OS utilizes a specialized kernel called workshop‑backend to execute Gadget code through a capability‑secure RPC tool named executeCode, streaming TypeScript snippets into sandboxed Dynamic Worker facets while enforcing strict isolation via worktree bindings and explicit Gatekeeper authorizations.

Cloudflare OS orchestrates AI‑driven development through a unique operating system architecture centered on the workshop‑backend kernel. When an AI agent needs to run code inside a user‑owned Gadget, the system leverages a carefully designed execution harness that balances flexibility with security. Understanding how Gadget code executions are harnessed requires examining the RPC definitions, kernel routing logic, and sandbox guarantees implemented across the cloudflare/cloudflare‑os repository.

The executeCode RPC Tool Definition

Every Gadget code execution begins with a formal RPC contract defined in packages/workshop‑shared/src/api.ts. This file declares the executeCode tool using Cap’n Web to generate a strongly‑typed schema that the AI agent consumes as a local function.

The tool accepts a stream of TypeScript or JavaScript source code and returns the evaluation result once the snippet finishes. By standardizing the interface in the shared API package, both the agent and the backend agree on serialization formats, streaming behavior, and error handling semantics before any code reaches the kernel.

Kernel Routing via the Overseer

Once the agent invokes the tool, control passes to the Overseer—the OS kernel logic residing in packages/workshop‑backend/src/overseer.ts. Inside this module, the function executeCodeMode intercepts the call and prepares the execution context.

The Overseer performs three critical actions:

  1. Worktree binding – It creates a worktree representing the target Gadget’s file system state, ensuring the code operates on the correct set of files.
  2. Environment injection – It constructs a temporary env object containing an RpcStub for the Gadget (self) and any explicitly authorized Gatekeeper bindings.
  3. Sandbox dispatch – It forwards the code and environment to a Dynamic Worker facet, a sandboxed runtime with no outbound network access by default.

This routing layer guarantees that Gadget code executions are harnessed only after the kernel verifies resource bindings and establishes the capability‑based security context.

Agent‑Side Code Streaming

The agent implementation in packages/workshop‑backend/src/agent.ts handles the client‑side orchestration of Gadget code executions. When the agent needs to modify a Gadget, it formats a tool‑call payload and streams the source string to the backend.

During execution, the running snippet interacts with the injected env:

  • self – The RpcStub exposing the Gadget’s own RPC surface, allowing the code to read or write files and invoke internal methods.
  • Gatekeeper stubs – Explicitly bound external resources that permit network egress or access to privileged APIs.

After the snippet returns, the backend streams the result back to the agent and immediately triggers cleanup routines.

Sandbox Guarantees and Security Boundaries

Security in Cloudflare OS relies on the Dynamic Worker facet architecture. Each Gadget code execution runs inside an isolated facet that inherits no ambient authority; network access, file system reach, and API capabilities must be explicitly granted through the worktree binding.

Key protections include:

  • Capability‑based restrictions – The env object injected by executeCodeMode exposes only the RpcStubs provisioned at call time. If a Gatekeeper binding is absent, the code cannot establish external connections.
  • Automatic resource disposal – Upon completion, the sandbox invokes [Symbol.dispose] on temporary RpcStubs to prevent server‑side leaks and ensure deterministic cleanup.
  • Reproducible isolation – Because the worktree snapshots the Gadget’s state before execution, repeated runs yield consistent environments regardless of external system changes.

This model allows the AI agent to write, test, and modify Gadgets on‑the‑fly without risking the host system or other tenants.

Code Examples

The following pattern demonstrates how an agent invokes code inside a Gadget named “SLIDES”:

// Agent‑side: invoke a snippet inside a Gadget called “SLIDES”
await tools.executeCode({
  // The code runs inside the Gadget’s env
  code: `
    // \`self\` is the Gadget RPC stub
    const deck = await self.createDeck({ title: "Q3 Review" });
    await deck.addSlide({ markdown: "# Welcome" });

    return deck.id;
  `,
});

On the backend, the executeCodeMode function orchestrates the sandboxed run:

// Backend – executeCodeMode (simplified)
async function executeCodeMode(chatId: number, code: string) {
  const worktree = await this.worktreeForChat(chatId);
  const env = { /* bindings for the Gadget and any Gatekeepers */ };
  const result = await worktree.runInSandbox(code, env);
  return result; // streamed back to the agent
}

Summary

  • Gadget code executions in Cloudflare OS are mediated by the workshop‑backend kernel through the executeCode RPC tool defined in packages/workshop‑shared/src/api.ts.
  • The Overseer module (overseer.ts) routes requests via executeCodeMode, creating worktree bindings and injecting capability‑limited environments.
  • Dynamic Worker facets provide sandboxed isolation, denying network access unless a Gatekeeper binding is explicitly provisioned.
  • Automatic disposal of RpcStubs via [Symbol.dispose] prevents resource leaks after snippet completion.
  • The agent streams code from agent.ts and receives results through the same asymmetric RPC channel, enabling real‑time iterative development.

Frequently Asked Questions

What is the workshop‑backend kernel in Cloudflare OS?

The workshop‑backend kernel is the central coordination layer of Cloudflare OS that manages interactions between AI agents, user‑owned Gadgets, and external Gatekeepers. According to the source code in cloudflare/cloudflare‑os, it functions as the OS kernel, exposing RPC interfaces and enforcing security boundaries during Gadget code executions.

How does the executeCode tool isolate Gadget executions?

The tool leverages Dynamic Worker facets created in packages/workshop‑backend/src/worktree-session.ts. Each execution receives a fresh sandbox with no ambient authority, and the Overseer injects only explicitly bound resources into the env object. This capability‑based approach ensures that Gadget code can interact only with files and network endpoints pre‑authorized by the kernel.

What prevents Gadget code from accessing unauthorized network resources?

By default, the Dynamic Worker facet has no outbound network access. The executeCodeMode function in overseer.ts binds network capabilities only when a Gatekeeper stub is included in the injected environment. Without this explicit binding, the sandboxed runtime blocks all external connection attempts.

How does the system prevent resource leaks after code execution?

After the snippet returns, the backend iterates over temporary RpcStubs and invokes their [Symbol.dispose] methods. This pattern, implemented in the worktree session layer, ensures that file handles, network sockets, and memory allocations are reclaimed immediately, preventing server‑side resource exhaustion across repeated Gadget code executions.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →