Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

24.6 KB
Raw Blame

TL;DR

The agent API groups Box-owned agents, submitted turns, and interaction across Rust, Python, Node.js, Go, C and the CLI.

Details

Agents is the Box-owned collection. agents.create("opencode", options) selects an implementation and returns an Agent instance; agents.get(agent_id) looks up that instance. Each agent owns its conversation and configuration; turns represent submitted work. The create argument selects an implementation, while agent_id identifies a created instance. Use agent methods to send work and handle requests, and turn methods to observe, steer or interrupt that work. See the failure contract for operation availability.

API by purpose

Purpose Rust Python Node.js Go
Namespace box.agents() box.agents box.agents box.Agents()
Agents agents.create/get, agent.close Same Same Create/Get, Close
Work agent.send/get_turn, turn.wait Same send/getTurn, wait Send/GetTurn, Wait
Events agent.events, turn.events Same Same Events
Interaction turn.steer/interrupt, agent.requests/respond Same Same Steer/Interrupt, Requests/Respond
Read-only state agent.state/config/capabilities(), turn.state() Properties Properties State/Config/Capabilities()

Rust also has agent.id(); the other SDKs do not yet.

Python exposes both async and synchronous handles, including SimpleBox, SyncBox and SyncSimpleBox. Node exposes the namespace on native JsBox and SimpleBox. Each SDK retains its error conventions.

Failure contract

Rust, Python, Node.js, the CLI, C and Go support the operations listed in OpenCode on a local runtime. Rust and C can also use these operations over the Box REST API. Go agent calls use the same C transport.

SDK Error behavior
Rust Err(BoxliteError::Unsupported(…)) naming the operation or option; no panic
Python UnsupportedError on awaiting operations or reading a property
Node.js Rejected operation promises; synchronous getter/event errors
Go Calls/getters return typed core *Error values and no result on failure; invalid arguments fail before submission; canceled calls return the context error
C Invalid arguments return InvalidArgument synchronously without a callback; accepted async calls return Ok and deliver core errors through the drain callback; getters return core errors synchronously
CLI boxlite agent … reports the error on stderr and exits with code 1

An unsupported event opening returns an error. Python and Node.js report it from opened() and the first read. Rust fails when its future is awaited; Go returns a nil stream with an error. C delivers an open failure through on_open with a null handle.

Unsupported calls do not return an agent or turn. C getters clear output pointers on failure.

OpenCode on a local runtime

Rust, Python, Node.js, the CLI, C and Go calls on a local runtime forward agents to OpenCode 2.2 inside the Box (design #2227). BoxLite installs nothing: the Box must already provide opencode 2.2.2 and sh, plus the provider configuration and keys OpenCode reads, such as ANTHROPIC_API_KEY in the Box environment. Another OpenCode version fails with Unsupported once its service answers, or with Execution when it lacks the opencode service commands. Rust agent.id() returns the ses_… session ID that agents.get accepts, including from another process.

agents.create("opencode") ──exec───► check OpenCode's service registration; set the
                                     service address to 0.0.0.0:47096 when different;
                                     read the service password
                          ──tunnel─► GET /api/info                  (exactly 2.2.2)
                          ──exec───► opencode service start         (only when none runs)
                          ──tunnel─► POST /api/session              → Agent (ses_…)
agent.send(text)          ──tunnel─► POST …/prompt, delivery queue  → AgentTurn (msg_…)
turn.wait()               ──tunnel─► inbox, history, pending requests
agent.events()            ──tunnel─► GET /api/event, live only

Python opens events before submitting work, so the live stream can receive the turn's first event:

agent = await box.agents.create("opencode")
events = agent.events()
await events.opened()
turn = await agent.send("Summarize this project")
result = await turn.wait()
await events.aclose()

Cancelling a Python event read preserves the pending event for the next read. Close the stream to release it without stopping the agent or the turn. OpenCode does not support turn event streams and rejects non-null data on send.

In Node.js, agent.events() also exposes opened() and return(). Use read({ signal }) to cancel one pending read without losing its event; the next read receives it. Plain next() has no per-read cancellation.

Operation Behavior
agents.create Starts OpenCode's managed service on first use and creates a session. Only cwd and config.model (provider/model) are accepted
agents.get Reads a session by its ses_… ID, starting the service again after a Box restart
agent.send Admits the text with queue delivery under a BoxLite-chosen msg_… ID. A lost response is retried once with that ID; a second failure is a Network error naming the ID to read with get_turn
agent.get_turn, turn.state get_turn reads the turn now, among the newest 1,000 messages of the session (older turns, and IDs of messages that are not inputs, are NotFound); turn.state returns the snapshot taken when the handle was obtained. A turn is queued in the inbox; running or waiting_input until its run records an outcome; completed, failed or cancelled from that outcome; unknown when its execution was cut off and a later run took the next input
turn.wait Polls every 500 ms. A timeout, an unknown turn, or a completed, cancelled or failed turn without a recorded result returns InvalidState; it never interrupts
agent.events Live events of the session and of subagent sessions created while the stream is open; cursor is None and after is rejected. Events of the session itself that name an input in OpenCode's inboxID carry it as turn_id; subagent events have none. Opening the stream fails with Network after 30 s without a response. The stream ends with one error, after any events that arrived before it: Network when the native stream ends or fails, Internal for an event that is not UTF-8 JSON or a subagent session ID that OpenCode would not mint, ResourceExhausted for an event over 1 MiB or a 1,001st subagent session
agent.config, agent.capabilities The session model; the operations above, with unknown limits as None

BoxLite runs OpenCode's own managed service, the opencode serve --service process that opencode service start launches, so OpenCode's recovery applies:

  • Address and password. The service listens on 0.0.0.0:47096 so the Box tunnel reaches it. OpenCode keeps that address and the service password in its service configuration (mode 0600) under the Box user's home. Processes in the Box running as the same user, including the agent's own tools, can read the password.
  • Refusals. agents.create and agents.get return InvalidState when OpenCode remote access is on, when a service started outside BoxLite runs at another address, when the service at port 47096 does not answer, or when another server holds that port. BoxLite never stops or signals a process.
  • Stale registrations. OpenCode's service registration outlives an unclean exit, and its pid can later belong to another process, which opencode service set would signal. BoxLite deletes a registration whose pid no longer runs opencode serve --service before it changes any setting.
  • Recovery. After a Box restart, the next agents.get starts the service again. It resumes an interrupted turn, then delivers queued inputs, at least once: a tool call may run twice. Background shells end cancelled. A clone of a Box with a turn in flight resumes its own copy of that turn.

Sessions deny reading .env and .env.* files (.env.example stays readable) and OpenCode's question tool. OpenCode's defaults would ask first, nobody can answer through BoxLite yet, and a pending ask holds every later input; denied, the tool call fails and the turn continues. A turn waiting on another permission, such as one asked in a subagent, lists it in its snapshot. A subagent's request belongs to the turn that created the subagent, or to a later turn that sends it a follow-up and is still waiting on it. Answering requests through BoxLite is not available yet; every other operation and option returns Unsupported before reaching OpenCode.

Run agent_opencode.rs for a complete example.

Record migration (breaking change)

Agent records from v0.11.0 represent values an adapter cannot know:

Field v0.11.0 Now
AgentState.cursor, AgentTurnState.cursor, AgentEvent.cursor Required string Optional; missing when the adapter cannot resume after it: None in Rust and Python, absent in TypeScript, null in C JSON, empty in Go
AgentCapabilities queue, steering and retention limits Required numbers Optional; missing means unknown or unsupported, never zero (Go: nil)

No operation returned these records before, so only code that reads or builds these fields changes.

Namespace ownership

Accessing a Box's agent namespace does not start or resume the Box. Python's SimpleBox, SyncBox and SyncSimpleBox accessors need no runtime initialization. Node's native JsBox.agents and SimpleBox.agents both expose Agents.

In C, boxlite_box_agents requires a live CBoxHandle and a writable output pointer. It returns Ok with an owned CAgents namespace without starting an agent. Release that namespace with boxlite_agents_free; release the Box separately with boxlite_box_free. A null Box handle or output pointer returns InvalidArgument.

Grouped options

In SDK calls, keep identifiers and message text positional; group optional arguments in these types:

Options type Used by Fields
AgentCreateOptions agents.create working directory, config, retry key
AgentSendOptions agent.send queue/reject mode, JSON data, retry key
AgentControlOptions close, respond, steer, interrupt retry key
AgentWaitOptions turn.wait timeout
AgentEventsOptions both events methods cursor

Rust/Go accept option structs; Python accepts dataclass instances; Node accepts typed objects. Python/Node may omit the options argument. Rust/Go use default/zero-valued option structs. C uses corresponding CAgent…Options pointers; null means omitted.

Inputs and records

Rust types live in boxlite::agents; Python types in boxlite.agents; TypeScript types are exported from the package; Go types use the Agent prefix.

  • Create selects an agent implementation and accepts a working directory, initial configuration and retry key.
  • Send accepts text, optional JSON data, a retry key, and queue (default) or reject mode.
  • Close, respond, steer and interrupt accept a retry key. Wait accepts an optional timeout.
  • Config includes model, reasoning, instructions, tools/MCP references, permissions, limits and output schema.
  • Requests retain their originating turn and distinguish a question from a permission request. Responses distinguish an answer from explicit permission approval/denial.
  • Agent/turn snapshots include an optional opaque cursor, requests and steering receipts; the cursor is absent when the adapter cannot resume events after it. Capability limits are optional: absent means unknown or unsupported, never zero. Results retain the turn ID, status, outcome, output, artifacts, usage and errors.
  • Unknown execution and steering states are representable. Accepted and applied steering are distinct; a question outcome is distinct from a final answer.

These records define SDK data types. The REST design maps them to nine HTTP operations, including snapshot reads, resumable events, steering and typed replies. It also defines cached getter behavior and retry headers. The Rust REST client forwards create, snapshot, turn, and control calls to an existing server. Response config accepts additional fields and validates known types; request config rejects unknown fields. Close and interrupt require HTTP 204. The remote requests() method is unsupported. The Rust client opens agent and turn SSE streams before returning, ignores comment heartbeats, validates parent IDs, and bounds event size and buffering. On an OpenCode agent subscription, a subagent event carries the subscribed agent's ID in the outer agent_id field. Its native payload identifies the child session, and its outer turn_id is null. After 30 seconds without stream data (two heartbeat intervals), the client reports a network error and closes the subscription. Dropping the stream releases the connection without cancelling the turn. Agent writes return redirects as errors and make one attempt. A turn result is valid for wait() only when its status matches a completed, failed, or cancelled turn snapshot. An unknown turn returns InvalidState even when the server includes a result. Server handlers are unavailable.

Node agent JSON numbers

Node agent calls, getters and event reads report a conversion error when a returned JSON number exceeds the native binding's supported numeric range. This includes nonzero numbers that would become zero, even inside arrays or objects. Other finite fractions use JavaScript number precision. If an event cannot be converted, subsequent reads report the same error.

Go JSON mapping

Go's internal agent converters use the core's snake_case JSON fields. Nullable strings become empty strings, a null turn result becomes nil, and null capability limits remain nil while a reported zero remains a pointer to zero.

Empty record arrays remain non-nil empty slices. Optional json.RawMessage data normalizes absent or top-level null to nil; false, zero, empty collections and nested nulls retain their JSON values.

Required event data and permission arguments preserve literal JSON null. Answers and explicit permission responses use different tagged records, so an answer cannot grant permission.

Retention is read from idempotency_retention_seconds using checked decimal conversion to time.Duration, without a float64 intermediate. Sub-nanosecond fractions are truncated; negative or out-of-range values return an error.

The core emits retention seconds as an exact decimal JSON number built from integer seconds and nanoseconds, including Go's maximum duration (9223372036.854775807 seconds). Its JSON values retain integer and decimal precision during parsing and serialization; Go keeps opaque payloads as json.RawMessage. Values already constructed as floating-point numbers retain that type's precision limits. Wait timeouts cross the C ABI as double seconds and do not promise exact nanosecond representation for large durations.

The Go and C bindings preserve send and answer data as validated JSON, including objects with a literal $serde_json::private::Number key. Turn results and snapshots preserve any data the adapter returns. OpenCode rejects non-null send data with Unsupported. Its terminal results and snapshots of those results contain data: null, including after an answer.

Go calls and getters use the C SDK and these converters. One runtime drainer dispatches asynchronous completions; getters copy their JSON synchronously. Both event methods return a stream after the native subscription connects.

Agent namespaces are acquired lazily. Closing a Box releases its local Box handle; an acquired namespace, agent or turn remains usable until Runtime.Close. Agent wrappers must not be copied after first use. Garbage collection releases local handles as a fallback, and Runtime.Close deterministically releases them. Agent.Close invokes the core operation; it does not release the local handle.

Cancellation stops the Go wait, not submitted agent work. Late native handles are released, including results already buffered when cancellation wins. Runtime.Close wakes pending calls with ErrRuntimeClosed and rejects new calls.

Go event streams

Open events before sending work: agent.Events(ctx, AgentEventsOptions{}) waits for native on_open. Opening errors return a nil stream. The opening context also controls the subscription after connection.

Next(ctx) permits one reader; concurrent reads return ErrInvalidState. Canceling that read returns its context error without consuming an event or canceling the subscription. A stream retains at most 64 events and 4 MiB of copied JSON. Oversized records are rejected before copying. Count or byte overflow cancels the subscription with ErrResourceExhausted, preserving its accepted prefix. Callbacks never wait for a reader, so a slow stream cannot block other calls.

An invalid event record is consumed once. Next returns a nil event and an *AgentEventDecodeError identifiable with errors.As. Missing or mistyped fields are named in the error without including the payload. All five outer fields are required. Cursor and turn ID accept null, unfamiliar string kinds are accepted, and data preserves any JSON value, including null. Call Next again to read the following event, or close the stream.

A native end returns buffered events followed by sticky io.EOF or the native error. Canceling the subscription context preserves buffered events, followed by its context error. The first recorded error wins; completed native EOF is final. Close discards unread events, wakes readers and requests native cancellation without waiting. It preserves an earlier error and otherwise produces io.EOF. Closing a stream does not interrupt agent work.

Runtime.Close discards buffers and makes reads return ErrRuntimeClosed, including when the read context is also canceled at the read decision. It cancels connected subscriptions before joining the ordinary drainer, then dispatches only subscription callbacks until their terminals arrive. Other queued callbacks are discarded during teardown. Pending connects do not hold shutdown open; their callback state is released after native runtime destruction. Garbage collection requests stream closure as a fallback; deterministic cleanup uses stream or runtime Close.

Example: handle operation errors

Python (the Box may already exist; this call starts no work):

from boxlite import AgentCreateOptions, UnsupportedError

try:
    agent = await box.agents.create(
        "coder", AgentCreateOptions(cwd="/workspace")
    )
except UnsupportedError as error:
    print(error)

Rust:

use boxlite::{BoxliteError, LiteBox};
use boxlite::agents::AgentCreateOptions;

async fn example(sandbox: &LiteBox) {
    let result = sandbox.agents()
        .create("coder", AgentCreateOptions::default()).await;
    assert!(matches!(result, Err(BoxliteError::Unsupported(_))));
}

C API and ownership

Include boxlite.h. boxlite_box_agents obtains CAgents from a live CBoxHandle; release it with boxlite_agents_free. A null Box/output pointer returns InvalidArgument.

Purpose C entry points
Agents boxlite_agents_create, boxlite_agents_get, boxlite_agent_close
Work boxlite_agent_send, boxlite_agent_get_turn, boxlite_agent_turn_wait
Events boxlite_agent_events, boxlite_agent_turn_events
Interaction boxlite_agent_turn_steer, boxlite_agent_turn_interrupt, boxlite_agent_requests, boxlite_agent_respond
Getters boxlite_agent_state/config/capabilities, boxlite_agent_turn_state

C option structs group the related arguments. CAgentCreateOptions contains cwd, config_json and idempotency_key; CAgentSendOptions contains mode, data_json and idempotency_key. Control options contain idempotency_key; event options contain after; wait options contain timeout_seconds. Null strings mean omitted. AgentSendQueue = 0 and AgentSendReject = 1.

Null options or a negative C timeout means no deadline. Rust/Go use optional durations; Python uses AgentWaitOptions.timeout in seconds; Node uses AgentWaitOptions.timeoutSeconds.

The C JSON fields use the following shapes. A question's schema and an answer's data may be omitted. Nullable output fields use JSON null; arrays remain arrays, including when empty. The Rust core owns the shared mapping used by the CLI and C bindings, so both surfaces use the same field names and validation rules.

Record C JSON fields
Config Optional model, reasoning, instructions, tools, mcp, permissions, limits, output_schema; tools/MCP are string arrays
Request id, turn_id, kind: either {"type":"question","text":"…","schema":null} or {"type":"permission","tool":"…","arguments":{}}
Response {"type":"answer","text":"yes"} with optional data, or {"type":"permission","approved":false}
Steering receipt id, turn_id, status: accepted, applied, unused or unknown
Agent snapshot id, status, nullable cursor, nullable active_turn_id, queued_turn_ids, requests, steering
Turn snapshot id, agent_id, status, nullable cursor, nullable result, requests, steering
Event nullable cursor, agent_id, nullable turn_id, kind string, JSON data
Result turn_id, status, nullable outcome (answer or question), nullable text, JSON data, artifacts string array, nullable JSON usage, nullable error string
Capabilities operations, input_kinds string arrays; nullable integer max_queued_turns, max_pending_steering; nullable idempotency_retention_seconds number

Agent status is ready, busy, closing, closed or unknown. Turn status is queued, running, waiting_input, interrupting, completed, cancelled, failed or unknown. Requests callbacks carry an array of request records; wait/steer callbacks carry a result/receipt respectively.

A synchronous error means no callback will run. State/config/capability getters clear out_json on error.

Send mode accepts AgentSendQueue or AgentSendReject; other values return InvalidArgument synchronously without scheduling a callback. Output/error pointers must be null or writable.

Errors written to out_error belong to the caller; release their messages with boxlite_error_free. Callback error pointers and JSON strings are borrowed for the callback's duration; copy their contents to retain them. JSON strings returned through getter output pointers belong to the caller; use boxlite_free_string.

boxlite_agent_free and boxlite_agent_turn_free release local handles only; they never close an agent or interrupt work. Null handles may be freed.

Event opening returns Ok when accepted; on_open receives the owned handle only after the native stream connects, or a null handle and error on failure. Open the agent stream before sending work when every live event is needed.

boxlite_agent_events_free signals cancellation without waiting for queue space. Already queued events are delivered first, followed by exactly one terminal on_event with null JSON; its error is null for cancellation or a natural end. Keep user_data valid until the terminal callback returns, or until on_open returns when opening fails.

While subscriptions are open, use one active boxlite_runtime_drain per runtime, including callback execution, and do not recursively drain the same runtime. Free subscriptions and drain their terminal callbacks before freeing the runtime; runtime free discards queued callbacks. Do not free a runtime while a drain or callback is active, or from its callback.

CLI commands

The CLI reference lists nine flat agent commands. BOX is positional. Creation uses --agent IMPLEMENTATION; other commands use --agent ID to select an instance, with --turn and --request selecting its work. inspect combines state and agent views, and events selects either scope. SDKs expose get/get_turn methods; CLI targeting subsumes handle lookup. create prints the new agent's ID, and every command prints JSON records in the C JSON shapes. CLI options reuse the five groups above and add AgentInspectOptions for view selection.