REFERENCE

SDK & API Reference

Complete lookup reference for @anyswarm/core exports, createSandbox, createRuntime, Agent lifecycle, send/onEvent semantics, runtime.files, Runtime management, Service protocol, and error codes.

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 saved anyswarm setup defaults, or accepts explicit endpoint, apiKey, resource limits, and creation lifetime. Trusted hosts can still pass { provider } for a custom SandboxProvider. Legacy exact disk quotas (isolation.disk) and endpointHost rewriting fail before allocation.

  • connection: uses a single publicUrl (supporting reverse-proxy path prefixes), with bindHost and bindPort controlling the host listener. modelGateway retains requestTimeoutMs, maxOutputTokens, and maxRequests.

  • models: defaults to streaming Responses; Pi also supports protocol: 'chat-completions' and capabilities: { contextWindow, maxOutputTokens, tools, reasoning }; trusted host modules can supply a custom ModelTransport. Upstream credentials stay strictly on the host.

  • filePolicy: independently configure initial, snapshot, replace, export, and session limits (maxBytes, maxFileBytes, maxFiles, maxEntries, timeoutMs) plus controllerSpoolBytes and workerSpoolBytes.

  • getExecutorCapabilities(selection): Pi supports contextFork, activeSteer, followUp, and one-at-a-time; Codex supports activeSteer, followUp, and all without context forking.

Agent lifecycle

  • runtime.spawn({ requestId, profile, parentId?, forkFrom?, writable?, files?, bindings?, secretEnv?, workspace?, collect? }): reserves a Slot (up to maxAgents), provisions the Sandbox, and resolves to an idle AgentInfo. Seed private files via files, or request a shared workspace from a trusted Provider declaring that capability. forkFrom clones live Session context on supported executors (pi).
  • runtime.get(agentId) / runtime.list({ parentId?, status? }): return current AgentInfo snapshots.
  • runtime.state: 'open' | 'closing' | 'closed'.

Input delivery & live observation

  • runtime.send(agentId, text, { requestId, mode?, wakeIfIdle?, source?, steeringMode? }):
    • Defaults to mode: 'steer' and wakeIfIdle: true; pass mode: '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' } when wakeIfIdle: false.
    • Reconcile unknown by replaying the exact requestId and arguments; changing arguments under the same requestId throws CONFLICT.
  • runtime.onEvent(listener): returns an unsubscribe() function. Register before spawn/send, then query get/list/state for initial state. When a subscriber accumulates 32 pending async callbacks, it receives a counted subscriberGap event after a callback settles; re-read current state via get/list to resynchronize.
    • Emits output, settled, error, exit, agentChanged, runtimeChanged, and management.
    • Events may arrive before send() resolves; listener errors are isolated and logged.

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 FileTree maps project-relative paths to UTF-8 or base64 regular files with optional 0o644 or 0o755 mode (limits: 10,000 files, 2 MiB per file, 16 MiB total).
  • snapshot(agentId, { requestId, paths, maxBytes? }): paths: ['.'] produces a complete:sha256:... digest; specific subpaths produce a partial:sha256:... digest.
  • replace(agentId, { requestId, expectedDigest, files, writable? }): checks the complete digest, pauses writers, atomically installs files (including deletions and modes) in the private workspace, optionally upgrades writable: true, and preserves the live session. Returns completed, failed (confirmed rollback), or unknown (reconcile with identical arguments).

Interrupt, stop, and close

  • runtime.interrupt(agentId, { requestId, timeoutMs? }): cancels pending Bridge calls, clears queued inputs (optionally returning discardedInputHashes), 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. Returns StopReceipt separating execution: 'stopped' | 'unknown' from cleanup: 'complete' | 'pending'.
  • runtime.close({ timeoutMs? }): default timeout 60_000 ms. Stops all Agents, retires dynamic Services, calls exportState(), closes host gateways, writes runtime.json, and returns CloseReceipt. Required export failures retain the Sandbox; retry stop() / 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.services uses register({ name, service, toolMode?, requestId, actorId? }), get(id), list() and health(id). Lifecycle methods start, stop, restart and retire accept { 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 by agentAccessPolicy).
  • runtime.management.get(): returns the current sequenced snapshot ({ sequence, profiles, services, access }). Subscribe via onEvent before reading, buffer management events with higher sequence, and re-read if a sequence gap appears.

Service protocol & built-in agent Service

  • Register a Service name, ServiceDefinition and optional toolMode. Operation keys supply the names. Schemas use strict synchronous JSON Schema. An omitted input schema accepts only {}.
  • Provider adapters receive validated input, trusted caller, logical operation_id, cancellation and assertAuthorized(). The default timeout is 30 seconds. The Bridge returns ServiceReply, 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 agent Service. 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 extend CreateRuntimeOptions with runDirectory, optional cleanupOnly, and restoreService(definition): Promise<ServiceRegistration | undefined>. Creation options add persistence: { deploymentId, contract, retainForMs? } and operationLimits. 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 resolved configuration or configPath, outputRoot, and optional clientCapabilities.questions.
  • Lifecycle: inspect available inputs, lifetimes, and member operations via describe(); start once with start({ cwd, prompt }, { requestId }); observe via onEvent(handler, { initialSnapshot: true }) and getState(); submit additional work with input(payload, { requestId }) or answer a pending question with respond(questionId, answer, { requestId }); then call stop({ requestId, reason }) and await completion to inspect business, export, and cleanup receipts.
  • JSONL RPC client: HarnessRpcClient wraps a caller-managed piped child process and exposes the same operations once ready resolves. 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 }), and context.runWithRuntime for owned Runtime work, and call runInput when awaiting an exclusive Agent turn. Dispatch callbacks receive both the caller’s requestId and a bounded operationId to reuse for native dispatch and receipt lookup.
  • Compatibility aliases: ProjectHarness, ProjectHarnessContext, ProjectHarnessResult, and inputDescription remain as deprecated aliases delegating to the same contract and will only be removed in a future announced compatibility release.
  • Helpers & reports: projectConfiguration validates trusted settings and ProjectPreflightError signals rejection before allocation; observeProjectRuntime attaches business state and receipt lookup to Session observation; projectResult reuses the current cleanup projection for older runWithReport callers. Read saved reports from the Host’s reportPath and verify runId in project-run.json; readHarnessResult continues to read older standalone files by Runtime ID.