Runtime is the control plane for a single multi-agent run. Once you have a Sandbox config, role Profiles, and Services, you use runtime to run the swarm, watch live events, move files safely, update permissions mid-run, and shut everything down cleanly.
For full signatures and error codes, see the SDK & API Reference.
1. Creating a Runtime
Start a new run with createRuntime():
import {
DEFAULT_WORKER_IMAGE,
ServiceRegistry,
createRuntime,
} from '@anyswarm/core';
const runtime = await createRuntime({
sandbox, // Immutable config from createSandbox()
executor: 'pi', // Default 'pi', or switch to 'codex'
// Optional: local Docker setup auto-discovers this; set publicUrl for remote or reverse-proxied hosts
...(process.env.ANYSWARM_RUNTIME_PUBLIC_URL
? { connection: { publicUrl: process.env.ANYSWARM_RUNTIME_PUBLIC_URL } }
: {}),
// Model aliases: upstream URLs and API keys stay strictly on the host Model Gateway
models: {
default: {
provider: process.env.ANYSWARM_MODEL_PROVIDER ?? 'openai',
model: process.env.ANYSWARM_MODEL_ID ?? 'gpt-5.4',
// protocol defaults to 'responses'; Pi also supports 'chat-completions'
upstream: {
url: process.env.ANYSWARM_MODEL_URL!,
headers: process.env.ANYSWARM_MODEL_TOKEN
? { authorization: `Bearer ${process.env.ANYSWARM_MODEL_TOKEN}` }
: {},
},
},
},
// Optional: tune per-stage file budgets for larger repos (initial / snapshot / replace / export / session)
// filePolicy: { initial: { maxBytes: 64 * 1024 ** 2 } },
services: new ServiceRegistry(), // Pre-registered shared Services (see Services & Permissions)
profiles: {
researcher: {
prompt: 'Inspect the repository and record key findings.',
model: 'default',
image: DEFAULT_WORKER_IMAGE,
writable: false,
services: {},
},
},
maxAgents: 4, // Maximum concurrent live Agents
outputDir: './runs', // Traces and artifacts are saved under outputDir/<runtime.id>/
});
createRuntime() sets up the run directory, Model Gateway, and Service Bridge, but starts zero sandboxes until your Harness explicitly calls runtime.spawn() (covered next in Agents & Profiles).
Flexible executors & model protocols: beyond the
'pi'and'codex'shorthands, which use the installed version, usecreatePiExecutor({ version: '1.4.0' }),createCodexExecutor(...), orcreateExecutorAdapter(...)for image-installed executors. Pi supports both Responses and Chat Completions (see SDK & API Reference).
Custom reasoning models
Declare a custom model’s limits and reasoning levels in models.<alias>.capabilities. For a Pi model whose upstream accepts xhigh, use:
capabilities: {
contextWindow: 128000,
maxOutputTokens: 16384,
tools: true,
reasoning: true,
thinkingLevelMap: { xhigh: 'xhigh' },
}
Each mapping value is the effort string sent upstream; null marks a level unsupported. Omitted entries retain Pi’s model defaults, and custom reasoning models need an explicit mapping for xhigh. Framework levels remain off, minimal, low, medium, high and xhigh; for an upstream that calls its highest effort max, configure xhigh: 'max' and request thinkingLevel: 'xhigh'. Use the upstream’s actual effort names and limits. The mapping is copied and frozen with the model configuration and included in the generated Pi catalog and model capability record.
Select a level with Profile.session.thinkingLevel, a spawn override, or runtime.session.configure(). An explicit unsupported level fails before the first model request at startup, or before any setter in a dynamic patch. It is never silently replaced with another level. Omitting thinkingLevel keeps the executor’s default; runtime.session.getState() reports its actual value and available levels. Existing configurations need a mapping only when they explicitly request an extended level that their custom model does not already advertise.
2. Monitoring what happens: runtime.onEvent()
Register your listener before calling spawn() or send() so you never miss early lifecycle events:
| What you want to do | Event type | When it fires |
|---|---|---|
| Stream Agent replies live | output |
As an Agent emits text chunks during a turn |
| Know when a turn finishes to trigger the next step | settled |
When a turn ends (outcome: 'completed' | 'failed' | 'aborted') |
| Handle crashes or unexpected exits | error / exit |
On execution errors or sandbox exits (fatal / expected flags) |
| Refresh UI, session stream, or state mirror | agentChanged / runtimeChanged / management / session |
When Agent state, session activity, Runtime state, or dynamic config changes |
| Detect dropped events under slow listeners | subscriberGap |
Emitted with the dropped count after an overloaded async listener drains |
A practical pattern driving coordination from settled:
const completed = new Set<string>();
const unsubscribe = runtime.onEvent((event) => {
// 1. Stream Agent output to your host console
if (event.type === 'output') {
process.stdout.write(`[${event.agentId.slice(0, 8)}] ${event.text}`);
return;
}
// 2. React when an Agent finishes its current turn
if (event.type === 'settled') {
if (event.outcome === 'completed') completed.add(event.agentId);
console.log(`Agent ${event.agentId.slice(0, 8)} finished turn: ${event.outcome}`);
return;
}
// 3. Catch failures or unexpected exits
if (event.type === 'error' || (event.type === 'exit' && !event.expected)) {
console.error('Runtime alert:', event);
}
});
Async backpressure: each listener can hold at most 32 unresolved async callbacks. If additional events arrive while the listener is saturated, they are dropped and the listener receives a
subscriberGapevent with the dropped count once a callback settles. Callruntime.get(),runtime.list(), orruntime.management.get()to resynchronize.
3. Working with sandbox files: runtime.files
Each Agent gets a private /workspace/project by default. When your Harness needs to read files from one Agent or sync them into another without restarting its session, use runtime.files:
// 1. Capture a consistent snapshot (file tree + SHA-256 digest) from coder's sandbox
const coderSnap = await runtime.files.snapshot(coder.id, {
requestId: 'snap-coder-1',
paths: ['.'],
});
// 2. Atomically replace another Agent's workspace using its last known digest (CAS)
const receipt = await runtime.files.replace(reviewer.id, {
requestId: 'sync-to-reviewer-1',
expectedDigest: reviewerInitialDigest, // from an earlier snapshot on reviewer
files: coderSnap.files,
// Optional: pass writable: true to unlock a read-only workspace on handoff
});
- Why pass
expectedDigest?files.replacepauses writer processes inside the target sandbox, checks that the directory has not changed unexpectedly, applies adds/edits/deletes atomically, and keeps the Agent’s conversation session intact. - Need to share files across multiple Agents? The built-in OpenSandbox provider isolates every workspace and rejects live shared mounts (see Sandbox migration notes) — use
runtime.filessnapshots or a shared Service instead. Only when using a customSandboxProviderthat declares shared-workspace support can you passworkspace: { id: 'shared-repo', mode: 'read-write' }toruntime.spawn()(and callruntime.stop()on all writers before exporting final artifacts).
4. Dynamic updates while a run is live
Initial Profiles and Services are snapshotted at creation time. When a Harness intentionally needs to evolve the team mid-run, use the audited management APIs:
runtime.profiles.register(...)— add a new immutable role Profile.runtime.services.register(...)/retire(...)— attach a new Service or drain and retire an existing one.runtime.access.get(...)/grant(...)/revoke(...)— inspect or update a live Agent’s Service permissions without restarting its sandbox.
5. Clean shutdown and recovery: runtime.close()
When the goal is met or your budget expires, call runtime.close():
const receipt = await runtime.close({ timeoutMs: 60_000 });
unsubscribe();
if (receipt.cleanup !== 'complete') {
// Inspect receipt.pending (e.g., blocked artifact export or sandbox delete), fix, and retry close()
console.warn('Pending cleanup items:', receipt.pending);
}
runtime.close() strictly follows archive-before-delete: stop executors → export sessions, Service states, and declared Profile.collect artifacts → delete sandboxes only after archiving succeeds. If a required export or delete fails, receipt.cleanup stays 'pending' with exact entries in receipt.pending, and retrying close() on the same Runtime safely resumes cleanup.
6. Durable recovery and Kubernetes
If your application needs to reclaim live sandboxes after an unexpected host process exit, opt into durable ownership when creating the Runtime:
const options = {
// Supply your original sandbox, models, profiles, services, and outputDir
...applicationOptions,
connection: {
publicUrl: process.env.ANYSWARM_RUNTIME_PUBLIC_URL,
bindHost: '0.0.0.0',
bindPort: 3100,
},
persistence: { deploymentId: 'cluster-a', contract: 'harness-v1', retainForMs: 900_000 },
operationLimits: { prepare: 8, stop: 8, transfer: 4, queued: 1024, waitMs: 60_000 },
};
Durable mode requires three invariants: a stable callback URL reachable from every Worker, private persistent storage for outputDir, and matching persistence settings when recovering. In Kubernetes deployments, set publicUrl to the Runtime Service’s ClusterIP so sandboxes can connect via exact IPv4 + port rules without DNS lookups. operationLimits configures independent concurrency and queue bounds for prepare, stop, and transfer operations; retained sandboxes default to a 15-minute window (retainForMs).
After the previous host process exits, reconnect to the surviving Workers with recoverRuntime():
import { recoverRuntime } from '@anyswarm/core';
const runtime = await recoverRuntime({
...options,
runDirectory: '/private/runs/original-runtime-id',
restoreService: async (definition) => trustedServiceResolver(definition),
});
- Restoring dynamic Services.
trustedServiceResolveris application code that returns a matching Service registration from its durable business state, orundefinedwhen restoration is unavailable. Supply all original options, including fresh host secrets. Dynamically registered Services require this resolver when absent from initial configuration. An unresolved Service keeps Agents fenced. Harness scheduling and Service business recovery need their own durable contracts. Original input IDs and Worker cursors are reconciled; recovery sends no replacement initial prompt. - Recovery scope: Takeover requires running on the same Linux host within the same OS boot and acquiring the exclusive SQLite writer lock. (The Kubernetes manifests inject the node identity via the downward API, so a restarted pod on the same unrebooted node can recover, whereas a different node or rebooted host is rejected.) Automatic cross-node failover and Worker process replacement are not yet supported; runs that were already closing continue cleanup only.
- Cleanup-only recovery (CLI): To reclaim cleanup authority and finish archiving/deleting sandboxes without resuming work, set
cleanupOnly: trueor run:
anyswarm recover --run-dir /private/runs/original-runtime-id --config /private/recovery.ts
The config module’s default export can be the original options object or a zero-argument async factory returning it. anyswarm recover runs cleanup-only recovery, calls close(), prints the receipt, and exits 0 only when cleanup is complete (otherwise 1, keeping pending items recorded). When a required export fails, the sandbox is retained until expiresAt — fix the issue and retry before expiry (check for retain-at-risk if the backend could not confirm the requested retention window).
- Event-path latency probe: Call
runtime.probeWorkerEvent(agentId, { requestId, timeoutMs })to measure end-to-end authenticated Worker-to-Runtime event latency without triggering a model request. Workers stream events over bounded cursor long polling; if an event gap is detected, Runtime pauses new work for that Agent and retains uncertain resources for inspection.
The Kubernetes deployment profile pins official components and generates private deployment inputs. The capacity workload defaults to a not-run plan. The real 2- and 8-Sandbox workloads used two worker VMs on one physical host and a controlled model endpoint. The 8-Sandbox workload ran for 15 minutes. A separate 2-Sandbox handoff used hosted Kimi K3. Tiers 32, 128 and 1,024 use local mock Agent APIs. Each simulation passed three waves through production SDK admission, durable ownership, events, export and cleanup. Physical cluster capacity at those sizes remains unverified. A passing workload still requires the separate failure and recovery matrix before a capacity claim. Obtain owner approval before large experiments. The full ownership and retry contract is in Architecture.
7. Session controls and Harness shutdown
Use the runtime.session namespace to inspect and control an individual Agent’s executor session (configure, compact, abortRetry, clearQueue, getState, getStats, and getMessages), or pass structured context payloads to runtime.send() with an explicit delivery mode ('append', 'nextTurn', 'steer', or 'followUp'). See Agent session settings and context for complete examples.
When a Runtime is managed through HarnessSession (see SDK & API Reference), stopping the run synchronously blocks new requests while letting in-flight operations reconcile. The Harness that owns the Runtime remains responsible for calling stop() / close(), archiving sessions, exporting required artifacts, and completing cleanup.
Next: learn how to define role Profiles, spawn persistent Agents, send messages, handle interrupts, and configure session controls in Agents & Profiles.