The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(agents): connect the Rust REST client (#3022)
Jiaqiang Wong1b7d4abea371
diff --git a/docs/reference/agents.md b/docs/reference/agents.mdindex c49b9a765..fbd892c83 100644--- a/docs/reference/agents.md+++ b/docs/reference/agents.md@@ -33,8 +33,9 @@ and `SimpleBox`. Each SDK retains its error conventions.### Failure contractRust, Python, Node.js, the CLI and C calls on a local runtime run the operations listed in-[OpenCode on a local runtime](#opencode-on-a-local-runtime). Go and remote-runtimes return unsupported errors before agent execution.+[OpenCode on a local runtime](#opencode-on-a-local-runtime). Rust and C can also use+these operations over the Box REST API. Go returns unsupported errors before+agent execution.| SDK | Error behavior ||---|---|@@ -60,8 +61,8 @@ Rust, Python, Node.js, the CLI and C calls on a local runtime forward agents tonothing: the Box must already provide `opencode` 2.2.2 and `sh`, plus the providerconfiguration and keys OpenCode reads, such as `ANTHROPIC_API_KEY` in the Boxenvironment. Another OpenCode version fails with `Unsupported` once its service-answers, or with `Execution` when it lacks the `opencode service` commands. Remote-runtimes and Go return `Unsupported`. `agent.id()` returns the `ses_…`+answers, or with `Execution` when it lacks the `opencode service` commands. Go+returns `Unsupported`. `agent.id()` returns the `ses_…`session ID that `agents.get` accepts, including from another process.```text@@ -102,7 +103,7 @@ read receives it. Plain `next()` has no per-read cancellation.| `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, or an `unknown` turn, returns `InvalidState` and never interrupts |+| `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` |@@ -195,12 +196,21 @@ These records define SDK data types. The[REST design](../contributing/investigations/2026-10-28-agent-rest-api-design.md)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 OpenAPI contract specifies nine agent HTTP operations, retry-key forwarding,-SSE events, and HTTP 204 close/interrupt responses. Runtime routes and the REST-client are unavailable. The OpenAPI components-define strict request objects and additive response records, including fractional-retention durations; implementations must validate known response fields while-accepting additional server fields.+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.### Go JSON mappingdiff --git a/sdks/c/README.md b/sdks/c/README.mdindex a619603b9..1e438ad63 100644--- a/sdks/c/README.md+++ b/sdks/c/README.md@@ -1444,7 +1444,7 @@ See `sdks/c/tests/` for the test suite.- `make test:unit:ffi` runs the Rust-side FFI tests; `make test:unit:c` and `make test:integration:c` build and run the C tests. `FILTER=<pattern>` narrows each.- Rust FFI tests borrowing runtime out-pointers should use `runtime.as_ref().expect(...)` at the borrow site, making the non-null precondition explicit to static analysis. Keep the allocation alive through the reference's last use, then free the runtime; a null check alone does not establish pointer validity.- `make test:unit:ffi FILTER=checkpoint` exercises checkpoint create/list/get/import/remove through loopback HTTP and the real post-and-drain queue, including callback-owned metadata, Box handles and errors. Native binding coverage runs these Rust FFI tests alongside the C executable tests; no VM is needed.-- `make test:unit:c FILTER=agents` obtains a live Box handle from a loopback REST server, checks successful namespace allocation and release, and verifies agent-operation errors without starting a VM. Null-handle checks alone cannot cover namespace ownership.+- `make test:unit:c FILTER=agents` obtains a live Box handle from a loopback REST server, validates the agent-create POST and JSON body, and checks the successful callback and returned agent ID. It also verifies namespace and agent release and synchronous input errors without starting a VM. Null-handle checks alone cannot cover namespace ownership.- `BOXLITE_TEST_OPENCODE_BINARY=/absolute/path/to/opencode make test:integration:c:agents` runs a compiled C caller and Rust agent against the same scripted model in separate local VMs. It compares result fields and the first event, and checks C getter and unsupported-steering behavior. The binary must be OpenCode 2.2.2 for the guest's Linux architecture and glibc.- C integration tests pin `alpine:3.19`, which avoids drifting to the latest Alpine release line; the tag still receives patch updates, so it does not guarantee an immutable userland. `test_ssh_integration.c` pulls it through the same registry mirrors the Python and Node suites use.- `FREE_STR_CALLS` counts string frees across the whole test process. A Rust test that frees a counted FFI payload, or reads the counter, must hold `FREE_STR_LOCK` for as long as it does so, even if it never reads the counter. Without the lock, plain `cargo test` threads count its frees in another test's delta. nextest's process-per-test runs hide this.diff --git a/sdks/c/tests/test_agents.c b/sdks/c/tests/test_agents.cindex 568253637..e727481ac 100644--- a/sdks/c/tests/test_agents.c+++ b/sdks/c/tests/test_agents.c@@ -1,10 +1,13 @@#include "boxlite.h"#include <arpa/inet.h>#include <assert.h>+#include <errno.h>#include <pthread.h>#include <stddef.h>#include <stdio.h>+#include <stdlib.h>#include <string.h>+#include <strings.h>#include <sys/socket.h>#include <sys/wait.h>#include <unistd.h>@@ -17,6 +20,7 @@ typedef struct GetRequest {typedef struct AgentRequest {int done;+ struct CAgent *agent;BoxliteErrorCode error_code;pthread_t caller;} AgentRequest;@@ -24,10 +28,11 @@ typedef struct AgentRequest {static void on_agent_created(struct CAgent *agent, const CBoxliteError *error,void *data) {AgentRequest *request = data;- assert(agent == NULL);- assert(error != NULL);+ assert(agent != NULL);+ assert(error == NULL);assert(pthread_equal(pthread_self(), request->caller));- request->error_code = error->code;+ request->agent = agent;+ request->error_code = Ok;request->done = 1;}@@ -43,6 +48,49 @@ static void write_all(int fd, const char *data) {}}+static int accept_request(int listener, const char *line, const char *body) {+ int client = accept(listener, NULL, NULL);+ assert(client >= 0);+ char request[4096] = {0};+ size_t used = 0;+ char *head_end = NULL;+ while ((head_end = strstr(request, "\r\n\r\n")) == NULL) {+ assert(used < sizeof(request) - 1);+ ssize_t count = read(client, request + used, sizeof(request) - used - 1);+ assert(count > 0);+ used += (size_t)count;+ }+ assert(strncmp(request, line, strlen(line)) == 0);+ if (body != NULL) {+ const char *header = request;+ size_t body_len = 0;+ while ((header = strstr(header, "\r\n")) != NULL && header < head_end) {+ header += 2;+ if (strncasecmp(header, "content-length:", 15) == 0) {+ char *end = NULL;+ errno = 0;+ unsigned long length = strtoul(header + 15, &end, 10);+ assert(errno == 0 && end != header + 15);+ assert(end[0] == '\r' && end[1] == '\n');+ assert(length < sizeof(request));+ body_len = (size_t)length;+ break;+ }+ }+ assert(body_len == strlen(body));+ size_t body_start = (size_t)(head_end + 4 - request);+ assert(body_len < sizeof(request) - body_start);+ while (used < body_start + body_len) {+ ssize_t count =+ read(client, request + used, body_start + body_len - used);+ assert(count > 0);+ used += (size_t)count;+ }+ assert(memcmp(request + body_start, body, body_len) == 0);+ }+ return client;+}+static pid_t start_box_server(uint16_t *port) {int listener = socket(AF_INET, SOCK_STREAM, 0);assert(listener >= 0);@@ -59,27 +107,8 @@ static pid_t start_box_server(uint16_t *port) {assert(child >= 0);if (child == 0) {alarm(15);- int client = accept(listener, NULL, NULL);- if (client < 0) {- _exit(11);- }- char request[4096] = {0};- size_t used = 0;- while (strstr(request, "\r\n\r\n") == NULL) {- ssize_t count = read(client, request + used, sizeof(request) - used - 1);- if (count <= 0) {- _exit(12);- }- used += (size_t)count;- if (used >= sizeof(request)) {- _exit(12);- }- request[used] = '\0';- }- const char *expected = "GET /v1/boxes/agent-box HTTP/1.1\r\n";- if (strncmp(request, expected, strlen(expected)) != 0) {- _exit(13);- }+ int client =+ accept_request(listener, "GET /v1/boxes/agent-box HTTP/1.1\r\n", NULL);write_all(client,"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n""Connection: close\r\n\r\n"@@ -88,6 +117,21 @@ static pid_t start_box_server(uint16_t *port) {"\"updated_at\":\"2026-07-14T00:00:00Z\",\"pid\":42,""\"image\":\"alpine:latest\",\"cpus\":1,\"memory_mib\":512}");close(client);+ client =+ accept_request(listener, "POST /v1/boxes/agent-box/agents HTTP/1.1\r\n",+ "{\"agent\":\"opencode\"}");+ write_all(+ client,+ "HTTP/1.1 201 Created\r\nContent-Type: application/json\r\n"+ "Connection: close\r\n\r\n"+ "{\"id\":\"ses_c_rest\",\"agent\":\"opencode\","+ "\"state\":{\"id\":\"ses_c_rest\",\"status\":\"ready\","+ "\"cursor\":null,\"active_turn_id\":null,\"queued_turn_ids\":[],"+ "\"requests\":[],\"steering\":[]},\"config\":{\"tools\":[],\"mcp\":[]},"+ "\"capabilities\":{\"operations\":[],\"input_kinds\":[],"+ "\"max_queued_turns\":null,\"max_pending_steering\":null,"+ "\"idempotency_retention_seconds\":null}}");+ close(client);close(listener);_exit(0);}@@ -155,7 +199,13 @@ static void test_live_box_namespace(void) {for (int attempt = 0; attempt < 20 && !agent_request.done; attempt++) {assert(boxlite_runtime_drain(runtime, 500, &error) >= 0);}- assert(agent_request.done && agent_request.error_code == Unsupported);+ assert(agent_request.done && agent_request.error_code == Ok);+ assert(agent_request.agent != NULL);+ char *state = NULL;+ assert(boxlite_agent_state(agent_request.agent, &state, &error) == Ok);+ assert(state != NULL && strstr(state, "\"id\":\"ses_c_rest\"") != NULL);+ boxlite_free_string(state);+ boxlite_agent_free(agent_request.agent);boxlite_agents_free(agents);boxlite_box_free(request.box);boxlite_runtime_free(runtime);diff --git a/src/boxlite/src/agents/mod.rs b/src/boxlite/src/agents/mod.rsindex 8d8028ca0..d18846a59 100644--- a/src/boxlite/src/agents/mod.rs+++ b/src/boxlite/src/agents/mod.rs@@ -3,9 +3,9 @@//! BoxLite forwards each operation to a coding agent's native interface inside//! the Box. The agent owns its conversation, execution and recovery; BoxLite//! owns the Box and the transport, and starts the agent's own service when-//! none runs. OpenCode 2.2 on a local runtime is the only implementation;-//! unsupported operations and options fail with `Unsupported` before reaching-//! the agent.+//! none runs. OpenCode 2.2 is the local implementation. REST runtimes forward+//! operations to the server's agent API; unsupported operations and options+//! fail with `Unsupported` before reaching the agent.//!//! Each implementation is one module whose agent type implements//! [`AgentBackend`]; `Agents::create` maps the implementation name to it.@@ -14,6 +14,8 @@ mod install;mod opencode;/// Shared JSON conversion for agent API consumers.pub mod records;+#[cfg(feature = "rest")]+mod rest;#[cfg(feature = "test-support")]mod test_support;mod types;@@ -45,6 +47,9 @@ trait AgentBackend: Send + Sync + std::fmt::Debug {/// Implementation and version named in errors, such as `OpenCode 2.2`.fn adapter(&self) -> &str;+ /// Stable implementation name used by the wire contract.+ fn implementation(&self) -> &str;+/// The native agent ID that `Agents::get` accepts.fn id(&self) -> &str;@@ -163,6 +168,13 @@ impl Agents {if self.test_backend {return Ok(Agent::for_test());}+ #[cfg(feature = "rest")]+ if let Ok(remote) = Arc::clone(&self.box_backend)+ .as_any_arc()+ .downcast::<crate::rest::litebox::RestBox>()+ {+ return rest::create(&remote, agent, &options).await;+ }match agent {opencode::IMPLEMENTATION => {self.require_local_runtime()?;@@ -183,6 +195,13 @@ impl Agents {if self.test_backend {return Ok(Agent::for_test());}+ #[cfg(feature = "rest")]+ if let Ok(remote) = Arc::clone(&self.box_backend)+ .as_any_arc()+ .downcast::<crate::rest::litebox::RestBox>()+ {+ return rest::get(&remote, agent_id).await;+ }self.require_local_runtime()?;if !opencode::is_session_id(agent_id) {return Err(BoxliteError::NotFound(format!(@@ -209,8 +228,8 @@ impl Agents {Ok(())}- /// Checked before any validation, so remote runtimes always see `Unsupported`.- /// A cloud tunnel can publish the agent's server; a local one stays on this host.+ /// Resolve the local Box for direct adapter calls and binary installation.+ /// REST create and get dispatch through their backend before this check.fn require_local_runtime(&self) -> BoxliteResult<Arc<BoxImpl>> {Arc::clone(&self.box_backend).as_any_arc()@@ -252,6 +271,11 @@ impl Agent {self.backend.id()}+ /// The agent implementation name, such as `opencode`.+ pub fn implementation(&self) -> &str {+ self.backend.implementation()+ }+/// Stop admissions and close the agent loop.pub async fn close(&self, options: AgentControlOptions) -> BoxliteResult<()> {self.backend.close(&options).await@@ -322,10 +346,22 @@ impl AgentTurn {let observe = async {loop {let state = self.backend.turn(&self.state.id).await?;+ let has_known_outcome = matches!(+ state.status,+ AgentTurnStatus::Completed+ | AgentTurnStatus::Cancelled+ | AgentTurnStatus::Failed+ );if let Some(result) = state.result {- return Ok(result);+ if has_known_outcome && state.status == result.status {+ return Ok(result);+ }+ return Err(BoxliteError::InvalidState(format!(+ "turn {} has status {:?} with result status {:?}",+ self.state.id, state.status, result.status+ )));}- if state.status == AgentTurnStatus::Unknown {+ if has_known_outcome || state.status == AgentTurnStatus::Unknown {return Err(BoxliteError::InvalidState(format!("turn {} ended without a recorded outcome",self.state.iddiff --git a/src/boxlite/src/agents/opencode/mod.rs b/src/boxlite/src/agents/opencode/mod.rsindex 290ab2e56..a90752370 100644--- a/src/boxlite/src/agents/opencode/mod.rs+++ b/src/boxlite/src/agents/opencode/mod.rs@@ -21,7 +21,7 @@mod http;#[cfg(test)]-mod tests;+pub(super) mod tests;use std::collections::{HashMap, HashSet};use std::sync::{Arc, LazyLock, PoisonError, Weak};@@ -243,6 +243,10 @@ impl AgentBackend for Session {ADAPTER}+ fn implementation(&self) -> &str {+ IMPLEMENTATION+ }+fn id(&self) -> &str {&self.id}diff --git a/src/boxlite/src/agents/opencode/tests/mod.rs b/src/boxlite/src/agents/opencode/tests/mod.rsindex aa8e5099e..84dfb3059 100644--- a/src/boxlite/src/agents/opencode/tests/mod.rs+++ b/src/boxlite/src/agents/opencode/tests/mod.rs@@ -149,6 +149,15 @@ fn respond(status: &str, body: Value) -> String {)}+#[cfg(feature = "rest")]+pub(in crate::agents) async fn scripted_events(events: &[Value]) -> AgentEventStream {+ let (session, _) = scripted_session(vec![event_response(events)]);+ session+ .events(&AgentEventsOptions::default())+ .await+ .unwrap()+}+/// An SSE response whose body ends when the scripted server closes the connection.fn event_response(events: &[Value]) -> String {let mut body = String::from(": heartbeat\n\n");diff --git a/src/boxlite/src/agents/records.rs b/src/boxlite/src/agents/records.rsindex 12f051a3e..a92b13075 100644--- a/src/boxlite/src/agents/records.rs+++ b/src/boxlite/src/agents/records.rs@@ -40,10 +40,7 @@ pub fn result(result: &AgentResult) -> Value {json!({"turn_id": result.turn_id,"status": turn_status(result.status),- "outcome": result.outcome.map(|outcome| match outcome {- AgentOutcome::Answer => "answer",- AgentOutcome::Question => "question",- }),+ "outcome": result.outcome.map(outcome_name),"text": result.text,"data": result.data,"artifacts": result.artifacts,@@ -53,12 +50,7 @@ pub fn result(result: &AgentResult) -> Value {}pub fn receipt(receipt: &AgentSteeringReceipt) -> Value {- let status = match receipt.status {- AgentSteeringStatus::Accepted => "accepted",- AgentSteeringStatus::Applied => "applied",- AgentSteeringStatus::Unused => "unused",- AgentSteeringStatus::Unknown => "unknown",- };+ let status = steering_status(receipt.status);json!({ "id": receipt.id, "turn_id": receipt.turn_id, "status": status })}@@ -165,25 +157,257 @@ pub fn parse_response(value: Value) -> BoxliteResult<AgentResponse> {})}-fn agent_status(status: AgentStatus) -> &'static str {- match status {- AgentStatus::Ready => "ready",- AgentStatus::Busy => "busy",- AgentStatus::Closing => "closing",- AgentStatus::Closed => "closed",- AgentStatus::Unknown => "unknown",+macro_rules! record_enum {+ ($encode:ident, $decode:ident, $ty:ty, $field:literal, { $($variant:path => $wire:literal),+ $(,)? }) => {+ fn $encode(value: $ty) -> &'static str {+ match value { $($variant => $wire),+ }+ }+ #[cfg(feature = "rest")]+ fn $decode(value: &str) -> BoxliteResult<$ty> {+ match value { $($wire => Ok($variant),)+ other => Err(invalid($field, other)) }+ }+ };+}++record_enum!(agent_status, parse_agent_status, AgentStatus, "status", {+ AgentStatus::Ready => "ready", AgentStatus::Busy => "busy", AgentStatus::Closing => "closing",+ AgentStatus::Closed => "closed", AgentStatus::Unknown => "unknown",+});+record_enum!(turn_status, parse_turn_status, AgentTurnStatus, "turn status", {+ AgentTurnStatus::Queued => "queued", AgentTurnStatus::Running => "running",+ AgentTurnStatus::WaitingInput => "waiting_input", AgentTurnStatus::Interrupting => "interrupting",+ AgentTurnStatus::Completed => "completed", AgentTurnStatus::Cancelled => "cancelled",+ AgentTurnStatus::Failed => "failed", AgentTurnStatus::Unknown => "unknown",+});+record_enum!(steering_status, parse_steering_status, AgentSteeringStatus, "steering status", {+ AgentSteeringStatus::Accepted => "accepted", AgentSteeringStatus::Applied => "applied",+ AgentSteeringStatus::Unused => "unused", AgentSteeringStatus::Unknown => "unknown",+});+record_enum!(outcome_name, parse_outcome, AgentOutcome, "outcome", {+ AgentOutcome::Answer => "answer", AgentOutcome::Question => "question",+});++#[cfg(feature = "rest")]+#[derive(Deserialize)]+pub(super) struct Resource {+ pub(super) id: String,+ pub(super) agent: String,+ pub(super) state: Option<State>,+ pub(super) config: Config,+ pub(super) capabilities: Capabilities,+}++#[cfg(feature = "rest")]+#[derive(Deserialize)]+pub(super) struct Config {+ model: Option<String>,+ reasoning: Option<String>,+ instructions: Option<String>,+ tools: Vec<String>,+ mcp: Vec<String>,+ permissions: Option<Value>,+ limits: Option<Value>,+ output_schema: Option<Value>,+}++#[cfg(feature = "rest")]+impl From<Config> for AgentConfig {+ fn from(value: Config) -> Self {+ Self {+ model: value.model,+ reasoning: value.reasoning,+ instructions: value.instructions,+ tools: value.tools,+ mcp: value.mcp,+ permissions: value.permissions,+ limits: value.limits,+ output_schema: value.output_schema,+ }}}-fn turn_status(status: AgentTurnStatus) -> &'static str {- match status {- AgentTurnStatus::Queued => "queued",- AgentTurnStatus::Running => "running",- AgentTurnStatus::WaitingInput => "waiting_input",- AgentTurnStatus::Interrupting => "interrupting",- AgentTurnStatus::Completed => "completed",- AgentTurnStatus::Cancelled => "cancelled",- AgentTurnStatus::Failed => "failed",- AgentTurnStatus::Unknown => "unknown",+#[cfg(feature = "rest")]+#[derive(Deserialize)]+pub(super) struct Capabilities {+ pub(super) operations: Vec<String>,+ pub(super) input_kinds: Vec<String>,+ pub(super) max_queued_turns: Option<usize>,+ pub(super) max_pending_steering: Option<usize>,+ pub(super) idempotency_retention_seconds: Option<f64>,+}++#[cfg(feature = "rest")]+#[derive(Deserialize)]+pub(super) struct State {+ pub(super) id: String,+ pub(super) status: String,+ pub(super) cursor: Option<String>,+ pub(super) active_turn_id: Option<String>,+ pub(super) queued_turn_ids: Vec<String>,+ pub(super) requests: Vec<Request>,+ pub(super) steering: Vec<Receipt>,+}++#[cfg(feature = "rest")]+#[derive(Deserialize)]+pub(super) struct Request {+ pub(super) id: String,+ pub(super) turn_id: String,+ pub(super) kind: RequestKind,+}++#[cfg(feature = "rest")]+#[derive(Deserialize)]+#[serde(tag = "type", rename_all = "snake_case")]+pub(super) enum RequestKind {+ Question { text: String, schema: Option<Value> },+ Permission { tool: String, arguments: Value },+}++#[cfg(feature = "rest")]+#[derive(Deserialize)]+pub(super) struct Receipt {+ pub(super) id: String,+ pub(super) turn_id: String,+ pub(super) status: String,+}++#[cfg(feature = "rest")]+#[derive(Deserialize)]+pub(super) struct Turn {+ pub(super) id: String,+ pub(super) agent_id: String,+ pub(super) status: String,+ pub(super) cursor: Option<String>,+ pub(super) result: Option<ResultRecord>,+ pub(super) requests: Vec<Request>,+ pub(super) steering: Vec<Receipt>,+}++#[cfg(feature = "rest")]+#[derive(Deserialize)]+pub(super) struct ResultRecord {+ pub(super) turn_id: String,+ pub(super) status: String,+ pub(super) outcome: Option<String>,+ pub(super) text: Option<String>,+ pub(super) data: Option<Value>,+ pub(super) artifacts: Vec<String>,+ pub(super) usage: Option<Value>,+ pub(super) error: Option<String>,+}++#[cfg(feature = "rest")]+pub(super) fn invalid(field: &str, value: &str) -> BoxliteError {+ BoxliteError::Internal(format!("invalid REST agent {field}: {value}"))+}++#[cfg(feature = "rest")]+impl TryFrom<ResultRecord> for AgentResult {+ type Error = BoxliteError;+ fn try_from(value: ResultRecord) -> BoxliteResult<Self> {+ let outcome = value.outcome.as_deref().map(parse_outcome).transpose()?;+ Ok(Self {+ turn_id: value.turn_id,+ status: parse_turn_status(&value.status)?,+ outcome,+ text: value.text,+ data: value.data,+ artifacts: value.artifacts,+ usage: value.usage,+ error: value.error,+ })+ }+}++#[cfg(feature = "rest")]+impl TryFrom<Turn> for AgentTurnState {+ type Error = BoxliteError;+ fn try_from(value: Turn) -> BoxliteResult<Self> {+ if value+ .result+ .as_ref()+ .is_some_and(|result| result.turn_id != value.id)+ || value+ .requests+ .iter()+ .any(|request| request.turn_id != value.id)+ || value+ .steering+ .iter()+ .any(|receipt| receipt.turn_id != value.id)+ {+ return Err(invalid("turn child identity", &value.id));+ }+ Ok(Self {+ id: value.id,+ agent_id: value.agent_id,+ status: parse_turn_status(&value.status)?,+ cursor: value.cursor,+ result: value.result.map(TryInto::try_into).transpose()?,+ requests: value.requests.into_iter().map(Into::into).collect(),+ steering: value+ .steering+ .into_iter()+ .map(TryInto::try_into)+ .collect::<BoxliteResult<_>>()?,+ })+ }+}++#[cfg(feature = "rest")]+impl TryFrom<Receipt> for AgentSteeringReceipt {+ type Error = BoxliteError;++ fn try_from(value: Receipt) -> BoxliteResult<Self> {+ let status = parse_steering_status(&value.status)?;+ Ok(Self {+ id: value.id,+ turn_id: value.turn_id,+ status,+ })}}++#[cfg(feature = "rest")]+impl From<Request> for AgentRequest {+ fn from(value: Request) -> Self {+ let kind = match value.kind {+ RequestKind::Question { text, schema } => AgentRequestKind::Question { text, schema },+ RequestKind::Permission { tool, arguments } => {+ AgentRequestKind::Permission { tool, arguments }+ }+ };+ Self {+ id: value.id,+ turn_id: value.turn_id,+ kind,+ }+ }+}++#[cfg(feature = "rest")]+impl TryFrom<State> for AgentState {+ type Error = BoxliteError;++ fn try_from(value: State) -> BoxliteResult<Self> {+ let status = parse_agent_status(&value.status)?;+ Ok(Self {+ id: value.id,+ status,+ cursor: value.cursor,+ active_turn_id: value.active_turn_id,+ queued_turn_ids: value.queued_turn_ids,+ requests: value.requests.into_iter().map(Into::into).collect(),+ steering: value+ .steering+ .into_iter()+ .map(TryInto::try_into)+ .collect::<BoxliteResult<_>>()?,+ })+ }+}++#[cfg(all(test, feature = "rest"))]+#[path = "records/tests/rest.rs"]+mod rest;diff --git a/src/boxlite/src/agents/records/tests/rest.rs b/src/boxlite/src/agents/records/tests/rest.rsnew file mode 100644index 000000000..d661823e6--- /dev/null+++ b/src/boxlite/src/agents/records/tests/rest.rs@@ -0,0 +1,215 @@+use super::*;++fn sample_turn(status: AgentTurnStatus) -> AgentTurnState {+ AgentTurnState {+ id: "turn-1".into(),+ agent_id: "agent-1".into(),+ status,+ cursor: Some("cursor".into()),+ result: Some(AgentResult {+ turn_id: "turn-1".into(),+ status,+ outcome: Some(AgentOutcome::Question),+ text: Some("answer".into()),+ data: Some(json!({"nested": null})),+ artifacts: vec!["file".into()],+ usage: Some(json!({"tokens": 1})),+ error: None,+ }),+ requests: vec![AgentRequest {+ id: "request-1".into(),+ turn_id: "turn-1".into(),+ kind: AgentRequestKind::Permission {+ tool: "shell".into(),+ arguments: json!({"x": 1}),+ },+ }],+ steering: vec![AgentSteeringReceipt {+ id: "steer-1".into(),+ turn_id: "turn-1".into(),+ status: AgentSteeringStatus::Applied,+ }],+ }+}++#[test]+fn shared_enum_mappings_are_bidirectional_and_reject_unknown_values() {+ for value in [+ AgentSteeringStatus::Accepted,+ AgentSteeringStatus::Applied,+ AgentSteeringStatus::Unused,+ AgentSteeringStatus::Unknown,+ ] {+ assert_eq!(+ parse_steering_status(steering_status(value)).unwrap(),+ value+ );+ }+ for value in [AgentOutcome::Answer, AgentOutcome::Question] {+ assert_eq!(parse_outcome(outcome_name(value)).unwrap(), value);+ }+ assert!(parse_agent_status("invalid").is_err());+ assert!(parse_turn_status("invalid").is_err());+ assert!(parse_steering_status("invalid").is_err());+ assert!(parse_outcome("invalid").is_err());+}++#[test]+fn shared_records_round_trip_turns_and_nested_values() {+ for status in [+ AgentTurnStatus::Queued,+ AgentTurnStatus::Running,+ AgentTurnStatus::WaitingInput,+ AgentTurnStatus::Interrupting,+ AgentTurnStatus::Completed,+ AgentTurnStatus::Cancelled,+ AgentTurnStatus::Failed,+ AgentTurnStatus::Unknown,+ ] {+ let original = sample_turn(status);+ let encoded = turn_state(&original);+ let decoded: AgentTurnState = serde_json::from_value::<Turn>(encoded.clone())+ .unwrap()+ .try_into()+ .unwrap();+ assert_eq!(turn_state(&decoded), encoded);+ }+}++#[test]+fn shared_records_round_trip_agent_states() {+ for status in [+ AgentStatus::Ready,+ AgentStatus::Busy,+ AgentStatus::Closing,+ AgentStatus::Closed,+ AgentStatus::Unknown,+ ] {+ let original = AgentState {+ id: "agent-1".into(),+ status,+ cursor: None,+ active_turn_id: Some("turn-1".into()),+ queued_turn_ids: vec!["turn-2".into()],+ requests: vec![AgentRequest {+ id: "request-1".into(),+ turn_id: "turn-1".into(),+ kind: AgentRequestKind::Question {+ text: "Continue?".into(),+ schema: Some(json!({"type":"string"})),+ },+ }],+ steering: vec![AgentSteeringReceipt {+ id: "steer-1".into(),+ turn_id: "turn-1".into(),+ status: AgentSteeringStatus::Unused,+ }],+ };+ let encoded = agent_state(&original);+ let decoded: AgentState = serde_json::from_value::<State>(encoded.clone())+ .unwrap()+ .try_into()+ .unwrap();+ assert_eq!(agent_state(&decoded), encoded);+ }+}++#[test]+fn turn_decoders_reject_invalid_enum_values() {+ for (path, field) in [+ ("/status", "turn status"),+ ("/result/status", "turn status"),+ ("/result/outcome", "outcome"),+ ("/steering/0/status", "steering status"),+ ] {+ let mut wire = turn_state(&sample_turn(AgentTurnStatus::Running));+ *wire.pointer_mut(path).unwrap() = json!("not-an-enum-value");+ let decoded: BoxliteResult<AgentTurnState> =+ serde_json::from_value::<Turn>(wire).unwrap().try_into();+ assert!(decoded.unwrap_err().to_string().contains(field), "{path}");+ }+}++#[test]+fn turn_decoders_reject_mismatched_child_ids() {+ for path in [+ "/result/turn_id",+ "/requests/0/turn_id",+ "/steering/0/turn_id",+ ] {+ let mut wire = turn_state(&sample_turn(AgentTurnStatus::Running));+ *wire.pointer_mut(path).unwrap() = json!("another-turn");+ let decoded: BoxliteResult<AgentTurnState> =+ serde_json::from_value::<Turn>(wire).unwrap().try_into();+ assert!(+ decoded+ .unwrap_err()+ .to_string()+ .contains("turn child identity"),+ "{path}"+ );+ }+}++#[test]+fn turn_decoders_accept_absent_result_and_empty_children() {+ let mut original = sample_turn(AgentTurnStatus::Queued);+ original.result = None;+ original.requests.clear();+ original.steering.clear();+ let wire = turn_state(&original);+ let decoded: AgentTurnState = serde_json::from_value::<Turn>(wire.clone())+ .unwrap()+ .try_into()+ .unwrap();+ assert_eq!(turn_state(&decoded), wire);+}++#[test]+fn state_decoders_reject_invalid_status_and_nested_receipts() {+ let original = AgentState {+ id: "agent-1".into(),+ status: AgentStatus::Ready,+ cursor: None,+ active_turn_id: None,+ queued_turn_ids: Vec::new(),+ requests: Vec::new(),+ steering: sample_turn(AgentTurnStatus::Running).steering,+ };+ for (path, field) in [+ ("/status", "status"),+ ("/steering/0/status", "steering status"),+ ] {+ let mut wire = agent_state(&original);+ *wire.pointer_mut(path).unwrap() = json!("not-an-enum-value");+ let decoded: BoxliteResult<AgentState> =+ serde_json::from_value::<State>(wire).unwrap().try_into();+ assert!(decoded.unwrap_err().to_string().contains(field), "{path}");+ }+}++#[test]+fn config_responses_round_trip_known_fields_and_ignore_extensions() {+ let original = AgentConfig {+ model: Some("provider/model".into()),+ reasoning: Some("high".into()),+ instructions: Some("be concise".into()),+ tools: vec!["shell".into()],+ mcp: vec!["docs".into()],+ permissions: Some(json!({"shell": false})),+ limits: Some(json!({"tokens": 100})),+ output_schema: Some(json!({"type": "object"})),+ };+ let expected = config(&original);+ assert_eq!(config(&parse_config(expected.clone()).unwrap()), expected);+ let mut wire = expected.clone();+ wire["provider_metadata"] = json!({"version": 2});+ assert!(parse_config(wire.clone()).is_err());+ let decoded: AgentConfig = serde_json::from_value::<Config>(wire).unwrap().into();+ assert_eq!(config(&decoded), expected);+ for path in ["/model", "/reasoning", "/tools", "/mcp"] {+ let mut wire = expected.clone();+ *wire.pointer_mut(path).unwrap() = json!(123);+ assert!(serde_json::from_value::<Config>(wire).is_err(), "{path}");+ }+}diff --git a/src/boxlite/src/agents/rest.rs b/src/boxlite/src/agents/rest.rsnew file mode 100644index 000000000..e70b1e3ae--- /dev/null+++ b/src/boxlite/src/agents/rest.rs@@ -0,0 +1,273 @@+//! Agent handles backed by the Box REST API.++use std::time::Duration;++use async_trait::async_trait;+use serde_json::Value;++use super::{+ Agent, AgentBackend, AgentCapabilities, AgentConfig, AgentControlOptions, AgentCreateOptions,+ AgentEventStream, AgentEventsOptions, AgentResponse, AgentSendMode, AgentSendOptions,+ AgentState, AgentSteeringReceipt, AgentTurnState,+};+use crate::rest::client::ApiClient;+use crate::rest::litebox::RestBox;+use crate::runtime::backend::BoxBackend;+use crate::{BoxliteError, BoxliteResult};++mod events;++use super::records::{Receipt, Resource, Turn, invalid};++fn segment(value: &str) -> BoxliteResult<String> {+ if value.is_empty() || value == "." || value == ".." {+ return Err(BoxliteError::InvalidArgument(+ "agent path identifier is empty or a dot segment".into(),+ ));+ }+ Ok(urlencoding::encode(value).into_owned())+}++struct RestAgent {+ client: ApiClient,+ path: String,+ id: String,+ adapter: String,+ state: Option<AgentState>,+ config: AgentConfig,+ capabilities: AgentCapabilities,+}++impl std::fmt::Debug for RestAgent {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter+ .debug_struct("RestAgent")+ .field("id", &self.id)+ .finish_non_exhaustive()+ }+}++fn from_resource(remote: &RestBox, path: String, resource: Resource) -> BoxliteResult<Agent> {+ if resource+ .state+ .as_ref()+ .is_some_and(|state| state.id != resource.id)+ {+ return Err(invalid("state id", &resource.id));+ }+ let retention = resource+ .capabilities+ .idempotency_retention_seconds+ .map(|seconds| {+ Duration::try_from_secs_f64(seconds)+ .map_err(|_| invalid("retention", &seconds.to_string()))+ })+ .transpose()?;+ let capabilities = AgentCapabilities {+ operations: resource.capabilities.operations,+ input_kinds: resource.capabilities.input_kinds,+ max_queued_turns: resource.capabilities.max_queued_turns,+ max_pending_steering: resource.capabilities.max_pending_steering,+ idempotency_retention: retention,+ };+ Ok(Agent::new(RestAgent {+ client: remote.agent_client().clone(),+ path,+ id: resource.id,+ adapter: resource.agent,+ state: resource.state.map(TryInto::try_into).transpose()?,+ config: resource.config.into(),+ capabilities,+ }))+}++pub(super) async fn get(remote: &RestBox, agent_id: &str) -> BoxliteResult<Agent> {+ let path = format!(+ "/boxes/{}/agents/{}",+ urlencoding::encode(remote.id().as_ref()),+ segment(agent_id)?+ );+ let resource: Resource = remote.agent_client().get_agent(&path).await?;+ if resource.id != agent_id {+ return Err(invalid("id", &resource.id));+ }+ from_resource(remote, path, resource)+}++pub(super) async fn create(+ remote: &RestBox,+ agent: &str,+ options: &AgentCreateOptions,+) -> BoxliteResult<Agent> {+ let path = format!(+ "/boxes/{}/agents",+ urlencoding::encode(remote.id().as_ref())+ );+ let config = &options.config;+ let has_config = config.model.is_some()+ || config.reasoning.is_some()+ || config.instructions.is_some()+ || !config.tools.is_empty()+ || !config.mcp.is_empty()+ || config.permissions.is_some()+ || config.limits.is_some()+ || config.output_schema.is_some();+ let mut create_options = serde_json::Map::new();+ if let Some(cwd) = &options.cwd {+ create_options.insert("cwd".into(), Value::String(cwd.clone()));+ }+ if has_config {+ create_options.insert("config".into(), super::records::config(config));+ }+ let mut body = serde_json::json!({"agent": agent});+ if !create_options.is_empty() {+ body["options"] = Value::Object(create_options);+ }+ let resource: Resource = remote+ .agent_client()+ .post_agent(&path, &body, options.idempotency_key.as_deref())+ .await?;+ if resource.agent != agent {+ return Err(invalid("implementation", &resource.agent));+ }+ let resource_path = format!("{path}/{}", segment(&resource.id)?);+ from_resource(remote, resource_path, resource)+}++#[async_trait]+impl AgentBackend for RestAgent {+ fn adapter(&self) -> &str {+ &self.adapter+ }+ fn implementation(&self) -> &str {+ &self.adapter+ }+ fn id(&self) -> &str {+ &self.id+ }+ fn config(&self) -> &AgentConfig {+ &self.config+ }+ fn capabilities(&self) -> AgentCapabilities {+ self.capabilities.clone()+ }+ fn state(&self) -> BoxliteResult<AgentState> {+ self.state+ .clone()+ .ok_or_else(|| BoxliteError::Unsupported("agent.state is not supported".into()))+ }+ async fn send(&self, text: &str, options: &AgentSendOptions) -> BoxliteResult<AgentTurnState> {+ let mut send_options = serde_json::Map::new();+ if options.mode == AgentSendMode::Reject {+ send_options.insert("mode".into(), Value::String("reject".into()));+ }+ if let Some(data) = &options.data {+ send_options.insert("data".into(), data.clone());+ }+ let mut body = serde_json::json!({"text": text});+ if !send_options.is_empty() {+ body["options"] = Value::Object(send_options);+ }+ let result: Turn = self+ .client+ .post_agent(+ &format!("{}/turns", self.path),+ &body,+ options.idempotency_key.as_deref(),+ )+ .await?;+ if result.agent_id != self.id {+ return Err(invalid("turn agent_id", &result.agent_id));+ }+ result.try_into()+ }+ async fn turn(&self, turn_id: &str) -> BoxliteResult<AgentTurnState> {+ let result: Turn = self+ .client+ .get_agent(&format!("{}/turns/{}", self.path, segment(turn_id)?))+ .await?;+ if result.agent_id != self.id {+ return Err(invalid("turn agent_id", &result.agent_id));+ }+ if result.id != turn_id {+ return Err(invalid("turn id", &result.id));+ }+ result.try_into()+ }+ async fn close(&self, options: &AgentControlOptions) -> BoxliteResult<()> {+ self.client+ .post_agent_no_content(+ &format!("{}/close", self.path),+ options.idempotency_key.as_deref(),+ )+ .await+ }+ async fn respond(+ &self,+ request_id: &str,+ response: AgentResponse,+ options: &AgentControlOptions,+ ) -> BoxliteResult<AgentTurnState> {+ let response = match response {+ AgentResponse::Answer { text, data } => {+ let mut value = serde_json::json!({"type": "answer", "text": text});+ if let Some(data) = data {+ value["data"] = data;+ }+ value+ }+ AgentResponse::Permission { approved } => {+ serde_json::json!({"type": "permission", "approved": approved})+ }+ };+ let path = format!("{}/requests/{}/respond", self.path, segment(request_id)?);+ let result: Turn = self+ .client+ .post_agent(+ &path,+ &serde_json::json!({"response": response}),+ options.idempotency_key.as_deref(),+ )+ .await?;+ if result.agent_id != self.id {+ return Err(invalid("turn agent_id", &result.agent_id));+ }+ result.try_into()+ }+ async fn steer(+ &self,+ turn_id: &str,+ text: &str,+ options: &AgentControlOptions,+ ) -> BoxliteResult<AgentSteeringReceipt> {+ let path = format!("{}/turns/{}/steer", self.path, segment(turn_id)?);+ let result: Receipt = self+ .client+ .post_agent(+ &path,+ &serde_json::json!({"text": text}),+ options.idempotency_key.as_deref(),+ )+ .await?;+ if result.turn_id != turn_id {+ return Err(invalid("receipt turn_id", &result.turn_id));+ }+ result.try_into()+ }+ async fn interrupt(&self, turn_id: &str, options: &AgentControlOptions) -> BoxliteResult<()> {+ let path = format!("{}/turns/{}/interrupt", self.path, segment(turn_id)?);+ self.client+ .post_agent_no_content(&path, options.idempotency_key.as_deref())+ .await+ }+ async fn events(&self, options: &AgentEventsOptions) -> BoxliteResult<AgentEventStream> {+ events::open(&self.client, &self.path, &self.id, None, options).await+ }+ async fn turn_events(+ &self,+ turn_id: &str,+ options: &AgentEventsOptions,+ ) -> BoxliteResult<AgentEventStream> {+ events::open(&self.client, &self.path, &self.id, Some(turn_id), options).await+ }+}diff --git a/src/boxlite/src/agents/rest/events.rs b/src/boxlite/src/agents/rest/events.rsnew file mode 100644index 000000000..4d760f830--- /dev/null+++ b/src/boxlite/src/agents/rest/events.rs@@ -0,0 +1,195 @@+//! Bounded SSE decoding for remote agent events.++use futures::StreamExt;+use serde::Deserialize;+use serde_json::Value;+use tokio::sync::mpsc;+use tokio_stream::wrappers::ReceiverStream;++use super::super::{AgentEvent, AgentEventStream, AgentEventsOptions};+use crate::rest::client::ApiClient;+use crate::rest::error::map_http_body;+use crate::{BoxliteError, BoxliteResult};++const MAX_EVENT_BYTES: usize = 1024 * 1024;+const EVENT_BUFFER: usize = 64;+// Allow two missed 15-second server heartbeats before reporting a stalled stream.+const READ_IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);++#[derive(Deserialize)]+struct WireEvent {+ cursor: Option<String>,+ agent_id: String,+ turn_id: Option<String>,+ kind: String,+ data: Value,+}++#[derive(Default)]+struct Parser {+ line: Vec<u8>,+ data: String,+ event: String,+ after_cr: bool,+ started: bool,+}++impl Parser {+ fn feed(&mut self, byte: u8) -> BoxliteResult<Option<(String, String)>> {+ if self.after_cr {+ self.after_cr = false;+ if byte == b'\n' {+ return Ok(None);+ }+ }+ if byte != b'\r' && byte != b'\n' {+ self.line.push(byte);+ if self.line.len() + self.data.len() > MAX_EVENT_BYTES {+ return Err(BoxliteError::ResourceExhausted(+ "agent event exceeds 1 MiB".into(),+ ));+ }+ return Ok(None);+ }+ self.after_cr = byte == b'\r';+ let line = std::str::from_utf8(&self.line)+ .map_err(|_| BoxliteError::Internal("agent event is not UTF-8".into()))?;+ let line = if self.started {+ line+ } else {+ self.started = true;+ line.strip_prefix('\u{feff}').unwrap_or(line)+ };+ let mut completed = None;+ if line.is_empty() {+ if !self.data.is_empty() {+ self.data.pop();+ completed = Some((+ std::mem::take(&mut self.event),+ std::mem::take(&mut self.data),+ ));+ } else {+ self.event.clear();+ }+ } else if !line.starts_with(':') {+ let (field, value) = line.split_once(':').unwrap_or((line, ""));+ let value = value.strip_prefix(' ').unwrap_or(value);+ match field {+ "event" => self.event = value.to_owned(),+ "data" => {+ self.data.push_str(value);+ self.data.push('\n');+ }+ _ => {}+ }+ }+ self.line.clear();+ if self.event.len() + self.data.len() > MAX_EVENT_BYTES {+ return Err(BoxliteError::ResourceExhausted(+ "agent event exceeds 1 MiB".into(),+ ));+ }+ Ok(completed)+ }+}++pub(super) async fn open(+ client: &ApiClient,+ path: &str,+ agent_id: &str,+ turn_id: Option<&str>,+ options: &AgentEventsOptions,+) -> BoxliteResult<AgentEventStream> {+ let response = client+ .agent_events(&format!("{path}/events"), options.after.as_deref(), turn_id)+ .await?;+ let agent_id = agent_id.to_owned();+ let turn_id = turn_id.map(str::to_owned);+ let (sender, receiver) = mpsc::channel(EVENT_BUFFER);+ tokio::spawn(async move {+ let mut parser = Parser::default();+ let mut stream = response.bytes_stream();+ loop {+ let next = tokio::select! {+ _ = sender.closed() => return,+ next = stream.next() => next,+ _ = tokio::time::sleep(READ_IDLE_TIMEOUT) => {+ let _ = sender.send(Err(BoxliteError::Network(+ "agent event stream idle for 30 seconds".into(),+ ))).await;+ return;+ }+ };+ let chunk = match next {+ Some(Ok(chunk)) => chunk,+ Some(Err(error)) => {+ let _ = sender+ .send(Err(BoxliteError::Network(format!(+ "agent event stream failed: {error}"+ ))))+ .await;+ return;+ }+ None => {+ let _ = sender+ .send(Err(BoxliteError::Network(+ "agent event stream ended".into(),+ )))+ .await;+ return;+ }+ };+ for byte in chunk {+ let frame = match parser.feed(byte) {+ Ok(Some(frame)) => frame,+ Ok(None) => continue,+ Err(error) => {+ let _ = sender.send(Err(error)).await;+ return;+ }+ };+ let (name, data) = frame;+ let result = if name == "error" {+ Err(map_http_body(+ reqwest::StatusCode::INTERNAL_SERVER_ERROR,+ &data,+ ))+ } else if name == "agent" || name.is_empty() {+ serde_json::from_str::<WireEvent>(&data)+ .map_err(|error| {+ BoxliteError::Internal(format!("invalid agent event: {error}"))+ })+ .and_then(|event| {+ if event.agent_id != agent_id+ || turn_id+ .as_ref()+ .is_some_and(|id| event.turn_id.as_ref() != Some(id))+ {+ return Err(BoxliteError::Internal(+ "agent event has wrong parent".into(),+ ));+ }+ Ok(AgentEvent {+ cursor: event.cursor,+ agent_id: event.agent_id,+ turn_id: event.turn_id,+ kind: event.kind,+ data: event.data,+ })+ })+ } else {+ Err(BoxliteError::Internal("unknown agent event type".into()))+ };+ let failed = result.is_err();+ if sender.send(result).await.is_err() || failed {+ return;+ }+ }+ }+ });+ Ok(Box::pin(ReceiverStream::new(receiver)))+}++#[cfg(test)]+#[path = "tests/events.rs"]+mod tests;diff --git a/src/boxlite/src/agents/rest/tests/events.rs b/src/boxlite/src/agents/rest/tests/events.rsnew file mode 100644index 000000000..602e03f86--- /dev/null+++ b/src/boxlite/src/agents/rest/tests/events.rs@@ -0,0 +1,308 @@+use super::*;++#[test]+fn parser_handles_chunk_boundaries_and_all_line_endings() {+ let mut parser = Parser::default();+ let input = b": keepalive\r\nevent: agent\rdata: {\"text\":\r\ndata: \"hi\"}\n\n";+ let frames: Vec<_> = input+ .iter()+ .filter_map(|byte| parser.feed(*byte).unwrap())+ .collect();+ assert_eq!(+ frames,+ vec![("agent".to_string(), "{\"text\":\n\"hi\"}".to_string())]+ );+ let value: Value = serde_json::from_str(&frames[0].1).unwrap();+ assert_eq!(value["text"], "hi");+}++#[test]+fn parser_rejects_oversized_or_invalid_utf8_lines() {+ let mut parser = Parser::default();+ for _ in 0..MAX_EVENT_BYTES {+ parser.feed(b'x').unwrap();+ }+ assert!(matches!(+ parser.feed(b'x'),+ Err(BoxliteError::ResourceExhausted(_))+ ));+ let mut parser = Parser::default();+ parser.feed(0xff).unwrap();+ assert!(matches!(parser.feed(b'\n'), Err(BoxliteError::Internal(_))));+}++#[test]+fn parser_accepts_initial_utf8_bom() {+ let mut parser = Parser::default();+ let frames: Vec<_> = "\u{feff}data: hello\n\n"+ .bytes()+ .filter_map(|byte| parser.feed(byte).unwrap())+ .collect();+ assert_eq!(frames, vec![(String::new(), "hello".to_string())]);+}++#[tokio::test]+async fn stream_delivers_events_before_one_terminal_error() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut request = Vec::new();+ let mut byte = [0];+ while !request.ends_with(b"\r\n\r\n") {+ socket.read_exact(&mut byte).await.unwrap();+ request.push(byte[0]);+ }+ let body = concat!(+ "event: agent\ndata: {\"cursor\":null,\"agent_id\":\"agent-1\",\"turn_id\":null,\"kind\":\"message\",\"data\":{}}\n\n",+ "event: error\ndata: {\"error\":{\"message\":\"stream unavailable\",\"type\":\"UnsupportedError\",\"code\":\"unsupported\"}}\n\n"+ );+ socket.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\n\r\n{body}", body.len()).as_bytes()).await.unwrap();+ });+ let client = ApiClient::new(&crate::BoxliteRestOptions::new(format!("http://{addr}"))).unwrap();+ let mut stream = open(+ &client,+ "/boxes/box-1/agents/agent-1",+ "agent-1",+ None,+ &Default::default(),+ )+ .await+ .unwrap();+ assert_eq!(stream.next().await.unwrap().unwrap().kind, "message");+ assert!(matches!(+ stream.next().await.unwrap(),+ Err(BoxliteError::Unsupported(_))+ ));+ assert!(stream.next().await.is_none());+ server.await.unwrap();+}++#[tokio::test]+async fn unknown_event_error_is_bounded() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut request = Vec::new();+ let mut byte = [0];+ while !request.ends_with(b"\r\n\r\n") {+ socket.read_exact(&mut byte).await.unwrap();+ request.push(byte[0]);+ }+ let body = format!("event: {}\ndata: {{}}\n\n", "x".repeat(4096));+ socket.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\n\r\n{body}", body.len()).as_bytes()).await.unwrap();+ });+ let client = ApiClient::new(&crate::BoxliteRestOptions::new(format!("http://{addr}"))).unwrap();+ let mut stream = open(+ &client,+ "/boxes/box-1/agents/agent-1",+ "agent-1",+ None,+ &Default::default(),+ )+ .await+ .unwrap();+ let error = stream.next().await.unwrap().unwrap_err().to_string();+ assert!(error.contains("unknown agent event type"), "{error}");+ assert!(error.len() < 256, "error contains {} bytes", error.len());+ server.await.unwrap();+}++#[tokio::test]+async fn dropping_stream_closes_the_http_connection() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut request = Vec::new();+ let mut byte = [0];+ while !request.ends_with(b"\r\n\r\n") {+ socket.read_exact(&mut byte).await.unwrap();+ request.push(byte[0]);+ }+ socket+ .write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\r\n")+ .await+ .unwrap();+ socket.read(&mut byte).await.unwrap()+ });+ let client = ApiClient::new(&crate::BoxliteRestOptions::new(format!("http://{addr}"))).unwrap();+ let stream = open(+ &client,+ "/boxes/box-1/agents/agent-1",+ "agent-1",+ None,+ &Default::default(),+ )+ .await+ .unwrap();+ drop(stream);+ assert_eq!(+ tokio::time::timeout(std::time::Duration::from_secs(5), server)+ .await+ .unwrap()+ .unwrap(),+ 0+ );+}++#[tokio::test]+async fn malformed_event_streams_report_one_terminal_error() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let cases = [+ ("data: not-json\n\n", false, "invalid agent event"),+ ("data: partial", true, "agent event stream failed"),+ ];+ let server = tokio::spawn(async move {+ for (body, truncated, _) in cases {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut header = Vec::new();+ while !header.ends_with(b"\r\n\r\n") {+ header.push(socket.read_u8().await.unwrap());+ }+ let length = body.len() + usize::from(truncated);+ socket.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {length}\r\nConnection: close\r\n\r\n{body}").as_bytes()).await.unwrap();+ }+ });+ let client = ApiClient::new(&crate::BoxliteRestOptions::new(format!("http://{addr}"))).unwrap();+ for (_, _, expected) in cases {+ let mut stream = open(&client, "/boxes/b/agents/a", "a", None, &Default::default())+ .await+ .unwrap();+ let error = stream.next().await.unwrap().unwrap_err();+ assert!(error.to_string().contains(expected), "{error}");+ assert!(stream.next().await.is_none());+ }+ server.await.unwrap();+}++#[tokio::test]+async fn idle_stream_yields_one_network_error() {+ use std::time::Duration;+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut header = Vec::new();+ while !header.ends_with(b"\r\n\r\n") {+ header.push(socket.read_u8().await.unwrap());+ }+ socket+ .write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\r\n")+ .await+ .unwrap();+ let _ = socket.read_u8().await;+ });+ let client = ApiClient::new(&crate::BoxliteRestOptions::new(format!("http://{addr}"))).unwrap();+ let mut stream = open(&client, "/agents/a", "a", None, &Default::default())+ .await+ .unwrap();+ tokio::time::pause();+ let event = tokio::time::timeout(Duration::from_secs(60), stream.next())+ .await+ .expect("silent SSE connection never timed out");+ assert!(matches!(event, Some(Err(BoxliteError::Network(_)))));+ assert!(stream.next().await.is_none());+ server.await.unwrap();+}++#[tokio::test]+async fn heartbeats_keep_an_idle_subscription_open() {+ use std::time::Duration;+ use tokio::io::{AsyncReadExt, AsyncWriteExt};++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut header = Vec::new();+ while !header.ends_with(b"\r\n\r\n") {+ header.push(socket.read_u8().await.unwrap());+ }+ socket+ .write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\r\n")+ .await+ .unwrap();+ socket+ });+ let client = ApiClient::new(&crate::BoxliteRestOptions::new(format!("http://{addr}"))).unwrap();+ let mut stream = open(&client, "/agents/a", "a", None, &Default::default())+ .await+ .unwrap();+ let mut socket = server.await.unwrap();+ for _ in 0..2 {+ tokio::time::sleep(Duration::from_secs(15)).await;+ socket.write_all(b": heartbeat\n\n").await.unwrap();+ }+ tokio::time::sleep(Duration::from_secs(5)).await;+ socket+ .write_all(b"event: agent\ndata: {\"agent_id\":\"a\",\"kind\":\"message\",\"data\":{}}\n\n")+ .await+ .unwrap();+ let event = tokio::time::timeout(Duration::from_secs(5), stream.next())+ .await+ .unwrap()+ .unwrap()+ .unwrap();+ assert_eq!(event.kind, "message");+}++#[tokio::test]+async fn agent_subscription_delivers_opencode_child_then_parent_events() {+ use crate::agents::{opencode::tests::scripted_events, records};+ use serde_json::json;+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let mut native = scripted_events(&[+ json!({"type":"session.created","data":{"parentID":"ses_test","sessionID":"ses_child"}}),+ json!({"type":"session.inbox.enqueued","data":{"sessionID":"ses_child","inboxID":"msg_child"}}),+ json!({"type":"session.inbox.enqueued","data":{"sessionID":"ses_test","inboxID":"msg_parent"}}),+ ]).await;+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut header = Vec::new();+ while !header.ends_with(b"\r\n\r\n") {+ header.push(socket.read_u8().await.unwrap());+ }+ socket+ .write_all(+ b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n",+ )+ .await+ .unwrap();+ while let Some(Ok(event)) = native.next().await {+ let frame = format!("event: agent\ndata: {}\n\n", records::event(&event));+ socket.write_all(frame.as_bytes()).await.unwrap();+ }+ });+ let client = ApiClient::new(&crate::BoxliteRestOptions::new(format!("http://{addr}"))).unwrap();+ let mut stream = open(+ &client,+ "/boxes/box/agents/ses_test",+ "ses_test",+ None,+ &Default::default(),+ )+ .await+ .unwrap();+ assert_eq!(+ stream.next().await.unwrap().unwrap().kind,+ "session.created"+ );+ let child = stream.next().await.unwrap().unwrap();+ assert_eq!(child.agent_id, "ses_test");+ assert_eq!(child.data["data"]["sessionID"], "ses_child");+ assert_eq!(child.turn_id, None);+ let parent = stream.next().await.unwrap().unwrap();+ assert_eq!(parent.agent_id, "ses_test");+ assert_eq!(parent.turn_id.as_deref(), Some("msg_parent"));+ server.await.unwrap();+}diff --git a/src/boxlite/src/agents/test_support.rs b/src/boxlite/src/agents/test_support.rsindex 82741cc69..1ac33eeb5 100644--- a/src/boxlite/src/agents/test_support.rs+++ b/src/boxlite/src/agents/test_support.rs@@ -39,6 +39,9 @@ impl AgentBackend for TestBackend {fn adapter(&self) -> &str {"test"}+ fn implementation(&self) -> &str {+ "test"+ }fn id(&self) -> &str {"agent-1"}diff --git a/src/boxlite/src/rest/client.rs b/src/boxlite/src/rest/client.rsindex 5a99dc0f4..1b974d7bf 100644--- a/src/boxlite/src/rest/client.rs+++ b/src/boxlite/src/rest/client.rs@@ -23,6 +23,20 @@ const REFRESH_LEEWAY: Duration = Duration::from_secs(60);/// File transfers cannot outlive the runner's 24-hour box lifetime cap.const FILE_REQUEST_TIMEOUT: Duration = Duration::from_secs(24 * 60 * 60);const TUNNEL_SETUP_TIMEOUT: Duration = Duration::from_secs(30);+const AGENT_RESPONSE_MAX_BYTES: usize = 16 * 1024 * 1024;++async fn read_agent_body(response: &mut reqwest::Response) -> BoxliteResult<Vec<u8>> {+ let mut body = Vec::new();+ while let Some(chunk) = response.chunk().await.map_err(transport_error)? {+ if chunk.len() > AGENT_RESPONSE_MAX_BYTES.saturating_sub(body.len()) {+ return Err(BoxliteError::ResourceExhausted(+ "agent response exceeds 16 MiB".into(),+ ));+ }+ body.extend_from_slice(&chunk);+ }+ Ok(body)+}/// The native REST transport is shared by every SDK binding and the CLI.fn client_identity_headers() -> reqwest::header::HeaderMap {@@ -105,6 +119,8 @@ pub(crate) type WsHandshakeResponse = tokio_tungstenite::tungstenite::handshake:#[derive(Clone)]pub(crate) struct ApiClient {http: Client,+ agent_writes: Client,+ stream_http: Client,tunnel_connector: TunnelConnector,base_url: String,/// Routing-slot value substituted into the `{prefix}` URL segment@@ -125,12 +141,30 @@ pub(crate) struct ApiClient {impl ApiClient {pub fn new(config: &BoxliteRestOptions) -> BoxliteResult<Self> {let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();- let http = Client::builder()- .default_headers(client_identity_headers())- .timeout(std::time::Duration::from_secs(300))- .connect_timeout(std::time::Duration::from_secs(300))+ let request_client = || {+ Client::builder()+ .default_headers(client_identity_headers())+ .timeout(std::time::Duration::from_secs(300))+ .connect_timeout(std::time::Duration::from_secs(300))+ };+ let http = request_client().build().map_err(|e| BoxliteError::Config(format!("failed to create HTTP client: {}", e)))?;+ // A write may already have taken effect at the first destination.+ let agent_writes = request_client()+ .redirect(reqwest::redirect::Policy::none())+ .retry(reqwest::retry::never())+ .build()+ .map_err(|e| {+ BoxliteError::Config(format!("failed to create agent write client: {e}"))+ })?;+ let stream_http = Client::builder()+ .default_headers(client_identity_headers())+ .connect_timeout(std::time::Duration::from_secs(30))+ .build()+ .map_err(|e| {+ BoxliteError::Config(format!("failed to create streaming HTTP client: {e}"))+ })?;let tunnel_connector = hyper_rustls::HttpsConnectorBuilder::new().with_native_roots().map_err(|e| BoxliteError::Config(format!("failed to load TLS roots: {e}")))?@@ -143,6 +177,8 @@ impl ApiClient {Ok(Self {http,+ agent_writes,+ stream_http,tunnel_connector,base_url,path_prefix,@@ -314,6 +350,109 @@ impl ApiClient {self.send_json(builder).await}+ pub(crate) async fn post_agent<T: DeserializeOwned>(+ &self,+ path: &str,+ body: &serde_json::Value,+ key: Option<&str>,+ ) -> BoxliteResult<T> {+ let mut builder = self.agent_writes.post(self.url(path)).json(body);+ if let Some(key) = key {+ builder = builder.header("Idempotency-Key", key);+ }+ self.send_agent_json(builder).await+ }++ pub(crate) async fn get_agent<T: DeserializeOwned>(&self, path: &str) -> BoxliteResult<T> {+ self.send_agent_json(self.http.get(self.url(path))).await+ }++ async fn send_agent_json<T: DeserializeOwned>(+ &self,+ builder: RequestBuilder,+ ) -> BoxliteResult<T> {+ let builder = self.authorize(builder).await?;+ let mut response = builder.send().await.map_err(transport_error)?;+ let status = response.status();+ let body = read_agent_body(&mut response).await?;+ if !status.is_success() {+ return Err(map_http_body(status, &String::from_utf8_lossy(&body)));+ }+ serde_json::from_slice(&body)+ .map_err(|error| BoxliteError::Internal(format!("invalid agent response: {error}")))+ }++ pub(crate) async fn post_agent_no_content(+ &self,+ path: &str,+ key: Option<&str>,+ ) -> BoxliteResult<()> {+ let mut builder = self+ .agent_writes+ .post(self.url(path))+ .json(&serde_json::json!({}));+ if let Some(key) = key {+ builder = builder.header("Idempotency-Key", key);+ }+ let builder = self.authorize(builder).await?;+ let mut response = builder.send().await.map_err(transport_error)?;+ let status = response.status();+ if status == StatusCode::NO_CONTENT {+ return Ok(());+ }+ let body = read_agent_body(&mut response).await?;+ if status.is_success() {+ return Err(BoxliteError::Internal(format!(+ "agent control returned unexpected HTTP {status}"+ )));+ }+ Err(map_http_body(status, &String::from_utf8_lossy(&body)))+ }++ pub(crate) async fn agent_events(+ &self,+ path: &str,+ after: Option<&str>,+ turn_id: Option<&str>,+ ) -> BoxliteResult<reqwest::Response> {+ let mut builder = self+ .stream_http+ .get(self.url(path))+ .header(reqwest::header::ACCEPT, "text/event-stream");+ if let Some(after) = after {+ builder = builder.query(&[("after", after)]);+ }+ if let Some(turn_id) = turn_id {+ builder = builder.query(&[("turn_id", turn_id)]);+ }+ let builder = self.authorize(builder).await?;+ tokio::time::timeout(Duration::from_secs(30), async {+ let mut response = builder.send().await.map_err(transport_error)?;+ if !response.status().is_success() {+ let status = response.status();+ let body = read_agent_body(&mut response).await?;+ return Err(map_http_body(status, &String::from_utf8_lossy(&body)));+ }+ let content_type = response+ .headers()+ .get(reqwest::header::CONTENT_TYPE)+ .and_then(|value| value.to_str().ok())+ .unwrap_or_default();+ if !content_type+ .split(';')+ .next()+ .is_some_and(|value| value.trim().eq_ignore_ascii_case("text/event-stream"))+ {+ return Err(BoxliteError::Internal(+ "agent event stream has invalid content type".into(),+ ));+ }+ Ok(response)+ })+ .await+ .map_err(|_| BoxliteError::Network("agent event stream opening timed out".into()))?+ }+/// A fractional create must not silently lose its requested CPU allocation.pub async fn create_box(&self, request: &CreateBoxRequest) -> BoxliteResult<BoxResponse> {let requested = request.cpus.map(CpuCount::new).transpose()?;@@ -821,6 +960,7 @@ fn ensure_capability(name: &str, enabled: Option<bool>) -> BoxliteResult<()> {#[cfg(test)]mod tests {+ mod agents;use super::ensure_capability;use super::*;use crate::rest::credential::{AccessToken, Credential};diff --git a/src/boxlite/src/rest/client/tests/agents.rs b/src/boxlite/src/rest/client/tests/agents.rsnew file mode 100644index 000000000..45a602447--- /dev/null+++ b/src/boxlite/src/rest/client/tests/agents.rs@@ -0,0 +1,194 @@+use super::*;+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::TcpListener;++#[tokio::test]+async fn agent_client_controls_require_204_and_forward_errors() {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let mut requests = Vec::new();+ for (status, body) in [+ ("204 No Content", ""),+ ("200 OK", "{}"),+ (+ "400 Bad Request",+ r#"{"error":{"message":"not supported","type":"UnsupportedError","code":"unsupported"}}"#,+ ),+ ] {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut header = Vec::new();+ while !header.ends_with(b"\r\n\r\n") {+ header.push(socket.read_u8().await.unwrap());+ }+ let header = String::from_utf8(header).unwrap().to_lowercase();+ let length: usize = header+ .lines()+ .find_map(|line| {+ line.strip_prefix("content-length:")+ .map(|v| v.trim().parse().unwrap())+ })+ .unwrap();+ let mut request_body = vec![0; length];+ socket.read_exact(&mut request_body).await.unwrap();+ assert_eq!(+ serde_json::from_slice::<serde_json::Value>(&request_body).unwrap(),+ serde_json::json!({})+ );+ requests.push(header);+ socket.write_all(format!("HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()).await.unwrap();+ }+ requests+ });+ let client = ApiClient::new(+ &BoxliteRestOptions::new(format!("http://{address}")).with_api_key("test-key"),+ )+ .unwrap();+ client+ .post_agent_no_content("/agents/a/close", Some("retry-1"))+ .await+ .unwrap();+ assert!(matches!(+ client.post_agent_no_content("/agents/a/close", None).await,+ Err(BoxliteError::Internal(_))+ ));+ assert!(matches!(+ client.post_agent_no_content("/agents/a/close", None).await,+ Err(BoxliteError::Unsupported(_))+ ));+ let requests = server.await.unwrap();+ assert!(requests[0].starts_with("post /v1/agents/a/close http/1.1\r\n"));+ assert!(requests[0].contains("authorization: bearer test-key\r\n"));+ assert!(requests[0].contains("idempotency-key: retry-1\r\n"));+ assert!(!requests[1].contains("idempotency-key:"));+}+#[tokio::test]+async fn agent_client_events_validate_handshake_and_forward_query() {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let mut requests = Vec::new();+ for (status, content_type, body) in [+ ("200 OK", "text/event-stream; charset=utf-8", ""),+ ("200 OK", "application/json", "{}"),+ (+ "400 Bad Request",+ "application/json",+ r#"{"error":{"message":"not supported","type":"UnsupportedError","code":"unsupported"}}"#,+ ),+ ] {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut header = Vec::new();+ while !header.ends_with(b"\r\n\r\n") {+ header.push(socket.read_u8().await.unwrap());+ }+ requests.push(String::from_utf8(header).unwrap().to_lowercase());+ socket.write_all(format!("HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()).await.unwrap();+ }+ requests+ });+ let client = ApiClient::new(+ &BoxliteRestOptions::new(format!("http://{address}")).with_api_key("test-key"),+ )+ .unwrap();+ client+ .agent_events("/agents/a/events", Some("cursor 1"), Some("turn/1"))+ .await+ .unwrap();+ assert!(matches!(+ client.agent_events("/agents/a/events", None, None).await,+ Err(BoxliteError::Internal(_))+ ));+ assert!(matches!(+ client.agent_events("/agents/a/events", None, None).await,+ Err(BoxliteError::Unsupported(_))+ ));+ let requests = server.await.unwrap();+ assert!(+ requests[0]+ .starts_with("get /v1/agents/a/events?after=cursor+1&turn_id=turn%2f1 http/1.1\r\n")+ );+ assert!(requests[0].contains("accept: text/event-stream\r\n"));+ assert!(requests[0].contains("authorization: bearer test-key\r\n"));+}+#[tokio::test]+async fn agent_client_rejects_oversized_and_malformed_json() {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ for body in [+ vec![b'x'; AGENT_RESPONSE_MAX_BYTES + 1],+ b"{invalid".to_vec(),+ ] {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut header = Vec::new();+ while !header.ends_with(b"\r\n\r\n") {+ header.push(socket.read_u8().await.unwrap());+ }+ socket+ .write_all(+ format!(+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",+ body.len()+ )+ .as_bytes(),+ )+ .await+ .unwrap();+ let _ = socket.write_all(&body).await;+ }+ });+ let client = ApiClient::new(&BoxliteRestOptions::new(format!("http://{address}"))).unwrap();+ let oversize = client.get_agent::<serde_json::Value>("/agents/a").await;+ assert!(matches!(oversize, Err(BoxliteError::ResourceExhausted(_))));+ let malformed = client.get_agent::<serde_json::Value>("/agents/a").await;+ assert!(matches!(malformed, Err(BoxliteError::Internal(_))));+ server.await.unwrap();+}++#[tokio::test]+async fn agent_writes_stop_at_first_redirect() {+ for (code, control) in [(307, false), (308, true)] {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let client = ApiClient::new(&BoxliteRestOptions::new(format!(+ "http://{}",+ listener.local_addr().unwrap()+ )))+ .unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut head = Vec::new();+ while !head.ends_with(b"\r\n\r\n") {+ head.push(socket.read_u8().await.unwrap());+ }+ let mut body = [0; 2];+ socket.read_exact(&mut body).await.unwrap();+ socket.write_all(format!("HTTP/1.1 {code} Redirect\r\nLocation: /unexpected\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").as_bytes()).await.unwrap();+ drop(socket);+ if let Ok(Ok((mut extra, _))) =+ tokio::time::timeout(std::time::Duration::from_secs(1), listener.accept()).await+ {+ let _ = extra+ .write_all(b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n")+ .await;+ return true;+ }+ false+ });+ if control {+ client+ .post_agent_no_content("/agents/a/close", None)+ .await+ .unwrap_err();+ } else {+ client+ .post_agent::<serde_json::Value>("/agents", &serde_json::json!({}), None)+ .await+ .unwrap_err();+ }+ assert!(+ !server.await.unwrap(),+ "agent write followed a {code} redirect"+ );+ }+}diff --git a/src/boxlite/src/rest/litebox.rs b/src/boxlite/src/rest/litebox.rsindex 91727ed50..db2a721c6 100644--- a/src/boxlite/src/rest/litebox.rs+++ b/src/boxlite/src/rest/litebox.rs@@ -53,6 +53,10 @@ struct TarDownload {}impl RestBox {+ pub(crate) fn agent_client(&self) -> &ApiClient {+ &self.client+ }+pub fn new(client: ApiClient, info: BoxInfo) -> Self {Self {client,@@ -3162,40 +3166,5 @@ mod tests {server.await.unwrap();}- /// Agents refuse a REST Box before any request: its tunnels can publish- /// the agent's server beyond this host.- #[tokio::test]- async fn agents_refuse_a_remote_box_before_any_request() {- let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();- let port = listener.local_addr().unwrap().port();- let rest_box = Arc::new(rest_box_for(port, "remote-box"));- let agents = crate::Agents::new(rest_box.clone(), rest_box);- let bound = Duration::from_secs(5);-- let created = tokio::time::timeout(- bound,- agents.create("opencode", crate::agents::AgentCreateOptions::default()),- )- .await- .expect("create must not wait on the server")- .err();- let fetched = tokio::time::timeout(bound, agents.get("ses_test"))- .await- .expect("get must not wait on the server")- .err();- // Input a local runtime would reject is still refused for the runtime.- let malformed_id = agents.get("not-a-session").await.err();- let mut bad_model = crate::agents::AgentCreateOptions::default();- bad_model.config.model = Some("no-provider".into());- let malformed_model = agents.create("opencode", bad_model).await.err();-- for error in [created, fetched, malformed_id, malformed_model] {- assert!(- matches!(&error, Some(BoxliteError::Unsupported(message)) if message == "agents require a local runtime"),- "{error:?}"- );- }- let connected = tokio::time::timeout(Duration::from_millis(100), listener.accept()).await;- assert!(connected.is_err(), "no request reached the server");- }+ mod agents;}diff --git a/src/boxlite/src/rest/litebox/tests/agents.rs b/src/boxlite/src/rest/litebox/tests/agents.rsnew file mode 100644index 000000000..4a88d1dbf--- /dev/null+++ b/src/boxlite/src/rest/litebox/tests/agents.rs@@ -0,0 +1,510 @@+use super::*;++#[tokio::test]+async fn remote_agent_get_reports_server_not_found() {+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let server = serve_once(+ listener,+ "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",+ );+ let rest_box = Arc::new(rest_box_for(port, "remote-box"));+ let agents = crate::Agents::new(rest_box.clone(), rest_box);++ let error = agents.get("ses_test").await.unwrap_err();+ assert!(matches!(error, BoxliteError::NotFound(_)), "{error:?}");+ let request = server.await.unwrap();+ assert!(request.starts_with("GET /v1/boxes/remote-box/agents/ses_test "));+}+#[tokio::test]+async fn remote_agent_get_reads_snapshot_without_state() {+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let head = read_request_head(&mut socket).await;+ let body = r#"{"id":"ses_test","agent":"opencode","state":null,"config":{"tools":[],"mcp":[],"model":"provider/model"},"capabilities":{"operations":["agent.send"],"input_kinds":["text"],"max_queued_turns":null,"max_pending_steering":null,"idempotency_retention_seconds":null}}"#;+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ socket.write_all(response.as_bytes()).await.unwrap();+ String::from_utf8(head).unwrap()+ });+ let rest_box = Arc::new(rest_box_for(port, "remote-box"));+ let agents = crate::Agents::new(rest_box.clone(), rest_box);+ let agent = agents.get("ses_test").await.unwrap();+ assert_eq!(agent.id(), "ses_test");+ assert_eq!(+ agent.config().unwrap().model.as_deref(),+ Some("provider/model")+ );+ assert!(matches!(agent.state(), Err(BoxliteError::Unsupported(_))));+ assert!(+ agent+ .capabilities()+ .unwrap()+ .operations+ .contains(&"agent.send".to_owned())+ );+ assert!(+ server+ .await+ .unwrap()+ .starts_with("GET /v1/boxes/remote-box/agents/ses_test ")+ );+}+#[tokio::test]+async fn remote_agent_create_send_and_get_turn() {+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let server = tokio::spawn(async move {+ let resource = r#"{"id":"ses_test","agent":"opencode","state":null,"config":{"tools":[],"mcp":[]},"capabilities":{"operations":["agent.send"],"input_kinds":["text"],"max_queued_turns":null,"max_pending_steering":null,"idempotency_retention_seconds":null}}"#;+ let turn = r#"{"id":"msg_test","agent_id":"ses_test","status":"queued","cursor":null,"result":null,"requests":[],"steering":[]}"#;+ for (expected, response) in [+ ("POST /v1/boxes/remote-box/agents ", resource),+ ("POST /v1/boxes/remote-box/agents/ses_test/turns ", turn),+ (+ "GET /v1/boxes/remote-box/agents/ses_test/turns/msg_test ",+ turn,+ ),+ ] {+ let (mut socket, _) = listener.accept().await.unwrap();+ let head = read_request_head(&mut socket).await;+ assert!(String::from_utf8_lossy(&head).starts_with(expected));+ let reply = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response}",+ response.len()+ );+ socket.write_all(reply.as_bytes()).await.unwrap();+ }+ });+ let rest_box = Arc::new(rest_box_for(port, "remote-box"));+ let agents = crate::Agents::new(rest_box.clone(), rest_box);+ let agent = agents+ .create("opencode", crate::agents::AgentCreateOptions::default())+ .await+ .unwrap();+ let turn = agent+ .send("hello", crate::agents::AgentSendOptions::default())+ .await+ .unwrap();+ assert_eq!(turn.state().unwrap().id, "msg_test");+ assert_eq!(+ agent+ .get_turn("msg_test")+ .await+ .unwrap()+ .state()+ .unwrap()+ .agent_id,+ "ses_test"+ );+ server.await.unwrap();+}+#[tokio::test]+async fn remote_agent_send_preserves_optional_request_values() {+ use crate::agents::{AgentSendMode, AgentSendOptions};+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let server = tokio::spawn(async move {+ let resource = r#"{"id":"ses_test","agent":"opencode","state":null,"config":{"tools":[],"mcp":[]},"capabilities":{"operations":["agent.send"],"input_kinds":["text"],"max_queued_turns":null,"max_pending_steering":null,"idempotency_retention_seconds":null}}"#;+ let turn = r#"{"id":"msg_test","agent_id":"ses_test","status":"queued","cursor":null,"result":null,"requests":[],"steering":[]}"#;+ let mut requests = Vec::new();+ for response in [resource, turn, turn, turn] {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut header = Vec::new();+ while !header.ends_with(b"\r\n\r\n") {+ header.push(socket.read_u8().await.unwrap());+ }+ let header = String::from_utf8(header).unwrap();+ let length: usize = header+ .lines()+ .find_map(|line| {+ line.to_ascii_lowercase()+ .strip_prefix("content-length:")+ .map(|value| value.trim().parse().unwrap())+ })+ .unwrap();+ let mut body = vec![0; length];+ socket.read_exact(&mut body).await.unwrap();+ requests.push((+ header,+ serde_json::from_slice::<serde_json::Value>(&body).unwrap(),+ ));+ socket.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response}", response.len()).as_bytes()).await.unwrap();+ }+ requests+ });+ let rest_box = Arc::new(rest_box_for(port, "remote-box"));+ let agent = crate::Agents::new(rest_box.clone(), rest_box)+ .create("opencode", Default::default())+ .await+ .unwrap();+ agent+ .send("hello", AgentSendOptions::default())+ .await+ .unwrap();+ agent+ .send(+ "hello",+ AgentSendOptions {+ mode: AgentSendMode::Queue,+ data: Some(serde_json::Value::Null),+ ..Default::default()+ },+ )+ .await+ .unwrap();+ agent+ .send(+ "hello",+ AgentSendOptions {+ mode: AgentSendMode::Reject,+ data: Some(serde_json::json!(false)),+ idempotency_key: Some("retry-1".into()),+ },+ )+ .await+ .unwrap();+ let requests = server.await.unwrap();+ for (header, _) in &requests[1..] {+ assert!(header.starts_with("POST /v1/boxes/remote-box/agents/ses_test/turns HTTP/1.1\r\n"));+ }+ assert_eq!(requests[1].1, serde_json::json!({"text":"hello"}));+ assert_eq!(+ requests[2].1,+ serde_json::json!({"text":"hello", "options":{"data":null}})+ );+ assert_eq!(+ requests[3].1,+ serde_json::json!({"text":"hello", "options":{"mode":"reject","data":false}})+ );+ assert!(+ requests[3]+ .0+ .to_ascii_lowercase()+ .contains("idempotency-key: retry-1\r\n")+ );+}++const RESOURCE: &str = r#"{"id":"ses_test","agent":"opencode","config":{"tools":[],"mcp":[]},"capabilities":{"operations":["agent.respond"],"input_kinds":["text"],"idempotency_retention_seconds":0.5}}"#;+const TURN: &str =+ r#"{"id":"msg_test","agent_id":"ses_test","status":"queued","requests":[],"steering":[]}"#;++async fn agent_exchange(+ listener: &TcpListener,+ expected: &str,+ expected_body: Option<serde_json::Value>,+ content_type: &str,+ status: &str,+ body: &str,+) -> String {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut header = Vec::new();+ while !header.ends_with(b"\r\n\r\n") {+ header.push(socket.read_u8().await.unwrap());+ }+ let header = String::from_utf8(header).unwrap();+ assert_eq!(+ header.lines().next().unwrap(),+ format!("{expected} HTTP/1.1")+ );+ if let Some(expected_body) = expected_body {+ let length = header+ .lines()+ .find_map(|line| {+ let (key, value) = line.split_once(':')?;+ key.eq_ignore_ascii_case("content-length")+ .then(|| value.trim().parse::<usize>().unwrap())+ })+ .unwrap();+ let mut bytes = vec![0; length];+ socket.read_exact(&mut bytes).await.unwrap();+ assert_eq!(+ serde_json::from_slice::<serde_json::Value>(&bytes).unwrap(),+ expected_body+ );+ }+ let reply = format!(+ "HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ socket.write_all(reply.as_bytes()).await.unwrap();+ header+}++#[tokio::test]+async fn remote_controls_forward_typed_responses_and_confirm_shutdown() {+ use crate::agents::{AgentResponse, AgentSteeringStatus};+ use serde_json::json;+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();+ let sandbox = Arc::new(rest_box_for(listener.local_addr().unwrap().port(), "box"));+ let server = tokio::spawn(async move {+ let base = "/v1/boxes/box/agents/ses_test";+ agent_exchange(+ &listener,+ &format!("GET {base}"),+ None,+ "application/json",+ "200 OK",+ RESOURCE,+ )+ .await;+ for (path, body, reply) in [+ (+ "requests/question/respond",+ json!({"response":{"type":"answer","text":"yes","data":42}}),+ TURN,+ ),+ (+ "requests/permission/respond",+ json!({"response":{"type":"permission","approved":false}}),+ TURN,+ ),+ (+ "turns/msg_test/steer",+ json!({"text":"stop editing"}),+ r#"{"id":"receipt","turn_id":"msg_test","status":"accepted"}"#,+ ),+ ("turns/msg_test/interrupt", json!({}), ""),+ ("close", json!({}), ""),+ ] {+ let status = if reply.is_empty() {+ "204 No Content"+ } else {+ "200 OK"+ };+ agent_exchange(+ &listener,+ &format!("POST {base}/{path}"),+ Some(body),+ "application/json",+ status,+ reply,+ )+ .await;+ }+ });+ let agent = crate::Agents::new(sandbox.clone(), sandbox)+ .get("ses_test")+ .await+ .unwrap();+ let answer = AgentResponse::Answer {+ text: "yes".into(),+ data: Some(json!(42)),+ };+ let turn = agent+ .respond("question", answer, Default::default())+ .await+ .unwrap();+ assert_eq!(turn.state().unwrap().id, "msg_test");+ let turn = agent+ .respond(+ "permission",+ AgentResponse::Permission { approved: false },+ Default::default(),+ )+ .await+ .unwrap();+ let receipt = turn+ .steer("stop editing", Default::default())+ .await+ .unwrap();+ assert_eq!(receipt.status, AgentSteeringStatus::Accepted);+ turn.interrupt(Default::default()).await.unwrap();+ agent.close(Default::default()).await.unwrap();+ server.await.unwrap();+}++#[tokio::test]+async fn remote_turn_events_reject_wrong_parent_and_report_disconnect() {+ use futures::StreamExt;+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();+ let sandbox = Arc::new(rest_box_for(listener.local_addr().unwrap().port(), "box"));+ let server = tokio::spawn(async move {+ let base = "/v1/boxes/box/agents/ses_test";+ agent_exchange(+ &listener,+ &format!("GET {base}"),+ None,+ "application/json",+ "200 OK",+ RESOURCE,+ )+ .await;+ agent_exchange(+ &listener,+ &format!("GET {base}/turns/msg_test"),+ None,+ "application/json",+ "200 OK",+ TURN,+ )+ .await;+ agent_exchange(&listener, &format!("GET {base}/events?turn_id=msg_test"), None, "text/event-stream", "200 OK",+ "data: {\"agent_id\":\"ses_test\",\"turn_id\":\"other\",\"kind\":\"message\",\"data\":{}}\n\n").await;+ agent_exchange(+ &listener,+ &format!("GET {base}/events"),+ None,+ "text/event-stream",+ "200 OK",+ ": heartbeat\n\n",+ )+ .await;+ });+ let agent = crate::Agents::new(sandbox.clone(), sandbox)+ .get("ses_test")+ .await+ .unwrap();+ let turn = agent.get_turn("msg_test").await.unwrap();+ let mut stream = turn.events(Default::default()).await.unwrap();+ assert!(+ matches!(stream.next().await, Some(Err(BoxliteError::Internal(message))) if message.contains("wrong parent"))+ );+ assert!(stream.next().await.is_none());+ let mut stream = agent.events(Default::default()).await.unwrap();+ assert!(+ matches!(stream.next().await, Some(Err(BoxliteError::Network(message))) if message.contains("ended"))+ );+ assert!(stream.next().await.is_none());+ server.await.unwrap();+}++#[tokio::test]+async fn remote_handles_reject_responses_for_other_resources() {+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();+ let sandbox = Arc::new(rest_box_for(listener.local_addr().unwrap().port(), "box"));+ let server = tokio::spawn(async move {+ for (path, body) in [+ ("other", RESOURCE.to_owned()),+ ("ses_test", RESOURCE.to_owned()),+ ("ses_test/turns/other", TURN.to_owned()),+ ("ses_test/turns/msg_test", TURN.replace("ses_test", "other")),+ ] {+ agent_exchange(+ &listener,+ &format!("GET /v1/boxes/box/agents/{path}"),+ None,+ "application/json",+ "200 OK",+ &body,+ )+ .await;+ }+ });+ let agents = crate::Agents::new(sandbox.clone(), sandbox);+ assert!(matches!(+ agents.get("..").await,+ Err(BoxliteError::InvalidArgument(_))+ ));+ assert!(matches!(+ agents.get("other").await,+ Err(BoxliteError::Internal(_))+ ));+ let agent = agents.get("ses_test").await.unwrap();+ for id in ["other", "msg_test"] {+ assert!(matches!(+ agent.get_turn(id).await,+ Err(BoxliteError::Internal(_))+ ));+ }+ server.await.unwrap();+}++#[tokio::test]+async fn wait_requires_matching_terminal_status() {+ for (status, result_status) in [+ ("running", "completed"),+ ("failed", "completed"),+ ("unknown", "unknown"),+ ] {+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();+ let sandbox = Arc::new(rest_box_for(listener.local_addr().unwrap().port(), "box"));+ let server = tokio::spawn(async move {+ agent_exchange(+ &listener,+ "GET /v1/boxes/box/agents/ses_test",+ None,+ "application/json",+ "200 OK",+ RESOURCE,+ )+ .await;+ let path = "GET /v1/boxes/box/agents/ses_test/turns/msg_test";+ agent_exchange(&listener, path, None, "application/json", "200 OK", TURN).await;+ let mut snapshot: serde_json::Value = serde_json::from_str(TURN).unwrap();+ snapshot["status"] = serde_json::json!(status);+ snapshot["result"] =+ serde_json::json!({"turn_id":"msg_test","status":result_status,"artifacts":[]});+ agent_exchange(+ &listener,+ path,+ None,+ "application/json",+ "200 OK",+ &snapshot.to_string(),+ )+ .await;+ });+ let agent = crate::Agents::new(sandbox.clone(), sandbox)+ .get("ses_test")+ .await+ .unwrap();+ let turn = agent.get_turn("msg_test").await.unwrap();+ assert!(+ matches!(+ turn.wait(Default::default()).await,+ Err(BoxliteError::InvalidState(_))+ ),+ "accepted result for {status} snapshot"+ );+ server.await.unwrap();+ }+}++#[tokio::test]+async fn remote_create_forwards_config_cwd_and_retry_key() {+ use crate::agents::{AgentConfig, AgentCreateOptions};+ use serde_json::json;+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();+ let sandbox = Arc::new(rest_box_for(listener.local_addr().unwrap().port(), "box"));+ let server = tokio::spawn(async move {+ let header = agent_exchange(+ &listener,+ "POST /v1/boxes/box/agents",+ Some(json!({+ "agent":"opencode","options":{"cwd":"/workspace","config":{+ "permissions":{"edit":"deny"},"limits":{"max_steps":3},"tools":[],"mcp":[]+ }}+ })),+ "application/json",+ "201 Created",+ RESOURCE,+ )+ .await;+ let keys: Vec<_> = header+ .lines()+ .filter_map(|line| line.split_once(':'))+ .filter(|(name, _)| name.eq_ignore_ascii_case("Idempotency-Key"))+ .map(|(_, value)| value.trim())+ .collect();+ assert_eq!(keys, ["create-42"]);+ });+ let options = AgentCreateOptions {+ cwd: Some("/workspace".into()),+ config: AgentConfig {+ permissions: Some(json!({"edit":"deny"})),+ limits: Some(json!({"max_steps":3})),+ ..Default::default()+ },+ idempotency_key: Some("create-42".into()),+ };+ let agent = crate::Agents::new(sandbox.clone(), sandbox)+ .create("opencode", options)+ .await+ .unwrap();+ assert_eq!(agent.id(), "ses_test");+ server.await.unwrap();+}diff --git a/src/cli/src/commands/serve/mod.rs b/src/cli/src/commands/serve/mod.rsindex b6667c7b3..03abc8921 100644--- a/src/cli/src/commands/serve/mod.rs+++ b/src/cli/src/commands/serve/mod.rs@@ -2142,6 +2142,7 @@ pub async fn execute(args: ServeArgs, global: &GlobalFlags) -> anyhow::Result<()#[cfg(test)]mod tests {+ mod agents;use super::*;use boxlite::runtime::options::NetworkSpec;use std::time::Duration;diff --git a/src/cli/src/commands/serve/tests/agents.rs b/src/cli/src/commands/serve/tests/agents.rsnew file mode 100644index 000000000..42d3a5850--- /dev/null+++ b/src/cli/src/commands/serve/tests/agents.rs@@ -0,0 +1,135 @@+//! REST client contracts exercised against a loopback backend.++use super::STUB_BOX_ID;+use axum::{+ Json, Router,+ http::StatusCode,+ routing::{get, post},+};+use boxlite::{BoxliteRestOptions, BoxliteRuntime};+use serde_json::{Value, json};+use std::sync::Arc;++fn resource() -> Value {+ json!({"id":"ses_test", "agent":"opencode", "state":null,+ "config":{"tools":[],"mcp":[]},+ "capabilities":{"operations":["agent.send","agent.events"],"input_kinds":["text"],+ "max_queued_turns":null,"max_pending_steering":null,"idempotency_retention_seconds":null}})+}+fn turn() -> Value {+ json!({"id":"msg_test","agent_id":"ses_test","status":"queued", "cursor":null,+ "result":null,"requests":[],"steering":[]})+}+#[tokio::test]+async fn remote_wait_reports_terminal_turn_without_a_recorded_result() {+ let upstream = Router::new()+ .route(+ "/v1/boxes/{id}",+ get(|| async {+ Json(json!({"box_id":STUB_BOX_ID,"name":null,"status":"running",+ "created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z",+ "pid":null,"image":"alpine:latest","cpus":1,"memory_mib":512}))+ }),+ )+ .route(+ "/v1/boxes/{id}/agents/{agent}",+ get(|| async { Json(resource()) }),+ )+ .route(+ "/v1/boxes/{id}/agents/{agent}/turns/{turn}",+ get(|| async {+ tokio::time::sleep(std::time::Duration::from_millis(150)).await;+ let mut state = turn();+ state["status"] = json!("completed");+ Json(state)+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let task = tokio::spawn(async move { axum::serve(listener, upstream).await.unwrap() });+ let runtime = BoxliteRuntime::rest(BoxliteRestOptions::new(format!("http://{addr}"))).unwrap();+ let sandbox = runtime.get(STUB_BOX_ID).await.unwrap().unwrap();+ let agent = sandbox.agents().get("ses_test").await.unwrap();+ let turn = agent.get_turn("msg_test").await.unwrap();+ let error = turn+ .wait(boxlite::agents::AgentWaitOptions {+ timeout: Some(std::time::Duration::from_secs(5)),+ })+ .await+ .unwrap_err();+ assert!(+ error+ .to_string()+ .contains("ended without a recorded outcome"),+ "{error}"+ );+ task.abort();+}+#[tokio::test]+async fn rest_review_config_accepts_additive_fields_and_validates_known_fields() {+ for invalid in [false, true] {+ let mut response = resource();+ response["config"]["provider_metadata"] = json!({"version": 2});+ response["config"]["model"] = if invalid {+ json!(123)+ } else {+ json!("provider/model")+ };+ assert!(boxlite::agents::records::parse_config(response["config"].clone()).is_err());+ let response = Arc::new(response);+ let upstream = Router::new()+ .route(+ "/v1/boxes/{id}",+ get(|| async {+ Json(json!({"box_id":STUB_BOX_ID,"name":null,"status":"running",+ "created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z",+ "pid":null,"image":"alpine:latest","cpus":1,"memory_mib":512}))+ }),+ )+ .route(+ "/v1/boxes/{id}/agents",+ post({+ let response = Arc::clone(&response);+ move || {+ let response = Arc::clone(&response);+ async move { (StatusCode::CREATED, Json((*response).clone())) }+ }+ }),+ )+ .route(+ "/v1/boxes/{id}/agents/{agent}",+ get({+ let response = Arc::clone(&response);+ move || {+ let response = Arc::clone(&response);+ async move { Json((*response).clone()) }+ }+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, upstream).await.unwrap() });+ let runtime =+ BoxliteRuntime::rest(BoxliteRestOptions::new(format!("http://{addr}"))).unwrap();+ let sandbox = runtime.get(STUB_BOX_ID).await.unwrap().unwrap();+ for result in [+ sandbox.agents().get("ses_test").await,+ sandbox+ .agents()+ .create("opencode", Default::default())+ .await,+ ] {+ if invalid {+ assert!(result.is_err(), "malformed response config was accepted");+ } else {+ let agent = result.expect("additive response config fields must be accepted");+ assert_eq!(agent.id(), "ses_test");+ assert_eq!(+ agent.config().unwrap().model.as_deref(),+ Some("provider/model")+ );+ }+ }+ server.abort();+ }+}