Cloudflare Computer Runtime Types Documentation: Complete TypeScript API Reference
Yes—Cloudflare Computer provides comprehensive documentation for its runtime types, with the definitive specifications located in docs/05_runtime_interface.md and the concrete TypeScript implementations in packages/computer/src/runtime/runtime.ts.
This guide explores the core runtime types that power Cloudflare Computer's code execution environment. The types define how you start, control, and observe code running in isolated workspaces, whether executing shell commands or JavaScript modules. All definitions are grounded in the official codebase at cloudflare/computer.
WorkspaceRuntime: The Primary Interface
The WorkspaceRuntime interface is the entry point for all code execution. It is the object returned by workspace.runtime in the Cloudflare Computer API.
Core Methods
| Method | Signature | Purpose |
|---|---|---|
exec |
exec(source: string, options?: WorkspaceRuntimeExecOptions): Promise<WorkspaceRuntimeExecHandle> |
Starts a new execution and returns a handle |
getExec |
getExec(id: string, options?: WorkspaceRuntimeGetOptions): Promise<WorkspaceRuntimeExecHandle> |
Re-attaches to an existing execution by UUID |
killExec |
killExec(id: string, options?: WorkspaceRuntimeKillOptions): Promise<void> |
Terminates a running execution |
disposeExec |
disposeExec(id: string, options?: WorkspaceRuntimeDisposeOptions): Promise<void> |
Releases resources for completed executions |
Source: [docs/05_runtime_interface.md](https://github.com/cloudflare/computer/blob/main/docs/05_runtime_interface.md)
Method Implementation Details
In packages/computer/src/runtime/runtime.ts, the WorkspaceRuntime implementation handles backend routing and execution lifecycle management. The exec() method validates the backend option against registered backends, then delegates to the appropriate execution engine.
WorkspaceRuntimeExecOptions: Configuring Executions
The WorkspaceRuntimeExecOptions interface controls how code runs. These options are passed to every exec() call.
interface WorkspaceRuntimeExecOptions {
id?: string; // Optional client-chosen UUID
backend?: string; // Backend selector (e.g., "container-shell")
cwd?: string; // Working directory for the command
encoding?: "utf8"; // stdout/stderr decoding
input?: WorkspaceRuntimeValue; // Structured input for callable backends
timeoutMs?: number; // Automatic termination timeout
env?: Record<string, string>; // Environment variables
stdin?: Uint8Array | string; // Raw stdin data when supported
}
Key behaviors from docs/16_code_execution.md:
id—If omitted, a UUID is generated automatically. Explicit IDs enable later re-attachment viagetExec().backend—Determines execution semantics. Valid values include"worker-shell","container-shell", and"worker-javascript".timeoutMs—Hard upper bound on execution duration. Exceeding this triggerskillExec()automatically.
WorkspaceRuntimeExecHandle: Controlling Active Executions
The handle returned by exec() implements ReadableStream<WorkspaceRuntimeEvent> and provides procedural control.
interface WorkspaceRuntimeExecHandle extends ReadableStream<WorkspaceRuntimeEvent> {
readonly id: string;
readonly backend: string;
result(): Promise<WorkspaceRuntimeResult>; // Resolves on completion
kill(signal?: KillSignal): Promise<void>; // User-initiated termination
[Symbol.dispose](): void; // Resource cleanup
}
Critical Constraint: Single-Consumer Streams
As documented in docs/05_runtime_interface.md, the handle stream is single-consumer. You must choose one consumption pattern:
- Event streaming—Iterate
for await (const event of handle)for real-time output - Result polling—Call
await handle.result()for final aggregated output
Attempting both on the same handle produces undefined behavior.
WorkspaceRuntimeResult: Execution Outcomes
The result() method resolves to a WorkspaceRuntimeResult containing complete execution metadata.
interface WorkspaceRuntimeResult {
status: "completed" | "failed" | "cancelled";
exitCode: number;
stdout: Uint8Array | string;
stderr: Uint8Array | string;
value?: WorkspaceRuntimeValue; // Only populated for module backends
pushed: number; // Files pushed before execution
pulled: number; // Files pulled after execution
skipped: SkippedEntry[];
sync: {
status: "complete" | "pending";
applied: number;
skipped: SkippedEntry[];
error?: string; // Present when status is "pending"
};
}
The value field distinguishes module backends from shell backends:
- Shell backends (
worker-shell,container-shell)—valueis alwaysundefined; usestdoutinstead - JavaScript module backend (
worker-javascript)—valuecontains the structured return value from the module's default export
Backend Routing and Type Behavior
The backend option fundamentally alters type semantics. Cloudflare Computer implements three primary backends, each with distinct characteristics documented across docs/05_runtime_interface.md, docs/16_code_execution.md, and docs/17_isolate_javascript.md.
Backend Comparison
| Backend | Type | Re-attachment | Streaming | Result Storage |
|---|---|---|---|---|
worker-shell |
One-shot | No | Buffered | In-memory only |
container-shell |
Persistent | Yes | Real-time | Process log with push/pull sync |
worker-javascript |
Durable | Yes | Event-based | SQLite journal in workspace |
Backend Selection Examples
// Container shell: persistent process with filesystem sync
const containerHandle = await workspace.runtime.exec(
"npm run build",
{ backend: "container-shell", cwd: "/workspace" }
);
// Worker JavaScript: isolated module with structured return
const jsHandle = await workspace.runtime.exec(
`export default async () => ({ timestamp: Date.now() });`,
{ backend: "worker-javascript" }
);
// Worker shell: simple one-shot command
const quickHandle = await workspace.runtime.exec(
"echo 'Hello World'",
{ backend: "worker-shell" }
);
Practical Code Examples
These examples demonstrate common patterns for Cloudflare Computer runtime types.
Example 1: Blocking Shell Execution with Result Inspection
const handle = await workspace.runtime.exec("cargo test --lib", {
backend: "container-shell",
cwd: "/workspace/crates/core",
encoding: "utf8",
timeoutMs: 300_000, // 5 minute timeout
});
const result = await handle.result();
if (result.status === "completed" && result.exitCode === 0) {
console.log("Tests passed:\n", result.stdout);
} else if (result.status === "cancelled") {
console.error("Tests timed out");
} else {
console.error("Test failures:\n", result.stderr);
}
Uses WorkspaceRuntimeExecHandle.result() for synchronous-style execution with full WorkspaceRuntimeResult analysis.
Example 2: JavaScript Module with Structured Return Value
const moduleSource = `
import { parse } from "node:path";
import fs from "node:fs/promises";
export default async function analyzePackage() {
const pkgRaw = await fs.readFile("/workspace/package.json", "utf8");
const pkg = JSON.parse(pkgRaw);
return {
name: pkg.name,
dependencies: Object.keys(pkg.dependencies || {}),
devDependencies: Object.keys(pkg.devDependencies || {}),
};
}
`;
const handle = await workspace.runtime.exec(moduleSource, {
backend: "worker-javascript",
env: { NODE_ENV: "analysis" },
});
const { value, status, sync } = await handle.result();
if (status === "completed" && sync.status === "complete") {
// 'value' is typed as WorkspaceRuntimeValue (here, a parsed object)
console.log(`Package ${value.name} has ${value.dependencies.length} deps`);
}
Demonstrates how the worker-javascript backend populates WorkspaceRuntimeResult.value with serialized module return values.
Example 3: Real-Time Streaming with Re-attachment
// Start a long-running process
const execId = crypto.randomUUID();
const handle = await workspace.runtime.exec(
"tail -n 0 -f /var/log/app.log",
{ backend: "container-shell", id: execId }
);
// Stream events for 30 seconds
const abortController = new AbortController();
setTimeout(() => abortController.abort(), 30_000);
try {
for await (const event of handle) {
if (event.type === "stdout") {
process.stdout.write(event.data);
} else if (event.type === "stderr") {
process.stderr.write(event.data);
}
}
} catch (e) {
if (e.name === "AbortError") {
console.log("\n--- Streaming paused, process continues ---");
}
}
// Later: re-attach and get final result
const reattached = await workspace.runtime.getExec(execId);
const finalResult = await reattached.result();
console.log("Final status:", finalResult.status, "exit code:", finalResult.exitCode);
Shows ReadableStream<WorkspaceRuntimeEvent> consumption and getExec() re-attachment pattern for durable executions.
Key Source Files for Runtime Types
| Path | Contents | Documentation Role |
|---|---|---|
packages/computer/src/runtime/runtime.ts |
Concrete WorkspaceRuntime implementation |
Source of truth for type implementations |
docs/05_runtime_interface.md |
Formal interface specifications | Primary reference for type semantics |
docs/16_code_execution.md |
Execution lifecycle and backend architecture | Backend selection guidance |
docs/17_isolate_javascript.md |
JavaScript isolate specifics | Module backend details |
Summary
WorkspaceRuntimeis the root interface exposed atworkspace.runtime, withexec()as the primary entry pointWorkspaceRuntimeExecOptionsconfigures timeout, backend, environment, and working directoryWorkspaceRuntimeExecHandleprovides both streaming (ReadableStream) and polling (result()) interfaces, but not simultaneouslyWorkspaceRuntimeResultdelivers final execution state, withvaluepopulated only for JavaScript module backends- Backend selection determines re-attachment capability, streaming behavior, and result durability
Frequently Asked Questions
Where are the Cloudflare Computer runtime types formally defined?
The authoritative documentation is in docs/05_runtime_interface.md at the repository root. The concrete TypeScript implementations reside in packages/computer/src/runtime/runtime.ts. For execution behavior specifics, consult docs/16_code_execution.md and docs/17_isolate_javascript.md.
Can I use the same execution handle for both streaming and result polling?
No. WorkspaceRuntimeExecHandle implements a single-consumer stream protocol. Once you begin iterating events with for await, calling result() produces undefined behavior. Choose streaming for real-time feedback or result() for simple blocking execution.
What values can the value field in WorkspaceRuntimeResult contain?
The value field carries structured data only from the worker-javascript backend, containing the JSON-serialized return value of the module's default export. Shell backends always leave value undefined; extract output from stdout instead.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →