Skip to content

Configuration Reference

SAM uses environment variables for platform configuration. User-specific settings (cloud provider tokens, agent API keys) are stored encrypted in the database, not as environment variables.

Superadmins change OAuth sign-in, the SAM Connector, operational switches, and the limits for collaboration, workflows, linked work, AI models for agents and agent email in Admin → Settings (on a self-hosted instance, the page arrived in v2026.10.17 and later groups with their features; see that guide). A value saved there wins over the matching variable on this page, which in turn wins over older KV values and the code default; Reset override removes the saved value, so the variable (if set) applies again. Encryption/signing roots, domains and Cloudflare resource bindings remain bootstrap configuration. New runtime tunables belong in the typed settings registry; the environment tables below retain migration compatibility.

Provider reset timestamp rounding is controlled in Admin → Settings by operations.providerLimitResetWindowToleranceMs (default 60000 milliseconds, range 0–300000). Repeated rejections for the same credential with resets within this tolerance share one wait.

Use the typed Operations admin settings below for live configuration. All eight are non-secret settings stored in D1. User opt-in is a separate per-user setting and defaults to off; clearing the installation switch never enables SAM for a user.

Admin setting key Default Permitted range and meaning
operations.samOperatorDisabled false Boolean; disables assistant turns/actions installation-wide while preserving saved user preferences.
operations.samOperatorWatchLifetimeMs 86400000 Integer 1–2147483647; own-work observation lifetime in milliseconds (24 hours). Expiry does not cancel the project task.
operations.samOperatorEventPageSize 25 Integer 1–25; maximum watches per scan, events per watch, and visible work cards.
operations.samOperatorWorkRefreshMs 30000 Integer 1000–2147483647; durable own-work refresh cadence in milliseconds, separate from browser refresh.
operations.samOperatorWatchRetryLimit 3 Integer 1–25; consecutive failed watch refreshes before updates stop. Successful pulls or requested follow-ups reset the count.
operations.samOperatorStreamFlushMs 80 Integer 16–2000; milliseconds between live updates while the assistant answers.
operations.samOperatorStreamHeartbeatMs 15000 Integer 1000–120000; keep-alive interval on a live answer stream.
operations.samOperatorStreamMaxSubscribers 4 Integer 1–20; browser tabs that can follow one answer live at the same time.

Each refresh selects at most 25 watches and reads at most 25 events per watch: at most 325 caller D1 reads, 75 cold ProjectData RPCs, and 625 local event-reference inserts, plus fixed alarm setup. A work-card read performs at most 75 D1 reads. Each watch persists its next check and charges an attempt before I/O; the alarm uses the earliest watch deadline. Failed watches defer until that deadline and stop after the retry limit, with a visible update warning. The watch lifetime also stops observation independently; neither condition cancels project work.

Admin setting overrides take precedence over registry defaults. The disabled setting is read without the normal settings cache before effects and fails closed when settings storage is unavailable. These controls use the typed settings registry only; no Worker bindings or deployment variables are needed.

Sources: apps/api/src/services/operator-settings.ts, admin-settings-registry.ts, and apps/api/src/durable-objects/sam-session/operator/work.ts.

Admin setting key Default Permitted range and meaning
operations.debuggerTools off off, read, read_ask or read_auto_safe; which debugger tools Operations-project agents may use. Read with no cache.
operations.auditRetentionDays 90 Integer 1–3650; days an operations_audit_log row is kept before the daily 0 3 * * * cron deletes it. If the setting cannot be read, that day’s purge is skipped.
operations.operatorNodeDeletionAllowAgentSessions true Boolean; whether an agent sign-in session may use POST /api/admin/nodes/:id/operator-deletion (Admin → Infrastructure → Stuck nodes). Read with no cache.

Read-tool limits (thresholds, caps and debug-package retention) are the operations.debugPackage* and operations.ops* admin settings defined in apps/api/src/services/fleet-ops/settings-definitions.ts; the daily 0 3 * * * cron deletes debug packages older than operations.debugPackageRetentionDays (default 7) from the Operations project library (purgeExpiredDebugPackages in apps/api/src/services/fleet-ops/debug-packages.ts). See Admin Settings.

Every debugger tool checks, on each call, that the setting allows the capability, the MCP token belongs to the Operations project, the token is task-scoped, and the task’s owner is an active superadmin in D1 (requireOperationsAccess in apps/api/src/services/operations-access.ts). A settings outage resolves the mode to off. See Admin Settings.

The assistant reuses existing SAM_MODEL (code default @cf/deepseek-ai/deepseek-v4.1-flash-1017 in resolveSamConfig; omitted from Wrangler bindings unless explicitly overridden through the GitHub Environment variable SAM_MODEL; this model requires the Workers Paid plan or prepaid AI Gateway credits, like the rest of SAM), context/window, tool-result and model-step limits from resolveSamConfig, plus SAM_LLM_TIMEOUT_MS (operator fallback 120000). Operator turn admission uses SAM_MESSAGE_MAX_LENGTH with a 16000-character fallback; legacy subtask-message readers can have a different fallback. No new provider API key is required specifically for enabling the assistant: it uses the installation’s supported platform AI configuration and usage gate.

These are Cloudflare Worker secrets, set during deployment. Pulumi auto-generates security keys on first deploy.

Secret Description
ENCRYPTION_KEY AES-256-GCM master key. Used for BetterAuth session cookies and user credential encryption unless a purpose-specific override below is set (auto-generated)
BETTER_AUTH_SECRET Optional purpose-specific override for BetterAuth session cookie signing/encryption. Falls back to ENCRYPTION_KEY when unset (apps/api/src/lib/secrets.ts)
BOOTSTRAP_OWNER_EMAIL Optional installer-managed Worker secret restricting first administration to this verified login email. Unset preserves manual-install behavior. Set before enabling login; preserve across updates. Also the recovery path when no superadmin remains (self-hosting guide).
CREDENTIAL_ENCRYPTION_KEY Optional purpose-specific override for AES-GCM encryption of user cloud/agent credentials. Falls back to ENCRYPTION_KEY when unset (apps/api/src/lib/secrets.ts)
JWT_PRIVATE_KEY RSA-2048 private key for signing tokens (auto-generated)
JWT_PUBLIC_KEY RSA-2048 public key for token verification (exposed via JWKS)
DEPLOY_SIGNING_PRIVATE_KEY Ed25519 private key for signing deployment apply payloads (auto-generated)
DEPLOY_SIGNING_PUBLIC_KEY Ed25519 public key derived during deployment for deployment node verification (auto-generated)
VAPID_PRIVATE_KEY Base64url P-256 private scalar used to authenticate Web Push delivery (auto-generated)
VAPID_PUBLIC_KEY Uncompressed base64url P-256 public key returned to browsers at runtime (derived during deployment)
VAPID_SUBJECT RFC 8292 contact URI for Web Push, defaulting to the deployment app origin (generated during deployment)
CF_API_TOKEN Cloudflare API token for infrastructure, DNS, Origin CA certificate issuance, observability, AI Gateway, Containers, and admin logs. Requires Account → Containers → Edit and Account → SSL and Certificates → Edit. Optional Account → Account Analytics → Read enables Admin Analytics charts and the daily Cloudflare cost snapshot on Admin → Health & cost.
CF_AIG_TOKEN Optional narrower Cloudflare AI Gateway Unified Billing token
CF_ZONE_ID Cloudflare zone ID for DNS record management
CF_ACCOUNT_ID Cloudflare account ID
DEVCONTAINER_CACHE_CLOUDFLARE_API_TOKEN Optional narrower Cloudflare token for managed devcontainer registry credentials
DEVCONTAINER_CACHE_CLOUDFLARE_ACCOUNT_ID Optional Cloudflare account override for managed devcontainer registry credentials
GITHUB_CLIENT_ID Optional fallback GitHub App client ID for OAuth; runtime admin config takes precedence
GITHUB_CLIENT_SECRET Optional fallback GitHub App client secret for OAuth; runtime admin config takes precedence
GITHUB_APP_ID Optional fallback GitHub App ID for installation tokens; runtime admin config takes precedence
GITHUB_APP_PRIVATE_KEY Optional fallback GitHub App private key (PEM or base64); runtime admin config takes precedence
GITHUB_APP_SLUG Optional fallback GitHub App URL slug; runtime admin config takes precedence
GITHUB_WEBHOOK_SECRET Optional fallback GitHub App webhook HMAC secret; runtime admin config takes precedence
GITLAB_HOST Optional fallback GitLab OAuth host, such as https://gitlab.com; runtime admin config takes precedence. A self-managed host set here can link GitLab sign-ins to existing accounts by email; one saved at runtime cannot
GITLAB_CLIENT_ID Optional fallback GitLab OAuth application ID; runtime admin config takes precedence
GITLAB_CLIENT_SECRET Optional fallback GitLab OAuth secret; runtime admin config takes precedence
AGENT_SIGN_IN_TRUST Optional, test instances only. JSON trust configuration that lets agents on a trusted SAM installation sign in here through workload identity. Unset, empty or invalid: off. Deploy-time only; removing the GitHub secret and redeploying deletes it. See Let agents sign in to a test instance.

Unless the deploy sets them itself (as it does BASE_DOMAIN), Worker variables come from [vars] in apps/api/wrangler.toml, falling back to the default in the code. [vars] lists only values that differ from the code default: every entry becomes a binding on the Worker, and Cloudflare limits how many one Worker can have. A variable missing from [vars] runs with the default listed on this page, and the Worker’s settings page shows no binding for it. On a self-hosted instance, a GitHub Environment variable of the same name replaces that value at deploy time, but only if the deploy forwards it: scripts/deploy/sync-wrangler-config.ts must read it, and the Sync Wrangler Config steps in .github/workflows/deploy-reusable.yml must pass it from vars. After a deploy, the Worker’s Settings → Variables and Secrets page in the Cloudflare dashboard shows the value it got. To change any other variable, edit wrangler.toml in your fork; updates then need a manual merge (see Updating an Existing Self-Hosted Instance).

Variable Default Description
BASE_DOMAIN — Root domain for the deployment (e.g., example.com)
PREVIEW_BASE_DOMAIN preview.BASE_DOMAIN Full isolated hostname used for interactive HTML previews
PREVIEW_URL_TTL_SECONDS 300 Lifetime of project/file/version-scoped interactive preview URLs in seconds
PREVIEW_SIGNING_KEY generated Deployment-owned HMAC key generated and persisted by Pulumi; not a manual prerequisite
VERSION — Deployment version string
SETUP_TOKEN — Plaintext first-run setup token generated on every deploy, readable in the Cloudflare dashboard and masked in the deploy log. Accepted only while setup is incomplete, which ends once an active superadmin exists
SETUP_FORCE (unset) Set to true to reopen /setup for lockout recovery
SETUP_RATE_LIMIT_MAX_ATTEMPTS 10 Max setup-token attempts per client IP (CF-Connecting-IP) per window
SETUP_RATE_LIMIT_WINDOW_SECONDS 900 Setup-token attempt window in seconds
D1_SESSION_MODE first-primary D1 Sessions API anchor for the Worker fetch handler. first-primary runs each request against one D1 session whose first query goes to the primary and whose later queries may be served by a caught-up read replica — same freshness, one wide-area round trip per request instead of one per query. disabled sends every query straight at the primary. An unrecognised value falls back to first-primary and is logged once per isolate. scheduled() and Durable Objects always use the unsessioned binding.
PLATFORM_CONFIG_CACHE_MS 60000 Per-isolate cache TTL for the resolved platform integration config (the GITHUB_*/GITLAB_*/GOOGLE_LOGIN_* fallbacks above and their runtime admin overrides). Resolving costs 14 D1 queries and runs on the auth preamble of every authenticated request. After a config change, isolates that already hold a cached copy converge within this window. Set to 0 to disable caching and always re-read D1.
GITHUB_INSTALLATION_TOKEN_CACHE_TTL_SECONDS 3000 KV cache TTL for GitHub App installation tokens. The default is shorter than GitHub’s one-hour token lifetime. Set to 0 to disable writes for new cache entries.
GITHUB_INSTALLATION_TOKEN_REFRESH_MARGIN_SECONDS 300 Cached GitHub App installation tokens that expire within this many seconds are minted again instead of reused, so a long cache TTL can never hand out an expiring token. Capped at 1800, half the one-hour token lifetime.
GITHUB_REPO_ACCESS_CACHE_TTL_SECONDS 300 KV TTL for per-user, per-installation, per-repository pagination hints. Every authorization checks GitHub with the current user token; cached grants are never trusted. Set to 0 to disable hint writes. Nonzero hint TTLs below 60 seconds use the KV minimum of 60 seconds.
GITHUB_TREE_CACHE_TTL_SECONDS 86400 KV cache TTL for immutable Git tree responses keyed by commit SHA. Branch refs are resolved to a commit SHA before lookup. Set to 0 to disable writes for new cache entries.
PROJECT_MULTIPLAYER_CACHE_TTL_MS 10000 Per-isolate cache TTL for project multiplayer state counts used by trigger-bearing pages. Set to 0 to disable the cache.
CREDENTIAL_ATTRIBUTION_CACHE_TTL_MS 10000 Per-isolate cache TTL for project credential attribution health used by trigger-bearing pages. Set to 0 to disable the cache.

Set in GitHub Settings → Environments → production:

Variable Description Example
BASE_DOMAIN Deployment domain example.com
RESOURCE_PREFIX Domain-derived Cloudflare resource name prefix sa379a6
PULUMI_STATE_BUCKET R2 bucket for Pulumi state sa379a6-pulumi-state
CF_CONTAINER_ENABLED Optional instant-session runtime toggle. Generated deploys default to true; set false to force VM runtime. false
WORKER_SECRET_BULK_MAX_OPS Optional deploy-script limit for queued Worker secret create/update/delete operations in one wrangler secret bulk payload. Defaults to 100; range 1–100. 75
D1_READ_REPLICATION_MODE Optional D1 read-replication mode applied on every deploy. Defaults to auto; set disabled to remove replicas. disabled
D1_SESSION_MODE Optional Worker D1 Sessions anchor. Defaults to first-primary; set disabled to send every query to the primary. An unrecognised value falls back to the default and is logged once per isolate. disabled
D1_RESTORE_RECOVERY_WINDOW_DAYS Optional D1 restore window for accounts with narrower retention. Defaults to 30; range 1–30. 7
D1_MIGRATION_CHURNING_TABLES Optional comma-separated <binding>.<table> subset of the reviewed retention/expiry table list. May narrow the built-in list but cannot expand it. OBSERVABILITY_DATABASE.platform_errors
D1_MIGRATION_CHURNING_TABLE_MAX_DECREASE_PERCENT Maximum allowed decrease for reviewed churning tables. Defaults to 50; range 0–100. A decrease exactly at the limit is accepted. 25
D1_MIGRATION_READ_ATTEMPTS Attempts for a deployment verification read rejected by D1 resource limits. Defaults to 3; range 1–5. Other failures and exhausted retries block deployment; migration writes are never retried. 3
D1_MIGRATION_READ_RETRY_DELAY_MS Delay between resource-limit read retries. Defaults to 10000 ms to clear the provider accounting window; range 0–60000. 10000

The reviewed default churning selectors (DEFAULT_D1_MIGRATION_CHURNING_TABLES in scripts/deploy/d1-migration-churning-tables.ts) are DATABASE.deployment_releases, DATABASE.diagnostic_reconciliation_state, DATABASE.github_trigger_inbox, DATABASE.github_webhook_deliveries, DATABASE.lifecycle_phase_timings, DATABASE.lifecycle_state_episodes, DATABASE.lifecycle_state_observations, DATABASE.node_lifecycle_decisions, DATABASE.node_log_captures, DATABASE.operations_action_approvals, DATABASE.operations_audit_log, DATABASE.project_files, DATABASE.pull_request_checks, DATABASE.registry_credential_rate_limits, DATABASE.session_snapshot_traces, DATABASE.session_snapshots, DATABASE.sessions, DATABASE.trigger_executions, DATABASE.verifications, DATABASE.vm_provisioning_leases, DATABASE.webhook_deliveries, and OBSERVABILITY_DATABASE.platform_errors. All other application tables retain zero row-decrease tolerance. Leave D1_MIGRATION_CHURNING_TABLES unset to use the complete reviewed default list. An explicit D1_MIGRATION_CHURNING_TABLES value replaces the default list, so it does not pick up tables added to the default later.

RESOURCE_PREFIX is generated from BASE_DOMAIN as s plus the first six hex characters of the domain’s SHA-256 hash. The self-host onboarding flow fills it in for you.

These optional Worker variables bound the server-side OCI registry lookups used when a deployment release submits tag-based images. Digest-pinned images are stored without registry network resolution.

Variable Default Description
DEPLOYMENT_IMAGE_RESOLVE_REQUEST_TIMEOUT_MS 10000 Per-registry request timeout
DEPLOYMENT_IMAGE_RESOLVE_TOTAL_TIMEOUT_MS 60000 Total tag-resolution wall-clock budget per release submission
DEPLOYMENT_IMAGE_RESOLVE_MAX_FETCH_ATTEMPTS 200 Maximum outbound registry/token fetches per resolver instance
DEPLOYMENT_IMAGE_RESOLVE_MAX_REDIRECTS 2 Maximum manually validated HTTPS redirects per outbound request
DEPLOYMENT_IMAGE_RESOLVE_TOKEN_RESPONSE_MAX_BYTES 65536 Maximum bearer-token JSON response size
DEPLOYMENT_IMAGE_RESOLVE_MAX_CONCURRENT_FETCHES 4 Maximum simultaneous outbound resolver fetches
DEPLOYMENT_IMAGE_RESOLVE_MAX_SERVICES 50 Maximum tag-based image references resolved per release submission

Required GitHub Actions secrets include CF_API_TOKEN, CF_ACCOUNT_ID, CF_ZONE_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, and PULUMI_CONFIG_PASSPHRASE. GitHub App/OAuth secrets (GH_CLIENT_ID, GH_CLIENT_SECRET, GH_APP_ID, GH_APP_PRIVATE_KEY, GH_APP_SLUG, GH_WEBHOOK_SECRET) and Google login OAuth secrets (GOOGLE_LOGIN_CLIENT_ID, GOOGLE_LOGIN_CLIENT_SECRET) are optional environment fallbacks; fresh deployments can set them through /setup instead. The separate Google infra/GCP OAuth pair (GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET) is used only for WIF and can be configured by a superadmin at /admin/integrations; runtime values override the environment fallback. Service-account JSON users need no infrastructure OAuth client. Deploy signing keys are generated and persisted by Pulumi during deployment; GitHub Environment values are only needed for explicit key overrides.

These variables affect the local sam CLI process only. They are not Worker runtime variables or GitHub Actions secrets.

Variable Default Description
SAM_CLI_MAX_API_RESPONSE_BYTES 1048576 Maximum API response body bytes the CLI reads before truncating/aborting.

Codex and Claude Code guided subscription login have no feature-on environment variable. They are available by default when the deployment includes the SANDBOX, CREDENTIAL_SETUP_SESSION, and SETUP_SESSION_POOL Worker bindings generated by SAM’s deployment configuration. Omitting one of those bindings disables the guided flow. SANDBOX_ENABLED continues to control separate administrative Sandbox runtime surfaces and is not required for guided login.

Variable Default Description
MAX_CONCURRENT_SETUP_SESSIONS 2 Maximum concurrent guided credential-setup sessions.
SETUP_SESSION_TTL_MS 900000 Guided session lifetime before automatic teardown.
SETUP_SESSION_CAPTURE_POLL_MS 3000 Interval for checking device-login and credential-capture state.
CODEX_DEVICE_AUTH_REQUEST_TIMEOUT_MS 30000 Timeout for each Codex app-server JSON-RPC request.
CLAUDE_SETUP_ENTER_DELAY_MS 1000 Delay before sending Enter as a separate stdin write after pasting Claude’s browser-displayed code.
CLAUDE_SETUP_EXCHANGE_TIMEOUT_MS 120000 Maximum wait for Claude’s CLI code exchange before a visible timeout.
CLAUDE_SETUP_REJECTION_SETTLE_MS 400 Wait for Claude CLI Ink redraws to settle before classifying an OAuth error.
CLAUDE_SETUP_VERIFICATION_POLL_MS 500 Interval for checking the sandbox handoff file for Claude’s browser-displayed code.
CLAUDE_SETUP_TTY_COLUMNS 512 PTY width for claude setup-token, reducing opaque-token wrapping.
CLAUDE_SETUP_OUTPUT_BUFFER_BYTES 32768 Maximum in-memory Claude PTY output retained for parsing.
CLAUDE_VERIFICATION_CODE_MAX_LENGTH 1024 Maximum accepted length of Claude’s browser-displayed code#state value.
CLAUDE_SETUP_ERROR_DETAIL_MAX_LENGTH 160 Maximum internal CLI error text used for classification; displayed diagnostics are allowlisted.
CLAUDE_OAUTH_TOKEN_MAX_LENGTH 8192 Maximum captured Claude OAuth token length.
SETUP_SESSION_SWEEP_MAX_CANDIDATES 50 Maximum expired sessions cleaned up by one scheduled sweep.
POOL_LEASE_BUFFER_MS 300000 Grace period after session TTL before a leaked capacity lease self-prunes.

The variables below tune the Instant (Cloudflare Container) runtime — how long a session stays awake, how long a wake may take, and how many snapshot restores are attempted before a session is failed. See Instant Sessions for what each of these means to a user.

Variable Default Description
CF_CONTAINER_ENABLED true Enables Cloudflare Container instant sessions for matching profiles and zero-config runtime selection. Set false to force cloud VM runtime.
CF_CONTAINER_SLEEP_AFTER 1h Normal inactivity window before an Instant container sleeps. Sleep remains recoverable through the runtime-neutral session snapshot.
CF_CONTAINER_ACTIVE_WORK_MAX_MS 7200000 Defensive maximum lifetime for an active-work keepalive lease.
CF_CONTAINER_KEEPALIVE_RENEW_INTERVAL_MS 300000 Interval used to renew the container activity timeout while prompt work is active.
CF_CONTAINER_WAKE_TIMEOUT_MS 120000 Maximum time for a sleeping container to launch, restore its snapshot, and accept the triggering request.
CF_CONTAINER_RECOVERY_MAX_ATTEMPTS 2 Maximum snapshot restore attempts before SAM reconciles the runtime, workspace, agent session, and active task to a visible terminal recovery failure.
INSTANT_STALE_CALLBACK_MARGIN_MS 60000 (60 sec) Freshness margin used to reject destructive (error/failed) callbacks arriving from a superseded Instant container generation after the runtime row was reconciled by a completed recovery.
CF_CONTAINER_CREATE_WORKSPACE_TIMEOUT_MS 120000 Budget for the synchronous instant-session create-workspace request, which includes the repository clone inside the container.
CF_CONTAINER_CLONE_FILTER blob:none Git partial-clone filter forwarded to instant containers as STANDALONE_CLONE_FILTER. Set off to force full clones.

CF_CONTAINER_RECOVERY_MAX_ATTEMPTS has a deployment-safety minimum of 2; smaller positive values resolve to 2.

Sleeping and reclaimed Instant and VM sessions are restored from a snapshot of the agent’s home directory and the repository work in progress. An ordinary sleep requires a complete snapshot before SAM tears down VM compute. When snapshots keep failing, a bounded fallback terminates the idle runtime while keeping its transcript and successful backups. If exact recovery cannot be verified, continuation uses a fresh workspace and the transcript (SAM could not save a complete snapshot). None of these limits are surfaced in the UI, so operators should set expectations deliberately — see What gets restored.

Variable Default Description
SESSION_SNAPSHOT_TTL_DAYS 7 Snapshot retention. A session sleeping longer than this cannot be fully restored.
SESSION_SNAPSHOT_TOTAL_BUDGET_BYTES 268435456 (256 MiB) Max combined size of the home + work-in-progress snapshot. The higher default favors bounded retained R2 state over keeping a VM alive when a typical agent harness has accumulated substantial durable state.
SESSION_SNAPSHOT_ENTRY_THRESHOLD_BYTES 268435456 (256 MiB) Largest single file the snapshot scanner will include. This matches the total budget so durable agent state databases are not skipped solely because they are larger than the former 50 MiB cap.
SESSION_SNAPSHOT_TRANSFER_IDLE_TIMEOUT_MS 30000 (30 sec) No-progress timeout for each snapshot upload or download.
SESSION_SNAPSHOT_UPLOAD_URL_TTL_SECONDS 900 (15 min) Lifetime of direct R2 upload URLs used so large snapshots do not traverse the Worker request-body boundary. Current agents bind exact length and SHA-256; busy legacy VM agents stream through a current same-user VM relay that independently authenticates both nodes and removes callback credentials before R2. When R2 S3 credentials are unavailable, SAM retains the Worker upload path.
SESSION_SNAPSHOT_REQUEST_TIMEOUT_MS 300000 (5 min) Budget for the vm-agent to accept the final checkpoint request. Durable completion is governed by progress reporting rather than this fixed wall clock.
SESSION_SNAPSHOT_PROGRESS_IDLE_TIMEOUT_MS 120000 (2 min) No-progress watchdog for an accepted final checkpoint. Current vm-agents periodically advance D1 progress while walking HOME or uploading artifacts; if progress stops, SAM records a degraded snapshot and that sleep attempt fails, counting against the sleep failure budget below.
SESSION_SNAPSHOT_POLL_INTERVAL_MS 1000 (1 sec) Interval used while the Worker waits for a VM agent’s asynchronous final checkpoint to commit in D1.
SESSION_SNAPSHOT_OPERATION_TIMEOUT 15m VM-agent checkpoint/restore deadline, using Go duration syntax. Before the first restore RPC, TaskRunner pins this duration plus SESSION_SNAPSHOT_REQUEST_TIMEOUT_MS as its retry window; retries and restarts cannot renew it.
SESSION_SNAPSHOT_PROGRESS_REPORT_INTERVAL 15s VM-agent throttle for best-effort progress callbacks during data-scaled snapshot work. This uses Go duration syntax and is passed to newly provisioned VMs and Instant containers.
SESSION_SNAPSHOT_PROGRESS_REPORT_TIMEOUT 5s VM-agent timeout for each best-effort snapshot progress callback. This uses Go duration syntax and is passed to newly provisioned VMs and Instant containers.
SESSION_SNAPSHOT_JSON_BODY_MAX_BYTES 262144 (256 KB) Maximum snapshot coordination request size accepted by the Worker.
SESSION_SNAPSHOT_R2_PREFIX session-snapshots Private object prefix. Session objects are deleted by the Worker from D1 lifecycle state, not by object age.
SESSION_SNAPSHOT_RECOVERY_MAX_ATTEMPTS 3 Replacement-VM wake attempts allowed in a burst. Once spent, further wakes are refused (recovery_attempts_exhausted) until SESSION_SNAPSHOT_RECOVERY_ATTEMPT_DECAY_MS has passed since the last failed attempt; the snapshot’s own expiry remains the hard limit.
SESSION_SNAPSHOT_RECOVERY_ATTEMPT_DECAY_MS 900000 (15 min) How long a spent wake-attempt burst stays spent before a new wake may be tried
SESSION_RECOVERY_LINEAGE_MAX_DEPTH 256 How many wake-to-wake links a wake follows back to the conversation’s first run to decide whether that run explicitly pinned its region. A wake without such a request only prefers the region it slept in.
SESSION_SLEEP_AFTER_MS 900000 (15 min) ProjectData-recorded idle interval before SAM automatically sleeps a VM session. Runtime heartbeats do not extend this clock. Completed and failed tasks queue sleep immediately. A still-active final prompt becomes eligible this interval after its last real work (VM re-reports do not count) or the task’s end, so working agents are not slept mid-turn. Ledger cleanup also uses it to protect the final response.
SESSION_SLEEP_SWEEP_BATCH_SIZE 10 Maximum due session sleep candidates selected and individually claimed by one scheduled sweep.
SESSION_SLEEP_SWEEP_WALL_BUDGET_MS 20000 (20 sec) Soft wall-clock budget for bounded D1/ProjectData eligibility and claim work. After a durable claim, final snapshot and teardown run through the scheduled event’s out-of-band lifetime. Remaining unclaimed rows stay due for the next sweep.
SESSION_SLEEP_RETRY_DELAY_MS 300000 (5 min) Retry delay after a fail-closed automatic sleep attempt.
SESSION_SLEEP_FAILURE_MAX_ATTEMPTS 3 Failed full snapshots before terminating the idle runtime through guarded cleanup. Retains transcript and successful backups even when exact Git/filesystem recovery cannot be verified.
SESSION_SLEEP_FAILURE_MAX_ELAPSED_MS 900000 (15 min) Elapsed budget after a failed snapshot before the same runtime-release fallback. Active work remains protected.
SESSION_SLEEP_MAX_ATTEMPTS 9 Legacy attempt ceiling retained for compatibility and diagnostic trigger classification. Exhaustion releases idle runtime rather than keeping compute running. Failed external stops/deletions keep retrying with backoff until confirmed.
FAILED_TASK_PRESERVATION_MAX_WAIT_MS 28800000 (8 hours) Longest a failed task’s runtime stays awake waiting for its preservation sleep, measured from the latest of the failure, an in-place wake and the start of the agent’s current turn. A turn that never ends defers that sleep without spending an attempt; past this wait the sweep tears the runtime down and says so in the chat (releaseStalledFailedTaskPreservation()).
SESSION_SLEEP_CLAIM_LEASE_MS 600000 (10 min) Time after which an interrupted automatic-sleep claim can be safely reclaimed.
HARNESS_BACKGROUND_WORK_LEASE_MS 300000 (5 min) Finite sleep-protection lease renewed by normalized harness background-work lifecycle signals. Expiry fails open to ordinary idle-sleep eligibility so a missing terminal signal cannot pin compute forever.
HARNESS_BACKGROUND_WORK_MAX_DURATION_MS 7200000 (2 hours) Absolute ceiling, measured from the last real session work (foreground work or harness lifecycle progress) rather than the last heartbeat, on how long background work may defer sleep. The sliding lease above is refreshed by periodic re-reports, so an adapter faithfully re-reporting a stale task set (for example an abandoned run_in_background dev server) would otherwise pin compute awake indefinitely.
ACP_ACTIVITY_ADMISSION_ENABLED true Enables Worker-side admission control for ACP activity callbacks. Redundant intermediate state is coalesced to protect ProjectData load; terminal/error and final idle transitions still bypass coalescing.
ACP_ACTIVITY_COALESCE_WINDOW_MS 2000 (2 sec) Minimum interval between redundant intermediate ProjectData activity writes, and the first retry delay for a coalesced report whose flush hit a retryable ProjectData failure (including a CPU-limit reset or lost connection); each further retry doubles the delay, capped at ACP_ACTIVITY_COALESCE_TTL_MS. Activity transitions, new prompt epochs, and terminal/error reports bypass this window.
ACP_ACTIVITY_COALESCE_TTL_MS 60000 (1 min) Maximum lifetime for a pending coalesced activity report before it is evicted and left to probe-backed session-activity reconciliation.
ACP_ACTIVITY_COALESCE_MAX_PENDING 512 Maximum pending coalesced activity reports retained by one Worker isolate. Capacity evictions are logged as activity telemetry rather than silently dropped.
ACP_ACTIVITY_BINDING_CACHE_TTL_MS 30000 (30 sec) Short-lived cache for already-authorized ACP session bindings used to avoid ProjectData reads during callback storms. Callback JWT authorization and D1 node/workspace liveness checks still run per request.
ACP_ACTIVITY_BINDING_CACHE_MAX_ENTRIES 2048 Maximum cached ACP activity bindings retained by one Worker isolate.
SESSION_SNAPSHOT_RECOVERY_CLAIM_LEASE_MS 600000 (10 min) Time after which an interrupted replacement-runtime wake claim can be reconciled or reclaimed.
SESSION_LIFECYCLE_ERROR_MAX_LENGTH 2048 Maximum session lifecycle and agent activity failure diagnostic detail stored in lifecycle records.
SESSION_SNAPSHOT_PURGE_ENABLED true Enables bounded expiry cleanup: terminalizes the sleeping chat, deletes its R2 objects, then removes D1 metadata. Chats slept by the fallback expire on the same seven-day schedule.
SESSION_SNAPSHOT_PURGE_BATCH_SIZE 250 Maximum expired snapshot rows deleted per daily purge.
SESSION_SLEEP_IN_FLIGHT_MAX_AGE_MS 1800000 (30 minutes) Absolute ceiling for preserving in-flight sleep lifecycle rows (scheduled, preparing, stopping, retry-eligible failed) from terminal session destroyers. Rows older than this are treated as wedged and must escape through bounded repair by runSessionSleepLifecycleRepair() in apps/api/src/scheduled/session-sleep-lifecycle-repair.ts instead of deferring forever.
SESSION_SLEEP_IN_FLIGHT_REPAIR_BATCH_SIZE 25 Maximum stale post-capture in-flight sleep rows repaired per scheduled sweep by runSessionSleepLifecycleRepair() in apps/api/src/scheduled/session-sleep-lifecycle-repair.ts. The repair only completes restorable, unexpired preparing/stopping rows as sleeping; it does not wake or replay work. Values above 100 are capped.
TERMINAL_SESSION_RECONCILE_PROJECT_BATCH_SIZE 25 Maximum projects inspected for stale active ProjectData session ledgers per scheduled sweep. Values above 200 are capped.
TERMINAL_SESSION_RECONCILE_BATCH_SIZE 25 Maximum active ProjectData chat_sessions candidates reconciled per project per scheduled sweep. Values above 200 are capped.
TERMINAL_SESSION_SUMMARY_RECONCILE_BATCH_SIZE 25 Maximum active D1 session_summaries candidates reconciled globally per scheduled sweep. Values above 200 are capped.
TERMINAL_SESSION_RECONCILE_DEFER_MS 3600000 (1 hour) Retry delay for live-head, snapshot-protected, or temporarily ineligible terminal-session ledger candidates. Values above 86400000 (24 hours) are capped.
TERMINAL_NODE_LIFECYCLE_REPAIR_BATCH_SIZE 25 Maximum active-looking workspace rows on terminal/deleted nodes repaired per scheduled sweep by runTerminalNodeLifecycleRepair() in apps/api/src/scheduled/terminal-node-lifecycle-repair.ts. The repair marks non-sleeping workspaces stopped, closes non-terminal agent sessions and open compute usage, and routes ProjectData cleanup through the sleeping-snapshot guard. Values above 100 are capped.
TERMINAL_NODE_LIFECYCLE_REPAIR_WALL_BUDGET_MS 10000 (10 seconds) Wall-clock budget for runTerminalNodeLifecycleRepair() in apps/api/src/scheduled/terminal-node-lifecycle-repair.ts inside the scheduled sweep. Values above 30000 are capped so this repair cannot monopolize the cron event.
REQUIRE_APPROVAL (unset: approval on) Signup approval gate: on unless false; any other value, including unset, keeps it on (envRequiresApproval, apps/api/src/services/signup-approval.ts). The Admin → Users switch overrides it. Without BOOTSTRAP_OWNER_EMAIL, first-user promotion is independent of this flag. Installer-bound deployments require the provider-verified owner — see First Login & Admin Access. On pending accounts, see Signup approval.
CAPACITY_POOL_BACKFILL_SCOPE_BATCH_SIZE 25 Maximum user scopes and maximum project scopes reconciled by one unscoped capacity-pool backfill pass. Values above 200 are capped; rerun the backfill to continue.
CAPACITY_POOL_SCHEDULED_RECONCILIATION_INTERVAL_MS 86400000 (24 hours) Minimum interval between scheduled capacity-pool reconciliation runs. Set to 0 to let every operational cron sweep reconcile; explicit UI/API reconcile requests are not throttled by this setting.
CAPACITY_POOL_LEGACY_WORKLOAD_MAPPING_JSON built-in slices Environment fallback for the versioned legacy small/medium/large to workload requirements adapter. Persisted platform_settings.capacityPools.legacyWorkloadMapping.v1 wins when present. Values are workload slices, not old whole-VM shapes.
CAPACITY_POOL_PLATFORM_DEFAULTS_JSON built-in defaults Environment fallback for platform resource requirement defaults used when no task/trigger/skill/profile/project/user layer sets a field. Persisted platform_settings.capacityPools.platformDefaults.v1 wins when present. Values are validated by the shared ResourceRequirements validator and must provide every field.
CAPACITY_POOL_SELECTION_SETTINGS_JSON built-in scoring weights Environment fallback for default capacity-pool selection weights and ranking rollout. Persisted platform_settings.capacityPools.selectionSettings.v1 wins when present. Candidate priority remains explicit pool policy; price comparisons are normalized by unit and currency, with unknown price sorted after known comparable prices.
ORIGIN_CA_CERT_VALIDITY_DAYS 7 Validity for per-node Cloudflare Origin CA certificates issued from node-generated CSRs. Must be one of Cloudflare’s supported values: 7, 30, 90, 365, 730, 1095, or 5475.

The rolloutCohortPercent field in capacity-pool selection settings accepts 0–100 (default 100). resolvePlacementRollout in packages/scheduler-core/src/placement-rollout.ts assigns stable user/pool cohorts. Enabled cohorts use the pool’s configured ranking; other cohorts use native balanced ranking while the reuse selector records which host the configured strategy would select and why the selections differ. The same eligible host set feeds both comparisons. Pool precedence, membership, credential generation, workload role, aggregate reservations, and paid allocation fences remain enforced at every percentage. Reducing rollout changes ranking; it never restores legacy size labels as allocation authority. Settings and plan columns remain additive, and readers accept plans without rollout diagnostics.

For the user-facing explanation of what these settings control — pool scopes and precedence, allowed offerings, strategies, exhaustion policies, and resource requirements — see the Compute Pools guide.

Deploy the normal additive migrations before starting the updated Worker. Existing tasks, workspaces, credentials, and recorded hardware remain in place. Background reconciliation creates missing default pools from existing credentials and resumes in bounded batches; opening the settings page is not required. Larger installations may need several scheduled passes before every scope is ready.

In project Infrastructure settings, inspect the effective default pool before starting new work. A project default takes precedence over a personal default, which takes precedence over installation capacity. These states need different responses:

Pool state What to do
Migration pending Allow reconciliation to finish; if it persists, check scheduled reconciliation errors and the affected credential.
Configured empty Add a machine from Available machines, or switch an account back on. Only Instant sessions run in an empty pool.
Source disabled Re-enable or replace the pool’s credential source.
Catalog unavailable Check provider access and retry after inventory refresh. A failed refresh preserves the last valid inventory.
Configured ready Start a small test workload and check its requested resources and provider-native hardware in the node details.

An administrator can verify completion in D1 by inspecting capacity_pools: migration_state must be complete for the affected pool. The durable user and project backfill cursors are stored in platform_settings under capacityPools.backfill.userCursor.v1 and capacityPools.backfill.projectCursor.v1. Their presence indicates resumable progress, not an error. Do not delete pools or reset cursors to resolve an unavailable credential.

Existing nodes without verified pool and provider identity may finish their current work but are not automatically treated as eligible pool capacity. New work must pass the current pool, credential, and resource checks. Previously recorded hardware remains visible even if an offering is later removed. Old browser, API, CLI, and MCP size fields remain accepted as compatibility inputs; new resource fields take precedence at the same configuration layer. Saved reservations survive retry rather than adopting changed defaults.

For a ranking rollback, reduce rolloutCohortPercent in the effective selection settings. This uses balanced ranking for the excluded cohort while retaining pool authorization and capacity checks. It does not roll back migrations, revive removed offerings, or permit reuse of unverified nodes. Keep the additive schema and saved plans; do not drop columns or recreate tables as a rollback step.

Activity coalescing and binding caches are per Worker isolate, so burst reduction scales with the number of active isolates for the same session. Delayed flushes carry their original observed event time, and ProjectData rejects stale writes so a delayed intermediate report cannot overwrite a newer idle/error state from another isolate.

Browser Library uploads and replacements accept one file of up to 50 MiB by default. Their effective file limit is the smaller of LIBRARY_UPLOAD_MAX_BYTES and library.multipartFileMaxBytes in Admin → Settings. The browser limit cannot exceed 50 MiB, including when the legacy environment override is higher: whole-file AES-GCM retains plaintext and ciphertext concurrently. Existing encrypted objects, metadata and download compatibility are unchanged.

Runtime setting Default Purpose
library.multipartFileMaxBytes 52428800 (50 MiB) Browser file ceiling; may be lowered, maximum 50 MiB.
library.multipartOverheadMaxBytes 65536 (64 KiB) Additional wire bytes above the file ceiling, and aggregate metadata bytes.
library.multipartMaxParts 16 Parts per request, including ignored fields.
library.multipartMaxHeaderBytes 8192 Header bytes per part.
library.multipartReadTimeoutMs 120000 Total ingress and parsing deadline, in milliseconds.

The 120-second ingress budget permits a full 50 MiB file at about 427 KiB/s; metadata consumes a small additional portion. Parsing uses 64 KiB allocation chunks (at most 802 buffers at the default wire limit) and releases them before encryption. Browser writes, HTTP downloads/previews, agent transfers and diagnostic-package capture share a 50 MiB memory budget per Worker isolate (acquireLibraryMemory() in apps/api/src/services/library-memory.ts). A browser upload reserves its declared Content-Length, which is then enforced while streaming; a download or preview reserves the stored file size and refuses (409) a stored object larger than that reservation. Every reservation adds 256 KiB for fixed buffers, so at most about 200 transfers fit. Agent transfers, diagnostic capture and uploads without a declared length reserve the whole budget. So several small uploads or previews run together, while a maximum-size file runs alone. A transfer that does not fit receives 429 (or the MCP retry error) without queuing file buffers. The reservation follows the file through encryption/storage or its actual consumer. HTTP reads copy at most 64 KiB per response pull and keep their reservation until consumption, cancellation or the egress deadline. Decrypted plaintext and ciphertext are released after their consumers finish. A load timeout keeps the reservation until the underlying load settles, so late work cannot overlap a new transfer.

LIBRARY_DOWNLOAD_TIMEOUT_MS (default 60000) bounds loading and HTTP egress separately; a full 50 MiB response needs about 854 KiB/s to meet the egress deadline. Awaited agent transfers use their existing VM transfer deadline and retain admission through request-body termination and exposed transport settlement. An opaque container RPC may retain bounded chunk copies after its existing timeout; it never receives a view of the whole plaintext. Multipart settings apply to browser writes; existing agent file-size limits remain in place. The canonical ownership implementation is apps/api/src/services/library-memory.ts; multipart parsing is in apps/api/src/routes/library-upload-request.ts.

Variable Default Description
LIBRARY_PROJECT_DELETE_CLEANUP_BATCH_SIZE 1000 Maximum project-owned library objects listed and deleted per R2 page after project deletion. Values above R2’s 1,000-object page maximum are capped.

Deployment release and compose artifact retention

Section titled “Deployment release and compose artifact retention”

The scheduled Worker first reconciles provably stale non-terminal compose releases, then prunes terminal deployment releases outside the protected window (apps/api/src/scheduled/d1-retention.ts:runDeploymentReleaseRetention()). Terminal retention always retains the newest releases per environment and the version reported in deployment_environments.observed_applied_seq. The stale reconciler only marks a created/applying compose-artifact release failed when D1 shows old release status activity, stable authenticated deployment-node observed state, no recent release fetch/apply events, a valid manifest, and a release version that is not the observed applied version. Unknown statuses, malformed manifests, missing observed state, active applying observations, and recent release events fail closed. Compose artifact cleanup then re-derives references from the remaining manifests (packages/app-deployment/src/scheduled/compose-image-artifact-cleanup.ts:runComposeImageArtifactCleanup()).

Variable Default Description
DEPLOYMENT_RELEASE_RETENTION_ENABLED true Enables bounded terminal release pruning.
DEPLOYMENT_RELEASE_RETENTION_COUNT 3 Newest releases protected per environment, in addition to observed-applied and non-terminal releases.
DEPLOYMENT_RELEASE_RETENTION_BATCH_SIZE 250 Maximum release rows deleted per run.
DEPLOYMENT_RELEASE_RETENTION_INTERVAL_HOURS 24 Minimum interval between release retention runs.
DEPLOYMENT_RELEASE_RETENTION_LAST_RUN_KV_KEY cleanup:deployment-releases:last-run KV interval marker.
DEPLOYMENT_RELEASE_RECONCILIATION_ENABLED true Enables stale non-terminal compose release reconciliation before terminal retention.
DEPLOYMENT_RELEASE_RECONCILIATION_BATCH_SIZE 50 Maximum stale non-terminal releases marked failed per retention run.
DEPLOYMENT_RELEASE_RECONCILIATION_STALE_HOURS 168 Minimum release status age before reconciliation can terminalize a stale non-terminal release.
DEPLOYMENT_RELEASE_RECONCILIATION_ACTIVITY_GRACE_HOURS 6 Recent release-event window that protects active fetch/apply work from reconciliation.
COMPOSE_IMAGE_ARTIFACT_CLEANUP_BATCH_SIZE 250 Maximum abandoned compose archives deleted per daily run.

Pulumi updates the existing assets bucket lifecycle resource on upgrades and creates the same rules on clean installs (infra/resources/storage.ts:r2BucketLifecycle). temp-uploads/ is transient browser-upload staging; tts/ is a regenerable audio cache. Durable library/ content is deleted only with its project, and reachable compose-image-artifacts/ are governed by deployment release retention. Archived ProjectData tool payloads stay private and retrievable through Worker/MCP access paths while message rows retain their text in the Durable Object, so these durable prefixes do not have age-only lifecycle rules.

Pulumi option Default Object prefix Description
sessionSnapshotTtlDays 7 session-snapshots/ Worker-owned retention from actual sleep; no age-only R2 lifecycle
diagnosticIncidentTtlDays 7 configured private Private diagnostic artifact retention
tempUploadTtlDays 1 temp-uploads/ Abandoned presigned browser upload retention
ttsTtlDays 30 tts/ Regenerable TTS audio-cache retention
n/a n/a project-data/tool-payloads/ Private ProjectData archive; Worker-owned retention only
n/a n/a resource-history/ Private workspace resource chunks; Worker-owned retention only

All TTL options must be positive integers. Set overrides with pulumi config set against the target stack before running its deployment workflow.

Google login and Google infrastructure authorization are independent credential families:

Variables Purpose Runtime precedence Redirect URIs
GOOGLE_LOGIN_CLIENT_ID, GOOGLE_LOGIN_CLIENT_SECRET BetterAuth user login /setup or superadmin runtime D1 → Worker env → unset /api/auth/callback/google
GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET Keyless GCP/WIF setup only Superadmin runtime D1 → Worker env → unset /auth/google/callback and /api/deployment/gcp/callback

Configuring one family never enables or modifies the other. Users who choose service-account JSON do not need either infrastructure OAuth variable.

Variable Default Description
GCP_SERVICE_ACCOUNT_JSON_MAX_BYTES 65536 Maximum UTF-8 byte size accepted by PUT /api/gcp/service-account
GCP_DEFAULT_ZONE us-central1-a Default Compute zone
GCP_IMAGE_FAMILY ubuntu-2404-lts-amd64 Compute image family. Native image overrides may be a family name or a Compute Engine image/family reference.
GCP_IMAGE_PROJECT ubuntu-os-cloud Compute image project
GCP_TOKEN_CACHE_TTL_SECONDS 3300 Maximum derivative access-token cache TTL; actual TTL is capped by Google’s returned expiry
GCP_IDENTITY_TOKEN_EXPIRY_SECONDS 600 SAM identity-token lifetime for WIF
GCP_OPERATION_POLL_TIMEOUT_MS 300000 Maximum wait for GCP asynchronous operations
GCP_API_TIMEOUT_MS 30000 GCP OAuth, IAM, and Compute request timeout
GCP_STS_SCOPE https://www.googleapis.com/auth/cloud-platform WIF STS exchange scope
GCP_SA_IMPERSONATION_SCOPES https://www.googleapis.com/auth/compute Comma-separated scopes for WIF service-account impersonation
GCP_SA_TOKEN_LIFETIME_SECONDS 3600 WIF impersonated access-token lifetime
GCP_STS_TOKEN_URL https://sts.googleapis.com/v1/token WIF STS endpoint override for controlled environments
GCP_IAM_CREDENTIALS_BASE_URL Google IAM Credentials API WIF impersonation base URL override

The service-account JWT bearer flow always uses https://oauth2.googleapis.com/token; it has no endpoint override, and uploaded token_uri values are ignored. Source credentials are encrypted in D1. Only derivative short-lived tokens are cached.

Variable Default Description
TASK_TITLE_MODEL @cf/google/gemma-4-26b-a4b-it Workers AI model for title generation
TASK_TITLE_MAX_LENGTH 100 Max characters in generated title
TASK_TITLE_TIMEOUT_MS 5000 Timeout before falling back to truncation
TASK_TITLE_GENERATION_ENABLED true Set false to disable AI generation
TASK_TITLE_SHORT_MESSAGE_THRESHOLD 100 Messages at or below this length bypass AI
TASK_TITLE_MAX_RETRIES 2 Max retry attempts on failure
TASK_TITLE_RETRY_DELAY_MS 1000 Base delay between retries (exponential backoff)
TASK_TITLE_RETRY_MAX_DELAY_MS 4000 Max delay cap for backoff
TASK_TITLE_ERROR_DIAGNOSTIC_MAX_LENGTH 512 Max sanitized provider-error diagnostic length
Variable Default Description
BRANCH_NAME_PREFIX sam/ Prefix for generated task output branches. Include the trailing separator (for example agent/).

Task workspaces are checked out on the generated output branch. Commits, pushes and pull requests are agent-directed; SAM does not publish changes automatically. See Where the work lands.

Variable Default Description
DEBUG_AGENT_MODEL @cf/deepseek-ai/deepseek-v4.1-flash-1017 Workers AI model for superadmin deployment diagnosis
DEBUG_AGENT_MAX_TURNS 6 Maximum model/tool turns per diagnosis
DEBUG_AGENT_RUN_TOKEN_LIMIT 96000 Combined token ceiling per diagnosis
DEBUG_AGENT_MODEL_OUTPUT_TOKENS 4096 Maximum output tokens requested per model turn
DEBUG_AGENT_DAILY_TOKEN_LIMIT 480000 Daily diagnosis token budget, counted per feature
DEBUG_AGENT_TOOL_RESULT_LIMIT 50 Maximum rows returned by a diagnosis tool
DEBUG_AGENT_TOOL_RESULT_BYTES 32768 Maximum serialized bytes per model-visible tool result
DEBUG_AGENT_MAX_WINDOW_HOURS 24 Maximum selectable diagnosis window
DEBUG_AGENT_TIMEOUT_MS 120000 Timeout for each diagnosis model request
DEBUG_AGENT_HARD_DEADLINE_MS 900000 Hard deadline for an active diagnosis
DEBUG_AGENT_STALE_HEARTBEAT_MS 120000 Orphan reconciler heartbeat threshold
DEBUG_AGENT_RETRY_BASE_DELAY_MS 2000 Initial transient step retry delay
DEBUG_AGENT_RETRY_MAX_DELAY_MS 60000 Maximum transient step retry delay
DEBUG_AGENT_STEP_MAX_RETRIES 3 Maximum classified transient retries per step

The /admin/errors view remains superadmin-only and may show local user IDs, IP addresses, and user-agent strings. Before any tool result enters model context, SAM recursively removes those fields plus credential-shaped values such as API tokens, JWTs, authorization headers, private keys, and long secret-like strings. Cloudflare credentials stay server-side and are never included in model messages or saved diagnosis text.

VM failures use a durable local SQLite outbox and a private R2 artifact. Generated deployments set the R2 prefix and object lifecycle from Pulumi; the remaining Worker bounds can be overridden through deployment environment variables.

Worker variable Default Description
MAX_VM_AGENT_ERROR_BODY_BYTES 32768 Maximum VM error batch body
MAX_VM_AGENT_ERROR_BATCH_SIZE 10 Maximum errors per VM batch
MAX_VM_AGENT_ERROR_SOURCE_LENGTH 256 Maximum redacted VM error source length
OBSERVABILITY_ERROR_MESSAGE_MAX_LENGTH 2048 Maximum persisted observability error message length
OBSERVABILITY_ERROR_STACK_MAX_LENGTH 4096 Maximum persisted observability stack length
OBSERVABILITY_ERROR_USER_AGENT_MAX_LENGTH 512 Maximum persisted observability user-agent length
VM_INCIDENT_R2_PREFIX diagnostic-incidents Private object prefix; generated from the Pulumi output
VM_INCIDENT_ARTIFACT_MAX_BYTES 2097152 Maximum compressed artifact size
VM_INCIDENT_REGISTRATION_MAX_BYTES 262144 Maximum registration JSON body
VM_INCIDENT_MANIFEST_MAX_BYTES 131072 Maximum redacted manifest
VM_INCIDENT_PREVIEW_MAX_BYTES 131072 Maximum redacted model/UI preview
VM_INCIDENT_MAX_ARTIFACTS_PER_NODE 50 Active artifact quota per node
VM_INCIDENT_MAX_BYTES_PER_NODE 104857600 Active expected-byte quota per node
VM_INCIDENT_RETENTION_DAYS 7 Private object and active metadata retention
VM_INCIDENT_METADATA_RETENTION_DAYS 30 Expired metadata retention after object deletion
VM_INCIDENT_PENDING_TIMEOUT_MINUTES 30 Incomplete-upload timeout and upload-lease duration
VM_INCIDENT_RECONCILE_BATCH_SIZE 50 Maximum artifacts/incidents repaired per scheduled pass (minimum: 6)

The VM Agent process accepts the corresponding ERROR_REPORT_* overrides for flush interval, batch size/bytes, outbox size and path, SQLite busy timeout, HTTP timeout, retry bounds, attempts, spool path/bytes, artifact bytes, retention, collector timeout/count/concurrency, document bytes, recursive value depth/items, string bytes, structured event limit, response-read bytes, and persisted-error bytes. Generated deployments pass these validated values through cloud-init into the VM Agent systemd service, so overrides apply to newly provisioned nodes. Defaults are listed in apps/api/.env.example; the common defaults are a 32 KiB error batch, 1,000-row outbox, 2 MiB artifact, 20 MiB spool, and 24-hour local retention.

Pulumi options diagnosticIncidentPrefix (default diagnostic-incidents) and diagnosticIncidentTtlDays (default 7, any positive integer) configure the private prefix and an independent R2 lifecycle rule. They do not require a separate bucket or manually managed Worker variable. The prefix cannot begin with the application-owned namespaces agents, cli, compose-image-artifacts, library, resource-history, session-snapshots, temp-uploads, or tts, because the lifecycle would otherwise expire unrelated objects.

Variable Default Description
PLATFORM_FEEDBACK_PROJECT_ID unset Bootstrap/environment fallback for the project that receives user issue reports and automated triage draft Ideas. The Admin → Integrations runtime setting is preferred and overrides it.
PLATFORM_FEEDBACK_TRIAGE_WINDOW_MINUTES 60 Lookback window for grouping recent platform errors
PLATFORM_FEEDBACK_TRIAGE_ERROR_LIMIT 100 Maximum platform error rows scanned per triage sweep
PLATFORM_FEEDBACK_TRIAGE_GROUP_LIMIT 5 Maximum grouped feedback candidates processed per triage sweep
PLATFORM_FEEDBACK_TRIAGE_EVIDENCE_LIMIT 10 Maximum bounded error references retained per grouped feedback record
PLATFORM_FEEDBACK_TRIAGE_CLAIM_TTL_MS 600000 Claim lease duration before a later sweep can reclaim the group
PLATFORM_FEEDBACK_TRIAGE_MAX_FAILURES 3 Maximum failed attempts before a group is rejected from auto-triage
PLATFORM_FEEDBACK_TRIAGE_FAILURE_REASON_MAX_LENGTH 240 Maximum characters stored or returned for sanitized failure reasons
PLATFORM_FEEDBACK_TRIAGE_BUDGET_DEFER_MS 86400000 Retry delay for per-run budget deferrals
PLATFORM_FEEDBACK_INCIDENT_DISPATCH_LEASE_TTL_MS 7200000 Dispatch lease before a failed incident trigger handoff can be reclaimed
PLATFORM_FEEDBACK_INCIDENT_AGENT_LEASE_TTL_MS 3600000 Agent claim lease before another task can reclaim a private incident
PLATFORM_FEEDBACK_INCIDENT_MAX_DISPATCH_ATTEMPTS 3 Failed or unfinished agent triage attempts before automatic retries stop
PLATFORM_FEEDBACK_INCIDENT_REOPEN_COOLDOWN_MS 1800000 Minimum elapsed time after terminal resolution/expiry before a newer occurrence can reopen the same signature; set 0 to disable cooldown-only suppression
PLATFORM_FEEDBACK_INCIDENT_RECLAIM_LIMIT 25 Maximum expired leases processed per dispatch or claim reclaim pass
PLATFORM_FEEDBACK_INCIDENT_MAX_AGE_MS 2592000000 Maximum active incident age before expiry
PLATFORM_FEEDBACK_INCIDENT_STALE_SINGLETON_MAX_AGE_MS 259200000 Maximum age for one-off pending incidents with no recurrence
PLATFORM_FEEDBACK_INCIDENT_STALE_SINGLETON_EXPIRY_BATCH_SIZE 25 Maximum stale singleton incidents expired per sweep
PLATFORM_FEEDBACK_INCIDENT_MIN_DISPATCH_SEVERITY error Minimum severity admitted to automatic VM incident dispatch
PLATFORM_FEEDBACK_INCIDENT_MIN_DISPATCH_BATCH_SIZE 2 Dispatch immediately once this many eligible incidents are ready
PLATFORM_FEEDBACK_INCIDENT_MIN_PENDING_AGE_MS 1800000 Dispatch a smaller eligible batch after this pending age
PLATFORM_FEEDBACK_INCIDENT_DISPATCH_RATE_WINDOW_MS 3600000 Rate-cap window for each incident trigger
PLATFORM_FEEDBACK_INCIDENT_MAX_DISPATCHES_PER_TRIGGER_WINDOW 1 Maximum dispatches one incident trigger may submit per rate window
PLATFORM_FEEDBACK_INCIDENT_AUTO_TRIGGER_ENABLED true Auto-create one private incident trigger when pending incidents exist and no incident trigger exists
PLATFORM_FEEDBACK_INCIDENT_TRIGGER_LIMIT 5 Maximum active incident triggers inspected per sweep
PLATFORM_FEEDBACK_INCIDENT_TRIGGER_NAME built-in Name for the auto-created private incident trigger
PLATFORM_FEEDBACK_INCIDENT_TRIGGER_TEMPLATE built-in Prompt template for the auto-created private incident trigger
PLATFORM_FEEDBACK_INCIDENT_SUMMARY_LIMIT 10 Maximum grouped incidents included in one incident-trigger backlog summary
PLATFORM_FEEDBACK_INCIDENT_EVIDENCE_REF_LIMIT 10 Maximum bounded evidence references retained per incident
PLATFORM_FEEDBACK_INCIDENT_EVIDENCE_MAX_BYTES 32768 Maximum serialized evidence bytes retained per incident
PLATFORM_FEEDBACK_INCIDENT_RESOLUTION_NOTE_MAX_LENGTH 2000 Maximum private incident resolution-note length

Resolved and expired incident signatures reopen only when a newer occurrence arrives after PLATFORM_FEEDBACK_INCIDENT_REOPEN_COOLDOWN_MS; older lookback-window occurrences remain closed. VM-agent incidents resolved with fix evidence also wait for occurrences from nodes reporting the current VM_AGENT_REQUIRED_VERSION, because Worker deploys do not update already-running VM binaries. Dispatch attempts are consumed when an agent reports failure, an unfinished claim expires after its owner stops working, or a dispatched agent sleeps or completes without classifying the incident. After the configured attempt limit, automatic retries stop and the incident records that triage exhausted its budget without resolution. Platform-side handoff/session failures still release the dispatch without consuming an agent attempt. Active investigators retain their claims with bounded renewal; sleeping tasks are left untouched when incident ownership is released. The original maximum incident age remains the upper bound.

Automated triage and superadmin-initiated diagnosis read the same DEBUG_AGENT_DAILY_TOKEN_LIMIT value but count against independent per-feature counters, so worst-case daily spend across both is twice this value. Automated triage treats budget exhaustion as a retryable deferral: daily exhaustion retries after the next UTC day starts, and per-run exhaustion uses PLATFORM_FEEDBACK_TRIAGE_BUDGET_DEFER_MS. Incident trigger agents run from the private grouped backlog and dispatch one agent for a bounded backlog summary, not one agent per occurrence. Automatic incident dispatch ignores pending signatures already linked to open tracked work and warning-only signatures below the configured severity floor, then applies the batch/age gate and per-trigger rate cap before reserving incidents.

The in-app Report an Issue flow files user-submitted reports as draft Ideas in the effective private Operations project (the feedback.projectId platform setting). Configure it from Admin → Integrations when possible; PLATFORM_FEEDBACK_PROJECT_ID remains the environment fallback when no runtime setting is saved. The feature is hidden entirely — both UI entry points disappear and GET /api/report-issue/config returns enabled: false — when no effective project exists or the effective project does not exist in this deployment’s database.

Variable Default Description
REPORT_ISSUE_TITLE_MAX_LENGTH 200 Truncation ceiling for the stored title (lowers only — see below)
REPORT_ISSUE_DESCRIPTION_MAX_LENGTH 5000 Truncation ceiling for the stored description (lowers only)
REPORT_ISSUE_CONTENT_MAX_LENGTH 65536 Maximum stored Idea body, including attached technical references
RATE_LIMIT_REPORT_ISSUE_POST 20 Report submissions allowed per clock hour, per authenticated user

The two length variables apply after request validation, so they can only lower the stored length — the request schema and the report dialog both enforce the built-in 200 / 5,000 caps regardless of what you set here.

See Reporting Issues for the user-facing flow and the untrusted-evidence Idea format.

SAM loads OpenCode Zen and OpenCode Go model choices through the authenticated model-catalog API, backed by Models.dev and cached in KV. If the upstream catalog or cache is unavailable, SAM falls back to the static catalog shipped with the app.

Variable Default Description
MODEL_CATALOG_SOURCE_URL https://models.dev/api.json Source URL for the dynamic model catalog
MODEL_CATALOG_CACHE_TTL_SECONDS 3600 KV cache TTL for normalized dynamic model catalog payloads
MODEL_CATALOG_FETCH_TIMEOUT_MS 5000 Timeout for the upstream catalog fetch before static fallback

The dashboard’s Active Tasks list (GET /api/dashboard/active-tasks, apps/api/src/routes/dashboard.ts) reads up to DASHBOARD_ACTIVE_TASK_CANDIDATE_LIMIT of the user’s most recently started active tasks, ranks them by newest message (or by when they started, if they have none yet), and only then applies the display limit. The open dashboard refreshes the list every 15 seconds while its tab is visible.

Variable Default Description
DASHBOARD_ACTIVE_TASK_LIMIT 6 Most recently active tasks the list shows
DASHBOARD_ACTIVE_TASK_CANDIDATE_LIMIT 100 Active tasks read and ranked before the display limit applies (also the maximum; each project’s candidates share one SQL statement’s binds)
DASHBOARD_INACTIVE_THRESHOLD_MS 900000 (15 min) A working task whose last message is newer than this shows Active; older shows Working

Conservative Cache-Control budgets for stable and semi-stable API GETs, letting the browser serve a cached body instantly while it revalidates in the background. All values are seconds and are clamped to [0, 86400]; an unparseable or negative value falls back to the default rather than caching for longer.

Authenticated responses are always emitted as private with Vary: Cookie, so neither a shared cache nor a second account in the same browser can be served another user’s body. Only the unauthenticated /api/config/* endpoints are marked public. Endpoints returning real-time data (chat messages, task status, session and workspace state) are deliberately excluded.

Variable Default Description
PUBLIC_CONFIG_CACHE_MAX_AGE_SECONDS 60 max-age for the unauthenticated /api/config/* endpoints
PUBLIC_CONFIG_CACHE_SWR_SECONDS 300 stale-while-revalidate for /api/config/*
MODEL_CATALOG_CACHE_MAX_AGE_SECONDS 60 max-age for GET /api/model-catalog/:agentType
MODEL_CATALOG_CACHE_SWR_SECONDS 300 stale-while-revalidate for the model catalog response
PROJECT_REFERENCE_CACHE_MAX_AGE_SECONDS 0 max-age for project agent-profile and skill lists (0 = always revalidate)
PROJECT_REFERENCE_CACHE_SWR_SECONDS 30 stale-while-revalidate for project agent-profile and skill lists

Direct node allocation and workspace creation use isolated NodeLifecycle Durable Object instances. These optional Worker runtime overrides accept positive integers; invalid or unset values use the defaults.

Variable Default Description
NODE_PROVISIONING_REQUEST_TIMEOUT_MS 5000 (5 s) Per-request budget for Cloudflare calls during allocation/reconciliation, also used for background readiness and workspace dispatch. The attempt’s cancellation budget is the admin setting operations.nodeProvisioningAttemptDeadlineMs (default 60 s, never below this value). It cuts only the steps before a provider create starts and the node DNS record; a started create, the publish of its result, and the later readiness and workspace dispatch are not bounded by it, so an attempt can run longer than 60 s.
NODE_PROVISIONING_RETRY_INTERVAL_MS 30000 (30 s) Delay between durable provisioning attempts.
NODE_PROVISIONING_MAX_AGE_MS 900000 (15 min) Maximum provisioning intent age before retries stop.
NODE_PROVISIONING_MAX_ATTEMPTS 30 Maximum provisioning attempts before retries stop.

Reaching either the age or attempt limit stops allocation retries. Diagnostic publication then uses a separate retry budget with the same interval and attempt limit; the age limit applies only to allocation and reconciliation. The unresolved intent is retained for inspection. Empty provider inventory does not authorize another provider create request or establish cleanup proof.

Variable Default Description
NODE_WARM_TIMEOUT_MS 1800000 (30 min) Time a managed workspace node stays warm after its last active workspace leaves
MAX_AUTO_NODE_LIFETIME_MS 14400000 (4 hr) Max lifetime for an auto-provisioned node holding no active workspaces
NODE_WARM_GRACE_PERIOD_MS 2100000 (35 min) Cron sweep grace period (must be > warm timeout)
NODE_LIFECYCLE_ALARM_RETRY_MS 60000 (1 min) Retry delay for DO alarm failures
NODE_LIFECYCLE_MAX_DESTROYING_AGE_MS 86400000 (24 hr) Backstop after which a destroying-state alarm self-cleans; infrastructure teardown remains owned by cron/provider reconciliation
DEFAULT_TASK_AGENT_TYPE opencode Default agent for autonomous idea execution

The cleanup sweep measures idleness from a node’s last workspace activity (COALESCE(MAX(workspaces.updated_at), nodes.created_at)), never from nodes.updated_at — heartbeats rewrite updated_at on every beat, so it tracks liveness rather than idleness. The eligibility check is implemented by claimNodeForCleanup() in apps/api/src/scheduled/node-cleanup/shared.ts.

Reaping only ever applies to nodes with node_role = 'workspace' and node_class != 'user-owned'. Deployment nodes host long-running user applications and legitimately hold zero workspaces forever, so they are never reaped by these timers; they are released when their last deployment environment is deleted.

A running, healthy managed workspace VM that holds no live workspace but never entered the warm window (its last-workspace handoff was missed) is handed to NodeLifecycle once its last workspace activity is older than NODE_EMPTY_WARM_HANDOFF_GRACE_MS. That starts the normal warm timeout; it does not shorten it. Implemented by sweepEmptyNodeWarmHandoff() in apps/api/src/scheduled/node-cleanup/empty-node-warm-handoff.ts.

Stopped managed VM nodes created directly through a canonical pool can also be reaped using their server-recorded pool, credential, and native-offering identity. They retain the same workspace-activity and active-claim guards. A short project warm timeout does not bypass the workspace idle window. Runtime teardown preserves the saved snapshot and conversation for recovery on a fresh node.

Variable Default Description
NODE_WORKSPACE_IDLE_TIMEOUT_MS 1800000 (30 min) Last-workspace-activity window before an auto-provisioned node_role = 'workspace' node with no active workspaces can be destroyed. Uses COALESCE(MAX(workspaces.updated_at), nodes.created_at), never heartbeat-updated nodes.updated_at.
NODE_ORPHAN_IDLE_TIMEOUT_MS legacy alias Backward-compatible alias used only when NODE_WORKSPACE_IDLE_TIMEOUT_MS is unset.
NODE_ABSOLUTE_MAX_LIFETIME_MS 86400000 (24 hr) Hard ceiling on auto-provisioned workspace node age. Applies even when a workspace row still reports running, provided no workspace has reported activity within the idle window — this is what stops a stuck workspace row from making a node immortal.
NODE_EMPTY_WARM_HANDOFF_GRACE_MS 1800000 (30 min) Last-workspace-activity grace before the cleanup sweep hands a running, healthy managed workspace VM that has no live workspace and no warm_since to NodeLifecycle. The normal warm timeout then applies.
ORPHANED_WORKSPACE_GRACE_PERIOD_MS 600000 (10 min) Grace before the cleanup sweep stops a task workspace in creating, running, or recovery whose task is terminal (sweepOrphanedWorkspaces() in apps/api/src/scheduled/node-cleanup/workspace-phases.ts). Measured from both the workspace’s creation and the latest terminal task’s end, so an eviction or recovery still finalizing for a just-ended task is not cut off. The end is completed_at, then the chronologically latest genuine matching terminal status event (SQLite and ISO timestamps are normalized), with updated_at as a conservative fallback when no terminal history exists.
NODE_CLEANUP_SWEEP_LIMIT 25 Max node candidates processed per cleanup phase per cron run.
NODE_CLEANUP_FAILURE_BACKOFF_MS 3600000 (1 hr) Expiring exclusion applied to failed cleanup candidates so a permanent provider error cannot monopolize the bounded page. A failed attempt always waits this long before the next one, except that a stopped/destroying node is retried no later than its stranded-node deadline (failureRetryAt() in apps/api/src/scheduled/node-cleanup/cleanup-outcome.ts); the shorter refusal re-check applies only to candidates refused before any attempt.
NODE_UNHEALTHY_DRAIN_AFTER_MS 600000 (10 min) Heartbeat-loss window before SAM posts a session notice and requests sleep on a managed workspace VM.
NODE_UNHEALTHY_RELEASE_AFTER_MS 1800000 (30 min) Heartbeat-loss window before SAM attempts strict provider deletion, even if the node still has active workspace rows. The value is clamped above the drain threshold.
NODE_UNHEALTHY_FLEET_MAX_FRACTION 0.5 Holds destructive cleanup when this fraction of at least three managed workspace VMs lose heartbeat together, indicating a possible heartbeat-intake incident. The hold escalates after the configured release and drain windows combined; it does not delete busy nodes on a timer.
NODE_UNHEALTHY_FLEET_MIN_NODES 3 Minimum number of managed workspace VMs required before the fleet-wide heartbeat-loss guard applies.
NODE_UNHEALTHY_PRESERVATION_TIMEOUT_MS 5000 (5 sec) Per-node budget for attempting chat notices and sleep requests before cleanup proceeds.
NODE_UNHEALTHY_RETRY_MS 60000 (1 min) Retry delay after provider deletion of an unhealthy node fails.
NODE_STOPPED_HANDOFF_SWEEP_BUDGET_MS 20000 (20 sec) Wall-clock budget for each of the stopped-node handoff, destroying-node handoff, provider-deletion confirm and stranded-node retirement phases. Candidates not started within the budget remain eligible for the next sweep; handoff candidates rotate, so a page of failing candidates cannot hold the head of every sweep.
NODE_STOPPED_HANDOFF_REQUEST_TIMEOUT_MS 5000 (5 sec) Per-candidate provider/DNS deadline for unhealthy-node release, deployment-node cleanup and provider orphan reconciliation, capped by remaining sweep time (provider orphan reconciliation instead gives each phase the full deadline and starts no candidate after the sweep budget). Stopped/destroying handoff and stranded-node retirement use the admin setting operations.nodeProviderDeletionRequestTimeoutMs instead (see Admin settings). Provider failures enter cleanup backoff.
WORKSPACE_CLEANUP_SWEEP_LIMIT 50 Max workspace candidates processed per cleanup phase per cron run.
NODE_AGENT_BACKGROUND_REQUEST_TIMEOUT_MS 5000 (5 s) VM-agent request timeout for background sweeps. Deliberately far below the interactive NODE_AGENT_REQUEST_TIMEOUT_MS (30 s) so a sweep over unreachable nodes cannot exhaust the Worker’s wall-clock budget.
WORKSPACE_DELETION_RETRY_BASE_MS 60000 (1 min) Initial retry delay after a VM workspace deletion remains unconfirmed.
WORKSPACE_DELETION_RETRY_MAX_MS 3600000 (1 hr) Maximum exponential backoff for an unconfirmed workspace deletion.
WORKSPACE_DELETION_MAX_RESIDENCE_MS 86400000 (24 hr) Maximum hot-retry residence before an unconfirmed deletion enters durable operator quarantine; its workspace remains stopping and replacement-fenced.
WORKSPACE_DELETION_ALARM_BATCH_SIZE 3 Maximum due workspace-deletion entries processed by one NodeLifecycle alarm, sized to stay within the Cloudflare Free-plan D1 query budget on the worst successful linked-workspace path.
WORKSPACE_DELETION_CALLBACK_SIGNAL_TTL_SECONDS 300 (5 min) Per-workspace and callback-kind throttle for payload-free workspace.deletion_unconfirmed_callback activity evidence.
WORKSPACE_DELETION_CALLBACK_SIGNAL_CLEANUP_LIMIT 25 Maximum expired callback telemetry throttle claims removed by one signal attempt.
WORKSPACE_DELETION_DIAGNOSTIC_MAX_LENGTH 500 characters Maximum sanitized deletion-attempt diagnostic stored in workspaces.error_message.

The cron and Durable Object switches are availability brakes. D1 controls normal settings, while legacy KV false or disabled remains an independent emergency disable veto, including during D1 outages. Missing configuration defaults to enabled; a storage outage preserves an already observed disabled brake. Explicit enable in Admin → Settings saves D1 first, then clears the KV veto. A failed KV update is an uncertain propagation outcome, not a rollback; reload and verify. Active superadmins can inspect and update both brakes through the settings UI or /api/admin/runtime-controls; emergency operators retain the KV procedure in .claude/rules/55-runaway-cost-emergency-ops.md.

Variable Default Description
CRON_SWEEPS_ENABLED_KV_KEY control-loops:cron-enabled KV key gating the five-minute operational sweep block
DO_ALARMS_ENABLED_KV_KEY control-loops:alarms-enabled Shared KV key gating alarm-bearing Durable Objects
CONTROL_LOOP_KILL_SWITCH_CACHE_MS 30000 In-memory switch cache; runtime clamps it to at most 30 seconds
CONTROL_LOOP_DISABLED_ALARM_RETRY_MS 300000 (5 min) Safe alarm recheck interval while DO work is disabled; values below 60 seconds are clamped
CRON_FAILURE_NOTIFICATION_THROTTLE_MS 3600000 (1 hr) Per-sweep throttle enforced by a KV cache plus an atomic per-user Notification DO claim; also how long an archive-breaker alert claim is held
CRON_FAILURE_NOTIFICATION_KV_PREFIX cron-failure-notification KV prefix for notification throttle markers
DIAGNOSIS_COMPLETED_STEP_MIN_DELAY_MS 1000 Minimum delayed re-arm for an already-completed diagnosis step
ORCHESTRATOR_ZERO_TASK_GRACE_MS 600000 (10 min) Grace period before an active orchestration with no tasks ends
ORCHESTRATOR_MAX_MISSION_LIFETIME_MS 86400000 (24 hr) Backstop that force-completes active or completing orchestrations

The five orchestrator.cancellation* controls are typed runtime settings editable in Admin Settings under Operations, rather than environment variables. The residence limit is captured as a durable deadline when cancellation starts or is explicitly retried; changing the setting does not extend an existing episode. Expired episodes block locally before any settings or D1 lookup.

Runtime setting Default Description
orchestrator.cancellationPageSize 25 Maximum tasks visited in one mission cancellation turn.
orchestrator.cancellationTurnMs 5000 Elapsed turn budget checked between task operations.
orchestrator.cancellationRetryPasses 3 Maximum passes before failed cancellation is blocked for explicit retry.
orchestrator.cancellationResidenceMs 900000 Maximum cancellation episode residence before blocking.
orchestrator.cancellationIntervalMs 1000 Alarm delay between pending cancellation turns.

Mission cancellation uses the existing orchestrator tracking and alarm (project-orchestrator/cancel-mission.ts, cancellation-config.ts). The mission stays paused while its tasks are being cancelled; completion is recorded only after no nonterminal task remains. A blocked cancellation stops rearming and requires an explicit cancellation retry. Completed task cancellations remain complete across retries.

These bounds limit work rather than guarantee completion within one episode. At the defaults, 10,000 tasks require at least 400 turns. If every turn uses its full five-second work budget plus the one-second alarm delay, that is approximately 40 minutes before scheduler and RPC overhead, exceeding the fifteen-minute residence limit. Such a mission will require explicit retries; raise the bounds deliberately for larger workloads. The turn budget is checked between operations and does not interrupt an RPC already in progress.

The scheduled Durable Object billing monitor reads these non-secret variables from the selected GitHub Environment, not from the API Worker runtime:

Variable Default/fallback Description
DO_WALL_TIME_SCRIPT_NAMES none Optional comma-separated API Worker filter for wall-time and invocation-rate analysis
DO_INVOCATION_RATE_REGRESSION_RATIO 2 Recent-versus-seven-day-baseline request-rate failure ratio
DO_CRON_LIVENESS_MAX_AGE_HOURS 3 Maximum age of the most recent targeted cron.completed event
DO_CRON_LIVENESS_SCRIPT_NAMES DO_WALL_TIME_SCRIPT_NAMES Explicit API Worker service target for cron liveness; the GitHub workflow derives both from RESOURCE_PREFIX and the selected stack when unset
DO_CRON_LIVENESS_ENDPOINT Cloudflare Workers Observability query endpoint Optional endpoint override for compatible/private telemetry gateways

The selected GitHub Environment’s CF_API_TOKEN secret must include the Cloudflare Workers Observability Write permission. Cloudflare requires that permission for the telemetry query endpoint even though this monitor only reads aggregated liveness telemetry.

Reclaims cloud servers that exist at the provider but which no live database row claims — for example when a server was created but the control plane failed before recording its instance ID.

Because this is the only path that destroys infrastructure on the basis of absent evidence, it fails closed at every step. A server must carry both the current control-plane env value and the exact Pulumi-generated installation marker before SAM consults D1. SAM then re-reads and revalidates the same provider resource immediately before it calls the provider delete API. Provider-account membership, server names, resource prefixes, and absence from this installation’s D1 are not ownership proof. Each provider call (the listing, the re-read, the delete) gets its own NODE_STOPPED_HANDOFF_REQUEST_TIMEOUT_MS, and no new candidate starts once the sweep budget (NODE_STOPPED_HANDOFF_SWEEP_BUDGET_MS) is spent; the rest wait for the next run.

On Google Cloud, a delete takes tens of seconds to finish, so SAM sends it without waiting, bound to the exact instance id and zone of the re-read, and the run reports it as requested (providerOrphansDeletionRequested in the cron summary) rather than destroyed. The next run finds the VM gone, or requests its deletion again if it is still there. This applies to the installation’s platform Google Cloud credential and to users’ Google Cloud credentials alike. Before sending, SAM re-reads the instance once more in that zone and refuses if its id, name or ownership labels changed. A failure confined to one user’s or project’s cloud account (a revoked token, a deleted project) is counted as providerOrphanAccountErrors in the cron summary and does not fail the sweep; failures with the platform account or SAM itself appear in failedSweeps.

Pulumi generates the non-secret installation identity automatically on first deploy, persists it in the stack state, and injects it into the Worker as SAM_INSTALLATION_ID; there is no manual GitHub Environment setting. An upgrade does not relabel existing servers. Legacy servers without the marker remain usable and are preserved indefinitely, while servers provisioned after the upgrade participate in normal orphan cleanup. If the Pulumi state is lost or recreated, the new identity safely leaves the old fleet unattributable instead of adopting it destructively. Any missing/malformed identity, ambiguous provider metadata, or failed/malformed D1 lookup skips deletion. Resources surfaced to reconciliation with non-owning metadata emit aggregate operator-visible counters.

Variable Default Description
PROVIDER_ORPHAN_RECONCILIATION_ENABLED true Set to false to disable provider-side reconciliation entirely.
PROVIDER_ORPHAN_MIN_AGE_MS 3600000 (1 hr) Minimum server age before it can be treated as an orphan. Must comfortably exceed provisioning time, since a server’s instance ID is recorded only after the provider returns it.
PROVIDER_ORPHAN_DESTROY_LIMIT 5 Max servers deleted (or, on Google Cloud, sent for deletion) per reconciliation run.
PROVIDER_ORPHAN_RECONCILE_INTERVAL_MS 3600000 (1 hr) Minimum interval between runs. Invoked by the 5-minute cron but self-throttled to this interval via KV.
Variable Default Description
PROJECT_INVITE_TOKEN_BYTES 32 Random bytes used for generated project invite link tokens
PROJECT_INVITE_DEFAULT_EXPIRY_DAYS 7 Default lifetime for invite links created without an explicit expiry
PROJECT_INVITE_MAX_EXPIRY_DAYS 30 Maximum allowed invite link lifetime, including explicit expiry-date input
PROJECT_OFFBOARDING_PLAN_TTL_SECONDS 900 Lifetime for project member offboarding preview plans before recomputation
Variable Default Description
NOTIFICATION_PROGRESS_BATCH_WINDOW_MS 300000 (5 min) Min interval between progress notifications per idea
NOTIFICATION_DEDUP_WINDOW_MS 60000 (60s) Dedup window for task_complete notifications
NOTIFICATION_AUTO_DELETE_AGE_MS 7776000000 (90 days) Auto-delete old notifications
MAX_NOTIFICATIONS_PER_USER 500 Max stored notifications per user
NOTIFICATION_PAGE_SIZE 50 Default page size for notification list
MAX_NOTIFICATION_PAGE_SIZE 100 Max allowed page size
HUMAN_INPUT_ESCALATION_FRACTIONS 0.25,0.75 Reminder points, questions asked before the inbox move only
HUMAN_INPUT_UNDELIVERED_GRACE_MS 7200000 (2 hr) Undelivered grace, questions asked before the inbox move only
HUMAN_INPUT_MAX_WAIT_MS 86400000 (24 hr) Hard limit, questions asked before the inbox move only
WEB_PUSH_TTL_SECONDS 86400 Push-service message TTL
WEB_PUSH_VAPID_TTL_SECONDS 43200 VAPID authorization-token lifetime
WEB_PUSH_DELIVERY_TIMEOUT_MS 10000 Per-attempt push-service timeout
WEB_PUSH_DELIVERY_BUDGET_MS 25000 Total fan-out budget, hard-capped at 25s below Worker background limit
WEB_PUSH_FANOUT_CONCURRENCY 8 Maximum concurrent endpoint deliveries
WEB_PUSH_MAX_ATTEMPTS 3 Bounded transient delivery attempts
WEB_PUSH_MAX_RETRY_AFTER_SECONDS 30 Maximum honored Retry-After delay
WEB_PUSH_MAX_PAYLOAD_BYTES 3500 Maximum unencrypted payload size
WEB_PUSH_FAILURE_THRESHOLD 5 Consecutive failures before disabling a subscription
WEB_PUSH_MAX_SUBSCRIPTIONS_PER_USER 8 Maximum retained browser endpoints per user
WEB_PUSH_USER_AGENT_MAX_LENGTH 512 Maximum stored browser description length
RATE_LIMIT_PUSH_SUBSCRIPTION 30 Subscription mutations per user per hour
Variable Default Description
TRIGGER_STALE_EXECUTION_TIMEOUT_MS 1800000 (30 min) Age before running executions are checked against linked task liveness
TRIGGER_STALE_QUEUED_TIMEOUT_MS 300000 (5 min) Age before queued executions are checked against linked task liveness
TRIGGER_EXECUTION_HARD_MAX_RESIDENCE_HOURS 48 Hard maximum execution residence backstop; live linked tasks still control concurrency and incident dispatch use
TRIGGER_EXECUTION_LOG_RETENTION_DAYS 90 Completed/failed/skipped execution log retention
TRIGGER_EXECUTION_CLEANUP_ENABLED enabled Set to false to disable the cleanup sweep
TRIGGER_STALE_RECOVERY_BATCH_SIZE 100 Maximum stale execution candidates processed per sweep
MAX_TRIGGERS_PER_PROJECT 20 Platform default trigger cap per project; wrangler.toml ships 10. A project owner can change it under Settings → Infrastructure → Scaling & Scheduling → Max Triggers
GITHUB_TRIGGERS_ENABLED unset false turns GitHub event triggers off and true forces them on; unset means on once a GitHub webhook secret is configured. Set it in wrangler.toml [vars]

SAM saves each GitHub delivery a trigger could use before acknowledging it, and the five-minute cron retries runs that failed to start (see When a trigger runs). Set these through GitHub Environment variables named GH_TRIGGER_RECOVERY_* (for example GH_TRIGGER_RECOVERY_MAX_ATTEMPTS), which the deploy passes to the Worker as GITHUB_TRIGGER_RECOVERY_*.

Variable Default Description
GITHUB_TRIGGER_RECOVERY_MAX_ATTEMPTS 12 Attempts to start a delivery’s run before giving up and notifying superadmins
GITHUB_TRIGGER_RECOVERY_RETRY_BASE_MS 30000 (30 s) First retry delay; it doubles after each failure
GITHUB_TRIGGER_RECOVERY_RETRY_MAX_MS 900000 (15 min) Longest retry delay
GITHUB_TRIGGER_RECOVERY_BATCH_SIZE 25 Deliveries one cron pass picks up
GITHUB_TRIGGER_RECOVERY_MAX_WALL_TIME_MS 20000 (20 s) Time after which a cron pass stops picking up more deliveries
GITHUB_TRIGGER_RECOVERY_LEASE_MS 60000 (60 s) How long one pass holds a delivery before another may retry it
GITHUB_TRIGGER_RECOVERY_PAYLOAD_MAX_BYTES 262144 (256 KiB) Largest delivery SAM saves; bigger ones are refused and start no run
GITHUB_TRIGGER_RECOVERY_PAYLOAD_RETENTION_MS 86400000 (24 h) How long a saved delivery is kept for retries
GITHUB_TRIGGER_RECOVERY_DEDUP_RETENTION_MS 7776000000 (90 days) How long a delivery ID is remembered, so a redelivery never starts a second run
Variable Default Description
WEBHOOK_TRIGGERS_ENABLED true Public generic webhook ingress kill switch
WEBHOOK_CREDENTIAL_CLAIM_TTL_SECONDS 600 Authenticated one-time MCP webhook credential claim lifetime
WEBHOOK_TRIGGER_MAX_BODY_BYTES 65536 Maximum JSON request body size
WEBHOOK_TRIGGER_MAX_FILTERS 10 Maximum deterministic filters per trigger
WEBHOOK_TRIGGER_MAX_FILTER_PATH_LENGTH 200 Maximum configured filter dot-path length
WEBHOOK_TRIGGER_MAX_FILTER_PATH_DEPTH 8 Maximum filter nesting depth at evaluation time
WEBHOOK_TRIGGER_MAX_INCLUDED_HEADERS 10 Maximum safe request headers copied into template context
WEBHOOK_TRIGGER_MAX_HEADER_NAME_LENGTH 100 Maximum configured included-header name length
WEBHOOK_TRIGGER_MAX_SOURCE_LABEL_LENGTH 100 Maximum optional source label length
WEBHOOK_TRIGGER_MAX_IDEMPOTENCY_KEY_LENGTH 200 Maximum accepted Idempotency-Key length
WEBHOOK_INGRESS_RATE_LIMIT_PER_MINUTE 120 Best-effort pre-auth request damping per client IP/window
WEBHOOK_TRIGGER_RATE_LIMIT_PER_MINUTE 60 Best-effort request damping per trigger/window
WEBHOOK_INVALID_TOKEN_RATE_LIMIT_PER_MINUTE 30 Best-effort invalid-token damping per client IP/window
WEBHOOK_RATE_LIMIT_WINDOW_SECONDS 60 Fixed rate-limit window length
WEBHOOK_DELIVERY_RETENTION_DAYS 7 Retention for redacted delivery audit metadata
WEBHOOK_DELIVERY_CLEANUP_BATCH_SIZE 500 Maximum expired audit rows deleted per cleanup pass
WEBHOOK_DELIVERY_DEFAULT_PAGE_SIZE 25 Default delivery-history page size
WEBHOOK_DELIVERY_MAX_PAGE_SIZE 100 Maximum delivery-history page size
WEBHOOK_DELIVERY_PROCESSING_LEASE_SECONDS 300 Lease before an unsubmitted processing delivery can recover

Webhook tokens use the existing ENCRYPTION_KEY as keyed-hash material and do not require a separate deployment secret. See Webhook Triggers for request, credential, filtering, and audit behavior.

Signed webhooks (Slack and HMAC) add three limits that are admin settings, not environment variables: operations.webhookQueueMaxPending (50 events waiting per trigger), operations.webhookQueueTtlSeconds (86400, how long an event waits for a free run) and operations.webhookSignatureToleranceSeconds (300, the allowed clock difference for a signed timestamp). A signing secret is encrypted with CREDENTIAL_ENCRYPTION_KEY when it is set, otherwise ENCRYPTION_KEY; no extra deployment secret is needed.

Webhook damping uses Cloudflare KV’s eventually consistent read-update-write behavior. It reduces accidental bursts and abuse but is not a strict distributed quota.

These control whether agents can stop and ask the person who started a chat for permission, ask them a question, or send a link to open — see When the Agent Needs You. All three switches are false in the checked-in configuration; set them as GitHub Environment variables to turn them on (see Let agents ask in chat). Turning a switch on applies to agent sessions started afterwards; sleep and wake preserve their recorded interaction settings; turning one off refuses new requests at once, even in running sessions.

A permission request in a Chat session, and every question, waits up to ACP_INTERACTION_PERMISSION_CONVERSATION_DEADLINE_MS; a permission request in a Task waits up to ACP_INTERACTION_PERMISSION_TASK_DEADLINE_MS. Both are cut short a minute (ACP_INTERACTION_DEADLINE_MARGIN_MS) before the agent’s own turn would time out.

Variable Default Description
ACP_INTERACTIONS_ENABLED false Turns on permission requests: an agent can ask the person who started a chat (or anyone they shared it with) before it acts, and waits for the answer. While false, SAM refuses every request at once. The other two switches need this one too. Turning it off stops new requests; ones already waiting can still be answered until they expire.
ACP_INTERACTION_FORMS_ENABLED false Turns on questions: a short form (choices, short text, numbers, yes/no) the agent asks in a Chat (conversation-mode) session. Agents decide when to ask; this switch only lets them. A form SAM can’t display is cancelled. Questions and answers are stored encrypted, and only the person who started the chat, and anyone they shared it with, can see them.
ACP_INTERACTION_URLS_ENABLED false Turns on links to open: a tool, usually an MCP server, asks the person who started a Chat session (or anyone they shared it with) to open an https:// page to sign in or approve something. SAM never opens the link itself and refuses local addresses and localhost callbacks.
ACP_INTERACTION_URL_DEADLINE_MS 600000 (10 min) Maximum URL request window, further limited by the live prompt deadline. Existing requests remain answerable when the URL switch is turned off.
ACP_INTERACTION_URL_MAX_CHARS 8192 Maximum HTTPS URL length. Overrides can lower this bound.
ACP_INTERACTION_URL_ELICITATION_ID_MAX_CHARS 256 Maximum wrapper URL request ID length. Overrides can lower this bound.
ACP_INTERACTION_URL_REDIRECT_DEPTH 2 Maximum nesting of explicit redirect/callback query URLs. Overrides can lower this bound; SAM does not fetch redirects.
ACP_INTERACTION_FORM_SCHEMA_MAX_BYTES 16384 (16 KiB) Maximum supported form schema size, including descriptions and previews.
ACP_INTERACTION_FORM_SCHEMA_MAX_PROPERTIES 20 Maximum fields in one supported form.
ACP_INTERACTION_FORM_SCHEMA_MAX_ENUM 50 Maximum choices per select or multi-select field.
ACP_INTERACTION_ANSWER_MAX_BYTES 16384 (16 KiB) Maximum accepted form answer payload size.
ACP_INTERACTION_ANSWER_STRING_MAX_BYTES 4096 (4 KiB) Maximum size of a string answer or selected choice.
ACP_INTERACTION_PERMISSION_TASK_DEADLINE_MS 1800000 (30 min) Runtime permission deadline for task sessions.
ACP_INTERACTION_PERMISSION_CONVERSATION_DEADLINE_MS 7200000 (2 hours) Runtime permission deadline for conversation sessions.
ACP_INTERACTION_DEADLINE_MARGIN_MS 60000 (1 min) Safety margin before the enclosing prompt deadline when computing a permission deadline.
ACP_INTERACTION_MAX_DEADLINE_MS 14400000 (4 hours) Longest any request may wait. Keep every deadline setting at or below it: while requests are on, a deadline above it makes the VM agent reject the session start, so new agent sessions fail to start until you fix it.
ACP_INTERACTION_MAX_PENDING_PER_SESSION 8 Most requests that can wait in one chat at once; a further request is refused.
ACP_INTERACTION_OPTIONS_MAX_COUNT 16 Most buttons a permission request can offer.
ACP_INTERACTION_REQUEST_MAX_BYTES 32768 (32 KiB) Largest request detail SAM accepts from an agent.
ACP_INTERACTION_DELIVERY_WINDOW_MS 900000 (15 min) How long SAM keeps trying to hand an answer to the agent (never past the request’s deadline) before the card says delivery is unconfirmed.
ACP_INTERACTION_SENSITIVE_PURGE_MS 3600000 (1 hour) How long a request’s question and answer are kept after it is settled; after that only its outcome remains.
ACP_INTERACTION_SUMMARY_RETENTION_MS 2592000000 (30 days) How long settled requests’ outcomes are kept. The newest 100 per chat are kept regardless.
ACP_INTERACTION_OPTION_ID_MAX_CHARS 128 Maximum permission option or form field identifier length accepted by the runtime bridge.
ACP_INTERACTION_OPTION_NAME_MAX_CHARS 200 Maximum permission option or form field label length accepted by the runtime bridge.
ACP_INTERACTION_RUNTIME_RECEIPT_LIMIT 256 Maximum in-memory idempotency receipts and distinct URL request IDs retained per live SessionHost generation. Exhausting the URL ID limit fails closed until a new runtime generation starts; retained IDs prevent late duplicate completion from binding to a new request.
ACP_INTERACTION_RUNTIME_RESPONSE_MAX_BYTES 65536 (64 KiB) Maximum response body read by the runtime for interaction creation and settlement.

The remaining ACP_INTERACTION_* settings (*_BATCH_SIZE, RETRY_*, ALARM_*, *_LAST_SETTLED) tune how SAM stores and delivers requests internally and rarely need changing; their defaults are in packages/shared/src/acp-interactions.ts.

Variable Default Description
ACP_SESSION_DETECTION_WINDOW_MS 300000 (5 min) Stale ProjectData ACP heartbeat detection window. VM sessions are not interrupted solely from stale/missing ProjectData heartbeat rows; the timeout must be paired with conclusive runtime/workspace evidence.
ACP_SESSION_MAX_FORK_DEPTH 10 Maximum session fork chain depth
ARCHIVED_FORK_HISTORY_MAX_CHARS 24000 Most characters of conversation history SAM hands the agent when you fork an archived or expired chat (from at most the last 200 stored entries). Set it in wrangler.toml [vars]

Task-managed ACP prompts use control-plane inactivity classification and the task absolute ceiling. ACP_TASK_PROMPT_TIMEOUT has been removed; legacy values no longer impose a duration-only failure. ACP_PROMPT_TIMEOUT applies only to unmanaged workspace sessions.

Variable Default Description
ACP_MESSAGE_BUFFER_SIZE 5000 Buffer size for ACP messages
ACP_STDERR_BUFFER_BYTES 4096 Agent stderr bytes retained for crash reports
ACP_PING_INTERVAL 30s WebSocket keepalive ping interval
ACP_PONG_TIMEOUT 10s Pong response timeout
ACP_PROMPT_RETRY_MAX_RETRIES 2 Max transient provider prompt retries after the initial attempt
ACP_PROMPT_RETRY_INITIAL_BACKOFF 15s Initial backoff before retrying transient provider prompt errors
ACP_PROMPT_RETRY_MAX_BACKOFF 2m Max exponential backoff for transient provider prompt retries
ACTIVITY_REREPORT_INTERVAL 60s Re-send prompting activity while a prompt is active
ACP_HARNESS_ACTIVITY_REPORT_DEBOUNCE 750ms Debounce ACP harness/tool-call activity reports before callbacks
ACP_CHECKPOINT_PREEMPT_GRACE 30s Graceful ACP cancel/close wait before harness force-stop
ACP_CHECKPOINT_PREEMPT_MAX_GRACE 2m Maximum caller-selected checkpoint rollover grace
ACP_CHECKPOINT_ROLLOVER_TIMEOUT 2m Full checkpoint restart and strict LoadSession deadline
ACTIVITY_TERMINAL_REPORT_ATTEMPTS 5 Retry attempts for terminal activity reports
ACTIVITY_TERMINAL_REPORT_BACKOFF 1s Backoff between terminal activity report retries
ACP_IDLE_SUSPEND_TIMEOUT 30m Idle session auto-suspend timeout
ACP_NOTIF_SERIALIZE_TIMEOUT 5s Notification serialization timeout
ACP_STEER_TIMEOUT 20s Bound on one live-steering request to the agent adapter

PROMPT_REQUEST_MAX_BYTES (default 4194304) caps the body of a prompt or steer request from the control plane; the VM agent answers 413 above it.

Variable Default Description
MCP_TOKEN_TTL_SECONDS 28800 (8 hours) Sliding inactivity timeout for agent MCP access
MCP_RATE_LIMIT 120 Max MCP requests per window
MCP_RATE_LIMIT_WINDOW_SECONDS 60 Rate limit window
MCP_DISPATCH_MAX_DEPTH 3 Max recursion depth for dispatch_task
MCP_DISPATCH_MAX_PER_TASK 5 Max dispatched tasks per parent task
MCP_DISPATCH_MAX_ACTIVE_PER_PROJECT 10 Max active dispatched tasks per project
ORCHESTRATOR_STOP_CAS_MAX_ATTEMPTS 2 Task-status CAS attempts after a hard stop

The SAM Connector is on by default. Its policy settings are edited by superadmins in Admin → Integrations → Connector, and from v2026.10.17 also in Admin → Settings; a value saved in either wins over the environment variable, and Reset to default (or Reset override) removes it. The variables below set the starting values, and the deploy passes each one through from a GitHub Environment variable of the same name. The deploy also creates the OAUTH_KV namespace the Connector stores OAuth state in; no setup is needed.

Variable Default Admin setting
CONNECTOR_ENABLED true Enable Connector
CONNECTOR_WRITE_ENABLED true Allow writes
CONNECTOR_CLIENT_REGISTRATION open (or allowlist) Client registration
CONNECTOR_ALLOWED_REDIRECT_HOSTS claude.ai,chatgpt.com,loopback Allowed redirect hosts
CONNECTOR_ACCESS_TOKEN_TTL_SECONDS 3600 Access token lifetime
CONNECTOR_REFRESH_TOKEN_TTL_SECONDS 2592000 (30 days) Refresh token lifetime
CONNECTOR_READ_RATE_LIMIT_PER_MINUTE 120 Reads per user per minute
CONNECTOR_WRITE_RATE_LIMIT_PER_MINUTE 30 Writes per user per minute
CONNECTOR_MAX_STARTS_PER_USER_PER_HOUR 10 Starts per user per hour
CONNECTOR_MAX_STARTS_PER_USER_PER_DAY 50 Starts per user per day

These protocol bounds are set only by environment variable:

Variable Default Description
CONNECTOR_REGISTRATION_PER_IP_PER_HOUR 20 Dynamic client registrations per IP address per hour
CONNECTOR_REGISTRATION_GLOBAL_PER_HOUR 100 Dynamic client registrations per hour across the installation (atomic)
CONNECTOR_CLIENT_IDLE_TTL_SECONDS 7776000 (90 days) How long an unused registered client lasts (see below)
CONNECTOR_CLIENT_NAME_MAX_LENGTH 200 Longest client name accepted at registration
CONNECTOR_REDIRECT_URI_MAX_COUNT 10 Most redirect URIs per registered client
CONNECTOR_OAUTH_REQUEST_MAX_BYTES 16384 (16 KiB) Largest OAuth request body
CONNECTOR_REQUEST_MAX_BYTES 262144 (256 KiB) Largest MCP request body
CONNECTOR_RESPONSE_MAX_BYTES 120000 Largest complete MCP response, text and structured data together
CONNECTOR_LIST_PAGE_SIZE 50 Page size for the connection and client lists in Settings and Admin
CONNECTOR_INBOX_SESSION_LIMIT 5 Chats, tasks, and notifications each inbox page checks (see below)

The per-IP registration limit also applies to vendor servers and NAT gateways that many people share, so size it, and the installation-wide limit, for how many people you expect to connect apps.

A registered client expires CONNECTOR_CLIENT_IDLE_TTL_SECONDS after it registered or was last renewed. A token exchange renews it only once half that time has passed, so an unused client expires between half and all of that time after its last token exchange.

CONNECTOR_INBOX_SESSION_LIMIT caps chats, tasks, and unread notifications separately on each “What needs me?” page. It counts the most recently active chats before leaving out those that don’t need the person, so a page can list fewer; the app follows nextCursor for more.

Variable Default Description
WHISPER_MODEL_ID @cf/openai/whisper-large-v3-turbo Transcription model
MAX_AUDIO_SIZE_BYTES 10485760 (10 MB) Max upload audio size
MAX_AUDIO_DURATION_SECONDS 60 Max recording duration
RATE_LIMIT_TRANSCRIBE 30 Max transcriptions per user per window
RATE_LIMIT_TRANSCRIBE_WINDOW_SECONDS 60 Transcription rate-limit window (seconds)
TTS_ENABLED true Enable/disable text-to-speech
TTS_MODEL @cf/deepgram/aura-2-en TTS model
TTS_SPEAKER luna TTS voice selection
TTS_ENCODING mp3 Audio output format
TTS_MAX_TEXT_LENGTH 100000 Max characters per TTS synthesis
TTS_TIMEOUT_MS 60000 TTS synthesis timeout
Variable Default Description
TASK_RUN_MAX_EXECUTION_MS 14400000 (4 hr) Age from which each stuck-task sweep checks an in_progress task’s task-scoped runtime liveness. A conclusively dead runtime is failed; a live one is kept, bounded only by TASK_RUN_ABSOLUTE_CEILING_MS
TASK_STUCK_QUEUED_TIMEOUT_MS 1200000 (20 min) Timeout for tasks stuck in queued state
TASK_STUCK_DELEGATED_TIMEOUT_MS 1860000 (31 min) Timeout for tasks stuck in delegated state
TASK_DO_MISMATCH_GRACE_MS 300000 (5 min) Minimum age before reconciling completed TaskRunner state with task-scoped liveness
STUCK_TASK_MAX_CANDIDATES_PER_SWEEP 100 Maximum active tasks inspected by each recovery sweep
STUCK_TASK_SCAN_CURSOR_KV_KEY scheduled:stuck-tasks:scan-cursor:v1 KV key used to resume bounded recovery scans fairly across active tasks
TASK_LIVENESS_MAX_ACP_SESSIONS 5 Maximum task-scoped ACP sessions inspected per liveness probe
TASK_LIVENESS_PROBE_TIMEOUT_MS 5000 (5 sec) Per-candidate timeout for ACP and Instant lifecycle probes used by ProjectData heartbeat deferral, idle cleanup, and stuck-task reconciliation; a timeout is inconclusive and preserves the task and workspace
TASK_LIVENESS_NODE_HEALTH_PROBE_TIMEOUT_MS 5000 (5 sec) Per-candidate timeout for stale-VM-node health probes used by ProjectData idle cleanup and stuck-task reconciliation; a timeout is inconclusive and preserves the task and workspace
IDLE_CLEANUP_MAX_CANDIDATES_PER_SWEEP 5 Maximum exact-session task candidates inspected by a ProjectData idle-cleanup pass; workspace deletion is deferred when this bound cannot prove every reporter-scoped runtime conclusively dead
IDLE_CLEANUP_MAX_RESIDENCE_MS 7200000 (2 hr) Maximum residence for a ProjectData idle-cleanup schedule before repeated preserved/error outcomes stop re-arming, preserve the workspace, and surface an attention marker
WORKSPACE_IDLE_TIMEOUT_MS 7200000 (2 hr) Installation default for how long an active chat session’s workspace can go without messages or terminal activity before ProjectData retires it, once its runtime is conclusively dead; a project’s Workspace Idle Timeout (30 min to 24 hr) overrides it
WORKSPACE_IDLE_BACKOFF_BASE_MS 600000 (10 min) First retry delay after a ProjectData workspace-idle check finds an idle workspace it cannot retire yet: inconclusive task candidates, a live or unprovable runtime, a missing project identity, or a failed check
WORKSPACE_IDLE_BACKOFF_MAX_MS 21600000 (6 hr) Maximum retry delay for repeated workspace-idle checks that cannot retire an idle workspace; the delay doubles from the base and resets on new activity or when the session wakes
TASK_RUN_ABSOLUTE_CEILING_MS 86400000 (24 hr) Absolute runaway-cost ceiling; first requests sleep for a conversation within the sleep grace, then fails runtimes that cannot sleep, including demonstrably live ones. Measured from the age of the currently allocated runtime generation (workspaces.created_at), not from tasks.started_at, and applied only while a runtime generation exists — a conversation whose workspace has been released holds no compute for it to bound
TASK_RUN_ABSOLUTE_CEILING_SLEEP_GRACE_MS 3600000 (1 hr) Longest the absolute ceiling allows a conversation sleep request or waits for a sleep that is still only in flight (scheduled, capturing, stopping or retrying) once the ceiling has passed. Measured on runtime-generation age, so sleep retries cannot renew it; a restorable sleep record always defers the ceiling. Keep it above SESSION_SLEEP_IN_FLIGHT_MAX_AGE_MS
STALLED_TASK_CLASSIFIER_ENABLED true Once a task is past TASK_RUN_MAX_EXECUTION_MS and kept alive only by an open agent turn, ask a Workers AI classifier whether the turn is stalled; a confident stalled verdict fails the task with “SAM detected a stalled agent turn after N minutes”. Set false to keep such turns running until the absolute ceiling. A value saved in Admin → Settings (operations.stalledTaskClassifierEnabled) wins over this variable
STALLED_TASK_CLASSIFIER_MIN_ACTIVITY_AGE_MS 3600000 (1 hr) How long the agent’s current turn (or its running work) must have gone on, and the transcript stayed quiet, before the classifier is asked
STALLED_TASK_CLASSIFIER_CONFIDENCE_THRESHOLD 0.8 Stalled probability required to fail the task; uncertain or failed classifications keep the task running
STALLED_TASK_CLASSIFIER_MODEL @cf/cloudflare/clef Workers AI model used for the stall classification
STALLED_TASK_CLASSIFIER_SELECTOR clef Clef selector passed with each classification
STALLED_TASK_CLASSIFIER_TIMEOUT_MS 10000 (10 sec) Per-classification timeout; a timeout counts as uncertain
STALLED_TASK_CLASSIFIER_MESSAGE_LIMIT 200 Most recent transcript rows read for the classification
STALLED_TASK_CLASSIFIER_TRANSCRIPT_MAX_CHARS 24000 Maximum transcript characters, lightly redacted, sent to the classifier
CLAUDE_CODE_COMPACTION_LOOP_DETECTOR_ENABLED true Enable Claude Code compaction-loop shutdown from recent message evidence
CLAUDE_CODE_COMPACTION_LOOP_RECENT_MESSAGE_LIMIT 40 Recent task-session messages to inspect for compaction-loop evidence
CLAUDE_CODE_COMPACTION_LOOP_WINDOW_MESSAGES 20 Rolling recent-message window used for compaction-loop detection
CLAUDE_CODE_COMPACTION_LOOP_MIN_PAIRS 3 Minimum Compacting... / Compacting completed marker pairs before failing a task
TASK_CALLBACK_TIMEOUT_MS 10000 Callback response timeout
TASK_CALLBACK_RETRY_MAX_ATTEMPTS 3 Max callback retry attempts
TASK_RUN_CLEANUP_DELAY_MS 5000 Delay before task cleanup
TASK_RECONCILIATION_IDLE_MS 300000 (5 min) Idle threshold before SAM sends a visible task check-in
TASK_RECONCILIATION_RESPONSE_DEADLINE_MS 60000 (1 min) Response deadline after a visible task check-in
TASK_RECONCILIATION_PROMPT_SOFT_STALL_MS 1800000 (30 min) In-flight prompt observation threshold before a non-interrupting reconciliation event
TASK_RECONCILIATION_PROMPT_HARD_STALL_MS 7200000 (2 hr) In-flight prompt hard-stall threshold before SAM requests prompt cancellation
TASK_RECONCILIATION_ACTIVE_WORK_HARD_STALL_MS 7200000 (2 hr) Hard ceiling for deferring an expired task check-in because prompt/tool work is still active
TASK_RECONCILIATION_MIN_ALARM_DELAY_MS 10000 (10 sec) Minimum delay before the next reconciliation alarm can fire
TASK_RECONCILIATION_MAX_CANDIDATES_PER_SWEEP 5 Maximum reconciliation candidates assessed per ProjectData alarm pass
TASK_RECONCILIATION_NODE_CALL_TIMEOUT_MS 5000 (5 sec) Bounded timeout for reconciliation check-in delivery and prompt cancellation
TASK_RECONCILIATION_CANDIDATE_LEASE_MS 30000 (30 sec) Durable claim floor preventing overlapping alarms from repeating reconciliation; the effective lease is clamped to cover the configured liveness-probe, node-call, and minimum-alarm-delay budgets
TASK_RECONCILIATION_MAX_CHECKINS 3 Maximum automatic check-ins without confirmed tool progress. At the limit, pause nudges and ask Clef once; human input or new completed tool work resets the budget. Classifier failure never grants more retries.
TASK_RECONCILIATION_PROBE_MAX_ATTEMPTS 3 Consecutive inconclusive task reconciliation attempts before quarantine
TASK_RECONCILIATION_QUARANTINE_MS 300000 (5 min) Cooldown after task reconciliation exhausts its inconclusive-attempt budget
INSTANT_START_STALE_TIMEOUT_MS 600000 (10 min) How long an Instant session may sit mid-launch (execution step instant_persistence) before the recovery sweep treats its start as stuck and fails it. Instant starts are accepted and then finished in the background, so this bounds a launch that never completes.

Durable prompt delivery and checkpoint storage

Section titled “Durable prompt delivery and checkpoint storage”

Durable prompt delivery is enabled by default so a follow-up can remain queued while a sleeping VM is replaced and restored. Legacy VM compatibility remains disabled: targets must advertise stable delivery receipts, and receipt ambiguity fails visibly rather than being guessed or replayed.

Variable Default Description
DURABLE_PROMPT_DELIVERY_ENABLED true Persist prompts and deliver them from ProjectData alarms, including sleeping-session wake.
PROMPT_DELIVERY_LEGACY_VM_COMPAT_ENABLED false Explicit old-VM compatibility switch; receipt ambiguity still fails visibly and is never guessed or replayed.
PROMPT_DELIVERY_MAX_CANDIDATES_PER_ALARM 5 Maximum delivery claims started by one alarm pass.
PROMPT_DELIVERY_MAX_ATTEMPTS 5 Counted delivery attempts before retryable busy/not-ready waits use capped backoff; TTL remains the hard bound.
PROMPT_DELIVERY_RETRY_BASE_MS 5000 Initial retry delay.
PROMPT_DELIVERY_RETRY_MAX_MS 300000 Maximum exponential retry delay.
PROMPT_DELIVERY_TTL_MS 3600000 Maximum unresolved delivery lifetime.
PROMPT_DELIVERY_RECEIPT_TIMEOUT_MS 30000 Age at which an unconfirmed claim enters receipt reconciliation.
PROMPT_DELIVERY_BACKGROUND_TIMEOUT_MS 5000 Deadline for pre-send target/recovery preparation and owner-approved recovery repair; also bounds background VM submit and receipt calls. Preparation timeouts remain retryable without sending a prompt.
PROMPT_DELIVERY_MIN_ALARM_DELAY_MS 1000 Minimum delay before the next delivery alarm.
ACP_LONG_TURN_SUPERVISOR_ENABLED false Reserved long-turn candidate/preemption engine switch; this release leaves it inert.
ACP_LONG_TURN_CHECKPOINT_MS 18000000 (5 hr) Reserved checkpoint eligibility threshold.
ACP_CHECKPOINT_PREEMPT_GRACE_MS 30000 Reserved graceful preemption window.
ORCHESTRATOR_WAIT_RECONCILE_INTERVAL_MS 30000 D1 reconciliation backstop interval for active parent waits.
ORCHESTRATOR_WAIT_MAX_CHILDREN 20 Maximum same-project task IDs selected by one durable wait (hard ceiling: 90, preserving D1 bind headroom).
ORCHESTRATOR_WAIT_MAX_ACTIVE_PER_PROJECT 100 Maximum active durable parent waits per project.
ORCHESTRATOR_WAIT_MAX_DURATION_MS 86400000 Maximum finite wait deadline.
ORCHESTRATOR_WAIT_MAX_CANDIDATES_PER_ALARM 10 Maximum wait subscriptions reconciled by one ProjectData alarm.

ProjectData stores a single prompt-delivery queue and checkpoint episodes keyed by ACP session and prompt epoch. Sleeping-session prompts stay in that queue until strict restore succeeds, then use stable receipts for exactly-once acceptance. Task agents can register wait_for_subtasks for same-project tasks; terminal hooks provide low-latency nudges, bounded alarms reconcile missed writers, and one stable delivery ID wakes the caller exactly once. Automatic checkpoint preemption remains disabled.

Liveness-gated recovery. Stuck-task recovery for in_progress tasks (including task-mode work paused at the awaiting_followup execution step) is gated on task-scoped liveness — a live workspace, node reachability, and an active task-scoped ACP session. A healthy, recent D1 node mirror satisfies the reachability gate directly; a stale or unhealthy mirror is only suspect and must be contradicted by a successful bounded node-health probe before task-scoped ACP classification continues. A shared-node heartbeat or health response alone is never sufficient. Consequently, TASK_RUN_MAX_EXECUTION_MS is the point from which a task with no proven live runtime is failed; a task with a demonstrably live runtime is preserved past it, bounded only by TASK_RUN_ABSOLUTE_CEILING_MS as a runaway-cost backstop (there is no separate hard timeout). When liveness cannot be determined (including a probe timeout, transport error, or failed health response), the task is left untouched (fail-safe). A live verdict does not mean work is happening: the task’s own agent may simply be alive and idle, waiting for its user. Each preserve is logged as stuck_task.skipped_active_heartbeat with the liveness basis (livenessReason), the agent’s work state (idle, prompt_turn_active, runtime_work_active, or prompt_turn_unproven for a turn that has reported nothing past SESSION_ACTIVITY_STALE_THRESHOLD_MS, logged as a warning) with its ages, and, for an idle agent, whether a sleep is in flight to release it. One stuck_task_heartbeat_skip row per task and basis is kept in the observability database. Idle runtimes are released by automatic sleep, not by stuck-task recovery (apps/api/src/scheduled/stuck-task-live-runtime.ts).

A sleeping conversation is never failed. Sleeping is what deletes a workspace and destroys its node, so a slept session is indistinguishable from a dead one by those signals alone. Before any terminal verdict, recovery reads the chat session’s own session_snapshots row through the same predicate the wake path uses to authorize a restore (restorableOrInFlightSleepSnapshotPredicateSql in apps/api/src/services/session-snapshot-sleep-predicate.ts, via loadTaskSleepPreservation). A session that is asleep and restorable, or with a sleep capture still in flight, is preserved with no status change and no error message — a restorable one including past TASK_RUN_ABSOLUTE_CEILING_MS, because a released runtime holds no compute for the cost ceiling to bound. The preserve is bounded on both arms and cannot strand a task: the restorable arm expires with the snapshot’s own expires_at, and the in-flight arm with SESSION_SLEEP_IN_FLIGHT_MAX_AGE_MS after the sleep’s latest attempt. Because every retry renews that age, a sleep that is only in flight on still-allocated compute defers the ceiling for at most TASK_RUN_ABSOLUTE_CEILING_SLEEP_GRACE_MS, measured on runtime-generation age (evaluateRunawayCostCeiling in apps/api/src/scheduled/stuck-task-ceiling.ts); past it the ceiling terminalizes the task and the terminal gate does not re-defer to that sleep. Once either lapses, the ordinary liveness path terminalizes the task with its accurate reason. A failed snapshot read withholds the verdict until the next sweep.

Variable Default Description
NODE_AGENT_READY_TIMEOUT_MS 900000 (15 min) Wait for VM agent to report ready
NODE_AGENT_READY_POLL_INTERVAL_MS 5000 Poll interval for agent readiness
VM_AGENT_REQUIRED_VERSION (deploy-generated) Required vm-agent build for reusable VM nodes. Official deploys derive this from the last commit that changed a vm-agent build input, not from the deployment commit, so a Worker-only deploy does not make every running node ineligible for reuse. Build inputs are packages/vm-agent/** minus exactly four pathspecs — .claude/, the top-level AGENTS.md, **/*_test.go and *_test.go — so a commit touching only those deliberately leaves the release, and the node pool, untouched. Any other file under that directory rotates the release even if it reads as documentation; the resolver excludes rather than includes so that an unrecognised new file fails safe. Binaries are published under that immutable release key first, and cloud-init requests that exact release. Leave unset only for local/manual development or skip-agent deploys.
TASK_RUNNER_STEP_MAX_RETRIES 3 Max retries per TaskRunner step before failing the task
TASK_RUNNER_RETRY_BASE_DELAY_MS 5000 Base delay for TaskRunner retry backoff
TASK_RUNNER_RETRY_MAX_DELAY_MS 60000 Maximum delay for TaskRunner retry backoff
TASK_RUNNER_AGENT_POLL_INTERVAL_MS 5000 TaskRunner D1 poll interval while waiting for a newly provisioned or explicitly pinned booting VM agent
TASK_RUNNER_AGENT_READY_TIMEOUT_MS 900000 (15 min) TaskRunner max wait for a provisioned VM agent before failing the task
TASK_RUNNER_AGENT_READY_FRESHNESS_SKEW_MS 30000 Timestamp skew tolerated between TaskRunner wait start, node heartbeat, and /ready signals
TASK_RUNNER_WORKSPACE_DISPATCH_TIMEOUT_MS 600000 (10 min) Max wait for VM-agent workspace dispatch acknowledgement
TASK_RUNNER_WORKSPACE_DISPATCH_BASE_DELAY_MS 30000 Base delay for workspace dispatch retry backoff
TASK_RUNNER_WORKSPACE_DISPATCH_MAX_DELAY_MS 120000 (2 min) Maximum delay for workspace dispatch retry backoff
TASK_RUNNER_WORKSPACE_READY_TIMEOUT_MS 1800000 (30 min) Max time from the workspace build start to its ready callback. Time queued for the node’s build slot is governed by the operations.workspaceBuildQueueTimeoutMinutes admin setting
TASK_RUNNER_WORKSPACE_READY_POLL_INTERVAL_MS 30000 D1 poll interval during the TaskRunner workspace-ready step
TASK_RUNNER_PROVISION_POLL_INTERVAL_MS 10000 TaskRunner provision status poll interval
TASK_RUNNER_PROVISION_TIMEOUT_MS 900000 (15 min) Max time for TaskRunner node provisioning before permanent failure
PROVISIONING_TIMEOUT_MS 1800000 (30 min) Cron backstop: errors a creating workspace this long after its build started, or after the queue budget if it never started. Keep it at or above TASK_RUNNER_WORKSPACE_READY_TIMEOUT_MS
NODE_HEARTBEAT_STALE_SECONDS 180 Seconds without a heartbeat before a node is treated as stale

Each VM runs the SAM agent and the workspace containers side by side. systemd slices keep the agent from being starved by the work it is supervising: sam-infra.slice holds the agent, sam-workload.slice is Docker’s cgroup parent, and both sit under sam.slice.

Memory and CPU are protected differently on purpose. Memory exhaustion kills the agent, so it gets a hard reservation. CPU contention only slows it, so it gets a proportional share — which Linux applies only when something is actually competing, and therefore costs nothing on an idle machine.

Variable Default Description
SAM_INFRA_SLICE_MEMORY_MIN_MB 256 systemd MemoryMin reserved for the agent slice
VM_AGENT_MEMORY_RESERVE_MB (set by deployment) Memory held back from the workload slice’s MemoryMax, leaving headroom for the agent
SAM_INFRA_SLICE_CPU_WEIGHT 1000 systemd CPUWeight for the agent slice (cgroup v2 range 1–10000). Higher than the workload weight so a saturated node cannot delay the heartbeat and get the node declared dead
SAM_WORKLOAD_SLICE_CPU_WEIGHT 100 systemd CPUWeight for the Docker workload slice — the cgroup v2 default

An out-of-range weight makes the unit fail to load, which would take the slice hierarchy and its memory reservation down with it, so cloud-init generation rejects anything outside 1–10000 rather than emitting it.

Variable Default Description
DEPLOY_PAYLOAD_EXPIRY_SECONDS 3600 Signed deployment apply payload lifetime
DEPLOYMENT_ROUTE_PORT_BASE 35000 First node-local loopback port reserved for app routes
DEPLOYMENT_ROUTE_PORT_SPAN 100 Number of loopback ports reserved per deployment environment
AGENT_DEPLOYMENT_RESERVED_ENVIRONMENT_NAMES prod,production Comma-separated environment names agents cannot create through MCP
MAX_ENVIRONMENTS_PER_DEPLOYMENT_NODE 5 Maximum deployment environments to place on one deployment node
DEPLOYMENT_DEFAULT_VM_SIZE small Default VM size for deployment nodes
DEPLOYMENT_MODEL_RUNNER_VM_SIZE medium VM size for deployment nodes that need Docker Model Runner
DEPLOYMENT_DEFAULT_CPU_LIMIT_MILLIS 250 Per-service CPU reservation when the whole resource block is omitted
DEPLOYMENT_DEFAULT_MEMORY_LIMIT_MB 256 Per-service memory limit/reservation when the whole resource block is omitted
DEPLOYMENT_DEFAULT_ROOT_DISK_MB 1024 Per-service root-disk reservation used for deployment placement
DEPLOYMENT_LOG_MAX_SIZE 10m Default json-file log max-size for compose-publish releases
DEPLOYMENT_LOG_MAX_FILE 3 Default json-file log max-file for compose-publish releases
MCP_DEPLOYMENT_COMPOSE_PREVIEW_MAX_BYTES 128000 Max Compose YAML size accepted by deployment route preview MCP tool
BUILD_PUBLISH_TOOL_TIMEOUT_MS 1260000 Worker-to-VM proxy timeout for deployments_write method publish
DEPLOY_ACME_EMAIL (unset) Optional ACME contact email emitted into deployment-node Caddy config
DEPLOY_ACME_CA (unset) Optional ACME CA directory override, useful for Let’s Encrypt staging
DOH_RESOLVER_URL https://cloudflare-dns.com/dns-query DNS-over-HTTPS resolver used to verify deployment custom domains and email SPF lookup budgets
DOH_TIMEOUT_MS 10000 Timeout for deployment custom-domain and email SPF DNS lookups
DEPLOY_COMPOSE_CMD docker compose Docker Compose command used by the deployment engine
DEPLOY_HEALTH_TIMEOUT 5m Deployment health-check timeout used by the VM agent
DEPLOY_RUNTIME_TIMEOUT 15m VM-agent max time for deployment-node host dependency setup
GRACEFUL_SHUTDOWN_TIMEOUT 30s VM-agent max time for graceful HTTP server shutdown after SIGTERM
SYSTEM_PROVISIONING_TIMEOUT 15m VM-agent max time for workspace host provisioning before bootstrap
CF_IP_FETCH_TIMEOUT 10s VM-agent timeout for Cloudflare IP range fetches during provisioning
BOOT_LOG_HTTP_TIMEOUT 10s VM-agent timeout for boot-log callbacks to the control plane
MCP_SHORT_COMMAND_TIMEOUT 10s VM-agent timeout for short MCP workspace command probes
MCP_DIFF_COMMAND_TIMEOUT 30s VM-agent timeout for MCP diff-summary git commands
MCP_BUILD_PREPARE_TIMEOUT 30s VM-agent timeout for MCP build/publish preparation probes
JWKS_FETCH_TIMEOUT 10s VM-agent startup JWKS fetch timeout
ACP_CREDENTIAL_SYNC_TIMEOUT 10s VM-agent ACP auth-file sync-back timeout during shutdown
ACP_RESTART_ATTEMPT_TIMEOUT 5m VM-agent bound on one automatic ACP agent restart attempt
ACP_ACTIVITY_REPORT_TIMEOUT 10s VM-agent timeout for each ACP activity callback attempt
ACP_USAGE_PROBE_TIMEOUT 10s VM-agent bound on one post-turn provider usage probe (Codex rollout read or OpenCode Go usage request)
OPENCODE_GO_USAGE_URL https://opencode.ai/zen/go/v1/usage VM-agent OpenCode Go usage endpoint probed with the session’s key after each completed opencode-go turn Must be https unless the host is loopback (localhost, 127.0.0.1, ::1), because the probe sends the key as a bearer token; the probe never follows redirects.
DEVCONTAINER_CACHE_PUSH_TIMEOUT 10m VM-agent best-effort devcontainer cache image push timeout
DEPLOY_PREFLIGHT_COMMAND_TIMEOUT 15s VM-agent deployment preflight diagnostic command timeout
LOG_STREAM_PING_WRITE_TIMEOUT 10s VM-agent log-stream WebSocket ping write deadline
DEPLOY_TEARDOWN_TIMEOUT 2m VM-agent max time for deployment environment teardown (stop/start)
DEPLOY_APPLY_IDLE_TIMEOUT 15m VM-agent idle watchdog for deployment apply (no-progress only)
BUILD_CONTEXT_MAX_ACTIVE_PER_WORKSPACE 1 Agent process environment: concurrent context collections/uploads per workspace. Nonpositive values use the default. Excess probes fail immediately with 409; no queue or retry, and normal publishing continues.
BUILD_CONTEXT_CALLBACK_MAX_ATTEMPTS 3 Agent process environment: bounded init/complete callback attempts for transport failures, incomplete init responses and HTTP 502/503/504. Other failures, including 409, are not retried. Each attempt uses HTTP_CALLBACK_TIMEOUT within the overall publish deadline.
BUILD_CONTEXT_CALLBACK_RETRY_DELAY 5s Cancellable delay between context callback attempts. Nonpositive retry settings use defaults. Exact committed descriptors can be replayed without duplicate transitions; canceled/terminal jobs remain rejected.
DEPLOY_BUILD_PUBLISH_TIMEOUT 20m VM-agent max time for host build + push + release publish
DEPLOY_PUBLISH_HEARTBEAT_INTERVAL 1m Publish executor heartbeat interval. Legacy agents are deadline-only; keep overrides well below the API stall threshold (minimum 150 seconds: two default intervals plus callback grace).
DEPLOY_ARTIFACT_DIAL_TIMEOUT 30s VM-agent TCP dial timeout for artifact downloads
DEPLOY_ARTIFACT_TLS_HANDSHAKE_TIMEOUT 15s VM-agent TLS handshake timeout for artifact downloads
DEPLOY_ARTIFACT_RESPONSE_HEADER_TIMEOUT 60s VM-agent first-response-header timeout for artifact downloads
DEPLOY_ARTIFACT_IDLE_TIMEOUT 2m VM-agent idle watchdog for artifact body-read progress
DEFAULT_RESOURCE_EVENT_BUFFER_SIZE 64 Capacity of each bounded pressure/Docker event queue; positive integer
DEFAULT_PSI_POLL_INTERVAL_SECONDS 10 Linux memory PSI sampling interval, in seconds
DEFAULT_CONTAINER_STATS_INTERVAL_SECONDS 30 Docker resource statistics sampling interval, in seconds
DEFAULT_PSI_MEMORY_SOME_WARNING_THRESHOLD 25 Warning threshold for the maximum PSI some-memory avg10/avg60 percentage
DEFAULT_PSI_MEMORY_SOME_CRITICAL_THRESHOLD 50 Critical threshold for the maximum PSI some-memory avg10/avg60 percentage
DEFAULT_PSI_MEMORY_FULL_WARNING_THRESHOLD 10 Warning threshold for the maximum PSI full-memory avg10/avg60 percentage
DEFAULT_PSI_MEMORY_FULL_CRITICAL_THRESHOLD 25 Critical threshold for the maximum PSI full-memory avg10/avg60 percentage
DEFAULT_EVICTION_DEBOUNCE_SECONDS 30 Minimum cooldown between ResourceGuard eviction attempts
DEFAULT_EVICTION_SNAPSHOT_TIMEOUT_SECONDS 120 VM-agent pre-stop ResourceGuard eviction snapshot deadline
DEFAULT_EVICTION_DOCKER_STOP_TIMEOUT_SECONDS 10 Grace period passed to docker stop --time during ResourceGuard eviction
DEFAULT_EVICTION_CALLBACK_RETRY_MAX_SECONDS 300 Backoff cap for durable eviction callback retries, in seconds; the operation lease is a lower bound and can exceed this cap. Delivery starts on a later heartbeat
DEFAULT_EVICTION_RESOLVE_TIMEOUT_SECONDS 5 Docker label resolution deadline before ResourceGuard eviction
EVICTION_FINAL_SNAPSHOT_TIMEOUT_SECONDS 300 VM-agent deadline for the post-stop final eviction capture; on timeout the pre-stop capture is kept
EVICTION_PARK_TIMEOUT 15m VM-agent bound on how long an eviction owns an agent exit before ordinary crash handling resumes (Go duration). Must be strictly greater than the combined stop, final capture and recording budgets; see the formula below.
SNAPSHOT_HELPER_MEMORY_LIMIT 1g docker --memory for a stopped-workspace snapshot helper; zero is rejected
SNAPSHOT_HELPER_PIDS_LIMIT 256 docker --pids-limit for a stopped-workspace snapshot helper
SNAPSHOT_HELPER_MIN_FREE_BYTES 1073741824 Free space kept on the Docker root after committing a source’s writable layer for a helper
RESOURCE_HISTORY_SAMPLE_INTERVAL 5s VM-agent retained resource-history cgroup sampling cadence
RESOURCE_HISTORY_CHUNK_INTERVAL 15m VM-agent retained resource-history chunk duration before upload
RESOURCE_HISTORY_SPOOL_DIR /var/lib/vm-agent/resource-history Node-local retry spool for resource-history chunks
RESOURCE_HISTORY_SPOOL_MAX_BYTES 20971520 Max node-local resource-history retry spool bytes
RESOURCE_HISTORY_UPLOAD_TIMEOUT 10s VM-agent deadline for one resource-history upload callback
RESOURCE_HISTORY_MAX_SAMPLES 4096 Max resource samples packed into one uploaded chunk

EVICTION_PARK_TIMEOUT must be strictly greater than 2.5 × DEFAULT_EVICTION_DOCKER_STOP_TIMEOUT_SECONDS + EVICTION_FINAL_SNAPSHOT_TIMEOUT_SECONDS + SESSION_SNAPSHOT_PROGRESS_REPORT_TIMEOUT + HTTP_CALLBACK_TIMEOUT (with all durations expressed in the same units). The stop budget includes the command deadline and its wait delay; the final-capture failure report has its own timeout. With the defaults, the combined budget is 360s (25s + 300s + 5s + 30s), so parking must exceed 360s; the default 15m does. Invalid combinations are rejected when the agent loads or validates its configuration. Zero parking uses the default; negative parking is rejected.

Variable Default Description
MAX_NODES_PER_USER 10 Max nodes per user
TASK_RUN_NODE_CPU_SHARE_BUDGET_PERCENT 100 CPU millicore share budget per node for aggregate workspace reservations
TASK_RUN_NODE_HOST_MEMORY_RESERVE_MB 1024 Memory reserved for the host/VM agent; offering selection, admission and the workload-slice cap all subtract it
TASK_RUN_NODE_DISK_PRESSURE_THRESHOLD_PERCENT 80 Fresh node disk telemetry at or above this percent vetoes new VM workspace and deployment admission
TASK_RUN_NODE_METRICS_TTL_MS 180000 Freshness window for occupied-node resource telemetry
TASK_RUN_NODE_CPU_SCORE_WEIGHT_PERCENT 40 CPU weight in existing-node load scoring after load average is normalized by vCPU
TASK_RUN_NODE_MEMORY_SCORE_WEIGHT_PERCENT 60 Memory weight in existing-node load scoring
VM_ADMISSION_CONTROL_MODE enforce VM task/session admission mode: off, shadow, or enforce
VM_ADMISSION_LEASE_TTL_MS 1200000 (20 min) Fenced provisioning-claim lease duration
VM_ADMISSION_RETRY_MIN_MS 15000 Minimum retry delay for tasks waiting on VM capacity
VM_ADMISSION_RETRY_MAX_MS 60000 Maximum retry delay for tasks waiting on VM capacity
VM_ADMISSION_WAIT_TIMEOUT_MS 7200000 (2 h) Maximum visible wait for VM capacity before failing the task
VM_ADMISSION_PROVIDER_COOLDOWN_MS 600000 (10 min) Cooldown after provider/account capacity errors such as Hetzner server limits
VM_ADMISSION_WAKE_BATCH_SIZE 25 Maximum waiting TaskRunner DOs nudged by one capacity event
VM_ADMISSION_DIAGNOSTIC_MESSAGE_MAX_LENGTH 500 Maximum provider diagnostic message length stored on admission records
MAX_AGENT_SESSIONS_PER_WORKSPACE 10 Max concurrent agent sessions
MAX_PROJECTS_PER_USER 100 Max projects per user
MAX_TASKS_PER_PROJECT 10000 Max ideas per project
MAX_TASK_MESSAGE_LENGTH 16000 Max task description and reserved prompt length
RESERVED_TASK_BRANCH_NAME_SEED_MAX_LENGTH 512 Max branch-name seed characters accepted by reserved task submissions
RESERVED_TASK_SOURCE_DISPLAY_NAME_MAX_LENGTH 512 Max source display-name characters accepted by reserved task submissions
RESERVED_TASK_REPOSITORY_ACCESS_FLOW_MAX_LENGTH 512 Max repository-access audit flow characters accepted by reserved submissions
RESERVED_TASK_INITIAL_STATUS_REASON_MAX_LENGTH 1024 Max initial status reason characters accepted by reserved task submissions
RATE_LIMIT_CALLBACK_TOKEN_RENEWAL 12 Workspace callback-token renewals accepted per workspace in each window; past it the renewal route answers 429 with Retry-After
RATE_LIMIT_CALLBACK_TOKEN_RENEWAL_WINDOW_SECONDS 3600 Window for RATE_LIMIT_CALLBACK_TOKEN_RENEWAL
Variable Default Description
MAX_SESSIONS_PER_PROJECT 10000 Max chat sessions per project
MAX_MESSAGES_PER_SESSION 100000 Max messages per chat session
COMMENT_BODY_MAX_LENGTH 8000 Max characters per message-anchored comment or reply body
COMMENT_QUOTE_MAX_LENGTH 2000 Max characters preserved from quoted message text
COMMENT_IDEMPOTENCY_KEY_MAX_LENGTH 200 Max clientMutationId length for message-anchored comment writes
COMMENT_LIST_LIMIT_DEFAULT 100 Default page size for comment thread lists
COMMENT_LIST_LIMIT_MAX 500 Max page size for comment thread lists
COMMENT_THREADS_PER_SESSION_MAX 1000 Max message-anchored comment threads per chat session
COMMENT_REPLIES_PER_THREAD_MAX 200 Max replies per message-anchored comment thread
PROJECT_COMMENT_LIST_LIMIT 100 Page size for the project-wide comment inbox
PROJECT_COMMENT_LIST_MAX 300 Max page size for the project-wide comment inbox
PROJECT_COMMENT_LIST_MAX_BYTES 4000000 Byte budget for one project-wide comment inbox response, so a few very long threads cannot exhaust the Durable Object RPC limit
DOCUMENT_CARD_RAW_OUTPUT_MAX_BYTES 16384 Max compact metadata bytes preserved for library document cards
PROJECT_DATA_TOOL_METADATA_MAX_BYTES 131072 Max stored tool_metadata bytes per message before oversized tool content is stripped into bounded metadata
PROJECT_DATA_STORAGE_TELEMETRY_ENABLED true Enables ProjectData databaseSize alarm measurement and D1 telemetry writes
PROJECT_DATA_STORAGE_LIMIT_BYTES 10000000000 Cloudflare SQLite-backed Durable Object storage limit used for ProjectData usage classification
PROJECT_DATA_STORAGE_MEASURE_INTERVAL_MS 3600000 Interval between full per-object ProjectData storage measurements. Each one appends a telemetry history row and evaluates the storage alerts; cleanup passes publish the latest size but never postpone it (measureAndPersistProjectDataStorage)
PROJECT_DATA_STORAGE_ALERT_INTERVAL_MS 21600000 Minimum interval between repeated ProjectData storage observability alerts of the same kind and status. Threshold (warning/critical/degraded) and cleanup-target-unreachable alerts are throttled separately (maybePersistProjectDataStorageAlert)
PROJECT_DATA_STORAGE_NOTICE_RATIO 0.6 ProjectData storage usage ratio classified as notice
PROJECT_DATA_STORAGE_WARNING_RATIO 0.8 ProjectData storage usage ratio classified as warning
PROJECT_DATA_STORAGE_CRITICAL_RATIO 0.9 ProjectData storage usage ratio classified as critical
PROJECT_DATA_STORAGE_DEGRADED_RATIO 0.95 ProjectData storage usage ratio classified as degraded
PROJECT_DATA_STORAGE_EMERGENCY_TARGET_RATIO 0.9 Target usage ratio for explicit superadmin ProjectData emergency purge calls
PROJECT_DATA_STORAGE_EMERGENCY_BATCH_ROWS 500 Oldest activity_events and acp_session_events rows deleted per table per emergency purge batch
PROJECT_DATA_STORAGE_EMERGENCY_MAX_BATCHES 4 Maximum emergency purge batches per explicit call
PROJECT_DATA_STORAGE_GROWTH_LOOKBACK_DAYS 7 Lookback window used to estimate ProjectData bytes/day growth and days to storage limit
PROJECT_DATA_STORAGE_TELEMETRY_LIST_LIMIT_DEFAULT 50 Default row count for admin ProjectData storage telemetry and history lists
PROJECT_DATA_STORAGE_TELEMETRY_LIST_LIMIT_MAX 200 Max accepted row count for admin ProjectData storage telemetry and history lists
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_ENABLED true Enables automatic ProjectData cleanup that archives expandable tool_metadata.content payloads to private R2 before stripping them from old message rows. NOT sufficient on its own: setting PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_CUTOFF_CREATED_AT arms the stricter approved-manifest plan, which additionally requires _PLAN_ID, _MANIFEST_KEY, _MANIFEST_SHA256 and all four _MAX_TOTAL_* ceilings. With the cutoff set and any of those blank, cleanup is enabled but builds no plan; the refusal is logged as project_data.tool_payload_cleanup.config_refused with the unmet field names.
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_PLAN_ID (empty) Immutable operator plan identifier; required with a fixed cleanup cutoff and persisted with continuation state to reject configuration drift
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MANIFEST_KEY (empty) Immutable R2 root key for the verified row-level target manifest; required with a fixed cleanup cutoff
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MANIFEST_SHA256 (empty) Expected SHA-256 of the approved target-manifest root; required with a fixed cleanup cutoff
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_BATCH_MANIFEST_MAX_BYTES 2000000 Verified approved-plan batch-manifest read/write ceiling; included in the immutable exact-plan fingerprint
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_ROOT_MANIFEST_MAX_BYTES 1000000 Verified approved-plan root-manifest read/write ceiling; included in the immutable exact-plan fingerprint
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_TOTAL_ROWS (empty) Hard cumulative approved target-row ceiling; required with a fixed cleanup cutoff
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_TOTAL_BYTES (empty) Hard cumulative approved projected-reclaim ceiling; required with a fixed cleanup cutoff
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_TOTAL_R2_OPERATIONS (empty) Hard cumulative R2 operation ceiling including manifest verification; exact execution transactionally charges the full per-pass allowance before external work and never refunds it
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_TOTAL_WALL_TIME_MS (empty) Hard cumulative cleanup wall-time ceiling; exact execution transactionally charges the full per-pass allowance before external work and never refunds it
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_PROJECT_IDS (empty) Optional comma-separated project allowlist for automatic cleanup; empty preserves cleanup eligibility for every project, while an emergency rollout can scope elevated budgets to exact projects. One variable, two meanings — see the note below
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_CUTOFF_CREATED_AT (empty) Optional fixed exclusive tool-message cutoff in epoch milliseconds; when set, the immutable verified manifest, cumulative ceilings, plan ID, and exactly one allowlisted project are required; invalid values fail closed
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_TRIGGER_RATIO 0.8 ProjectData storage usage ratio that starts automatic tool payload archival cleanup even before the retention cadence is due
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_TARGET_RATIO 0.75 ProjectData storage usage ratio below which automatic tool payload cleanup stops
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_BATCH_ROWS 500 Maximum eligible tool-message candidates processed by one automatic cleanup alarm batch; ordinary selection may examine a larger physical row window bounded by PROJECT_DATA_STORAGE_RELIEF_MEASURE_MAX_BATCH_ROWS
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_BATCH_BYTES 2097152 Legacy tool_metadata read budget per automatic pass; an ordinary retention pass may admit its first oversized candidate up to the archive metadata ceiling, while a fixed exact plan requires its row ceiling to fit this budget
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_ROW_BYTES 1048576 Maximum single legacy tool_metadata row bytes read into JS by archival cleanup; larger rows fail closed unless the operator deliberately raises this limit
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MIN_SESSION_AGE_DAYS 7 Legacy terminal-session age guard retained for storage telemetry compatibility; tool payload archival uses PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_RETENTION_DAYS
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_RECHECK_MS 86400000 Delay before the next automatic cleanup alarm batch when more candidates remain; daily by default
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_MAX_SESSIONS_PER_ALARM 25 Deprecated legacy terminal-session cleanup knob retained for env compatibility; archival cleanup scans tool-message rows directly and is bounded by rows, bytes, and wall time instead
PROJECT_DATA_TOOL_PAYLOAD_CLEANUP_WALL_TIME_MS 20000 Absolute wall-clock deadline shared by candidate processing and every R2 write/read-back operation in one cleanup pass
PROJECT_DATA_TOOL_PAYLOAD_MANUAL_CLEANUP_MAX_BATCH_ROWS 500 Hard row cap for one explicit superadmin manual ProjectData tool payload archival cleanup pass
PROJECT_DATA_TOOL_PAYLOAD_MANUAL_CLEANUP_MAX_BATCH_BYTES 2097152 Maximum configurable legacy tool_metadata read budget for one explicit manual pass; the ordinary-path first-row exception applies unless a fixed exact plan binds the row ceiling within this budget
PROJECT_DATA_TOOL_PAYLOAD_MANUAL_CLEANUP_MAX_WALL_TIME_MS 20000 Hard wall-clock cap for one explicit manual cleanup pass
PROJECT_DATA_TOOL_PAYLOAD_MANUAL_CLEANUP_RECHECK_MS 86400000 Persisted project-scoped cooldown after an explicit manual cleanup pass; daily by default
PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_RETENTION_DAYS 5 Message age before expandable tool payload JSON may be archived to private R2 and stripped from the ProjectData DO
PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_INTERVAL_MS 86400000 Cadence for the retention-driven ProjectData tool payload archival scan
PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_R2_PREFIX project-data/tool-payloads Private R2 prefix used for archived ProjectData tool payload JSON objects
PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_WRITE_TIMEOUT_MS 5000 Per-R2 write/read-back verification timeout for automatic archival cleanup; timeout leaves the original payload in ProjectData and defers retry
PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_MAX_OPERATIONS 1500 Maximum R2 PUT, GET, and body-read operations reserved by one cleanup pass
PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_RETRY_DELAY_MS 300000 Row-level retry deferral after retryable archive/write failures
PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_CHUNK_BYTES 524288 R2 chunk size used when archiving legacy tool payload metadata larger than one archive object slice
PROJECT_DATA_TOOL_PAYLOAD_ARCHIVE_MAX_METADATA_BYTES 1900000 Absolute bounded read cap for legacy oversized tool payload metadata; larger rows fail closed and remain in ProjectData
PROJECT_DATA_STORAGE_RELIEF_MEASURE_BATCH_ROWS 500 Default row budget for superadmin ProjectData relief measurement slices
PROJECT_DATA_STORAGE_RELIEF_MEASURE_MAX_BATCH_ROWS 5000 Maximum physical row window accepted for superadmin/preflight relief measurements and examined by one ordinary cleanup candidate-selection slice
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_ENABLED false Enables the scheduled, read-only, fixed-cutoff ProjectData tool-payload relief preflight; requires the exact plan, project, and cutoff variables below
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_PLAN_ID (empty) Immutable operator plan identifier used to resume one preflight without mixing evidence from another run
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_PROJECT_ID (empty) Exact ProjectData project targeted by the enabled preflight
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_CUTOFF_CREATED_AT (empty) Fixed exclusive tool-message creation cutoff in epoch milliseconds; required while preflight is enabled
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_BATCH_ROWS 5000 Maximum physical chat_messages rowid window examined by one preflight slice before eligibility filtering
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_INTERVAL_MS 300000 Persisted minimum interval between preflight slices
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MAX_BATCHES 100 Overall claimed-attempt ceiling; an incomplete successful scan becomes truncated at the ceiling, while the final failed attempt becomes failed
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MAX_ROWS 500000 Overall physical chat_messages rows-examined ceiling for one preflight plan before eligibility filtering
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MAX_BYTES 2000000000 Overall projected net reclaimable-byte evidence ceiling for one preflight plan
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_LEASE_MS 60000 D1 claim lease that prevents overlapping slices; must exceed the wall-time budget by the configured lease margin
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_WALL_TIME_MS 20000 Absolute per-slice deadline shared by bounded ProjectData measurement and verified R2 manifest writes/read-backs; failures retain the prior cursor and fail closed for retry
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_SLICES_PER_RUN 1 Maximum sequential, separately leased slices in one scheduled invocation; later slices bypass only that invocation’s persisted cadence
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_RUN_WALL_TIME_MS 25000 Aggregate invocation admission budget used to decide whether another full sequential slice can start; must exceed the per-slice wall-time budget by the return margin
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_LEASE_MARGIN_MS 5000 Required lease headroom above the per-slice wall-time budget
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_RETURN_MARGIN_MS 500 Required return headroom inside measurement, slice, and aggregate run budgets
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MEASUREMENT_WALL_TIME_MS 10000 Explicit ProjectData measurement budget inside one slice; plus the return margin it must not exceed the slice wall budget
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_MAX_STATE_BYTES 1750000 Combined D1 JSON byte ceiling for accumulated session and target-batch proof state in one preflight row
PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_ERROR_MAX_LENGTH 1000 Character ceiling for a persisted preflight failure diagnostic
PROJECT_DATA_ARCHIVE_SHARDING_ENABLED false Feature switch for exact archive read routing. It is disabled when unset; enabling it alone does not run the unscoped scheduled sweep
PROJECT_DATA_ARCHIVE_GLOBAL_SWEEP_ENABLED false Separate feature switch for the unscoped scheduled archive-sharding sweep. It is disabled when unset; scheduled global migration also requires exact archive routing to be enabled
PROJECT_DATA_ARCHIVE_GLOBAL_SWEEP_INTERVAL_MS 86400000 Persisted cadence gate for unscoped scheduled archive-sharding sweeps; the five-minute handler claims the cadence row only when due. Code fallback is daily; the checked-in wrangler.toml ships 540000 (9 min), normally claiming every second five-minute tick (~10 min; timing jitter can defer a claim). A claim migrates sessions within the PROJECT_DATA_ARCHIVE_WALL_TIME_MS per-tick bound (shipped 60000, checked between candidates and inside migrations) and PROJECT_DATA_ARCHIVE_SWEEP_SESSIONS, with compact migrations subject to the daily reservation budget (legacy migrations reserve nothing, so a zero allowance does not stop legacy sweeps). Roughly 144 claims/day targets ~72k copied rows/hour at the measured ~12k rows/tick, versus ~36k/hour at the previous 18-minute interval (~20-minute ticks). Refused, failed or budget-limited claims publish nothing
PROJECT_DATA_ARCHIVE_SHARD_COUNT 128 Deterministic archive-shard fanout used when assigning terminal sessions to ProjectData archive Durable Objects
PROJECT_DATA_ARCHIVE_SWEEP_PROJECTS 1 Maximum projects selected by one archive-sharding cron pass
PROJECT_DATA_ARCHIVE_SWEEP_SESSIONS 10 Most sessions one archive-sharding pass may copy (in-flight plus new candidates); candidates refused by the write budget or by the root object take no slot. The checked-in wrangler.toml ships 50, a safety cap that PROJECT_DATA_ARCHIVE_WALL_TIME_MS reaches first
PROJECT_DATA_ARCHIVE_SWEEP_MESSAGE_BUDGET 20000 Cumulative message_count the operator-scoped canary packs into one run, and its SQL ceiling for unnamed sessions. The unscoped sweep does not use it: since the resumable cursor its only per-session selection limit is the ceiling derived from the daily write budget (resolveSweepAffordability). The checked-in wrangler.toml ships 10000
PROJECT_DATA_ARCHIVE_SESSION_GRACE_MS 604800000 Minimum terminal-session age before archive-sharding may consider a session
PROJECT_DATA_ARCHIVE_PRECOPY_REFUSAL_RETRY_MS 86400000 How long a session the root object refused at prepare (pre-copy invariant, e.g. active_session_state) stays out of unscoped sweep selection; journal frozen/precopy_refused, location back at root; a named-session canary bypasses it
PROJECT_DATA_ARCHIVE_FAILED_RETRY_DELAY_MS 3600000 Minimum age of a failed archive journal before an unscoped sweep reclaims it, so PROJECT_DATA_ARCHIVE_POISON_AFTER_ATTEMPTS spans hours rather than consecutive cadence ticks; 0 disables it and a named-session canary bypasses it
PROJECT_DATA_ARCHIVE_CHUNK_ROWS 500 Maximum rows exported in one idempotent transcript archive chunk
PROJECT_DATA_ARCHIVE_CHUNK_BYTES 16777216 Maximum bytes exported in one archive chunk; clamped below Cloudflare’s 32MiB RPC ceiling
PROJECT_DATA_ARCHIVE_HASH_PAGE_ROWS 500 Rows read per statement while streaming a session’s terminal-version hash inside the ProjectData Durable Object; bounds object memory by page size instead of session size
PROJECT_DATA_ARCHIVE_LEASE_MS 300000 D1 CAS journal lease duration for archive-sharding work. Renewed at chunk, verification-page and phase boundaries once less than half remains (renewLeaseIfDue), and released when a migration pauses at the tick deadline
PROJECT_DATA_ARCHIVE_WALL_TIME_MS 5000 Wall-clock deadline for one archive-sharding cron pass, checked between candidates and inside a migration: a migration that has advanced pauses at the next copy chunk, R2 verification page or phase boundary and the next pass resumes it, so a pass runs up to this plus one in-flight RPC (the longest is an R2 verification page, bounded by PROJECT_DATA_ARCHIVE_R2_TIMEOUT_MS; the flip is an O(1) write-generation check). Code fallback 5 s; the checked-in wrangler.toml ships 60000 (about 6 small sessions or ~5k messages per pass)
PROJECT_DATA_ARCHIVE_ROLLOUT_LIST_LIMIT_DEFAULT 25 Default row limit for superadmin archive-sharding rollout inspection and failed/poisoned/frozen migration list endpoints
PROJECT_DATA_ARCHIVE_ROLLOUT_LIST_LIMIT_MAX 100 Maximum accepted row limit for D1-only superadmin archive-sharding rollout inspection endpoints. Frozen-intent DO inspection is capped separately.
PROJECT_DATA_ARCHIVE_FROZEN_INTENT_INSPECTION_LIMIT_DEFAULT 5 Default row limit for GET /archive-sharding/frozen-intents; each row may perform source and target ProjectData DO RPCs, so this endpoint intentionally has a smaller hot-object fan-out budget
PROJECT_DATA_ARCHIVE_FROZEN_INTENT_INSPECTION_LIMIT_MAX 10 Maximum accepted frozen-intent detail inspection limit; configured values above 10 are clamped to the reviewed hot-DO fan-out ceiling and request limits above the configured max are rejected
PROJECT_DATA_ARCHIVE_MANUAL_CANARY_MAX_SESSIONS 5 Maximum sessions a superadmin scoped manual archive-sharding canary request may select; default requests select one session and dry-run by default
PROJECT_DATA_ARCHIVE_MANUAL_CANARY_MAX_WALL_TIME_MS 15000 Maximum wall-clock budget accepted by the superadmin scoped manual archive-sharding canary endpoint
PROJECT_DATA_ARCHIVE_ROLLOUT_WARNING_EXAMPLES_MAX 5 Maximum malformed-row warning examples returned by archive rollout read/list endpoints
PROJECT_DATA_ARCHIVE_ROLLOUT_WARNING_REASON_MAX_LENGTH 300 Maximum characters per malformed-row warning reason returned by archive rollout read/list endpoints
PROJECT_DATA_ARCHIVE_POISON_AFTER_ATTEMPTS 3 Consecutive claims that fail without moving the migration forward before it is poisoned and the project circuit breaker opens. A claim that advanced (copied a chunk, verified a page, crossed a phase) and then failed keeps its phase, resets the count and resumes on the next pass, so a large session spanning many passes is not poisoned by an unrelated transient failure. Each opening sends every active superadmin one Operational Failure notification and records one /admin/errors entry (alertProjectDataArchiveBreakerOpened)
PROJECT_DATA_ARCHIVE_R2_PREFIX project-data/session-archives Private R2 prefix for terminal-session archive recovery chunks and manifests
PROJECT_DATA_ARCHIVE_SEARCH_MAX_OWNERS 4 Archive-shard owner batch size for one project-wide message-search continuation (maximum 64; invalid/out-of-range values use 4); callers continue until coverage is complete
PROJECT_DATA_ARCHIVE_SEARCH_CONCURRENCY 4 Concurrent archive-owner queries in one batch (maximum 16; invalid/out-of-range values use 4)
PROJECT_DATA_ARCHIVE_SEARCH_REPAIR_SESSIONS 1 Incomplete published archive sessions advanced per owner query (maximum 16); remaining repair stays explicit and resumable
PROJECT_DATA_ARCHIVE_SEARCH_REPAIR_CHUNKS 1 Immutable compact R2 chunks consumed per session repair step (maximum 64)
PROJECT_DATA_ARCHIVE_SEARCH_CONTINUATION_TTL_MS 900000 Lifetime of a signed, query-bound complete-history continuation (maximum 24 hours)
PROJECT_DATA_ARCHIVE_SEARCH_CURSOR_MAX_BYTES 1048576 Maximum continuation bytes accepted before decoding or emitted after signing (maximum 4 MiB)
PROJECT_DATA_ARCHIVE_SEARCH_ERROR_LIMIT 20 Maximum entries retained independently in each public execution- and index-error collection (maximum 100); full details remain in server logs
PROJECT_DATA_SEARCH_FTS_CANDIDATE_LIMIT 2000 Newest full-text matches ranked per ProjectData message search; when more match, results report rootSearch.ftsCandidatesTruncated
PROJECT_DATA_SEARCH_FTS_SCAN_LIMIT 20000 Full-text index entries inside a session’s rowid span that a session-scoped search examines, newest first, to collect that session’s newest matches; never smaller than PROJECT_DATA_SEARCH_FTS_CANDIDATE_LIMIT
PROJECT_DATA_SEARCH_KEYWORD_SCAN_ROW_LIMIT 50000 Newest raw messages the keyword fallback scans for not-yet-indexed text; older rows are reported as rootSearch.keywordScanTruncated
PROJECT_DATA_ALARM_SECTION_GATING_ENABLED true Run only the ProjectData alarm sections that are due each tick; false runs every section every tick
PROJECT_DATA_ALARM_FULL_RUN_INTERVAL_MS 900000 Maximum interval between ProjectData alarm ticks that run every section regardless of due times
PROJECT_DATA_ALARM_DUE_TOLERANCE_MS 2000 A ProjectData alarm section due within this many ms of the tick runs in that tick
PROJECT_DATA_ALARM_SLOW_SECTION_MS 1000 ProjectData alarm sections at or above this wall time log project_data.alarm.section_slow
WORKSPACE_RESOURCE_RAW_RETENTION_DAYS 90 Retention for immutable raw resource-history gzip chunks in the private archive R2 binding
WORKSPACE_RESOURCE_SUMMARY_RETENTION_DAYS 180 Retention for bounded D1 workspace resource summary rows
WORKSPACE_RESOURCE_UNCOMPRESSED_MAX_BYTES 8388608 Max decoded resource chunk JSON bytes accepted/read before rejecting detail payloads
WORKSPACE_RESOURCE_METADATA_MAX_BYTES 8192 Max summary or completeness JSON bytes stored in D1 for one resource chunk/summary
WORKSPACE_RESOURCE_TOOL_NAME_MAX_BYTES 256 Max UTF-8 bytes retained and returned for one resource-history tool name; longer metadata names are truncated at a complete Unicode character
WORKSPACE_RESOURCE_UPLOAD_MAX_BYTES 2097152 Max compressed resource-history chunk bytes accepted by the callback upload route
WORKSPACE_RESOURCE_DETAIL_MAX_POINTS 720 Max samples returned by one raw detail read after spike-preserving downsampling
WORKSPACE_RESOURCE_LIST_LIMIT 24 Max resource-history chunk index rows returned for one contextual read
WORKSPACE_RESOURCE_TIMELINE_MAX_CHUNKS 1000 Max chunks the session resource timeline lists; the oldest beyond it are left out and disclosed as omittedChunkCount
WORKSPACE_RESOURCE_ROLLUP_BUCKET_MS 60000 Width of each per-chunk rollup bucket computed on upload
WORKSPACE_RESOURCE_ROLLUP_MAX_BUCKETS 60 Max rollup buckets stored per chunk; the bucket width widens in whole multiples to fit
WORKSPACE_RESOURCE_CLEANUP_BATCH_SIZE 50 Max expired resource-history chunks and summaries processed per scheduled cleanup sweep
WORKSPACE_RESOURCE_OBJECT_CLEANUP_LIMIT 5000 Max resource-history R2 objects deleted when a project or workspace is deleted; deletion paginates until the prefix is empty or this safety budget is reached

A completed fixed tool-payload plan writes an explicit terminal marker rather than an indefinite timestamp. Later alarm or manual entry points no-op after validating the same immutable fingerprint. A different fingerprint also fails closed; there is deliberately no automatic reset or supersession, so an emergency runbook must include a reviewed follow-up reset before ordinary cleanup is expected to resume.

Archive-sharding rollout is deliberately staged. The scheduled coordinator in packages/project-data/src/scheduled/project-data-archive-sharding.ts still does no work unless PROJECT_DATA_ARCHIVE_GLOBAL_SWEEP_ENABLED=true and exact archive routing is active through PROJECT_DATA_ARCHIVE_SHARDING_ENABLED=true. Both switches are ordinary Worker [vars]: a GitHub Environment variable of the same name replaces the checked-in wrangler.toml value at deploy time, and the deploy log prints every such override that differs from wrangler.toml. When the sweep is enabled, each cron.completed log carries projectDataArchiveShardingSkipReason (disabled, exact_routing_disabled, missing_r2_binding, cadence_not_due, cadence_running, cadence_unavailable) or the tick’s selected/migrated/refused/failed counts. A session the root object refuses before any copy (for example one that still holds an active session_state row) is returned to root in the same tick with a frozen/precopy_refused journal and is skipped by the sweep for PROJECT_DATA_ARCHIVE_PRECOPY_REFUSAL_RETRY_MS.

The unscoped sweep selects sessions only from projects under storage pressure (STORAGE_PRESSURE_GATE_SQL, projectDataArchiveCandidateSql()): the project’s last project_data_storage_telemetry row must report a usage_ratio at or above the admin setting operations.projectDataArchiveMinStorageUsagePercent (default 50, 0 turns the gate off). A project with no telemetry row, or one older than operations.projectDataArchiveStorageTelemetryMaxAgeHours (default 24), stays eligible. The gate reads only the stored row and its age, so with PROJECT_DATA_STORAGE_TELEMETRY_ENABLED=false it holds nothing once the rows already stored have passed that age. In-flight migrations, pending reclaim and the operator-scoped canary are not gated. Each cron.completed log carries projectDataArchiveShardingStoragePressureMinUsageRatio and the ...StoragePressureHeldSessions/HeldProjects/HeldMessages counts of what the gate left in root (null when the count query failed). See Archiving ended chats.

The shipped cadence (540000, 9 minutes, rounded to about 10 minutes by the five-minute cron) and per-tick wall bound (60000, 60 seconds) target about 72k copied raw rows/hour, compared with the measured 36k/hour at the previous 18-minute interval (~20-minute ticks). Excluding inflow, 4.75M rows take about 66 hours (2.75 days) versus 132 hours (5.50 days). The global sweep resumes within sessions; its message budget is only a scoped-canary packing limit. The 6M daily reservation ceiling covers the measured fixture’s ~5.33M units/day at that target with ~12.6% headroom. Reservations are not billed rows: measured 1.38 (partial production phases) to 2.57 (full fixture) writes/raw row imply ~2.4M-4.4M writes/day for under three days. For comparison, if billed writes equalled reservation units, 6M would cost about $6/day at $1/M, $3.60/day above 2.4M. This is a ceiling-equivalent illustration, not a measured billing cap; the measured write range above implies about $2.4-$4.4/day. D1, R2 and compute costs are separate. Cost per archived row does not change with cadence. Idle ticks cost two D1 statements. The sweep runs after every lifecycle sweep in the cron chain so that budget cannot delay them. failed journals wait PROJECT_DATA_ARCHIVE_FAILED_RETRY_DELAY_MS before a sweep retries them, so the three-attempt poison budget still spans hours at the shorter cadence. The frozen-intent inspection route skips precopy_refused rows (nothing exists on either object to inspect) and the problem-migrations list sorts them after rows that need a human. Before changing the global sweep switch, operators use the superadmin routes in apps/api/src/routes/admin/project-data-storage.ts to inspect one project’s D1 journal/location/breaker state and run a scoped dry-run canary for a specific project and optional session. Dry-runs work while both rollout switches are false and never call source deletion RPCs. Non-dry scoped canaries fail closed unless exact archive routing is active, because publishing or deleting source rows while exact reads still resolve to root can render conversations empty. Failed, poisoned, or frozen rows are inspected through the frozen-intent route (and listed under Admin → Storage → Problem migrations). A migration that never reached source deletion is cleared with Abandon (the page’s button, or POST .../migrations/:migrationId/abandon); one past source deletion is recovered through the copy-back helper with exact archive routing enabled. While a copy-back is restoring rows, reclaim is fenced off that session (do_meta key archive_copy_back_in_progress:<session>) until the copy-back is marked restored. Both take an explicit operator reason, and neither closes the project’s circuit breaker.

Safe operator sequence for ProjectData storage relief:

  1. Inspect current telemetry with GET /api/admin/project-data/storage?projectId=<projectId>. Before building an approval manifest, freeze competing source mutations: disable tool-payload, event-log, and grouped/FTS cleanup, and leave both archive-sharding switches off.
  2. For an emergency exact plan, configure the immutable PROJECT_DATA_STORAGE_RELIEF_PREFLIGHT_{PLAN_ID,PROJECT_ID,CUTOFF_CREATED_AT} scope plus row, byte, attempt, slice, run-admission, state, and manifest limits. Enable the scheduled preflight only for that scope.
  3. Wait for a terminal project_data_storage_relief_preflights row. Accept only a complete or deliberately bounded truncated result with exact totals and a non-null target_manifest_key, byte count, and SHA-256. The preflight reads every batch and root manifest back from R2 and verifies bytes and SHA-256 before persisting these proofs; independently inspect the root and referenced batch proofs before approval.
  4. Disable preflight and keep cleanup frozen. Present the exact project, cutoff, row targets, manifest keys/hashes, cumulative ceilings, switches, failure behavior, expected relief, observation window, and stop conditions for explicit human approval. Broad rollout approval does not substitute for this plan approval.
  5. Only after approval, configure cleanup with the same plan/project/cutoff, exact root key/SHA-256, and cumulative row/byte/R2-operation/wall-time ceilings. Execute only approved bounded passes, using POST /api/admin/project-data/storage/:projectId/tool-payload-cleanup with a non-empty reason and unique idempotencyKey when an explicit manual slice is required.
  6. Each payload archive object/chunk is written to an immutable content-addressed R2 key and read back for byte/SHA-256 verification before a guarded transaction changes only chat_messages.tool_metadata; chat_messages.content is never changed. Stop on any manifest, archive, source-hash, scope, cap, timeout, or circuit-breaker uncertainty.
  7. After every pass, inspect terminationReason, before/after databaseSize, reclaimed bytes, row counts, cursor/recheck state, and cooldown, then re-measure with POST /api/admin/project-data/storage/:projectId/measure. Stop at the approved target or any approved stop condition.
  8. A completed fixed plan is terminal. Before ordinary retention cleanup resumes, use a separately reviewed follow-up reset; do not reuse or silently supersede the emergency plan fingerprint.
Variable Default Description
PROJECT_DATA_MATERIALIZATION_PAGE_ROWS 500 Tokens read into memory by one chat-search materialization SELECT, bounding Durable Object isolate memory
PROJECT_DATA_MATERIALIZATION_MAX_ROWS_PER_PASS 5000 Tokens one chat-search materialization pass indexes before leaving the rest to the next pass
PROJECT_DATA_MATERIALIZATION_MAX_GROUP_CHARS 65536 Grouped-row size past which a continuing run starts a new row instead of rewriting the accumulated content
PROJECT_DATA_MATERIALIZATION_SWEEP_LIMIT 50 Sessions indexed by one chat-search materialization backfill call
PROJECT_DATA_MATERIALIZATION_SWEEP_SCAN_LIMIT 500 Sessions examined by one chat-search materialization backfill call
PROJECT_DATA_GROUPED_FTS_CLEANUP_ENABLED false Enables cleanup of old terminal-session grouped message rows and their FTS entries under storage pressure. wrangler.toml ships true, so this is ON; a cleaned session falls back to keyword search and is never re-indexed
PROJECT_DATA_GROUPED_FTS_CLEANUP_TRIGGER_RATIO 0.9 ProjectData usage ratio that starts grouped/FTS derived-data cleanup
PROJECT_DATA_GROUPED_FTS_CLEANUP_TARGET_RATIO 0.85 ProjectData usage ratio below which grouped/FTS cleanup stops
PROJECT_DATA_GROUPED_FTS_CLEANUP_BATCH_SESSIONS 2 Maximum terminal sessions examined by one grouped/FTS slice; candidate selection pages IDs first and reads at most one extra session for continuation
PROJECT_DATA_GROUPED_FTS_CLEANUP_BATCH_ROWS 1000 Maximum grouped message rows deleted by one grouped/FTS canary slice
PROJECT_DATA_GROUPED_FTS_CLEANUP_BATCH_BYTES 4194304 Maximum grouped message content bytes deleted by one grouped/FTS canary slice
PROJECT_DATA_GROUPED_FTS_CLEANUP_MIN_SESSION_AGE_DAYS 7 Minimum terminal-session age before grouped/FTS derived rows may be cleaned
PROJECT_DATA_GROUPED_FTS_CLEANUP_RECHECK_MS 86400000 Delay before the next grouped/FTS cleanup slice when more candidates remain. Also the back-off after an overload/reset error, measured from when that error was recorded. wrangler.toml ships 300000 (5 minutes)
PROJECT_DATA_GROUPED_FTS_CLEANUP_WALL_TIME_MS 5000 Soft wall-clock budget for one grouped/FTS cleanup slice
PROJECT_DATA_GROUPED_FTS_CLEANUP_WALL_UNSAFE_RATIO 0.98 Refuses grouped/FTS cleanup writes when the object is too close to the configured storage limit
PROJECT_DATA_GROUPED_FTS_CLEANUP_WEAK_RECLAIM_BYTES 1 Stops grouped/FTS cleanup if a slice deletes rows but databaseSize does not drop by at least this many bytes
PROJECT_DATA_GROUPED_FTS_WALL_RECOVERY_MAX_ROWS 10000 Ceiling on grouped rows one superadmin grouped/FTS wall-recovery call may prune
PROJECT_DATA_GROUPED_FTS_WALL_RECOVERY_MAX_BYTES 33554432 Ceiling on grouped content bytes one grouped/FTS wall-recovery call may prune
PROJECT_DATA_GROUPED_FTS_WALL_RECOVERY_MAX_SESSIONS 500 Ceiling on sessions one grouped/FTS wall-recovery call may consider, and on its skipSessionIds length
PROJECT_DATA_GROUPED_FTS_WALL_RECOVERY_TRANSACTION_ROWS 500 Grouped rows pruned per wall-recovery transaction
PROJECT_DATA_GROUPED_FTS_WALL_RECOVERY_TRANSACTION_BYTES 8388608 Grouped content bytes held in memory per wall-recovery transaction
PROJECT_DATA_EVENT_LOG_CLEANUP_ENABLED true Enables automatic deletion of old low-value terminal-session activity_events and terminal ACP event history when storage remains above the cleanup target
PROJECT_DATA_EVENT_LOG_CLEANUP_BATCH_ROWS 500 Maximum terminal activity_events rows and terminal acp_session_events rows deleted per automatic cleanup alarm batch
PROJECT_DATA_EVENT_LOG_CLEANUP_MIN_SESSION_AGE_DAYS 7 Minimum terminal-session age before automatic event-log cleanup may delete its activity/ACP event history
PROJECT_DATA_EVENT_LOG_CLEANUP_RECHECK_MS 86400000 Delay before the next terminal event-log cleanup alarm batch when more candidates remain; daily by default
PROJECT_EVENT_MAX_ACTIVE_SUBSCRIPTIONS_PER_PROJECT 200 Maximum active durable event subscriptions in one ProjectData object
PROJECT_EVENT_FILTER_MAX_VALUES_PER_FIELD 20 Maximum exact/set values accepted for one v1 event filter field
PROJECT_EVENT_FILTER_MAX_MATCH_KEYS 100 Maximum deterministic match keys compiled for one event subscription
PROJECT_EVENT_FILTER_MAX_STRING_BYTES 160 Maximum bytes for event source/type/subject, filter values, delivery keys, fingerprints, and event idempotency strings
PROJECT_EVENT_METADATA_MAX_BYTES 8192 Maximum normalized event metadata JSON bytes stored in ProjectData
PROJECT_EVENT_METADATA_MAX_DEPTH 4 Maximum nesting depth for normalized event metadata
PROJECT_EVENT_METADATA_MAX_KEYS 64 Maximum total object keys in normalized event metadata
PROJECT_EVENT_METADATA_MAX_ARRAY_ITEMS 64 Maximum array items in normalized event metadata
PROJECT_EVENT_DISPLAY_MAX_BYTES 4096 Maximum deterministic untrusted event display JSON bytes
PROJECT_EVENT_DISPLAY_MAX_LABELS 12 Maximum labels accepted in event display data
PROJECT_EVENT_RAW_PAYLOAD_REF_MAX_BYTES 512 Maximum optional raw-payload reference JSON bytes; raw webhook bodies are not persisted in ProjectData
PROJECT_EVENT_REASON_MAX_BYTES 1024 Maximum diagnostic reason bytes on subscriptions, batches, and attempts
PROJECT_EVENT_MAX_MATCHES_PER_EVENT 100 Maximum durable subscription matches written for one admitted normalized event
PROJECT_EVENT_DELIVERY_BATCH_MAX_EVENTS 50 Maximum event matches in one durable delivery batch
PROJECT_EVENT_DELIVERY_ATTEMPT_MAX_PER_BATCH 10 Maximum recorded delivery attempts for one event delivery batch
PROJECT_EVENT_SCHEDULE_MAX_SCHEDULES 128 Maximum active schedules per project
PROJECT_EVENT_SCHEDULE_MAX_WATCHES 64 Maximum active or paused standing watches per project
PROJECT_EVENT_SCHEDULE_MAX_RETAINED_SCHEDULES 4096 Maximum retained schedule records of all states per project; cancellation does not free retained capacity
PROJECT_EVENT_SCHEDULE_MAX_RETAINED_WATCHES 256 Maximum retained watch records of all states per project; revocation does not free retained capacity
PROJECT_EVENT_SCHEDULE_PROMPT_MAX_BYTES 32768 Maximum scheduled action prompt size in UTF-8 bytes; start_session admission also validates MAX_TASK_MESSAGE_LENGTH
PROJECT_EVENT_SCHEDULE_MAX_HORIZON_MS 2592000000 Maximum future scheduling horizon (30 days)
PROJECT_EVENT_SCHEDULE_LATE_GRACE_MS 86400000 Maximum late admission grace after due time
PROJECT_EVENT_SCHEDULE_DELIVERY_TTL_MS 86400000 Maximum durable message lifetime, also bounded by schedule expiry
PROJECT_EVENT_SCHEDULE_SWEEP_BATCH_SIZE 20 Maximum schedule or watch candidates processed per alarm pass
PROJECT_EVENT_SCHEDULE_CLAIM_LEASE_MS 60000 Finite admission/submission claim lease
PROJECT_EVENT_SCHEDULE_RETRY_BASE_MS 30000 Retry and accepted execution reconciliation interval
PROJECT_EVENT_SCHEDULE_MAX_ATTEMPTS 8 Maximum uncertain task submission attempts
PROJECT_EVENT_SCHEDULE_MAX_DEFERRAL_MS 86400000 Maximum deferral before a new task may initially start
PROJECT_EVENT_WATCH_COOLDOWN_MIN_MS 60000 Minimum time between standing watch executions
PROJECT_EVENT_WATCH_MAX_EXECUTIONS 100 Maximum configurable executions per standing watch
PROJECT_EVENT_WATCH_MAX_CONCURRENT 3 Maximum configurable concurrent actions per standing watch
PROJECT_EVENT_CHANNEL_MAX_CHANNELS 128 Maximum catalog generations per project
PROJECT_EVENT_CHANNEL_MESSAGE_MAX_BYTES 4096 Maximum channel message UTF-8 bytes, also subject to canonical metadata limits
PROJECT_EVENT_CHANNEL_NAME_MAX_BYTES 64 Maximum channel name bytes
PROJECT_EVENT_CHANNEL_PUBLISH_WINDOW_MS 60000 Per-project fixed publish window in milliseconds
PROJECT_EVENT_CHANNEL_PUBLISH_MAX_PER_WINDOW 120 Maximum newly committed channel publishes per project window; retained replays do not consume quota
PROJECT_EVENT_CHANNEL_CURSOR_TTL_MS 3600000 History cursor and unfinished catch-up lifetime in milliseconds; continuation never extends it
PROJECT_EVENT_CHANNEL_CATALOG_IDLE_TTL_MS 2592000000 Minimum idle time before reclaiming an empty catalog generation without live catch-up
AGENT_MESSAGE_CHANNELS_ENABLED true wrangler.toml sets true (code fallback false). Send agent messages (every class) over SAM-managed agent-dm.* pair channels. Effective only while PROJECT_EVENT_WAKE_ENABLED and durable prompt delivery are on; when it is not effective, agent-to-agent sends are refused
AGENT_MESSAGE_CHANNEL_MAX_CHANNELS 1024 Maximum agent-dm.* pair channels per project, separate from PROJECT_EVENT_CHANNEL_MAX_CHANNELS
AGENT_MESSAGE_SUBSCRIPTION_ROTATION_GRACE_MS 300000 Replace a managed pair subscription this close to the end of its wake lifetime when it owes no pending wake
AGENT_MESSAGE_MAX_ACTIVE_SUBSCRIPTIONS 100 Share of PROJECT_EVENT_MAX_ACTIVE_SUBSCRIPTIONS_PER_PROJECT that SAM-managed agent-message subscriptions may hold; idle ones on other pairs are released first
PROJECT_EVENT_LIST_LIMIT 50 Default ProjectData event-subscription list/status page size
PROJECT_EVENT_LIST_MAX 200 Maximum ProjectData event-subscription list/status page size
PROJECT_EVENT_SUBSCRIPTION_EVENT_CURSOR_MAX_LENGTH 512 Maximum opaque list_subscription_events cursor length accepted by ProjectData pull delivery
PROJECT_EVENT_RECENT_STATUS_LIMIT 50 Maximum rows returned per section in recent event-subscription status inspection
PROJECT_EVENT_RETENTION_DAYS 30 Retention window for terminal ProjectData event-subscription records
PROJECT_EVENT_RETENTION_BATCH_ROWS 500 Maximum old rows pruned per event-subscription retention category per pass
PROJECT_EVENT_SOURCE_OUTBOX_BATCH_ROWS 25 Maximum producer-side outbox row mutations per trigger cleanup pass. Must be an integer of at least 2 for claim plus settlement; invalid values reject before any writes. Per-call budget overrides have the same minimum.
PROJECT_EVENT_SOURCE_OUTBOX_MAX_ATTEMPTS 8 Maximum ProjectData admission attempts before a source intent is marked permanent_failed
PROJECT_EVENT_SOURCE_OUTBOX_TTL_MS 86400000 Maximum lifetime for a producer-side event admission intent
PROJECT_EVENT_SOURCE_OUTBOX_RETRY_BASE_MS 30000 Initial retry delay for failed source event admission
PROJECT_EVENT_SOURCE_OUTBOX_RETRY_MAX_MS 1800000 Maximum retry delay for failed source event admission
PROJECT_EVENT_SOURCE_OUTBOX_PROCESSING_LEASE_MS 60000 Lease before an in-flight source event admission intent can be claimed by reconciliation
PROJECT_EVENT_RETENTION_INTERVAL_MS 86400000 Default delay before the next ProjectData event retention alarm after a complete pass; daily by default
PROJECT_EVENT_RETENTION_MIN_ALARM_DELAY_MS 60000 Minimum delay before a follow-up event retention alarm when more bounded work remains or a due checkpoint is re-armed
PROJECT_EVENT_WAKE_ENABLED true wrangler.toml sets true (code fallback false). Enables same-chat event wakes for v2 prompt-delivery subscriptions (runtime_steer by default); false leaves event delivery pull-only
PROJECT_EVENT_WAKE_MATERIALIZATION_MIN_ALARM_DELAY_MS 1000 Minimum delay before a ProjectData alarm retries wake materialization after due matches are present
PROJECT_EVENT_WAKE_MATERIALIZATION_BACKOFF_BASE_MS 5000 Initial persisted backoff for a failed event-wake materialization or retention alarm phase
PROJECT_EVENT_WAKE_MATERIALIZATION_BACKOFF_MAX_MS 300000 Maximum persisted backoff for repeated event-wake materialization or retention alarm failures
PROJECT_EVENT_WAKE_PROMPT_TTL_MS 86400000 Hard lifetime for queued same-chat event wake prompts before physical delivery is rejected; also bounds how long an undelivered wake holds its chat
PROJECT_EVENT_WAKE_READ_GRACE_MS 86400000 Read/ack grace retained on accepted event-wake batches after natural subscription expiry
PROJECT_EVENT_WAKE_TARGET_COOLDOWN_MS 30000 Delay before retrying an event wake for a chat whose transcript or project mailbox is at capacity. A chat with an undelivered wake is skipped until that wake is accepted, without this cooldown
PROJECT_EVENT_WAKE_SUBSCRIPTION_COOLDOWN_MS 30000 Per-subscription cooldown after a wake batch is queued, and the smallest minWakeIntervalSeconds an agent can choose
PROJECT_EVENT_WAKE_SUBSCRIPTION_LIFETIME_MS 86400000 Maximum operational lifetime for same-chat wake delivery on a v2 event subscription when the requested subscription expiry is absent or farther out
PROJECT_EVENT_WAKE_MAX_PER_SUBSCRIPTION 50 Maximum same-chat wake prompt batches materialized for one v2 event subscription
PROJECT_EVENT_SOURCE_OUTBOX_SWEEP_WALL_MS 2500 Per-pass wall-clock budget for producer-side outbox reconciliation before the sweep yields
PROJECT_EVENT_SOURCE_OUTBOX_ADMISSION_TIMEOUT_MS 5000 Per-intent timeout for the ProjectData admission call; timed-out calls are treated as ambiguous and retried through the fenced outbox
PROJECT_EVENT_SOURCE_OUTBOX_TERMINAL_RETENTION_MS 604800000 Retention window for terminal outbox rows before the bounded cleanup removes admitted, expired, and permanent_failed history
MESSAGE_SIZE_THRESHOLD 102400 Max message size in bytes
SESSION_IDLE_TIMEOUT_MINUTES 15 Idle session timeout in minutes. wrangler.toml ships 60
SESSION_ACTIVITY_STALE_THRESHOLD_MS 300000 (5 min) Threshold before stale working activity is checked against authoritative SessionHost inventory
SESSION_ACTIVITY_PROBE_TIMEOUT_MS 5000 (5 s) Timeout for the vm-agent session-activity probe. Background control-loop budget — deliberately far below the interactive node-agent timeout
SESSION_ACTIVITY_PROBE_MAX_ATTEMPTS 3 Consecutive unreachable probes after which a stale working state is quarantined until an authoritative report refreshes it
SESSION_ACTIVITY_PROBE_MAX_CANDIDATES 10 Stale-activity candidates probed per ProjectData alarm pass
DO_SUMMARY_SYNC_DEBOUNCE_MS 5000 Debounce for DO-to-D1 summary sync
SESSION_INDEX_MAX_ROWS 1000 Sessions mirrored into the D1 session_summaries index per project. A project holding more is recorded as incomplete and its chat sidebar reads fall back to the Durable Object
SESSION_INDEX_MAX_STALENESS_MS 900000 (15 min) How stale the session index may be before the per-project sidebar list stops trusting it and falls back to the Durable Object
CREDENTIAL_LIMIT_WARNING_PERCENT 75 Advisory warning threshold for credential quota utilization samples
CREDENTIAL_LIMIT_CRITICAL_PERCENT 90 Advisory critical threshold for credential quota utilization samples
CREDENTIAL_LIMIT_MAX_OBSERVATIONS_PER_REPORT 16 Maximum credential-limit observations accepted from one VM usage callback or proxy report
CREDENTIAL_LIMIT_TRANSITION_RECOMPUTE_ATTEMPTS 4 Maximum predecessor-CAS recomputes for one credential-limit observation when concurrent samples update the same window
CREDENTIAL_LIMIT_ADMISSION_MAX_ACTIVE_PER_PROJECT 1000 Maximum active credential-limit event admissions per project (range: 1–100000)
CREDENTIAL_LIMIT_READ_MAX_ROWS 200 Maximum credential usage-limit window rows returned by one read request (GET /api/projects/:id/credential-limits, GET /api/credentials/limits, MCP workspace_read method credential_limits)
CREDENTIAL_LIMIT_ADMISSION_RETRY_BATCH_SIZE 25 Maximum pending credential-limit event admissions retried per batch (range: 1–500)
CREDENTIAL_LIMIT_ADMISSION_RETENTION_DAYS 30 Retention of inactive credential-limit window observations in days (range: 1–365)
CREDENTIAL_LIMIT_USAGE_CALLBACK_MAX_BODY_BYTES 32768 Maximum raw JSON bytes accepted for one authenticated VM usage callback before schema validation
CREDENTIAL_LIMIT_USAGE_CALLBACK_RATE_LIMIT_RPM 120 Authenticated VM usage callbacks accepted per session in each rate-limit window
CREDENTIAL_LIMIT_USAGE_CALLBACK_RATE_LIMIT_WINDOW_SECONDS 60 Usage callback rate-limit window in seconds
CREDENTIAL_LIMIT_OBSERVATION_MAX_AGE_MS 86400000 Oldest provider observation timestamp accepted for credential-limit telemetry
CREDENTIAL_LIMIT_OBSERVATION_FUTURE_SKEW_MS 300000 Future clock skew accepted for credential-limit observation timestamps
CREDENTIAL_LIMIT_RESET_MAX_FUTURE_MS 691200000 Maximum future provider reset timestamp accepted for credential-limit telemetry
CREDENTIAL_LIMIT_SUPPORTED_PROVIDERS anthropic,openai,opencode Comma-separated allowlist of providers accepted by credential-limit telemetry
CREDENTIAL_LIMIT_SUPPORTED_SOURCES built-in sources Comma-separated allowlist of VM-agent and AI-proxy telemetry source identifiers accepted by credential-limit telemetry
CREDENTIAL_LIMIT_SUPPORTED_WINDOW_TYPES built-in windows Comma-separated allowlist of provider quota window identifiers accepted by credential-limit telemetry
AI_PROXY_REQUEST_BODY_MAX_BYTES 1048576 Maximum raw JSON bytes accepted by OpenAI-compatible, Anthropic-native, and passthrough AI proxy request endpoints before request validation
AI_PROXY_DEFAULT_MODEL @cf/google/gemma-4-26b-a4b-it Model the AI proxy uses when a sam-mode request names no model and no usable admin default is saved on the AI Proxy admin page (KV). A saved admin default whose model is no longer in the platform catalog (for example one Cloudflare retired) is ignored and this value applies; resolved in routes/ai-proxy-model-resolution.ts (readAdminDefaultAIProxyModel, resolveModelId)
AI_PROXY_ALLOWED_MODELS platform catalog Comma-separated models the AI proxy serves on every route that spends platform credentials, the native Anthropic endpoint included; any other model returns 400

Ordinary ProjectData storage alarms record O(1) databaseSize telemetry and bounded cleanup row/byte counters. Category breakdown scans are reserved for explicit/admin measurement paths so hot ProjectData alarms do not delay lifecycle bookkeeping.

Variable Default Description
DO_RETRY_MAX_ATTEMPTS 8 Max attempts for transient Durable Object RPC reset/overload errors
DO_RETRY_BASE_DELAY_MS 100 Base retry delay in milliseconds for transient Durable Object RPC failures
DO_RETRY_MAX_DELAY_MS 250 Max per-attempt retry delay for transient Durable Object RPC failures
DO_RETRY_CONNECTION_LOST_MAX_ATTEMPTS 3 Attempts (capped at DO_RETRY_MAX_ATTEMPTS) for an idempotent ProjectData read whose connection to the object was lost or that encounters SQLITE_NOMEM. Mutations never retry SQLITE_NOMEM. An idempotent read that exhausts its attempts on either error or a CPU-limit reset returns 503 PROJECT_DATA_UNAVAILABLE
PROJECT_DATA_ENSURE_MEMO_MAX_ENTRIES 2000 Max ProjectData Durable Objects one Worker isolate remembers as already having a persisted projectId, so ensureProjectId costs one RPC per isolate instead of one before every DO call
Variable Default Description
MAX_PROJECT_RUNTIME_ENV_VARS_PER_PROJECT 150 Max env vars per project
MAX_PROJECT_RUNTIME_FILES_PER_PROJECT 50 Max files per project
MAX_PROJECT_RUNTIME_ENV_VALUE_BYTES 8192 Max bytes per env var value
MAX_PROJECT_RUNTIME_FILE_CONTENT_BYTES 131072 Max bytes per file content
MAX_PROJECT_RUNTIME_FILE_PATH_LENGTH 256 Max file path length
MAX_DEPLOYMENT_ENV_VARS_PER_ENVIRONMENT 100 Max deployment config vars per environment
MAX_DEPLOYMENT_ENV_VALUE_BYTES 65536 Max bytes per deployment config value
MAX_DEPLOYMENT_ENV_TOTAL_BYTES 262144 Max aggregate deployment config env size
MAX_MCP_CONNECTIONS_PER_SCOPE 25 Max bring-your-own MCP servers per scope
MCP_CONNECTION_URL_MAX_BYTES 2048 Max MCP endpoint URL size
MCP_CONNECTION_TOKEN_MAX_BYTES 8192 Max MCP bearer token size
MAX_MCP_CONNECTION_HEADERS 10 Max custom headers per MCP server
MCP_CONNECTION_HEADER_VALUE_MAX_BYTES 8192 Max bytes per MCP custom header value
Variable Default Description
HETZNER_API_TIMEOUT_MS 30000 Hetzner API request timeout
HETZNER_CAPACITY_RETRY_INITIAL_DELAY_MS 15000 Initial delay for transient Hetzner capacity retry backoff
HETZNER_CAPACITY_RETRY_MAX_DELAY_MS 120000 Maximum delay per transient Hetzner capacity retry wait
HETZNER_CAPACITY_RETRY_MAX_ATTEMPTS 10 Maximum transient Hetzner capacity retry attempts
HETZNER_CAPACITY_RETRY_BUDGET_MS 300000 Total transient Hetzner capacity retry budget
HETZNER_MAX_LIST_PAGES 100 Maximum pages per Hetzner list request
CF_API_TIMEOUT_MS 30000 Cloudflare API request timeout
GCP_API_TIMEOUT_MS 30000 GCP OAuth, IAM, and Compute request timeout
NODE_AGENT_REQUEST_TIMEOUT_MS 30000 VM Agent request timeout
DIGITALOCEAN_API_TIMEOUT_MS 30000 DigitalOcean API request timeout
DIGITALOCEAN_IP_POLL_TIMEOUT_MS 20000 Bounded best-effort public IPv4 poll budget
DIGITALOCEAN_IP_POLL_INTERVAL_MS 3000 Public IPv4 poll interval
DIGITALOCEAN_ACTION_POLL_TIMEOUT_MS 60000 Block Storage action completion budget
DIGITALOCEAN_ACTION_POLL_INTERVAL_MS 1000 Block Storage action poll interval
DIGITALOCEAN_MAX_LIST_PAGES 20 Maximum pages per DigitalOcean list request
DIGITALOCEAN_REGION fra1 Default DigitalOcean region
DIGITALOCEAN_IMAGE ubuntu-24-04-x64 Default Droplet image slug
CF_CONTAINER_CREATE_WORKSPACE_TIMEOUT_MS 120000 Instant-session create-workspace budget (includes in-container clone)

Some requests go to a URL the code does not fix: a browser’s Web Push endpoint, the base URL of a user’s OpenAI-compatible credential, a registry named in a deployment manifest, the issuer of an agent sign-in trust, and the workspace URL check_dns_status probes. SAM checks the host of each before the request (classifyHost in packages/worker-core/src/network-hosts/classify.ts): loopback, private ranges, carrier-grade NAT, unique-local IPv6, localhost, single-label names and .local/.internal/.lan-style names are private; link-local, cloud metadata hosts and reserved ranges are forbidden. Literal addresses are recognised in every spelling a URL parser accepts (decimal, hex, octal, IPv4-mapped and other IPv6 embeddings).

Request Rule Where
Web Push subscription Endpoint must be HTTPS on a public host when saved; a stored endpoint that fails the check is skipped at delivery and logged as web_push.endpoint_refused (no URL in the log). Redirects are never followed. schemas/notifications.ts, lib/web-push.ts, durable-objects/notification-push.ts
OpenAI-compatible credential base URL Must be HTTPS on a public host when saved or updated; a stored base URL that fails the check is skipped when the AI proxy resolves an upstream (ai_proxy_passthrough.upstream_refused), so the request gets the usual 401 “no compatible upstream credential”. routes/composable-credentials.ts, routes/ai-proxy-passthrough-upstream.ts
Agent sign-in issuer keys Fetched through guardedFetch with no redirects; a refused issuer answers 503 ISSUER_KEYS_UNAVAILABLE and logs agent_sign_in.issuer_keys_refused. services/agent-sign-in/verify.ts
Deployment-release registry lookups Registry, token realm and every redirect must be HTTPS on a public host. packages/app-deployment/src/image-resolver-outbound.ts
check_dns_status Follows only redirects that stay on the workspace’s own origin, each re-checked; reports any other redirect with its status without requesting it, and reports failures as fixed categories, never raw error text. A private-domain install may reach its own private workspace host. routes/mcp/check-dns-status.ts

The AI proxy’s three passthrough calls also use guardedFetch (routes/ai-proxy-passthrough.ts). It checks every redirect hop and keeps only Accept, Accept-Language, Content-Type, Content-Language and User-Agent on a hop to another origin, and refuses a 307 or 308 that would carry a request body to another origin.

Admin setting Default Meaning
outbound.maxRedirects 3 Redirect hops a guarded fetch follows, each re-checked, range 0–10. 0 refuses every redirect. Used by AI proxy passthrough, admin LLM endpoints, GitLab profile/API calls and check_dns_status. If settings cannot be read, no redirect is followed. Category Operations.

GitLab sign-in and API requests refuse private and metadata hosts. OAuth code exchange and token refresh refuse redirects; profile and API requests follow only validated hops within the configured cap. Node control calls refuse redirects. Workspace previews preserve application redirects while refusing any redirect that exposes the SAM proxy token.

The check reads names, not DNS answers: a public name that resolves to a private address passes. On Cloudflare the Worker’s request leaves from Cloudflare’s network, not from the installation’s private network.

The lint rule sam/no-unguarded-outbound-fetch keeps new requests on this path (packages/eslint-plugin-sam/docs/rules/no-unguarded-outbound-fetch.md).

Variable Default Description
OBSERVABILITY_ERROR_RETENTION_DAYS 30 Error log retention
OBSERVABILITY_ERROR_MAX_ROWS 100000 Max stored error rows
OBSERVABILITY_ERROR_BATCH_SIZE 25 Error ingestion batch size
OBSERVABILITY_ERROR_MESSAGE_MAX_LENGTH 2048 Maximum persisted message length
OBSERVABILITY_ERROR_STACK_MAX_LENGTH 4096 Maximum persisted stack length
OBSERVABILITY_ERROR_USER_AGENT_MAX_LENGTH 512 Maximum persisted user-agent length
OBSERVABILITY_LOG_QUERY_RATE_LIMIT 30 Log queries per minute per admin

The tunnel environment settings below are provisioning inputs: a VM keeps the transport, connector binary and systemd configuration it received at creation. They do not reconfigure existing VMs.

Tunnel API retries and resource cleanup use Admin → Settings → Operations instead of deployment variables. These controls apply to subsequent calls and cleanup sweeps without redeploying:

Admin setting Default Meaning
vmTunnels.apiAttempts 3 Provisioning attempts for transient GET/PUT/DELETE failures, range 1–10. Creation is never retried; cleanup uses one attempt per request.
vmTunnels.apiRetryDelayMs 250 Linear retry delay step in milliseconds, range 1–30000.
vmTunnels.cleanupRequestTimeoutMs 10000 Per-request background timeout, range 1–30000 ms, capped by CF_API_TIMEOUT_MS.
vmTunnels.cleanupBatchSize 10 Journal rows processed per sweep, range 1–100.
vmTunnels.cleanupSweepBudgetMs 30000 Cloudflare I/O deadline for the sweep, range 1–120000 ms. Cancels an in-flight request; D1 bookkeeping finishes afterward and remaining rows stay due.
vmTunnels.cleanupBackoffBaseMs 60000 Initial cleanup retry delay, range 1–86400000 ms.
vmTunnels.cleanupBackoffMaxMs 3600000 Maximum cleanup retry delay, range 1–604800000 ms. Ownership remains recorded until cleanup succeeds.
vmTunnels.cleanupStuckAttempts 6 Failed attempts before subsequent failures are logged at error severity, range 1–100.
vmTunnels.provisioningBudgetMs 20000 Extra time a durable provisioning attempt (direct workspace or node creation) gets for tunnel setup, on top of the attempt budget operations.nodeProvisioningAttemptDeadlineMs (default 60000), range 1–120000 ms. Tunnel setup is resumable: an attempt that still runs out continues from its recorded progress on the next attempt.
vmTunnels.pendingCreateSettleMs 900000 How long cleanup keeps waiting for a tunnel or DNS create whose response was never observed, range 60000–86400000 ms.

If a Cloudflare create response is lost, cleanup retains the ownership journal and checks again at the capped backoff interval, even after finding no remaining resources. This prevents a delayed create from leaving an untracked tunnel or DNS record. Once vmTunnels.pendingCreateSettleMs has passed since the last unobserved create, a cleanup that finds and deletes everything left for that incarnation (or finds nothing) marks the row cleaned (pendingCreateSettled in apps/api/src/services/node-tunnel-cleanup.ts); at the defaults a stranded row is cleaned within about 30 minutes. Every failed or deadline-cut provisioning attempt records the tunnel step it stopped in and the cause, in the node_provisioning.attempt_failed / node_provisioning.attempt_aborted log and in the journal row’s last_error.

Deployment nodes use the tunnel for their VM agent connection only. Their app routes keep the public IP: grey-cloud A records with Caddy terminating TLS through ACME on ports 80 and 443, and verified custom domains work unchanged. Routing app traffic through the tunnel would need edge certificates for nested *.apps. hostnames and Cloudflare for SaaS for custom domains, so it is not done.

Variable Default Description
VM_AGENT_TRANSPORT vm-public-dns Transport for newly provisioned managed VMs, workspace and deployment nodes alike: vm-public-dns or cloudflare-tunnel. Existing nodes and instant containers keep their current transport. Deployment nodes keep serving app routes on their public IP.
VM_AGENT_TUNNEL_PORT 8444 Dedicated loopback HTTP ingress for cloudflared; must differ from the private agent listener port.
CLOUDFLARED_VERSION 2026.10.7 Connector release; only versions with pinned architecture checksums in cloud-init are accepted.
VM_AGENT_TUNNEL_LISTENER_WAIT_SECONDS 120 Elapsed connector startup wait for the loopback agent listener (1-3600 seconds).
VM_AGENT_TUNNEL_PROBE_TIMEOUT_SECONDS 2 Maximum duration of one loopback health probe (1-60 seconds).
VM_AGENT_TUNNEL_PROBE_INTERVAL_SECONDS 1 Pause between loopback health probes (1-60 seconds).
VM_AGENT_TUNNEL_RESTART_SECONDS 5 Connector service restart delay (1-3600 seconds).
VM_AGENT_PROTOCOL https Protocol for VM agent communication
VM_AGENT_PORT 8443 VM agent listening port
VM_AGENT_MEMORY_RESERVE_MB 1024 Optional Docker workload-slice memory reserve for VM-agent reachability headroom
SAM_INFRA_SLICE_MEMORY_MIN_MB 256 systemd MemoryMin for the VM-agent/system-services slice
DOCKER_MEMORY_MIN_MB 512 Minimum Docker MemoryMax retained when VM_AGENT_MEMORY_RESERVE_MB is enabled
SAM_INFRA_SLICE_CPU_WEIGHT 1000 systemd CPUWeight for the VM-agent slice (cgroup v2 range 1–10000)
SAM_WORKLOAD_SLICE_CPU_WEIGHT 100 systemd CPUWeight for the Docker workload slice (cgroup v2 default)
HEARTBEAT_DOCKER_STATS_TIMEOUT 2s VM-agent timeout for heartbeat Docker stats used by workspace memory telemetry
HEARTBEAT_WORKSPACE_METRICS_MAX_CONTAINERS 8 Maximum workspace containers measured by one heartbeat
HEARTBEAT_WORKSPACE_METRICS_MAX_OUTPUT_BYTES 65536 Maximum bytes read from each heartbeat Docker metric command
ORIGIN_CA_CERT_VALIDITY_DAYS 7 Validity for per-node Origin CA certificates signed by the API Worker

New public-DNS nodes generate /etc/sam/tls/origin-ca-key.pem locally in cloud-init and fetch only the signed certificate from POST /api/nodes/:id/origin-ca-certificate (packages/cloud-init/src/template-ingress.ts, apps/api/src/routes/node-lifecycle.ts). Legacy ORIGIN_CA_CERT and ORIGIN_CA_KEY Worker secrets are not required for new node provisioning.

With VM_AGENT_TRANSPORT=cloudflare-tunnel, SAM creates one remotely managed tunnel per new managed VM incarnation, for workspace and deployment nodes alike, and points its existing backend hostname at that tunnel. The API still uses HTTPS to Cloudflare; cloudflared connects outbound from the VM and forwards to a dedicated authenticated loopback listener. The VM receives only its connector token, stored in a mode-0400 credential file readable by the dedicated connector service, and does not request an Origin CA certificate. Agent and SSH ports are blocked on public interfaces. Preview ports, terminals, and API agent calls use the tunnel. Deployment-node app routes do not: they stay public on ports 80 and 443 (see below). Instant containers retain their Durable Object transport. The setting does not migrate running nodes. Set it back to vm-public-dns to change future provisioning; existing tunnel nodes continue using their tunnels until deleted.

VM workspace admission uses persisted workspaces.resolved_reservation_json snapshots and provider capacity fields in a final single-statement D1 reservation (apps/api/src/services/workspace-placement.ts). Aggregate CPU, memory, and disk reservations plus exclusiveNode control packing. Fresh telemetry remains mandatory on occupied nodes; disk pressure and CPU saturation veto reuse, while live memory percentage is a scoring signal rather than a second capacity gate (packages/scheduler-core/src/workspace-resource-capacity.ts, apps/api/src/durable-objects/task-runner/node-selection.ts). There is no workspace-count or co-tenant cap: MAX_WORKSPACES_PER_NODE and maxCoTenants were removed, and legacy reservation rows that still carry maxCoTenants are admitted on their resource reservations alone. Live memory-threshold settings remain scoring inputs, not gates. VM agents report optional per-workspace memory telemetry in heartbeat metrics when Docker stats can be collected within the configured bounds (packages/vm-agent/internal/server/health.go, packages/vm-agent/internal/sysinfo/docker_metrics.go).

For managed VM nodes, the effective host-memory reserve contract is shared by admission and cloud-init: project scaling overrides win, then TASK_RUN_NODE_HOST_MEMORY_RESERVE_MB, then VM_AGENT_MEMORY_RESERVE_MB, then the 1024 MB default. Keep it at or above the host’s real idle memory use (about 460–770 MB on a 4 GB node and more on larger ones, measured 2026-11-08): offering selection assumes the reserve covers the host, and admission charges measured use instead whenever it is larger, so a smaller reserve lets SAM provision machines that then refuse the work they were started for. Cloud-init applies the cgroup hierarchy only on newly provisioned nodes. Existing nodes need a drain/recreate, a VM-agent/bootstrap upgrade flow, or a manual in-place systemd/Docker reconfiguration before they can be treated as protected by the workload-slice cap; SAM does not destructively evict existing workspaces to retrofit this.

SAM keeps workspace deletion pending until the node verifies that its exact container, owned volume and host clone are absent. A failed removal retains its deletion record for bounded retries after an agent restart. Automatic cleanup requires a verified full snapshot of the exact runtime, or a final capture taken after an eviction stopped the container, and an evicted source is deleted only after its conversation was fully restored elsewhere and that wake committed; failed snapshots, uncertain ownership and eviction sources with only a live capture remain protected. The preservation receipt lives on the source workspace (workspaces.preservation_receipt_json), so it survives the replacement workspace taking over the conversation’s snapshot. Explicit permanent deletion follows the user’s deletion request. Deletion first removes any leftover snapshot helper for the workspace, since its volume reference would block the volume removal.

New nodes receive NODE_USER_ID and NODE_RUNTIME_INCARNATION_ID from provisioning. Nodes without these identities cannot report strict physical deletion proof. Configured standalone/user roots without a SAM ownership record are preserved rather than recursively deleted. The ownership record pins the device and inode of the workspace root SAM created (createOwnedWorkspaceRoot in packages/vm-agent/internal/server/workspace_cleanup_inventory.go), so the initial clone empties that root in place rather than replacing it (clearWorkspaceDirForClone in packages/vm-agent/internal/bootstrap/workspace_dir_reset.go).

The control plane retries an unconfirmed deletion with exponential backoff between WORKSPACE_DELETION_RETRY_BASE_MS and WORKSPACE_DELETION_RETRY_MAX_MS. The stopped-workspace cron safety net only enqueues workspaces missing from that queue; it leaves an entry that is already retrying on its own backoff and failure diagnostic (sweepStaleStoppedWorkspaces in apps/api/src/scheduled/node-cleanup/workspace-phases.ts).

The VM-agent service accepts WORKSPACE_DELETION_RETRY_INTERVAL (default 1m), WORKSPACE_DELETION_ATTEMPT_TIMEOUT (30s), WORKSPACE_DELETION_BATCH_SIZE (32) and WORKSPACE_DELETION_TOMBSTONE_RETENTION (168h). One deletion attempt is bounded by WORKSPACE_DELETION_ATTEMPT_TIMEOUT, not by a file count, so a typical repository clone is removed in a single attempt (removeDeletionRoot in packages/vm-agent/internal/server/workspace_deletion_path.go). Once the VM agent accepts a deletion request and holds the workspace lifecycle lock, the attempt keeps running even if the control plane stops waiting for the response; if it does not finish, the agent wakes its local retry loop at once instead of waiting for the next interval (handleSafeDeleteWorkspace and wakeWorkspaceDeletionReconciler). Completed local deletion receipts are pruned in bounded batches; unfinished intents are retained. Automatic local retries stop when their verified snapshot authority expires. A new permanent deletion request can explicitly authorize the same exact target.

Image-transfer housekeeping runs with the same bounded periodic backstop and uses the following service environment variables:

Variable Default Purpose
SAM_IMAGE_TRANSFER_SCRATCH_DIR OS temporary directory plus sam-image-transfers Private directory for SAM-owned publish/deploy archive transfers
SAM_IMAGE_TRANSFER_SCRATCH_DRY_RUN true Report abandoned candidates without deleting them
SAM_IMAGE_TRANSFER_SCRATCH_RETENTION 24h Minimum age of an abandoned operation; active leases always protect transfers
SAM_IMAGE_TRANSFER_SCRATCH_MAX_ENTRIES 64 Directory entries inspected per sweep
SAM_IMAGE_TRANSFER_SCRATCH_MAX_FILES 128 Maximum files inspected in one operation
SAM_IMAGE_TRANSFER_SCRATCH_MAX_RECLAIM_BYTES 1073741824 Maximum candidate/reclaimed bytes per sweep

The scratch root must be private and owned by the VM-agent user. Every parent directory must be owned by that user or root and must prevent other users from replacing its children; trusted sticky directories such as /tmp are supported. Unsafe custom roots or TMPDIR paths are rejected before transfer files are created.

Successful transfers still remove their own temporary archives. Housekeeping excludes unmarked legacy files, workspace and snapshot data, user caches, nested Docker volumes, build caches, and current or rollback images. Unknown files, links, mounts and directories remain protected. Disk pressure never authorizes deleting user work.

Applied via cloud-init on each node:

Setting Default Description
SystemMaxUse 500M Max disk space for journal
SystemKeepFree 1G Minimum free disk to maintain
MaxRetentionSec 7day Max log retention period
Storage persistent Persist logs across reboots
Compress yes Compress stored entries

Files attached to a project chat message are staged in R2 and delivered with the message (Attach Files to a Message). The browser enforces the built-in size and count limits as well, so lowering those takes effect but raising them doesn’t; the upload-link lifetime isn’t checked in the browser. Set them in wrangler.toml [vars].

Variable Default Description
ATTACHMENT_UPLOAD_MAX_BYTES 52428800 (50 MB) Max size per attached file
ATTACHMENT_UPLOAD_BATCH_MAX_BYTES 209715200 (200 MB) Max total size per message
ATTACHMENT_MAX_FILES 20 Max files per message
ATTACHMENT_PRESIGN_EXPIRY_SECONDS 900 (15 min) Lifetime of each upload link

Upload links (attachments, session snapshots, compose image artifacts and build contexts) are all signed by one client, getR2PresignTarget() in apps/api/src/services/r2-s3-client.ts. On Cloudflare it addresses https://<CF_ACCOUNT_ID>.r2.cloudflarestorage.com with R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY and R2_BUCKET_NAME. A runtime whose R2 binding keeps objects in its own S3 store sets R2_S3_ENDPOINT, R2_S3_BUCKET, R2_S3_KEY_PREFIX and R2_S3_REGION (its SigV4 signing region, for example auto for Google Cloud Storage or us-west-2 for AWS S3; there is no default, because a wrong region makes every signed URL fail), plus optional R2_S3_FORCE_PATH_STYLE (default path style); links then target <R2_S3_BUCKET>/<R2_S3_KEY_PREFIX><key> (resolveR2PresignConfig() in apps/api/src/services/r2-presign-config.ts). A partially configured store disables presigning rather than falling back to Cloudflare, and attachment requests then answer 403.

These apply to files uploaded straight into a workspace from its own page, and to files downloaded from a workspace. FILE_UPLOAD_MAX_BYTES and FILE_UPLOAD_TIMEOUT are VM agent settings that SAM doesn’t pass to the machines it starts, so their defaults apply. On the Worker, FILE_UPLOAD_BATCH_MAX_BYTES is an early check: it can lower the batch limit, but not raise it past the VM agent’s 250 MB.

Variable Default Description
FILE_UPLOAD_MAX_BYTES 52428800 (50 MB) Max size per uploaded file
FILE_UPLOAD_BATCH_MAX_BYTES 262144000 (250 MB) Max total size per upload batch
FILE_UPLOAD_TIMEOUT 120s Upload timeout (VM agent)
FILE_UPLOAD_TIMEOUT_MS 120000 (120s) Upload proxy timeout (Worker)
FILE_DOWNLOAD_TIMEOUT_MS 60000 (60s) Download proxy timeout
FILE_DOWNLOAD_MAX_BYTES 52428800 (50 MB) Max download file size
Variable Default Description
FILE_PROXY_TIMEOUT_MS 15000 File proxy request timeout
FILE_PROXY_MAX_RESPONSE_BYTES 2097152 (2 MB) Max file proxy response size
FILE_RAW_MAX_SIZE 52428800 (50 MB) Max raw binary file size (VM agent)
FILE_RAW_TIMEOUT 60s Raw file streaming timeout (VM agent)
FILE_RAW_PROXY_MAX_BYTES 52428800 (50 MB) Max raw file proxy size (Worker)
Variable Default Description
REPO_BROWSE_MAX_INLINE_BYTES 1000000 (1 MB) Max bytes to inline as text in the file viewer; larger stream raw
REPO_BROWSE_MAX_COMPARE_FILES 300 Max changed files in an Artifacts diff before truncation
Variable Default Description
MCP_IDEA_CONTEXT_MAX_LENGTH 500 Max characters of the reason an agent gives when it links its chat to an idea (ideas_write method link_session). The idea an agent gets at start-up is capped by the operations.agentIdeaContextMaxLength admin setting
MCP_IDEA_LIST_LIMIT 20 Default page size for ideas_read method list
MCP_IDEA_LIST_MAX 100 Max page size for ideas_read method list
MCP_IDEA_SEARCH_MAX 20 Max results from ideas_read method search
MCP_RELATED_IDEA_SEARCH_LIMIT 10 Default results from ideas_read method related
MCP_TASK_LIST_LIMIT 10 Default page size for tasks_read method list
MCP_TASK_LIST_MAX 50 Max page size for tasks_read method list
MCP_TASK_SEARCH_LIMIT 10 Default page size for tasks_read method search
MCP_TASK_SEARCH_MAX 20 Max results from tasks_read method search
MCP_TASK_DETAIL_RECENT_MESSAGE_LIMIT 5 Recent assistant messages returned by tasks_read method get
MCP_TASK_DETAIL_MESSAGE_SNIPPET_LENGTH 2000 Max characters per assistant message snippet in tasks_read method get
MCP_MESSAGE_SEARCH_LIMIT 10 Default page size for sessions_read method search
MCP_MESSAGE_SEARCH_MAX 20 Max results from sessions_read method search
SEARCH_QUERY_MAX_LENGTH 4096 Max total UTF-8 bytes retained by idea, task, knowledge, and message search as a DoS guard; responses disclose truncation
SEARCH_QUERY_MAX_TERM_LENGTH 48 Max LIKE-safe UTF-8 bytes retained per search term; higher values clamp to SQLite’s safe pattern ceiling
SEARCH_QUERY_MAX_TERMS 40 Max whitespace-delimited terms retained by those search surfaces; higher values clamp to the safe D1 parameter ceiling and responses disclose truncation
MCP_MESSAGE_LIST_LIMIT 50 Default page size for sessions_read method messages
MCP_MESSAGE_LIST_MAX 200 Max messages per sessions_read method messages request
MCP_ARCHIVED_TOOL_PAYLOAD_LIST_LIMIT 10 Default page size for sessions_read method tool_payloads
MCP_ARCHIVED_TOOL_PAYLOAD_LIST_MAX 50 Max archived payloads per sessions_read method tool_payloads
MCP_COMMENT_LIST_LIMIT 10 Default page size for comments_read method list
MCP_COMMENT_LIST_MAX 25 Max threads per comments_read method list request
MCP_COMMENT_BODY_MAX_LENGTH 4000 Max comment/reply body characters accepted through MCP
MCP_COMMENT_QUOTE_MAX_LENGTH 1000 Max quoted source-message characters returned to agents
COMMENT_DIRECTIVE_CONTEXT_MAX_LENGTH 6000 Max send-to-agent comment directive prompt length
MCP_TRIGGER_LIST_LIMIT 20 Default page size for list_triggers
MCP_TRIGGER_LIST_MAX 100 Max triggers per list_triggers request
MCP_INCIDENT_LIST_LIMIT 10 Default page size for private list_incident_queue
MCP_INCIDENT_LIST_MAX 50 Max private incidents per list_incident_queue request

Project event MCP tools use the ProjectData event limits above: PROJECT_EVENT_LIST_LIMIT, PROJECT_EVENT_LIST_MAX, and PROJECT_EVENT_SUBSCRIPTION_EVENT_CURSOR_MAX_LENGTH.

Variable Default Description
VITE_FILE_PREVIEW_INLINE_MAX_BYTES 10485760 (10 MB) Images below this size render inline automatically
VITE_FILE_PREVIEW_LOAD_MAX_BYTES 52428800 (50 MB) Images below this size show click-to-load; above shows download link
VITE_PASTED_TEXT_ATTACHMENT_THRESHOLD 4000 Pasted text at least this long becomes a text-file attachment. The deploy doesn’t pass it through, so set it when you build the web app yourself
VITE_ATTACHMENT_SNIFF_BYTES 4096 Bytes read from an attachment’s start to tell text from binary and draw its card’s first line
VITE_ATTACHMENT_PREVIEW_TEXT_MAX_BYTES 262144 (256 KB) Bytes of a text attachment read into the composer’s preview; the whole file is still sent
VITE_ATTACHMENT_PREVIEW_TEXT_MAX_LINES 2000 Lines of a text attachment the composer’s preview renders
VITE_ATTACHMENT_PREVIEW_LINE_MAX_CHARS 20000 Characters per line the composer’s text preview renders before cutting a long line
VITE_ATTACHMENT_LINE_COUNT_MAX_BYTES 8388608 (8 MB) Text attachments up to this size are read in full so the card shows an exact line count
VITE_ANALYTICS_MAX_QUEUE_SIZE 100 Max client-side analytics events retained before oldest events drop
VITE_ANALYTICS_FLUSH_THRESHOLD 10 Client event count that triggers an immediate analytics flush
VITE_ANALYTICS_FLUSH_INTERVAL_MS 5000 Client analytics background flush interval in milliseconds
VITE_DEBUG_DIAGNOSIS_EVENT_MAX_PAGES 100 Max paginated diagnosis-event pages loaded per browser request
VITE_ATTENTION_WINDOW_MS 86400000 (24 h) How recent a chat’s request for you must be to keep it in the session list’s Needs attention section. Set it when you build the web app yourself
VITE_CHAT_DELTA_MAX_PAGES 50 Max newer-message pages one chat refresh drains before failing visibly
VITE_CHAT_TIMELINE_MAX_PAGES 200 Max pages fetched per loop when the chat timeline drawer opens
VITE_CHAT_LOAD_UNTIL_MAX_PAGES 400 Max older-message pages chased while resolving a timeline jump
VITE_PROJECT_LIST_LIMIT 50 Projects loaded into each shared list-cache entry
VITE_PROJECT_POLL_INTERVAL_MS 30000 Project-list page refresh cadence in milliseconds; 0 disables
VITE_SIDEBAR_PROJECT_POLL_INTERVAL_MS 60000 App-shell project-list refresh cadence in milliseconds; 0 disables
VITE_WORKSPACE_PORTS_POLL_MS 10000 Workspace forwarded-port base refresh cadence in milliseconds
VITE_WORKSPACE_PORTS_BACKOFF_MAX_MS 120000 Maximum backoff between forwarded-port readiness polls
VITE_WORKSPACE_PORTS_FAILURE_BUDGET 6 Consecutive unavailable port-list responses before circuit cooldown
VITE_WORKSPACE_PORTS_BACKOFF_JITTER_RATIO 0.2 +/- jitter ratio applied to forwarded-port readiness backoff delays
VITE_WORKSPACE_PORTS_CIRCUIT_RESET_MS 300000 Open-circuit cooldown before probing forwarded-port readiness again
VITE_SESSION_INFRA_RETRY_DELAYS_MS 2000,5000,10000 Comma-separated retry delays for chat Details workspace/node fetches
VITE_PROJECT_PREFETCH_DELAY_MS 120 Mouse dwell before project-detail prefetch; focus/touch are immediate
VITE_BACKGROUND_FETCH_DELAY_MS 150 Delay before background query activity is shown and announced
VITE_ACP_PERMISSION_POLL_MS 2000 Pending ACP permission snapshot refresh cadence
VITE_ACP_PERMISSION_RECOVERY_POLL_MS 30000 Empty-snapshot recovery cadence after a missed realtime attention event
VITE_ACP_PERMISSION_QUERY_RETRY_COUNT 3 Transient ACP permission snapshot retries; 0 disables retries
VITE_CHUNK_LOAD_RETRY_DELAY_MS 350 Wait before retrying a failed lazy route-chunk import
VITE_CHUNK_RELOAD_COOLDOWN_MS 15000 Minimum gap between chunk-recovery reloads; guards against a reload loop
VITE_ROUTE_FALLBACK_REVEAL_DELAY_MS 180 Delay before the route loading spinner fades in, avoiding a flash
VITE_QUERY_PERSIST_MAX_AGE_MS 86400000 (24 h) How long a persisted query-cache record may be restored after writing
VITE_QUERY_PERSIST_THROTTLE_MS 1000 Minimum gap between IndexedDB writes of the query cache
VITE_QUERY_PERSIST_RESTORE_TIMEOUT_MS 250 Budget for the initial cache restore before failing open to no cache
VITE_CHAT_TRANSCRIPT_CACHE_TTL_MS 86400000 (24 h) How long a chat transcript stays cached after it was last used
VITE_CHAT_TRANSCRIPT_CACHE_MAX_SESSIONS 20 Most chat transcripts cached at once; older ones are evicted
VITE_CHAT_TRANSCRIPT_PERSIST_MAX_ROWS 500 Newest rows of each chat transcript written to IndexedDB
VITE_AGENT_CATALOG_STALE_TIME_MS 300000 Freshness window for the installable agent catalog query
VITE_PROVIDER_CATALOG_STALE_TIME_MS 300000 Freshness window for provider catalog size/location/price metadata
VITE_TRIAL_STATUS_STALE_TIME_MS 60000 Freshness window for platform compute availability
VITE_CACHED_COMMANDS_STALE_TIME_MS 300000 Freshness window for cached slash-command registries
VITE_REPORT_ISSUE_CONFIG_STALE_TIME_MS 300000 Freshness window for the report-issue availability flag
VITE_PROJECT_CREATE_CONFIG_STALE_TIME_MS 300000 Freshness window for project-creation config flags
VITE_CREDENTIAL_LIMITS_STALE_TIME_MS 30000 Freshness window for credential usage-limit windows shown in the chat header, on account cards in Settings → Agents, and in Settings → Advanced
VITE_CREDENTIAL_LIMITS_REFETCH_INTERVAL_MS 60000 Poll cadence for credential usage-limit windows while the tab is visible (paused in the background)
VITE_ACCOUNT_MAP_REFETCH_INTERVAL_MS 60000 Poll cadence for the Account Map while the tab is visible (paused in the background)
VITE_IDEAS_POLL_MS 30000 Ideas list refresh cadence while the tab is visible
VITE_IDEA_DETAIL_POLL_MS 30000 An idea page’s refresh cadence (its state and updates) while the tab is visible
VITE_IDEA_NEEDS_YOU_VISIBLE 3 Needs you cards shown on the Ideas list before the rest fold under “N more need you”
VITE_IDEA_UPDATE_MAX_LENGTH 4000 Characters the idea page’s Add an update… box accepts (the server allows up to the collaboration.ideaUpdateBodyMaxLength admin setting)
VITE_AUTOMATION_POLL_MS 30000 Automation page refresh cadence for schedules and watches while the tab is visible
VITE_DEPLOYMENTS_ACTIVE_POLL_MS 5000 Deployments refresh cadence while a deploy, start or pause is in progress or a domain is turning on
VITE_DEPLOYMENTS_IDLE_POLL_MS 30000 Deployments refresh cadence otherwise; both cadences pause while the tab is hidden
VITE_DEPLOY_HELP_FIX_PROMPT_TEMPLATE built-in text Request a Deployments Ask an agent puts in a new chat for a problem; {environment} is the name
VITE_DEPLOY_HELP_DEPLOY_PROMPT_TEMPLATE built-in text Request Ask an agent puts in a new chat to deploy; {environment} is the name
VITE_AUTOMATION_ATTENTION_WINDOW_MS 259200000 (3 d) How long a failed one-time automation or workflow stays under Needs your attention
VITE_AUTOMATION_RECENT_RUNS_PER_TRIGGER 10 Runs read per trigger for the Automation overview, and shown on a watch’s page
VITE_AUTOMATION_MAX_RUN_READS 25 Most triggers whose runs the Automation overview or History reads, one request each
VITE_AUTOMATION_MAX_LIST_PAGES 2 Pages of schedules and watches the Automation overview reads
VITE_AUTOMATION_PREVIEW_ROWS 5 Rows shown in the Automation overview’s Coming up, Recently and Workflows
VITE_AUTOMATION_RUNS_PAGE_SIZE 20 Runs per page on a trigger’s Automation page
VITE_AUTOMATION_CHAT_PICKER_LIMIT 100 Chats offered when an automation messages a chat; capped at the API’s 100
VITE_AUTOMATION_MAX_CHANNEL_PAGES 5 Channel catalog pages read on Behind the scenes → Channels
VITE_WORKFLOW_RUN_POLL_MS 10000 An open running workflow’s refresh cadence while the tab is visible; finished runs are not polled
VITE_WORKFLOW_RUNS_PAGE_SIZE 20 Workflow runs per page on Automation → Workflows; capped at the API’s 50
VITE_SAM_SETTINGS_POLL_MS 10000 Private SAM preference/availability polling in milliseconds; pauses in hidden tabs
VITE_SAM_ACTIVE_POLL_MS 2000 Private SAM polling while turns, actions or tracked project work remain active; pauses in hidden tabs
VITE_SAM_STREAMING_POLL_MS 15000 Private SAM safety-net polling while the running turn’s live stream is connected
VITE_SAM_STREAM_RECONNECT_MS 1500 Delay step before reopening a dropped live SAM stream (grows with each attempt)
VITE_SAM_STREAM_MAX_RECONNECTS 5 Live SAM stream reconnect attempts per turn before relying on polling alone

The control-plane UI writes an allowlisted slice of its query cache to IndexedDB so a full page reload paints from cache instead of refetching. Persisted slices are limited to allowlisted project summaries, stripped library indexes, and project-chat session messages. Credentials, admin diagnostics, node and workspace runtime details, file contents, signed URLs, and mutation state are never written to disk.

Records are namespaced by authenticated user and by a schema version, and are deleted on sign-out and on account switch, so one account can never be shown another account’s cached data. If IndexedDB is unavailable — private browsing, a storage quota failure, or a disabled store — the app degrades silently to its normal in-memory cache.

Project chat transcripts are kept for VITE_CHAT_TRANSCRIPT_CACHE_TTL_MS after they were last loaded or updated, capped at the VITE_CHAT_TRANSCRIPT_CACHE_MAX_SESSIONS most recently used. A chat opened inside that window renders from the cache at once and refreshes in the background; a chat that is not cached loads its newest page first, and older history loads as you scroll up. On disk each transcript keeps only its newest VITE_CHAT_TRANSCRIPT_PERSIST_MAX_ROWS rows, however far back it was read, so a chat restored after a reload pages older history back in the same way. The cache is only read after the sign-in check completes.

SAM uses first-party analytics ingestion for operational/product aggregates. Browser events are batched to /api/t; request analytics are written by API middleware when enabled. Analytics is best-effort and disabled paths preserve normal application behavior.

Client page/referrer fields follow a privacy normalization contract before enqueue: query strings, fragments, protocol, host/userinfo for page values, credentials, emails, UUIDs/ULIDs, long opaque tokens, common secret prefixes, repository/code file identifiers, and values after sensitive route markers are removed or replaced with [redacted]. Non-sensitive nested path shape, event names, durations, UTM source/medium/campaign, session ID, visitor/authenticated user ID, and explicit safe entity metadata are preserved for aggregate reporting.

Variable Default Description
ANALYTICS_ENABLED true Enable API middleware analytics; set false to skip request event writes
ANALYTICS_SKIP_ROUTES (built-in skip list) Comma-separated extra route prefixes/patterns excluded from middleware writes
ANALYTICS_DATASET (deployment-generated) Cloudflare Analytics Engine dataset name
ANALYTICS_SQL_API_URL https://api.cloudflare.com/client/v4/accounts Analytics Engine SQL API base URL override
ANALYTICS_DEFAULT_PERIOD_DAYS 30 Default admin analytics query lookback in days
ANALYTICS_TOP_EVENTS_LIMIT 50 Max rows returned by top-events admin query
ANALYTICS_WEBSITE_TRAFFIC_TOP_PAGES_LIMIT 20 Max top pages/referrers/events in website traffic sections
ANALYTICS_INGEST_ENABLED true Enable browser event ingestion at /api/t; false returns success without writes
RATE_LIMIT_ANALYTICS_INGEST 500 Analytics ingest requests allowed per IP per hour
MAX_ANALYTICS_INGEST_BATCH_SIZE 25 Max browser events accepted per ingest request
MAX_ANALYTICS_INGEST_BODY_BYTES 65536 Max ingest request body size in bytes
MAX_ANALYTICS_DURATION_MS 3600000 Max accepted page-duration value; larger values are clamped

Cloudflare installations write analytics to Workers Analytics Engine and read them through the Analytics Engine SQL API (queryAnalyticsEngine() in apps/api/src/routes/admin-analytics-query.ts), which needs CF_ACCOUNT_ID and CF_API_TOKEN. Without them the admin analytics routes answer 404 FEATURE_UNAVAILABLE (analyticsQuery) instead of a server error. A self-hosted build can instead install a local sink (installAnalyticsD1Sink() in apps/api/src/selfhost/analytics/): with ANALYTICS_SINK="d1" it records and reads the same events in the analytics_events table of OBSERVABILITY_DATABASE. That table is created by a self-host-only migration (apps/api/src/selfhost/observability-migrations.ts), never on Cloudflare, and its retention is bounded by the self-host admin settings analytics.d1.retentionDays (default 90) and analytics.d1.maxRows (default 500,000), applied by the 5-minute observability purge in batches of analytics.d1.purgeBatchRows (default 5,000) for at most analytics.d1.purgeTickBudgetMs (default 10,000) per run; unfinished deletes continue on the next run. The Cloudflare Worker does not install the sink, so ANALYTICS_SINK has no effect there.

Admin → Logs search reads Workers Observability with the same account API (queryWorkerLogs()), and Admin → Stream is fed by the tail worker. A deployment without a tail worker declares LOG_TAIL_AVAILABLE="false"; both pages then show where to read logs on the server instead (publicPlatformCapabilities() reports logSearch and liveLogStream).

External analytics forwarding is off by default. When enabled, SAM forwards only analytics rows already accepted by first-party ingestion/middleware; it does not bypass the client-side URL normalization contract.

Variable Default Description
ANALYTICS_FORWARD_ENABLED false Enable external analytics event forwarding
ANALYTICS_FORWARD_EVENTS key conversion events Comma-separated list of events to forward
ANALYTICS_FORWARD_LOOKBACK_HOURS 25 Hours to look back for events
ANALYTICS_FORWARD_CURSOR_KEY analytics-forward-cursor KV key used to remember forwarded progress
ANALYTICS_FORWARD_SQL_LIMIT 10000 Max rows fetched per forwarding run
ANALYTICS_SQL_FETCH_TIMEOUT_MS 30000 Timeout for Analytics Engine SQL fetches
SEGMENT_WRITE_KEY (unset) Segment Write Key for event forwarding
SEGMENT_API_URL https://api.segment.io/v1/batch Segment API endpoint
SEGMENT_MAX_BATCH_SIZE 100 Max events per Segment batch request
GA4_MEASUREMENT_ID (unset) Google Analytics 4 Measurement ID
GA4_API_SECRET (unset) Google Analytics 4 API secret
GA4_API_URL https://www.google-analytics.com/mp/collect GA4 Measurement Protocol endpoint
GA4_MAX_BATCH_SIZE 25 Max events per GA4 batch request

PROJECT_DATA_ARCHIVE_COMPACT_ENABLED=false is the default. Enabling it affects newly journaled terminal-session migrations only. Their format is pinned in D1 and the shard, so retries, reads and copy-back continue with that format after the flag is disabled. Legacy shards are not rewritten by deployment. Keep the existing global-sweep throttle while validating a compact canary.

Optional Worker variable Default Meaning
PROJECT_DATA_ARCHIVE_COMPACT_ENABLED false Write new archives as compact SQLite + compressed R2; existing formats remain readable.
PROJECT_DATA_ARCHIVE_DAILY_WRITE_BUDGET 250000 Installation-wide daily allowance of ESTIMATE UNITS (not billed rows) for compact migrations; 0 pauses admission of new migrations. A migration reserves its whole estimate once, when it is journaled; resuming it on later passes charges nothing. The checked-in wrangler.toml and production GitHub Environment override ship 6000000 in lockstep. At factor 2, the measured fixture reserves 6476 units per 2100 raw rows; 72k rows/hour needs ~5.33M units/day. The previous 2400000 allowance could not sustain that target. This is a reservation ceiling, not billed usage; see the throughput and cost discussion above.
PROJECT_DATA_ARCHIVE_WRITE_ESTIMATE_FACTOR 32 Safety multiplier applied to the row inventory estimateArchiveWrites already counts (rows, archived tool payloads, grouped rows, and 512-byte units of grouped FTS text, including source deletion) — NOT an independent amplification factor. The checked-in wrangler.toml ships 2. Production measurement 2026-09-14: two project_data_archive_write_budget samples an hour apart give ~65,001 estimated writes per migration, i.e. ~8,000 inventory units at the then-shipped factor of 8; four isolated archive ticks billed 5,950/6,436/7,942/9,823 Durable Object rows. Billed rows per inventory unit therefore spans 0.74-1.23, and 2 exceeds the worst observed ratio by ~63%. Raising it does not make the work safer, only more expensive in budget terms: at 8 the same allowance bought 12 migrations/day while the hourly cadence allowed 24, so half the sweep ticks reclaimed nothing. Sample size is small (2 budget samples, 4 telemetry buckets) — re-measure before changing it.
PROJECT_DATA_ARCHIVE_R2_TIMEOUT_MS 10000 R2 I/O deadline shared across each compact read/export/seal operation, in milliseconds. A chunk write gives each of its R2 calls its own deadline of this length.
PROJECT_DATA_ARCHIVE_BUDGET_RECEIPT_RETENTION_MS 604800000 Unused reservation receipt retention (7 days); clamped to at least one UTC budget day.
PROJECT_DATA_ARCHIVE_BUDGET_RECEIPT_CLEANUP_LIMIT 100 Maximum expired receipts removed per unused release; zero disables cleanup.

Compact archives keep session metadata, a dedicated derived search projection, consolidated conversation text, grouped FTS and existing tool-archive pointers in SQLite. Original message rows (IDs, timestamps, order, origins and full tool metadata) live in immutable gzip R2 chunks in the private PROJECT_DATA_ARCHIVE_R2 binding. SQL chunk references contain sizes, SHA-256, role counts, time bounds and message IDs. Exact history and tool expansion fetch and verify those chunks. Missing/corrupt objects fail the request; they do not silently produce a truncated history. The original terminal hash and search-projection count/hash coverage must match before publication and source deletion. Already-published archives without current coverage are repaired through durable raw/grouped cursors: compact raw history advances by configured R2 chunks, while legacy raw rows and grouped fallback advance by the configured hash-page size. The resumable projection commitment and FTS counts are verified before coverage becomes complete. This is one-time backfill work and is reported separately from steady-state query coverage. Version 2 recovery manifests include the compressed-object references; legacy version 1 manifests remain unchanged.

Compact chunk exports use the smaller of PROJECT_DATA_ARCHIVE_CHUNK_BYTES and 2 MiB, with an 8 MiB serialized/decompressed object ceiling. A single valid row above the configured chunk target travels alone up to the absolute Durable Object RPC ceiling; it is never truncated or allowed to livelock the cursor. Rows above that platform ceiling still fail closed and remain on the source. R2 objects have no automatic expiry: deleting them destroys archive history and recovery data.

Everything in this section applies only when PROJECT_DATA_ARCHIVE_COMPACT_ENABLED is true: the write-budget reservation and the derived selection ceiling are both gated on it (selectCandidates / processArchiveMigrationBatch in packages/project-data/src/scheduled/project-data-archive-sharding.ts). Legacy (non-compact) archiving reserves nothing; its pass is bounded by PROJECT_DATA_ARCHIVE_WALL_TIME_MS and PROJECT_DATA_ARCHIVE_SWEEP_SESSIONS.

The write allowance is a durable admission estimate, not a hard invoice cap. Each migration reserves, once when it is journaled, 1,000 writes plus the estimate factor times the sum of raw rows, grouped rows, tool-pointer rows and grouped UTF-8 text bytes rounded up to 512-byte units. The installation-wide D1 reservation is atomic, resets on the next UTC day and is never refunded after an interrupted attempt. Contenders that definitively lose journal creation or lease acquisition before doing archive writes, and candidates the root object refuses before copying (precopy_refused), release their reservation with an idempotent D1 receipt. The pool covers this SAM installation; other installations on the same Cloudflare account need separate headroom. Source inventory is rechecked under the transcript lock before creating its intent. New sessions that cannot reserve remain readable on root; existing interrupted migrations resume without a new reservation. The estimate counts at most 1,000,000 inventory units (ARCHIVE_MAX_ESTIMATE_INVENTORY_UNITS). Unscoped candidate selection is bounded by a ceiling derived from the daily allowance itself (until 2026-11-13 also by PROJECT_DATA_ARCHIVE_SWEEP_MESSAGE_BUDGET, which made every session above 10,000 messages unselectable). The derivation floors twice, in two steps: archiveAffordableWriteUnits() computes floor((allowance - 1000) / factor) — the largest estimate the allowance can ever admit — and archiveAffordableMessageCeiling() then computes floor(units / (1 + PROJECT_DATA_ARCHIVE_SWEEP_UNIT_OVERHEAD_PERCENT / 100)) (both in packages/project-data/src/archive/write-budget.ts). Collapsing the two floors into one expression can differ by one at some factor/overhead combinations. Deriving the second half means a selector can never offer a candidate the write budget must refuse on every attempt. Two independently configured ceilings previously had to agree by hand, and when the deployed allowance was lowered without lowering the message budget, largest-first selection re-picked the same unaffordable session on every pass and reclaimed nothing for four days while still reporting success.

The derived ceiling assumes an overhead; it does not measure one. A session whose real tool-payload, grouped-row and FTS-unit cost exceeds the assumption is still refused at reservation time, and the pass then descends to the next-smaller candidate (PROJECT_DATA_ARCHIVE_SWEEP_FALLTHROUGH_DEPTH controls how many spare candidates it reads for that purpose). A candidate refused by the write budget opens no migrating fence, stays readable on root, and consumes no session slot. A candidate the root object refuses before copying closes its fence, returns to root, releases its reservation and also consumes no slot (processArchiveMigrationBatch).

The two refusals are distinguished because they need different responses. exceeds_allowance means the session costs more than the entire daily pool and waiting cannot help; window_exhausted means the day’s pool is spent and the next UTC window refills it. After PROJECT_DATA_ARCHIVE_BUDGET_STALL_ALERT_SWEEPS consecutive passes that migrate nothing and see only the former, the sweep cadence row reports partial with an actionable last_error instead of succeeded. A session whose estimate exceeds the whole daily allowance is refused as exceeds_allowance until the allowance is raised.

Source reclaim and SQLite/FTS index maintenance still consume writes. project_data_archive_sql_usage reports actual cursor writes. The flip (finalizeSourceDelete) commits the routing anchors and the source_deleted intent without deleting rows, so project_data_archive_candidate_migrated.sourceFinalization reports zero rows deleted; the rows are then reclaimed in bounded pages (reclaimArchiveSourcePage, PROJECT_DATA_ARCHIVE_CHUNK_ROWS rows per page) under the tick’s PROJECT_DATA_ARCHIVE_WALL_TIME_MS, reported as reclaim on the same event and as reclaimedRows / reclaimPending in the sweep stats. A reclaim a deadline, reset or older coordinator left unfinished is found from the root object’s own source_deleted intents and rows at the start of the next tick (reclaimPendingSources). That pass visits only projects with a flipped journal row whose reclaim D1 has not seen complete (project_data_archive_migrations.reclaim_pending, D1 migration 0237; 1 by default, so pre-existing rows and rows an older coordinator writes are covered). A completed reclaim clears the flag. So does a complete listing of the root object that does not name a row, but only for rows read from D1 before the listing started, so a flip committed concurrently is never cleared. Sessions fenced by an in-progress copy-back are listed as fenced and keep their flag. A tick therefore wakes no root object when nothing is left to reclaim; without the flag, 21 clean projects on staging made a 3-second tick take 20 seconds and archive nothing. While rows remain, reads route to the shard, project search dedupes by session and message id, and comments on the session are refused; copy checkpoints retain the last operation, operation ID, ordinal, byte totals, lease epoch, and timing for reset attribution. These invocation timings are diagnostic only: billed Durable Object duration comes from Cloudflare durableObjectsPeriodicGroups.sum.duration. Compare aligned daily metrics with these events before raising throughput, and separate one-time repair/backfill from steady-state search. At the default 250,000 estimated writes/day, 30 days admits at most 7.5 million estimated migration writes. Normal application traffic, legacy migrations, operator copy-back and other Workers are outside this pool, so operators must reserve account headroom separately. A zero allowance pauses new compact migrations without breaking reads, in-flight migrations or completed crash-gap publication; disable PROJECT_DATA_ARCHIVE_GLOBAL_SWEEP_ENABLED for a hard stop. Reclaim is paged, so no single root transaction deletes a whole session.

A migration is a resumable cursor (migrateClaimedCandidate): the journal phase, the D1 copy checkpoints, the shard’s chunk receipts, the shard’s verification progress and verdict (do_meta key archive_target_verify:<session>) and the root rows left to reclaim. A pass resumes an in-flight migration without re-running the source prepare and without a new write reservation; it rotates the claim’s source-intent token instead (reattachClaimToken). A claim that fails after moving the migration forward keeps its phase and resumes on the next pass; only claims that move nothing count toward PROJECT_DATA_ARCHIVE_POISON_AFTER_ATTEMPTS. Until the flip the session stays readable from the root object, which still holds every row (resolveExactReadOwner routes migrating to the root; isSourceExactReadFenced), while writes stay fenced.

Root work is bounded by a write-generation fence (Durable Object migration 076-archive-source-write-generation): triggers count every write to the rows a terminal version hashes (messages, grouped rows, tool-payload archives, session anchor columns, message comments) for a session whose source intent has not flipped, including writers that skip the transcript fence. The prepare fences the session and reads the generation under the transcript lock, hashes in pages while yielding to other requests (local measurement: 100,000 messages hashed in 302 slices, longest 70 ms), then re-checks the generation (archiveSourcePrepareIntent). The flip compares the generation instead of re-hashing (finalizeSourceDelete with proveByWriteGeneration; about 1 ms locally); intents prepared before the fence, and coordinators calling the older archiveSourceFinalizeDelete, still re-hash. The prepare records terminal-version components, and before the flip a compact copy is re-read from R2 in pages bounded by PROJECT_DATA_ARCHIVE_R2_TIMEOUT_MS per call (verifyArchiveTargetPage): each raw chunk must hash to the receipt the root computed at export, rows must be in strictly increasing export order (UTF-8 byte order), the row count must equal the prepared count, and the shard’s anchor, grouped rows and tool-payload archives must match the root’s components. A deterministic verdict (a receipt, order, identity, count or component mismatch) is kept, so a later failure does not re-read the copy; a transient R2 error keeps the verified progress and is retried. An in-flight migration whose intent predates the fence re-runs the yielding prepare once on resume. If the flip finds the root changed or busy (a moved write generation, a new attention marker, a runtime row), it returns a refusal (archiveSourceFlip) and the migration is unwound (unwindFlipRefusal): the reason is recorded, the root intent removed, the shard copy deleted in bounded pages (archiveTargetAbandonPage), then the journal frozen as precopy_refused and the location returned to root; a claim that finds the intent gone finishes an interrupted unwind. The session is retried after PROJECT_DATA_ARCHIVE_PRECOPY_REFUSAL_RETRY_MS, never poisoned. A candidate whose lower-bound estimate (1000 + factor x message_count) cannot fit the remaining daily allowance is refused without asking the root object to scan it. Sweep stats report yielded, flipUnwound, verifiedChunks, reclaimedBytes and reclaimStuck; a flipped session still holding root rows more than three sweep intervals plus one wall time after its flip logs project_data_archive_reclaim_stuck at error level with the recovery action.

After any compact archive is published, rollback must retain compact readers (disable the writer flag to pause new migrations). Before downgrading to a build without paged reclaim, roll forward or let pending reclaims finish (the root object holds no archive_reclaim_pending: keys in do_meta): an older build neither reclaims those rows nor refuses comments on them. Deploying a binary from before compact-reader support would read empty raw SQL tables for those sessions; copy them back and verify root ownership before considering such a downgrade.

Certificate issuance retries transport failures, HTTP 429 and HTTP 5xx with capped exponential backoff. Cloud-init also retries its certificate fetch and reports a fixed boot-failure reason when bootstrap cannot continue. Tasks replace a failed fresh VM only after its deletion is confirmed, before any workspace execution. The default is one replacement; a second boot failure ends with its specific reason. Wrong agent versions fail immediately, while a VM without any heartbeat gets six minutes by default.

  • ORIGIN_CA_RETRY_MAX_ATTEMPTS — Maximum upstream certificate attempts including the first; retries transport, 429 and 5xx only (default: 3).
  • ORIGIN_CA_RETRY_BASE_DELAY_MS — Initial upstream certificate retry delay (default: 500).
  • ORIGIN_CA_RETRY_MAX_DELAY_MS — Cap on upstream certificate exponential backoff (default: 2000).
  • ORIGIN_CA_REQUEST_TIMEOUT_MS — Deadline per upstream certificate request, including reading its body (default: 10000).
  • CLOUD_INIT_AGENT_DOWNLOAD_TIMEOUT_SECONDS — Deadline for the agent binary download, including DNS and connection time (default: 60). Failure triggers the best-effort boot-failure callback.
  • CLOUD_INIT_CERT_MAX_ATTEMPTS — Maximum cloud-init CSR POST attempts including the first (default: 3).
  • CLOUD_INIT_CERT_BASE_DELAY_SECONDS — Initial cloud-init certificate retry delay (default: 2).
  • CLOUD_INIT_CERT_MAX_DELAY_SECONDS — Cap on cloud-init certificate exponential backoff (default: 8).
  • CLOUD_INIT_CERT_REQUEST_TIMEOUT_SECONDS — Deadline per cloud-init certificate request and best-effort boot-failure report; must exceed the upstream API retry budget (default: 45).
  • TASK_RUNNER_FIRST_HEARTBEAT_TIMEOUT_MS — Fresh VM first-heartbeat deadline, capped by TASK_RUNNER_AGENT_READY_TIMEOUT_MS (default: 360000).
  • TASK_RUNNER_BOOT_MAX_REPLACEMENTS — Maximum fresh VM boot replacements per task run; 0 disables replacement; workspace execution is never replayed (default: 1).

Set these optional variables in the GitHub deployment Environment; the deployment pipeline forwards them to the Worker. No new secrets are required. Certificate request and retry budgets should remain below the first-heartbeat deadline.

The optional Worker variables CLI_RECEIPT_REQUEST_MAX_BYTES (default 262144) and CLI_RECEIPT_RESPONSE_MAX_BYTES (default 65536) accept positive byte counts. Keyed requests exceeding the request limit are rejected before reservation; replies exceeding the response limit leave the receipt pending for reconciliation. These are runtime configuration overrides, not credentials or required deployment secrets.

Portable application build-context settings

Section titled “Portable application build-context settings”

Installation admins edit these at Admin → Settings. They use the existing R2 binding and S3 credentials; no new Worker variables or infrastructure are required. Executor selection is reserved for the later Cloudflare executor rollout.

Setting Default Purpose
deployments.buildContextCollectionMode off shadow enables an asynchronous hidden context probe on publish; actual build execution remains unchanged
deployments.buildContextStartTimeoutMs 10,000 Bounds control-plane wait for source collection acceptance
deployments.buildContextMaxBytes 2 GiB Maximum raw tar (including headers) and compressed bundle bytes
deployments.buildContextCollectTimeoutMs 120,000 Source collection deadline
deployments.buildContextUploadTtlSeconds 300 Presigned upload/download URL lifetime
deployments.buildContextRetentionHours 48 Minimum age before abandoned/terminal bundles are deleted
deployments.buildContextCleanupBudgetMs 10,000 Work budget per daily cleanup pass
deployments.buildContextCleanupPageSize 250 R2 listing page size; a persisted cursor resumes remaining pages

Collection has no file-count cutoff. For a 100,000-file context near 1.5 GiB, tar headers add at least 49 MiB, plus filename/padding metadata. At 50 MiB/s the payload alone needs about 31 seconds to collect and another 31 seconds to upload; filesystem traversal, compression, and network conditions add time. Collection stops at its deadline rather than repeatedly processing a fixed batch. Phase timings are stored in publish-job events. The source request retains the existing overall VM publish timeout (20 minutes by default) and emits publish heartbeats throughout collection/upload.

Edit runtime controls in Admin → Settings. Instant sessions always use Cloudflare; deployments.buildExecutor selects the VM-session executor. These controls are independent of the default-off context shadow probe. Keep the VM setting at node until staging validates Cloudflare publishing from a VM with unchanged source build/save counters and a served release; that validation remains pending.

Runtime setting Default Meaning
deployments.buildExecutor node VM build executor (node or cloudflare); explicit Cloudflare selection never silently falls back
deployments.builderMaxConcurrent 6 Platform reservations, clamped to the deployed class capacity; maximum 6
deployments.builderProjectMaxConcurrent 2 Per-project reservations; maximum 2
deployments.builderReservationGraceMs 300,000 Grace after the stored builder deadline before cron force-releases unconfirmed reservations with an alert; active jobs become unknown, and physical shutdown may remain unconfirmed
deployments.builderDeadlineMs 1,200,000 Absolute deadline after first admission; also capped by the overall publish-job deadline
deployments.builderCapacityBackoffMs 30,000 Delay before retrying platform capacity errors
deployments.builderDrainLimit 6 Maximum queued jobs considered per cron tick
deployments.builderDaemonReadyTimeoutMs 60,000 DinD readiness deadline
deployments.publishCallbackMaxBodyBytes 1,048,576 Maximum actual JSON bytes for authenticated publish events, image artifacts and release callbacks, for source and builder tokens.
deployments.builderCallbackTimeoutMs 30,000 Control-plane HTTP timeout; also controls bootstrap HTTP shutdown
deployments.builderCallbackAttempts 3 Maximum attempts for retryable callbacks
deployments.builderCallbackRetryDelayMs 5,000 Delay between retryable callbacks
deployments.builderHeartbeatIntervalMs 15,000 Builder liveness callback interval

Deployment topology is configured through GitHub Environment variables:

Variable Default Meaning
DEPLOY_BUILDER_INSTANCE_TYPE standard-4 Cloudflare Container instance type; applies on deployment
DEPLOY_BUILDER_MAX_INSTANCES 6 ComposeBuilderContainer class capacity; runtime admission never exceeds it

The deploy generator mirrors actual class capacity into the Worker binding DEPLOY_BUILDER_CLASS_MAX_INSTANCES; do not set that binding independently. Builder images contain Docker, Compose and sam-builder; no installation or user credentials are baked into them. Each job receives only a job-and-attempt callback token and short-lived presigned URLs for its context and image keys. The control plane checks the builder against VM_AGENT_REQUIRED_VERSION, when configured, before accepting a job.

Application builders have unrestricted internet egress. Package installation in Dockerfile RUN steps and direct presigned object transfers use normal TLS trust; there is no builder host allowlist, outbound proxy, or interception CA setting. Isolation relies on the dedicated microVM, one-job callback authority, and hard deadline. See the security architecture.

A superadmin can set these keys under Admin → Settings → AI models. Reset llm.openAICompatible.baseUrl to restore normal Cloudflare routing. No endpoint is enabled by default (services/llm-endpoint-settings.ts).

Setting Default Meaning
llm.openAICompatible.baseUrl unset OpenAI-style base URL, such as https://llm.example.com/v1; omit /chat/completions. Overrides Workers AI chat, task titles, diagnosis and SAM agent calls.
llm.openAICompatible.apiKey unset Optional Bearer key, encrypted in platform credentials and never returned by settings reads.
llm.openAICompatible.model unset Endpoint model ID; falls back to the caller’s requested model.
llm.openAICompatible.agentModel unset Override for SAM and project agents.
llm.openAICompatible.taskTitleModel unset Override for title generation.
llm.openAICompatible.diagnosisModel unset Override for diagnosis.
llm.openAICompatible.aiProxyModel unset Override for the proxy’s Workers AI chat route.
llm.openAICompatible.allowPrivateNetwork false Explicitly allow an operator endpoint on a private host. Metadata/link-local hosts remain forbidden.
aiProxy.directUpstreamEnabled false Enable platform and BYO AI proxy routes when no addressable Cloudflare AI Gateway exists. Requires a provider credential for platform calls. Ignored when a gateway is addressable.
aiProxy.perUserMonthlyCostCeilingUsd 0 Monthly spend ceiling applied to every user, in whole USD (0 = none). Superadmin only. Applies only without an addressable gateway; ignored when one exists.

The endpoint capability reuses the existing per-isolate settings cache (up to 60 seconds); a warm, unconfigured Cloudflare call performs no additional D1 or credential reads. Configured URL/key pairs share one atomic D1 snapshot and TTL, so another isolate’s rotation cannot mix an old URL with a new key (services/llm-endpoint-snapshot.ts:resolveLlmEndpointSettings). Admin changes invalidate the local cache immediately. Unreadable configuration refuses the request instead of sending prompts to another provider: the Workers AI proxy returns 503, and title generation falls back to truncation. Title and diagnosis settings lookups receive at most one quarter of the caller’s inference time budget (services/platform-capabilities.ts:resolveLlmEndpointCapability, services/llm-chat-target.ts:resolveWorkersAiChatTargetWithin).

Configured endpoints receive their own model and key, with no Cloudflare attribution headers or Workers AI template controls. Every redirect is validated; cross-origin body replay is refused and credentials are stripped on cross-origin GET redirects. Streaming calls preserve the caller’s stream_options.include_usage choice. Missing usage is estimated for token budgets; estimates are never presented as measured run usage (packages/ai-proxy/src/llm-chat-target.ts, packages/ai-proxy/src/ai-token-usage-accounting.ts).

Proxy routes authenticate before checking availability, so unauthenticated callers always get 401. Availability means the operator switch permits proxy calls and either a gateway ID and account ID form an addressable gateway, or the admin explicitly enabled direct upstreams. A standalone gateway ID is insufficient. Custom-baseURL credentials are returned to workspaces only as a SAM proxy configuration; if the proxy does not serve them, agent-key returns 404 (services/ai-proxy-availability.ts:isAiProxyEnabled, routes/workspaces/runtime-agent-key.ts).

Daily token budgets apply to both routes. Without a gateway, SAM estimates platform model spend from its catalog into the existing per-user budget counter, and the monthly cap reads that total; the provider invoice remains authoritative. A missing local cost read refuses a capped call. The KV fallback reads at most 31 days in parallel. With a gateway, the hourly gateway-log cache remains the spend record. An operator endpoint’s model has no catalog price and contributes zero dollars to this cap, including on installations with a gateway; set spending limits at the endpoint/provider as appropriate (packages/ai-proxy/src/ai-monthly-cost-cap.ts, packages/ai-proxy/src/ai-gateway-availability.ts:isMonthlyCostCapAvailable).

Without a gateway, the cap each call is checked against is the lower of the user’s own cap and aiProxy.perUserMonthlyCostCeilingUsd (ai-monthly-cost-cap.ts:effectiveMonthlyCostCapUsd, the one cap predicate shared by the gate, GET /api/usage/ai/budget and budget validation). A user who clears their cap is still held to the ceiling, and PUT /api/usage/ai/budget refuses a cap above it. The ceiling is per user, not a total across users. The operator chooses its amount in Admin; validation requires nonnegative whole USD within numeric precision, with no separate business maximum. It is read from the per-isolate admin settings cache (a change applies within 60 seconds), only on the no-gateway path, so a gateway installation’s /ai/v1 reads are unchanged. If the settings snapshot cannot be read after its cache expires, locally metered platform-funded inference is refused with a retryable 503 SERVICE_UNAVAILABLE, logged as ai_proxy.monthly_cost_ceiling_unreadable. The same protection applies on a cold isolate; no extra last-known ceiling is reused during an outage (services/ai-proxy-ports.ts). Gateway calls and locally own-funded calls do not read this ceiling. A failed monthly-spend read also refuses inference with a retryable 503, without reporting that the cap has been reached. A call refused by the monthly cap or the daily token budget is a 429 whose message names that limit. The VM agent reports it as sam_ai_usage_limit_reached, not provider_overloaded, so the chat shows “AI usage limit reached” without a retry suggestion (packages/vm-agent/internal/acp/sam_usage_limit.go, packages/shared/src/failure-classification.ts). Once a ceiling is set, every gated call on such an installation reads the month’s priced total (one Durable Object call), not only calls by users with their own cap. Passthrough calls served by a platform-owned credential are priced too; a user’s or project’s own credential is their own spend. Spend is priced after each response, so calls admitted together before the total crosses the cap can each overshoot it by their own cost. A stored per-user settings row that cannot be parsed is ignored (platform defaults, logged as ai_proxy.budget_settings_row_skipped) rather than failing the call. Priced calls also record a per-model, per-day row in the same counter transaction, which the usage page shows as model and day breakdowns on installations without a gateway (packages/ai-proxy/src/ai-model-usage.ts).

Locally metered passthrough calls using an installation-owned credential must use a model in SAM’s pricing catalog and that model’s canonical provider endpoint (origin and base path). Unknown models and custom endpoints aliasing catalog model names are refused before forwarding: a compatible protocol or configured provider label does not establish a catalog price. Use a user/project-owned credential for custom passthrough endpoints; the native operator-endpoint exception described above is unchanged. Missing provider usage is estimated from serialized request bytes (including tool schemas, system prompts and structured tool history) and generated output. Provider-reported usage takes precedence over these fallback estimates. User- and project-owned credentials remain usable after platform-funded monthly spend reaches its limit; daily token budgets still apply to all calls. An administrator ceiling denial directs the user to their administrator or the next month.

A test installation can prove platform-funded metering and spending limits with no AI key. For allowlisted users, SAM-managed (sam mode) calls to /ai/v1/chat/completions, /ai/v1/responses and /ai/anthropic/v1/messages (and count_tokens) are answered in-process by a fake model instead of Anthropic or OpenAI (services/ai-test-upstream.ts). Every gate still runs: auth, model allowlist, tier, daily token budget and the monthly cap. The fake’s response goes through the normal accounting path: it is priced from the catalog, recorded in the per-user counter and counted against the cap. Nothing leaves the Worker, and no platform key or Cloudflare token is sent. Passthrough routes (/ai/proxy/:wstoken/*) and Workers AI (@cf/*) models are not faked: an allowlisted user’s passthrough calls still spend the real key.

It is off unless all of these hold:

Lock Where Meaning
AI_TEST_UPSTREAM_ENABLED=true Worker var Deploy-time lock, absent by default. Only the exact value true counts.
ENVIRONMENT Worker var Must be staging, staging2, selfhost, development or test. Production, unset and anything else are refused.
No AI Gateway Worker vars Only where SAM meters spend itself (no addressable gateway). With a gateway, spend comes from the gateway’s logs, which an in-process answer never reaches.
aiProxy.testUpstreamUserIds Admin setting User ids whose calls are faked (at most 50; default empty = off). Every other user keeps the real model.

aiProxy.testUpstreamCostPerCallCents (admin setting, default 40) is the list-price cost each fake call reports. The fake sizes its reported output tokens so the requested model’s catalog price comes to that cost, so pick a catalog model whose output price keeps your test under the daily token budget (for example an Opus model: $0.40 is about 16,000 output tokens). The fake spend is recorded in the listed users’ real counters for the month.

In practice this means a self-host box. Put AI_TEST_UPSTREAM_ENABLED=true in deploy/selfhost/.state/secrets.env (mode 0600) and run pnpm selfhost:deploy. To turn it off, delete the line and run pnpm selfhost:deploy --unset AI_TEST_UPSTREAM_ENABLED: on a sealed box, deleting the line alone keeps the sealed value. The Cloudflare deploy pipeline does not forward this variable, and Cloudflare installations have an AI Gateway anyway.