containers
AGENTS.md270 starsChanged 3 months agoApache-2.0View on GitHub
Guidelines for AI agents working on the @cloudflare/containers package. This is the @cloudflare/containers npm package — a TypeScript library that wraps Cloudflare's container-enabled Durable Objects. It provides lifecycle management, HTTP/WebSocket proxying, outbound interception, scheduling, and load balancing utilities on top of the Cloudflare Workers runtime. Key exports (src/index.ts): Add a new file to the .changeset directory representing a new version when wrapping up changes so they get released. Do NOT change CHANGELOG.md, that is codegenerated on a release MR that…
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
The file
We split this AGENTS.md into the rules it gives an agent
6 rules. About 0 are common, 1 is distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 18
Add a new file to the .changeset directory representing a new version when wrapping up changes so they get released.
- Distinctive: line 19
Do NOT change CHANGELOG.md, that is codegenerated on a release MR that is automated.
- Very specific: line 114
Use this.schedule() instead of overriding alarm().
- Very specific: line 140
Run a single example's scripts with pnpm --filter <package-name> <script> (e.g.
- Very specific: line 156
Do not override
alarm(): Use schedule() instead; the internal alarm handler manages container activity timers. - Very specific: line 170
Call runner.destroy([id]) when the test needs to fire the worker's /destroy?id=<id> route — for example, to exercise a container's onStop …
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md
Guidelines for AI agents working on the @cloudflare/containers package.
Project Overview
This is the @cloudflare/containers npm package — a TypeScript library that wraps Cloudflare's container-enabled Durable Objects. It provides lifecycle management, HTTP/WebSocket proxying, outbound interception, scheduling, and load balancing utilities on top of the Cloudflare Workers runtime.
Key exports (src/index.ts):
Container— base class, extendsDurableObjectContainerProxy—WorkerEntrypointused for outbound HTTP interceptionoutboundParams— helper for typed outbound handler paramsgetRandom,loadBalance(deprecated),getContainer,switchPort— utility functions
Releasing
Add a new file to the .changeset directory representing a new version when wrapping up changes so they get released.
Do NOT change CHANGELOG.md, that is codegenerated on a release MR that is automated.
Repository Layout
src/
index.ts # Public exports
lib/
container.ts # Container + ContainerProxy class implementations
helpers.ts # generateId, parseTimeExpression
utils.ts # getRandom, getContainer, loadBalance, switchPort
types/ # Shared TypeScript types
examples/ # Runnable example Workers using the packageBuild output goes to dist/. Do not edit files in dist/.
Core Concepts
Container Class (src/lib/container.ts)
Container extends DurableObject. Each instance wraps exactly one container process via ctx.container.
Key instance properties:
defaultPort?: number— port used byfetch()andcontainerFetch()when none is specifiedrequiredPorts?: number[]— ports checked duringstartAndWaitForPortssleepAfter: string | number— inactivity timeout beforeonActivityExpired()fires (default"10m")envVars,entrypoint,enableInternet— container start config defaultspingEndpoint: string— endpoint polled to confirm container readiness (default"ping")
Important timeouts (constants in container.ts):
TIMEOUT_TO_GET_CONTAINER_MS = 8_000— time to get a container instanceTIMEOUT_TO_GET_PORTS_MS = 20_000— time to wait for ports to be readyINSTANCE_POLL_INTERVAL_MS = 300— polling intervalMAX_ALARM_RETRIES = 3— max alarm retries before scheduling next
Lifecycle hooks (override in subclasses):
onStart()— fired onstopped → running → healthytransitionsonStop(params)— fired when container shuts downonError(error)— fired on errors; default logs and rethrowsonActivityExpired()— fired whensleepAftertimeout expires; default callsthis.stop()
Starting a container:
start(startOptions?, waitOptions?)— starts without waiting for portsstartAndWaitForPorts(args)— starts and polls until ports are readywaitForPort(waitOptions)— polls a single port; returns tries used
HTTP methods:
fetch(request)— forwards HTTP + WebSocket; usesdefaultPortorcf-container-target-portheadercontainerFetch(requestOrUrl, portOrInit?, port?)— HTTP only (no WebSocket); flexible signatures
Utility methods:
stop(signal?)— sends signal (defaultSIGTERM)destroy()— sendsSIGKILLgetState()— returns currentStaterenewActivityTimeout()— resets the inactivity timerschedule(when, callback, payload?)— schedules a future callback via DO alarms
Outbound Interception
ContainerProxy (WorkerEntrypoint) handles outbound HTTP from the container. It must be exported from the Worker entrypoint alongside Container subclasses.
Handler priority (highest to lowest):
- Runtime
setOutboundByHostoverride - Static
outboundByHost - Runtime
setOutboundHandlercatch-all - Static
outbound - Direct internet (if
enableInternet = true)
Static configuration (set on the class):
static outboundByHost = { 'example.com': handler }
static outbound = catchAllHandler
static outboundHandlers = { myHandler: handler }Runtime configuration (call on instance):
await this.setOutboundByHost('example.com', 'myHandler');
await this.setOutboundHandler('myHandler');
await this.removeOutboundByHost('example.com');
await this.setOutboundByHosts({ 'example.com': 'myHandler' });Scheduling
Use this.schedule() instead of overriding alarm(). The alarm handler manages container lifecycle internally. Scheduled callbacks must be method names on the class.
await this.schedule(30, 'myCallback', { data: 'payload' }); // 30s delay
await this.schedule(new Date('2026-01-01'), 'myCallback'); // specific timeUtility Functions (src/lib/utils.ts)
getRandom(binding, n?)— picks one ofninstances (default 3) by random namegetContainer(binding, name?)— gets a named instance (default"cf-singleton-container")switchPort(request, port)— setscf-container-target-portheader; use withfetch()for WebSocket supportloadBalance— deprecated alias forgetRandom
Development
pnpm build # tsc compile to dist/
pnpm typecheck # type check without emitting
pnpm typecheck:all # root + every example
pnpm lint # eslint
pnpm format # prettier
pnpm test # runs integration tests in each examples/*/test directory
pnpm test:unit # runs unit tests in src/tests/Run a single example's scripts with pnpm --filter <package-name> <script> (e.g. pnpm --filter containers-websocket-example test).
Unit tests live in src/tests/ (mocked container ctx, no Docker required). Integration tests live in examples/*/test/ and spawn wrangler dev + Docker containers. When adding new functionality, decide which is more appropriate — prefer the unit test if the behavior can be exercised with the mocks in src/tests/fixtures.ts; otherwise add or extend an example test.
Common Patterns
Always set defaultPort in subclasses unless you're doing manual port routing.
WebSocket forwarding requires fetch() + switchPort(), not containerFetch().
Outbound interception requires exporting ContainerProxy from the Worker entrypoint:
export { ContainerProxy } from '@cloudflare/containers';Do not override alarm(). Use schedule() instead; the internal alarm handler manages container activity timers.
Error states: Container state transitions are stopped → running → healthy → stopping → stopped. The stopped_with_code status carries an exit code.
Integration tests use the runner fixture from examples/test-helpers, which provisions a WranglerDevRunner and tears it down automatically when the test resolves:
import { test } from '../../test-helpers';
test('my test', async ({ runner }) => {
const url = await runner.getUrl();
// ...
});Call runner.destroy([id]) when the test needs to fire the worker's /destroy?id=<id> route — for example, to exercise a container's onStop hook before the fixture tears wrangler down.
Changeset
This repo uses changesets. When making a user-facing change, add a changeset:
pnpm changesetDoes it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

