A Profile is a role blueprint; an Agent is a persistent executor session spawned from that blueprint. This page covers how you define roles, run multi-turn Agents, send messages, and recover cleanly from interrupts or timeouts.
1. Defining roles with Profiles
Declare your roles in createRuntime({ profiles }):
const profiles = {
researcher: {
addedSystemPrompt: 'Investigate performance bottlenecks in the codebase and publish verified findings to the board.',
model: 'default', // Alias from runtime.models
image: DEFAULT_WORKER_IMAGE, // Container image for this role
writable: false, // Whether /workspace/project starts writable
services: { board: ['publish', 'search'] }, // Least-privilege Service allowlist
collect: { paths: ['notes.md'], includeGit: false, maxBytes: 1_048_576, required: false }, // Artifacts exported before close
},
};
Why is
imageon Profile instead of Runtime? Different roles in one swarm often need different toolchains — for example, general researchers can use the locally prepared Worker (workerImageFor(executor)orDEFAULT_WORKER_IMAGE), while a formal-verification specialist uses an image with Lean or custom compilers preinstalled. When every role uses the same environment, simply pass the same image constant on each Profile.
Other optional fields include spawnProfiles and allowContextFork (for delegating child Agents via the built-in agent Service) and network: { allow: [...] } (to permit specific internal IPv4 endpoints).
A Profile always needs image. resolveSandboxConnection() resolves connection settings and can return no image; use connection.image ?? workerImageFor(executor) when constructing the Profile. A missing image reports profiles.<name>.image and the helper to use, before any Sandbox allocation.
Local tools and Service tools
tools belongs to the Profile. Omission uses the backend’s supported local defaults, an explicit array replaces the defaults, and tools: [] disables local tools. Pi defaults to read, bash, edit and write. Host-selected extensions can register custom local tools that the Profile explicitly selects. Unknown or unloaded names fail startup.
Service permissions belong to services. Omission and {} grant no operations, including the automatically registered agent Service. Service tools are added after authorization and survive tools: []. Choose serviceToolMode: 'direct', 'code' or 'cli'. A Profile override takes precedence over a registration’s toolMode, followed by the SDK default direct. Pi supports all three. CLI requires an enabled Bash tool. Codex requires explicit CLI mode and rejects direct/code or explicit local tool selection.
addedSystemPrompt appends role instructions after the backend’s base prompt, tool instructions and AnySwarm context. Existing prompt and session.tools configuration receives an explicit migration error. Session controls such as thinking, retry and compaction remain in session. Profile changes apply to new Agents. Change existing Agents’ Service grants through Runtime access management. The Host checks every call immediately; Pi refreshes declarations at the next run boundary without automatically waking the Agent. Inspect runtime.session.getState(agent.id) for the effective tools and the applied directory version.
const reader = {
model: 'default', image: DEFAULT_WORKER_IMAGE, writable: false,
tools: [], services: { board: ['list'] }, serviceToolMode: 'direct',
addedSystemPrompt: 'Read the shared Board through its Service tool.',
};
2. Persistent session lifecycle and capacity slots
spawn() ──► starting ──► idle ◄──► running ──► stop() / close() ──► closing ──► closed
│ │
└───────────┴──► unexpected exit ──► exited ──► stop() / close()
// Boot an Agent (optionally seeding private files into /workspace/project)
const researcher = await runtime.spawn({
requestId: 'spawn-researcher-1',
profile: 'researcher',
files: {
'brief.txt': { encoding: 'utf8', data: 'Focus on memory allocation and cache invalidation.' },
},
});
Three practical things to remember:
- Agents start
idle:spawn()prepares the container and executor session without making any model calls until you callruntime.send(). - Context and files persist across turns: when a turn finishes and returns to
idle, the Agent retains its conversation history and local files so you can keep asking follow-up questions. - Slots are freed only on
stop()/close(): every open Agent (includingidleandexited) occupies one slot out ofmaxAgents. Callruntime.stop(agent.id)when a member is no longer needed to archive its session, remove its container, and free the slot.
3. Sending messages: runtime.send()
Pick the delivery mode that matches your coordination style:
| Options | Behavior | Common use case |
|---|---|---|
mode: 'steer' (default) |
Injects guidance into an active turn at a safe boundary (or starts a turn if idle) | Mid-flight requirement updates or pushing urgent peer notices |
mode: 'followUp' |
Queues behind the current turn and runs next (or starts immediately if idle) | Sequential multi-step instructions |
wakeIfIdle: false |
Delivers only if busy; if idle, returns not-accepted (idle) without waking the Agent |
Non-waking mailboxes that avoid spending tokens on minor notices |
const receipt = await runtime.send(
researcher.id,
'Inspect the caching layer and publish verified findings to the board.',
{ requestId: 'task-1', mode: 'followUp' },
);
4. Admission vs. completion, and safe retries
runtime.send() returns an admission receipt — it tells you whether the executor accepted the message, not whether the turn finished:
accepted(started/queued/handled): wait for thesettledevent onruntime.onEvent()to know when the turn ends.not-accepted: e.g.,wakeIfIdle: falsefound the Agent idle — keep the message in your Harness mailbox for later.unknown: if a timeout or disconnect makes delivery ambiguous, never switch to a newrequestId(that could execute the task twice). Retrysend()with the exact samerequestIdand payload to reconcile whether it was accepted.
Likewise, a
settledevent only proves the model stopped its turn — verify real success against your Service state and exported files.
5. Interrupting work without losing context: runtime.interrupt()
To stop a running Agent mid-turn while keeping its container, workspace, and conversation history intact:
const result = await runtime.interrupt(researcher.id, {
requestId: 'interrupt-1',
});
// If queued messages were cleared before running, result.discardedInputHashes
// lists their SHA-256 digests so your Harness mailbox can restore them cleanly.
interrupt() aborts active inference and in-flight Bridge calls, clears queued inputs, and leaves the Agent ready for fresh send() calls.
6. Session controls and structured context
Explicit thinking levels must be supported by the selected model. Configure custom levels with the model capability mapping; unsupported startup or dynamic values are rejected instead of clamped.
Add session to a Profile or an individual runtime.spawn() call to configure thinking level, compaction and retry behavior, queue modes and explicit sandbox resources. Select local tools through Profile.tools. Nested fields passed at spawn override the Profile’s defaults while omitted fields inherit them. Call runtime.session.getState(agent.id) to inspect the executor’s active settings.
const agent = await runtime.spawn({
profile: 'researcher',
requestId: 'researcher-session',
session: { thinkingLevel: 'low', retry: { enabled: true } },
});
// Update session settings while the Agent is alive
await runtime.session.configure(
agent.id,
{ thinkingLevel: 'medium', compaction: { enabled: true } },
{ requestId: 'configure-researcher' },
);
// Inject structured context without triggering a model turn
await runtime.send(
agent.id,
{
type: 'context',
customType: 'project-reference',
content: 'Use the reviewed revision.',
display: false,
details: { revision: 'reviewed' },
},
{ requestId: 'reference', delivery: 'append' },
);
// Inspect live session state, usage statistics, and messages
const state = await runtime.session.getState(agent.id);
const stats = await runtime.session.getStats(agent.id);
const messages = await runtime.session.getMessages(agent.id, { limit: 50, maxBytes: 65_536 });
Structured context delivery modes
Every structured context message (type: 'context') sent via runtime.send() requires an explicit delivery mode:
delivery mode |
Behavior |
|---|---|
'append' |
Appends context at a safe executor boundary without starting a new model turn. |
'nextTurn' |
Holds the context until the next turn starts. |
'steer' / 'followUp' |
Uses the same mid-turn or queued timing as text inputs and accepts wakeIfIdle. |
Calling interrupt(), clearQueue(), or stop() discards pending nextTurn and queued context, while context already committed to history remains available. Receipts and events record the assigned inputId and delivery outcome.
Session management operations
runtime.session.compact(agentId, { requestId }): Triggers manual context compaction. Requires the Agent to beidlewith no turn starting (returns'busy'while active); pause your Harness scheduler for that Agent while compacting.runtime.session.abortRetry(agentId, { requestId }): Cancels an active executor retry, which may cause the current turn to fail.runtime.session.clearQueue(agentId, { requestId }): Clears unconsumed inputs queued inside the executor and returns discarded text hashes and context IDs so your Harness can reconcile its own mailboxes or batches.- Idempotency & capabilities: Session mutations follow the same
requestIdrules asruntime.send()— if a response is lost or returns'unknown', retry with the exact samerequestIdand payload (changing arguments throwsCONFLICT). Available operations depend on the executor’s advertised capabilities and startup handshake; unsupported or unavailable queries return'unsupported'or'unavailable'.getMessages()defaults to 100 messages / 64 KiB (configurable up to 1,000 messages / 256 KiB) and flags truncation when exceeded.
Guarding automatic compaction with hooks.beforeCompact
To cap automatic context compactions (for example, stopping an Agent before a 4th automatic compaction), register hooks.beforeCompact in createRuntime() and return 'stop' when request.reason !== 'manual' && request.successfulAutoCompactions >= 3 (return 'allow' otherwise). The Runtime awaits your hook within a bounded timeout before compacting; returning 'stop' runs the Agent’s normal archival, required artifact export, and cleanup flow. Your hook receives an AbortSignal and should treat cancellation as final for that decision.
Session events and runnable example
- Session event stream: Subscribe to
runtime.onEvent()before sending work. Session events arrive as{ type: 'session', agentId, event }. StreamingmessageStart,textDelta, andmessageEndevents share amessageId(accumulate deltas per message and content block, then replace with the finalmessageEndpayload);toolActivitylists currently running tool calls. Session totals and current context usage are reported separately (forked history can contribute to session totals), and cost isnullwhen model pricing is unconfigured. - Runnable example: See
examples/agent-session.tsfor a complete program demonstrating the 3-compaction stop policy,append/nextTurncontext injection, state/stats/message inspection, and shutdown receipts. Runanyswarm run ./examples/agent-session.ts /absolute/config.ts worker 'Your prompt'(the config module default-exportsCreateRuntimeOptionswith a 120s work window and 30s cleanup window).
Next: see how Agents talk safely to models and shared Services across the Host Gateway.