CORE BUILDING BLOCKS

Services

Register shared business capabilities, grant Agent operations, and manage Service instances.

A Service gives Agents a shared business capability. The business module owns its rules and state. Its operation interface describes what callers can do, and its AnySwarm adapter maps calls to the business module or an external provider. The Runtime manages the Service instance and the Host Bridge checks the Agent’s identity, access and input on every call.

Register and grant an operation

import { inProcessService, ServiceRegistry } from '@anyswarm/core';

const services = new ServiceRegistry();
const catalog = { title: 'Release checklist', entries: ['Verify package', 'Check cleanup'] };

services.register('checklist', inProcessService({
  description: 'Read the release checklist',
  operations: { read: { description: 'Read all checklist entries', sideEffect: 'read' } },
}, { read: () => catalog }), { toolMode: 'direct' });

const reader = {
  model: 'default', image: 'your-worker-image', writable: false,
  tools: [],
  services: { checklist: ['read'] },
  addedSystemPrompt: 'Read the checklist before reporting release readiness.',
};

Pass services and profiles: { reader } to createRuntime(). A registration has one name, and the keys in operations are its operation names. Each name has 1 to 128 characters, starts with a lowercase ASCII letter, and can also contain lowercase ASCII letters, digits, hyphens and underscores. Omitted inputSchema accepts only {}. An optional outputSchema validates the successful business value. Omitted sideEffect takes the conservative write default. idempotent and timeoutMs describe the operation. The Bridge dispatches each call once.

register() captures the definition and checks static schemas. The Runtime creates the adapter and runs any preparation and readiness hooks. All authorized Agents in a Run share the same instance. Use a factory to create state for that Run, or bind an existing system explicitly. The example above shares an existing in-memory object. The persistent Board example keeps its business library, schema and adapters separate and commits entries to SQLite.

Choose the provider and the Agent tool mode

Provider Registration Where it runs
In-process inProcessService(interface, handlers) Inside the Host process. The Host owns execution and its resource limits.
HTTP httpService(interface, { url, operations, mapResponse, token }) A separately running API. The Host maps method, path, headers and JSON in each operation, and supplies the authentic caller from the Bridge context. See the Python Board example.
MCP mcpService({ url, token }) or mcpService({ command, args }) A remote Streamable HTTP server or an owned Linux stdio subprocess. The Host discovers tools, imports their schemas and connects using its own credentials.
External CLI For example ghIssuesService({ repository, token }) A Host adapter builds a restricted argument vector, starts a subprocess and interprets its result. See the GitHub Issues example.

For a copyable Linux example, Managed MCP and process uses root SDK exports to run a stdio MCP server and a managed Host process. It checks the original structured result and rich content. Separate commands verify attached shutdown and clean up the recorded process after a Controller crash. Agent Control prints the lead’s turn separately from the original Runtime close receipt.

Use Profile.serviceToolMode to override a registration’s toolMode. If both are omitted, the mode is direct.

Mode Agent entry point Backend
direct One named native tool per authorized operation Pi
code tool_search and Pi’s codemode with authorized proxies. Each proxy call goes to the Bridge. Pi
cli swarm service list, swarm service view <id>, and swarm service invoke <id> <operation> Pi and Codex with a usable shell

Profile.tools controls local backend tools. Omit it for backend defaults, pass an array to select tools, or pass [] to disable local tools. With a tool-capable Pi model, direct and code Service tools work with tools: []. For CLI on Pi, the effective local tools must include bash. Models configured with capabilities.tools: false cannot receive Service access in any mode. For Codex explicitly select serviceToolMode: 'cli' and leave tools omitted. Sandbox file and network policy controls the other ways a process can access data.

Live grants and revocations use runtime.access. The Host checks current authority even while the Agent still holds an older description or script. Pi reports the access revision and the directory version it applied at a safe turn boundary. MCP additions appear for explicit grant. If a remote tool is removed, a later reappearance needs a new grant.

Default Services and Agent control

Core registers only agent by default. A new user ServiceRegistry is empty. createRuntime() assembles the built-in agent entry. Board, TaskPool’s task/context/judge/catalog, and other domain Services are provided by their Harness or application.

Registration and authorization are separate. An Agent with services: {} or no services receives no Service operation grants. To manage direct children, grant services: { agent: ['spawn', 'get', 'send', 'stop'] } and set spawnProfiles to the allowed child Profiles. For example use tools: [] and serviceToolMode: 'direct' or 'code' on Pi, or use the CLI Profile in the agent-control example.

Operation Model-side parameters and defaults Target and further permission Result
spawn Required profile. Optional text input, mode (steer by default, also followUp), fork (false by default). Creates a direct child from spawnProfiles. Forking also requires allowContextFork and backend support. Agent identity plus initialInput, which is null, an input receipt, or an explicit rejection.
get Required agent_id. Self or a direct child. Current Agent status and public result information.
send Required agent_id and text input. mode defaults to steer, also accepts followUp. wake_if_idle defaults to true. Self or a direct child. Input receipt with accepted (started/queued/handled), not-accepted (idle), or unknown.
stop Required agent_id. Direct child. Stop receipt with execution, cleanup, artifacts and public errors.
access_get Required agent_id. Host agentAccessPolicy must permit the query. Current operation grants and access version.
grant / revoke Required agent_id, service_id, and a nonempty, unique operations array. The Host agentAccessPolicy must allow every operation. Self-mutation is denied. Updated grants and access version.

Run the bundled flow.sh in a lead Agent using the sample Profile. It takes the child ID from the spawn response, queries that child, sends text and stops it.

agent.send delegates text delivery to the same Runtime machinery as Host runtime.send(). The Host API also supports structured context and trusted delivery controls. Input acceptance confirms delivery or queue admission. Observe the child’s execution and business result separately. For spawn and send, the built-in operation identity lets an authorized caller reconcile identical input using the original ID. Changing the parameters under that ID returns CONFLICT. The CLI takes the logical ID from --request-id. Target scope or policy failures return NOT_ALLOWED; input schema rejection occurs before dispatch.

Interpret replies and inspect evidence

swarm service invoke, Pi native tools and Pi code proxies expose ServiceReply. Inspect ok. Read result on success or error.code, message, optional details and retryable on failure. A provider can add serializable text, image or other content blocks. The generic CLI exits 0 on success and 1 when the reply has ok: false. Existing named commands such as swarm agent get preserve their older result view.

Bridge meta.operationId correlates a logical operation; attemptId identifies one dispatch. requestOutcome is not_executed for a pre-dispatch rejection, returned for a usable provider reply (including a business failure), or unknown when the execution result cannot be established. failureSource identifies Service, Bridge or transport. When no Bridge response arrives, record the logical ID and use any check the Service provides. Treat replay and idempotency as properties of the specific Service. The Trace Viewer uses the corresponding dispatch record.

An MCP tool’s structuredContent becomes the result. If a successful tool declares an output schema, it must supply valid structured content. Its original content blocks remain available. isError becomes MCP_TOOL_ERROR with public structured details. Interactive MCP continuation has an explicit unsupported result.

Manage and observe an instance

Use runtime.services.get/list to inspect readiness, ownership and available management state. A lifecycle-enabled Service supports Host start, stop, restart and retire as permitted, using a request ID. health calls a provider health hook when available. The Host owns managed resources. An attached lifecycle releases local connections and leaves the external server running. An ordinary HTTP mapping provides calls to an existing API. It has no implicit authority to stop or restart that API.

Close and retire fence new calls and drain in-flight work. The optional exportState hook supplies public observation JSON for Trace Viewer. Optional metadata can give a capture timestamp, business revision, field descriptions, summary values and table columns. The state export is separate from business durability. The Service owns its original database and successful commit. Runtime recovery explains the retained Run and storage requirements.

To display business state during a Run, implement ServiceAdapter.readState({ signal }). Its return value is { state, capturedAt, revision?, presentation? }. Select public fields explicitly and use the signal for any I/O. Supply an ISO capture timestamp and use JSON Pointer paths for summary fields and table columns. SDK and RPC clients can use optional presentation hints to render the returned state.

The Runtime owner can call runtime.services.listState() and runtime.services.readState(name). A HarnessSession client uses session.services.list() and session.services.read(runtimeId, name). Reads are limited to one second and 64 KiB each. A read can return unsupported, unavailable, timeout, or error, with the previous capture time when available. The adapter hook is host-only. See the Persistent Board example for a package-root Service adapter and Harness.

Migrate existing SDK code

Replace registerService({ manifest, adapter }) with register(name, definition). Integrations that still use a legacy hosted manifest can adapt it with services.register(...serviceFromManifest({ manifest, adapter })). Move Profile.session.tools to Profile.tools and Profile.prompt to Profile.addedSystemPrompt. Read .result from a successful generic CLI reply and use stderr for local usage errors. Existing Trace files remain readable.

For recovery of an HTTP mapping, set recoveryIdentity to a stable JSON value covering configuration captured by its request/response mapping functions. The helper fingerprints the endpoint, authentication, limits, mapping functions and this value. Change it when closure-held routes, methods, headers or response interpretation change. Fresh Runs work without this pin. Recovery then stays blocked because those closures cannot be verified. Managed process helpers capture and fingerprint executable, arguments, working directory and effective environment. Runtime get/list exposes the resulting configuration fingerprint.