This reference covers the public runtime exports, method contracts, and error recovery rules for @anyswarm/core. For conceptual guides, start with Runtime & Agents and Services & Permissions; for exact TypeScript declarations, see Types & Source Map; for host and container CLIs, see CLI Reference.
Install the SDK
Run this command in your Node.js project to add the TypeScript SDK as a dependency. Use Node.js 22.19 or later.
npm install @anyswarm/core
Import the SDK from @anyswarm/core. The same install exposes the project-local CLI through npm exec -- anyswarm. To run anyswarm directly from any directory, use a global CLI install.
Public package exports
All public values and TypeScript types are imported from the single root entry @anyswarm/core:
| Export | Kind | Purpose |
|---|---|---|
createSandbox(config) |
Function | Creates a reusable OpenSandbox connection handle or plugs in a custom { provider } SandboxProvider. |
resolveSandboxConnection(overrides?) |
Function | Resolves Lifecycle URL, local token, and image defaults matching the CLI (use only in trusted host config). |
createRuntime(options) |
Async function | Opens a Run control plane (outputDir/<runtimeId>/, Service Bridge, Model Gateway) with configurable executor, filePolicy, and durable persistence options. |
resolveFilePolicy(policy?) |
Function | Validates and fills file budgets with the defaults used by Runtime and the project host. Harness authors can use the resolved limits for local candidate checks. |
recoverRuntime(options) |
Async function | Reopens a durable Run under verified same-host, same-boot ownership; supports cleanup-only mode and dynamic Service restoration. |
createHarnessSession(harness, options) / HarnessRpcClient |
Function / Class | Drives a standard Harness in-process or over a JSONL child-process pipe with live events, questions, and member controls. |
runProjectRpc(session, input, write, launchDirectory, initialInput?, options?) |
Function | Serves HarnessSession JSONL over a host-owned stream. detachOnDisconnect keeps the Session running when that observer disconnects. |
createPiExecutor({ version }) / createCodexExecutor({ version }) |
Function | Pins an exact built-in executor version when supplied; 'pi' / 'codex' shorthands remain supported. |
createExecutorAdapter(declaration) / EXECUTOR_ADAPTER_PROTOCOL |
Function / Constant | Declares an image-installed external executor adapter (anyswarm-executor-v1). |
DEFAULT_WORKER_IMAGE / workerImageFor(selection) |
Constant / Function | Select local Worker preparation for the Runtime’s executor, or select a particular executor and optionally pin its version. |
getExecutorCapabilities(selection) |
Function | Static capability lookup for a configured executor (no network side effects). |
ServiceRegistry |
Class | Accepts register(name, definition, { toolMode? }) for Runtime assembly. |
inProcessService(interface, handlers) |
Function | Binds operation names to host business handlers. |
httpService(interface, options) |
Function | Maps a Service interface to a regular HTTP API. |
mcpService(options) |
Function | Discovers and invokes remote Streamable HTTP or managed Linux stdio tools. |
managedProcessLifecycle(options) |
Function | Starts and stops an owned Linux process using recorded identity. |
serviceFromManifest(registration) |
Function | Adapts a legacy manifest and adapter for register(). |
createInProcessAdapter / createHttpJsonAdapter |
Functions | Legacy adapter helpers for retained manifest integrations. |
Harness, HarnessContext, HarnessInput, HarnessJson |
Types | Describe a standard ESM Harness entry, captured input, host callbacks, and final result. |
ProjectPreflightError, projectConfiguration, observeProjectRuntime, projectResult |
Class / Functions | Normalize trusted configuration, signal rejection before allocation, observe Runtime state, and project the saved result. |
runInput, createInputAdmission, runWithReport, readHarnessResult, createOwnedResources |
Functions | Track an exclusive turn, fence new input, save or inspect a report, and reconcile owned resources. |
checkGitProject, seedTeamRepository, seededCheckoutInstruction, initializeGitRepository, importGitTree, commitGitTree, isGitTreePath |
Functions | Validate and seed a Git project from a captured FileTree, and generate its initial checkout instructions. |
decodeFileTree, snapshotFileTree, completeFileTreeDigest, stableStringify, AnySwarmError, requestHttp, httpClient |
Functions / Class | Work with bounded file bytes and stable digests, retain structured error codes, or connect to a trusted Service. |
All five reference Harness applications build directly against this root entry. Lifecycle and file-handling rules are specified in the Harness author contract, and built-in aliases load the bundled entries.
Runtime starts its own Service Bridge, Model Gateway, and built-in agent Service. In-process Services created by an example need no separate container; external collaboration facilities and optional Mathlib Search are deployed and owned by each example, and registering a Service with the SDK does not start or destroy them. See the deployment guide.
createSandbox(config) & createRuntime(options)
import {
DEFAULT_WORKER_IMAGE,
ServiceRegistry,
createRuntime,
createSandbox,
} from '@anyswarm/core';
const sandbox = createSandbox(); // reads defaults saved by anyswarm setup
const runtime = await createRuntime({
sandbox,
executor: 'pi', // 'pi' (default) | 'codex' | createPiExecutor(...) | createExecutorAdapter(...)
// Optional: set publicUrl when Workers reach the host via a custom address or reverse proxy
// connection: { publicUrl: 'http://172.17.0.1:43100' },
models: {
default: {
provider: 'openai',
model: 'gpt-5.4',
// protocol defaults to 'responses'; Pi also supports 'chat-completions' or a custom ModelTransport
upstream: { url: modelUrl, headers: modelHeaders },
},
},
services: new ServiceRegistry(),
profiles: {
reader: { model: 'default', image: DEFAULT_WORKER_IMAGE, writable: false, services: {} },
},
maxAgents: 2,
outputDir: './runs',
});
-
createSandbox: reads savedanyswarm setupdefaults, or accepts explicitendpoint,apiKey, resource limits, and creation lifetime. Trusted hosts can still pass{ provider }for a customSandboxProvider. Legacy exact disk quotas (isolation.disk) andendpointHostrewriting fail before allocation. -
connection: uses a singlepublicUrl(supporting reverse-proxy path prefixes), withbindHostandbindPortcontrolling the host listener.modelGatewayretainsrequestTimeoutMs,maxOutputTokens, andmaxRequests. -
models: defaults to streaming Responses; Pi also supportsprotocol: 'chat-completions'andcapabilities: { contextWindow, maxOutputTokens, tools, reasoning }; trusted host modules can supply a customModelTransport. Upstream credentials stay strictly on the host. -
filePolicy: independently configureinitial,snapshot,replace,export, andsessionlimits (maxBytes,maxFileBytes,maxFiles,maxEntries,timeoutMs) pluscontrollerSpoolBytesandworkerSpoolBytes. -
getExecutorCapabilities(selection): Pi supportscontextFork,activeSteer,followUp, andone-at-a-time; Codex supportsactiveSteer,followUp, andallwithout context forking.
Agent lifecycle
runtime.spawn({ requestId, profile, parentId?, forkFrom?, writable?, files?, bindings?, secretEnv?, workspace?, collect? }): reserves a Slot (up tomaxAgents), provisions the Sandbox, and resolves to anidleAgentInfo. Seed private files viafiles, or request a shared workspace from a trusted Provider declaring that capability.forkFromclones live Session context on supported executors (pi).runtime.get(agentId)/runtime.list({ parentId?, status? }): return currentAgentInfosnapshots.runtime.state:'open' | 'closing' | 'closed'.
Input delivery & live observation
runtime.send(agentId, text, { requestId, mode?, wakeIfIdle?, source?, steeringMode? }):- Defaults to
mode: 'steer'andwakeIfIdle: true; passmode: 'followUp'to queue work after the current execution. - Returns
InputReceipt({ status: 'accepted', disposition: 'started' | 'queued' | 'handled' }or{ status: 'unknown' }), or{ status: 'not-accepted', reason: 'idle' }whenwakeIfIdle: false. - Reconcile
unknownby replaying the exactrequestIdand arguments; changing arguments under the samerequestIdthrowsCONFLICT.
- Defaults to
runtime.onEvent(listener): returns anunsubscribe()function. Register beforespawn/send, then queryget/list/statefor initial state. When a subscriber accumulates 32 pending async callbacks, it receives a countedsubscriberGapevent after a callback settles; re-read current state viaget/listto resynchronize.- Emits
output,settled,error,exit,agentChanged,runtimeChanged, andmanagement. - Events may arrive before
send()resolves; listener errors are isolated and logged.
- Emits
Controlled file primitives (runtime.files)
const original = await runtime.files.snapshot(agentId, { requestId: 'capture-1', paths: ['.'] });
const receipt = await runtime.files.replace(agentId, {
requestId: 'replace-1',
expectedDigest: original.digest,
files: nextTree,
writable: true,
});
- A
FileTreemaps project-relative paths to UTF-8 or base64 regular files with optional0o644or0o755mode (limits: 10,000 files, 2 MiB per file, 16 MiB total). snapshot(agentId, { requestId, paths, maxBytes? }):paths: ['.']produces acomplete:sha256:...digest; specific subpaths produce apartial:sha256:...digest.replace(agentId, { requestId, expectedDigest, files, writable? }): checks the complete digest, pauses writers, atomically installsfiles(including deletions and modes) in the private workspace, optionally upgradeswritable: true, and preserves the live session. Returnscompleted,failed(confirmed rollback), orunknown(reconcile with identical arguments).
Interrupt, stop, and close
runtime.interrupt(agentId, { requestId, timeoutMs? }): cancels pending Bridge calls, clears queued inputs (optionally returningdiscardedInputHashes), and aborts active work while keeping container, session, files, and Slot.runtime.stop(agentId, { timeoutMs? }): revokes credentials on entry, confirms executor stop, archives the session, collects declared files, deletes the Sandbox, and frees the Slot. ReturnsStopReceiptseparatingexecution: 'stopped' | 'unknown'fromcleanup: 'complete' | 'pending'.runtime.close({ timeoutMs? }): default timeout60_000ms. Stops all Agents, retires dynamic Services, callsexportState(), closes host gateways, writesruntime.json, and returnsCloseReceipt. Required export failures retain the Sandbox; retrystop()/close()on the same Runtime after resolving blockers.
Runtime management
Update Profiles, Services, and Agent permissions while a Run is open (all mutations require stable requestIds):
runtime.profiles:register({ id, requestId, profile, actorId? }),get(id),list()— adds immutable Profiles mid-Run.runtime.servicesusesregister({ name, service, toolMode?, requestId, actorId? }),get(id),list()andhealth(id). Lifecycle methodsstart,stop,restartandretireaccept{ serviceId, requestId, timeoutMs?, actorId? }. See lifecycle and recovery.runtime.access:get(agentId),grant({ agentId, serviceId, operations, requestId, binding? }),revoke({ agentId, serviceId, operations, requestId })— mutates live Agent Service grants (optionally gated byagentAccessPolicy).runtime.management.get(): returns the current sequenced snapshot ({ sequence, profiles, services, access }). Subscribe viaonEventbefore reading, buffermanagementevents with highersequence, and re-read if a sequence gap appears.
Service protocol & built-in agent Service
- Register a Service name,
ServiceDefinitionand optionaltoolMode. Operation keys supply the names. Schemas use strict synchronous JSON Schema. An omitted input schema accepts only{}. - Provider adapters receive validated input, trusted
caller, logicaloperation_id, cancellation andassertAuthorized(). The default timeout is 30 seconds. The Bridge returnsServiceReply, with a business value or public error and operation/attempt metadata. - Optional
exportState({ signal })exports public observation JSON at close or retire. See Trace Viewer for evidence and file links. - Core registers the built-in
agentService. Explicit grants are required for all operations. See the operation table and example.
For host anyswarm commands, container swarm commands, and environment variables, see CLI Reference.
Error codes & recovery
| Code / status | Meaning | How to handle |
|---|---|---|
INVALID_CONTRACT / SERVICE_INPUT_INVALID |
Invalid arguments, config, or JSON Schema input | Fix the input or config; the operation did not execute |
SERVICE_OUTPUT_INVALID |
Adapter returned JSON violating output_schema |
For writes, state may already have changed — inspect Service state before retrying |
NOT_FOUND / NOT_ALLOWED |
Unknown agent/operation, missing Profile grant, fatal fence, or Runtime closing | Check Profile grants and agent status; do not retry unauthorized calls |
CONFLICT |
Same requestId reused with different arguments, digest/version mismatch, or no free Slot (maxAgents) |
Use a fresh requestId for new parameters, refresh digests, or wait for stop() to free a Slot |
OPERATION_UNKNOWN / status: 'unknown' from Runtime input |
Host wait expired or transport dropped after dispatch | Reconcile by repeating the exact same requestId and arguments |
SERVICE_TIMEOUT / unknown Service write |
The adapter may already have performed its side effect | Retain operation_id and reconcile through that Service’s own idempotency contract; Registry does not auto-retry writes |
cleanup: 'pending' |
Execution stop, session archive, required collect, or Sandbox delete incomplete |
Inspect pending[].action and errors, resolve the blocker, and retry stop() / close() on the same Runtime |
Durable recovery and Worker probes
recoverRuntime(options: RecoverRuntimeOptions): Promise<Runtime>: exported from@anyswarm/core. Its options extendCreateRuntimeOptionswithrunDirectory, optionalcleanupOnly, andrestoreService(definition): Promise<ServiceRegistration | undefined>. Creation options addpersistence: { deploymentId, contract, retainForMs? }andoperationLimits. Recovery verifies the original persistence contract along with same-host, same-boot ownership.runtime.probeWorkerEvent(agentId, { requestId, timeoutMs? }): sends a probe through the normal event ingestion path on a live Agent and resolves with{ requestId, elapsedMs }once the correlated Worker event reaches Core. See Runtime durable recovery.
HarnessSession
Create a unified session handle for a multi-agent Run with createHarnessSession(harness, options) from the package root:
- Options: choose
lifetime('task'or'interactive'), a resolvedconfigurationorconfigPath,outputRoot, and optionalclientCapabilities.questions. - Lifecycle: inspect available inputs, lifetimes, and member operations via
describe(); start once withstart({ cwd, prompt }, { requestId }); observe viaonEvent(handler, { initialSnapshot: true })andgetState(); submit additional work withinput(payload, { requestId })or answer a pending question withrespond(questionId, answer, { requestId }); then callstop({ requestId, reason })and awaitcompletionto inspect business, export, and cleanup receipts. - JSONL RPC client:
HarnessRpcClientwraps a caller-managed piped child process and exposes the same operations oncereadyresolves. See the standalone Harness Session example and the Harness lifecycle manual.
Authoring and compatibility
A standard Harness module default-exports a Harness whose run method receives HarnessContext and returns business, artifact, and cleanup evidence. The Session adds Run identity, questions, operation receipts, and report-save evidence to form HarnessResult (the outer runId and Core’s runtime.id identify distinct lifecycles).
- Recommended API: new modules use
inputDescriptor,context.registerAgentControls({ runtime }), andcontext.runWithRuntimefor owned Runtime work, and callrunInputwhen awaiting an exclusive Agent turn. Dispatch callbacks receive both the caller’srequestIdand a boundedoperationIdto reuse for native dispatch and receipt lookup. - Compatibility aliases:
ProjectHarness,ProjectHarnessContext,ProjectHarnessResult, andinputDescriptionremain as deprecated aliases delegating to the same contract and will only be removed in a future announced compatibility release. - Helpers & reports:
projectConfigurationvalidates trusted settings andProjectPreflightErrorsignals rejection before allocation;observeProjectRuntimeattaches business state and receipt lookup to Session observation;projectResultreuses the current cleanup projection for olderrunWithReportcallers. Read saved reports from the Host’sreportPathand verifyrunIdinproject-run.json;readHarnessResultcontinues to read older standalone files by Runtime ID.