Skip to content

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

feat(go): connect agent calls and getters to the C SDK (#2936)

Jiaqiang Wongefdf6480b3bd
diff --git a/docs/reference/agents.md b/docs/reference/agents.md
index fbd892c83..4fd34f33b 100644
--- a/docs/reference/agents.md
+++ b/docs/reference/agents.md
@@ -32,17 +32,16 @@ and `SimpleBox`. Each SDK retains its error conventions.
### Failure contract
-Rust, Python, Node.js, the CLI and C calls on a local runtime run the operations listed in
+Rust, Python, Node.js, the CLI, C and Go support the operations listed in
[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.
+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 | `*Error` with `Code: ErrUnsupported` and no result |
+| 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 |
@@ -56,13 +55,13 @@ on failure.
### OpenCode on a local runtime
-Rust, Python, Node.js, the CLI and C calls on a local runtime forward agents to OpenCode 2.2 inside the Box
+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](https://github.com/boxlite-ai/boxlite/issues/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. Go
-returns `Unsupported`. `agent.id()` returns the `ses_…`
+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.
```text
@@ -212,6 +211,14 @@ 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
@@ -230,6 +237,34 @@ 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 `Unsupported`; subscriptions are a separate delivery step.
+
+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.
+
### Example: handle operation errors
Python (the Box may already exist; this call starts no work):
diff --git a/make/coverage.mk b/make/coverage.mk
index 772cd8649..1b3c9f3be 100644
--- a/make/coverage.mk
+++ b/make/coverage.mk
@@ -89,10 +89,11 @@ coverage\:vmm\:boot: _ensure-kvm _ensure-vmm-kernel $(VMM_BALLOON_INIT) $(VMM_DI
@cargo llvm-cov report $(COVERAGE_REPORT_ARGS) --lcov --output-path target/coverage/lcov.info
# Go's reports include every package, including packages with no tests.
-coverage\:go: dev\:go
+coverage\:go:
+ @$(MAKE) dev:go GO_CARGO_FEATURES="--features test-support"
@mkdir -p target/coverage
@rc=0; \
- (cd sdks/go && go test -tags boxlite_dev -covermode=atomic -coverpkg=./... \
+ (cd sdks/go && go test -a -count=1 -tags boxlite_dev,boxlite_agent_test -covermode=atomic -coverpkg=./... \
-coverprofile="$(PROJECT_ROOT)/target/coverage/go-sdk.out" $(GOTEST_FILTER) ./...) || rc=$$?; \
(cd src/deps/libgvproxy-sys/gvproxy-bridge && go test -covermode=atomic -coverpkg=./... \
-coverprofile="$(PROJECT_ROOT)/target/coverage/gvproxy.out" $(GOTEST_FILTER) ./...) || rc=$$?; \
diff --git a/make/dev.mk b/make/dev.mk
index 141971b1f..00d8fc314 100644
--- a/make/dev.mk
+++ b/make/dev.mk
@@ -52,7 +52,7 @@ dev\:node: $(if $(SETUP_DONE),,runtime\:debug)
# Build Go SDK locally (debug mode, static linking)
dev\:go: $(if $(SETUP_DONE),,runtime\:debug)
@echo "🔨 Building Go SDK (debug)..."
- @cargo build -p boxlite-c
+ @cargo build -p boxlite-c $(GO_CARGO_FEATURES)
@bash $(SCRIPT_DIR)/build/fix-go-symbols.sh target/debug/libboxlite.a
@cd sdks/go && go build -tags boxlite_dev ./...
@echo "✅ Go SDK built. You can now run: cd sdks/go && go test -tags boxlite_dev -v ./..."
diff --git a/make/test.mk b/make/test.mk
index 313ed5c41..dc2c6e7ba 100644
--- a/make/test.mk
+++ b/make/test.mk
@@ -659,7 +659,8 @@ test\:all\:python:
# Node.js SDK unit tests.
test\:unit\:node: _ensure-node-deps
@echo "🧪 Running Node.js SDK unit tests..."
- @cd sdks/node && npm test -- $(VITEST_FILTER)
+ @cargo build -p boxlite-node --example agent_record_fixture
+ @cd sdks/node && BOXLITE_AGENT_FIXTURE_DIR="$(abspath $(or $(CARGO_TARGET_DIR),target))/debug/examples" npm test -- $(VITEST_FILTER)
@echo "🧪 Running Node.js binding (Rust) unit tests..."
@cargo test -p boxlite-node --lib $(CARGOTEST_FILTER)
@@ -698,8 +699,8 @@ test\:all\:c:
# Go SDK unit tests.
test\:unit\:go:
@echo "🧪 Running Go SDK unit tests..."
- @$(MAKE) dev:go
- @cd sdks/go && go test -tags boxlite_dev $(GOTEST_RACE) -v $(GOTEST_FILTER) ./...
+ @$(MAKE) dev:go GO_CARGO_FEATURES="--features test-support"
+ @cd sdks/go && go test -a -count=1 -tags boxlite_dev,boxlite_agent_test $(GOTEST_RACE) -v $(GOTEST_FILTER) ./...
# Native Go archive import/export tests require a supported host.
# Keep them in the VM-capable integration workflow, outside hosted unit coverage.
diff --git a/openapi/tests/test_agent_spec.py b/openapi/tests/test_agent_spec.py
index 971ed98c8..8f83e406a 100644
--- a/openapi/tests/test_agent_spec.py
+++ b/openapi/tests/test_agent_spec.py
@@ -134,29 +134,30 @@ class AgentSpecTest(unittest.TestCase):
validate("AgentEvent", json.loads(data))
def test_record_fields_and_fractional_retention(self):
- records = (ROOT / "src/boxlite/src/agents/records.rs").read_text()
- functions = dict(re.findall(
- r"pub fn (\w+)\([^\n]*\).*?\n(.*?)(?=\npub fn |\n///|\nfn |\Z)",
- records, re.S,
- ))
- for schema, function in {
- "AgentState": "agent_state", "AgentTurnState": "turn_state",
- "AgentResult": "result", "AgentSteeringReceipt": "receipt",
- "AgentCapabilities": "capabilities", "AgentEvent": "event",
+ # go_json_fixture_matches_core_records checks these records against Rust output.
+ records = json.loads((ROOT / "sdks/go/testdata/agents.json").read_text())
+ for schema, sample in {
+ "AgentState": "state", "AgentTurnState": "turn", "AgentResult": "result",
+ "AgentSteeringReceipt": "receipt", "AgentCapabilities": "capabilities",
+ "AgentEvent": "event", "AgentConfig": "config",
}.items():
- fields = set(re.findall(r'"(\w+)"\s*:', functions[function]))
- self.assertEqual(set(SCHEMAS[schema]["properties"]), fields, schema)
- config_fields = set(re.findall(r'"(\w+)"\s*:', functions["config"]))
- config_fields.update(re.findall(r'\(\s*"(\w+)"\s*,', functions["config"]))
- self.assertEqual(set(SCHEMAS["AgentConfig"]["properties"]), config_fields)
- request = functions["requests"]
- outer = re.search(r'json!\(\{ "id":.*?\}\)', request).group()
- self.assertEqual(set(SCHEMAS["AgentRequest"]["properties"]),
- set(re.findall(r'"(\w+)"\s*:', outer)))
- for variant in SCHEMAS["AgentRequest"]["properties"]["kind"]["oneOf"]:
- kind = variant["properties"]["type"]["const"]
- record = re.search(r'json!\(\{ "type": "' + kind + r'".*?\}\)', request).group()
- self.assertEqual(set(variant["properties"]), set(re.findall(r'"(\w+)"\s*:', record)))
+ with self.subTest(schema=schema):
+ record = records[sample]
+ self.assertEqual(set(SCHEMAS[schema]["properties"]), set(record))
+ validate(schema, record)
+
+ request_schema = SCHEMAS["AgentRequest"]
+ variants = {
+ variant["properties"]["type"]["const"]: variant["properties"]
+ for variant in request_schema["properties"]["kind"]["oneOf"]
+ }
+ self.assertEqual(set(variants), {r["kind"]["type"] for r in records["requests"]})
+ for request in records["requests"]:
+ kind = request["kind"]
+ with self.subTest(kind=kind["type"]):
+ self.assertEqual(set(request_schema["properties"]), set(request))
+ self.assertEqual(set(variants[kind["type"]]), set(kind))
+ validate("AgentRequest", request)
validate("AgentCapabilities", {"operations": [], "input_kinds": [], "max_queued_turns": 0,
"max_pending_steering": None, "idempotency_retention_seconds": 0.5})
self.assertFalse(jsonschema.Draft202012Validator(SCHEMAS["AgentTurnStatus"]).is_valid("bogus"))
diff --git a/sdks/c/Cargo.toml b/sdks/c/Cargo.toml
index 346465288..d0c25c9ec 100644
--- a/sdks/c/Cargo.toml
+++ b/sdks/c/Cargo.toml
@@ -13,6 +13,7 @@ crate-type = ["cdylib", "staticlib"]
[features]
default = []
+test-support = ["boxlite/test-support"]
[dependencies]
boxlite = { workspace = true, features = ["rest"] }
diff --git a/sdks/c/cbindgen.toml b/sdks/c/cbindgen.toml
index 8d7b3c466..82c7d3401 100644
--- a/sdks/c/cbindgen.toml
+++ b/sdks/c/cbindgen.toml
@@ -22,7 +22,7 @@ parse_deps = false
# the names must remain exported.
[export]
include = ["BoxliteDomainTargetType", "CAgentSendMode"]
-exclude = ["sockaddr_storage"]
+exclude = ["sockaddr_storage", "boxlite_test_agents_new", "boxlite_test_agents_wait_pending", "boxlite_test_agents_wait_queue", "boxlite_test_agents_free_counts"]
[export.rename]
sockaddr_storage = "struct sockaddr_storage"
diff --git a/sdks/c/include/boxlite.h b/sdks/c/include/boxlite.h
index 1c58ec145..b00c1aa77 100644
--- a/sdks/c/include/boxlite.h
+++ b/sdks/c/include/boxlite.h
@@ -123,6 +123,9 @@ typedef struct CAgentEvents CAgentEvents;
// Agent turn handle.
typedef struct CAgentTurn CAgentTurn;
+// One observation of a turn, owned by the caller.
+typedef struct CAgentWait CAgentWait;
+
// Box-owned namespace; release with boxlite_agents_free.
typedef struct CAgents CAgents;
@@ -997,6 +1000,21 @@ enum BoxliteErrorCode boxlite_agent_turn_wait(struct CAgentTurn *turn_arg,
void *user_data_arg,
CBoxliteError *out_error);
+// Start a wait and return its independently releasable handle. On synchronous
+// refusal, out_wait is cleared and the callback is never queued. On acceptance,
+// keep user_data valid through the single completion dispatched by runtime_drain.
+enum BoxliteErrorCode boxlite_agent_turn_wait_cancellable(struct CAgentTurn *turn_arg,
+ const struct CAgentWaitOptions *options_arg,
+ CAgentJsonCb callback_arg,
+ void *user_data_arg,
+ struct CAgentWait **out_wait,
+ CBoxliteError *out_error);
+
+// Release once, including after normal completion. NULL is accepted.
+// Release never blocks. If cancellation wins, the callback reports Stopped.
+// The turn and other waiters continue.
+void boxlite_agent_wait_free(struct CAgentWait *wait);
+
// Steer this turn without submitting another turn.
// out_error may be null or writable.
enum BoxliteErrorCode boxlite_agent_turn_steer(struct CAgentTurn *turn_arg,
diff --git a/sdks/c/src/agents.rs b/sdks/c/src/agents.rs
index 1b7eac867..8b045f0da 100644
--- a/sdks/c/src/agents.rs
+++ b/sdks/c/src/agents.rs
@@ -15,6 +15,10 @@ use crate::event_queue::{EventQueue, RuntimeEvent, push_event};
use crate::{CBoxHandle, CBoxliteError};
use tokio::runtime::Runtime as TokioRuntime;
+#[cfg(feature = "test-support")]
+#[path = "agents/tests/go_support.rs"]
+mod go_test_support;
+
/// Box-owned namespace; release with boxlite_agents_free.
pub struct CAgents {
core: boxlite::Agents,
@@ -194,7 +198,7 @@ unsafe fn deliver<T>(
}
unsafe fn deliver_json(
- result: Result<serde_json::Value, BoxliteError>,
+ result: Result<impl std::fmt::Display, BoxliteError>,
callback: unsafe extern "C" fn(*const c_char, *const CBoxliteError, *mut c_void),
data: usize,
) {
@@ -567,11 +571,7 @@ pub unsafe extern "C" fn boxlite_agent_respond(
required_string(response_json_arg, "response_json"),
out_error
);
- let value = checked!(
- serde_json::from_str(&json).map_err(|e| BoxliteError::InvalidArgument(e.to_string())),
- out_error
- );
- let response = checked!(boxlite::agents::records::parse_response(value), out_error);
+ let response = checked!(boxlite::agents::records::parse_response(&json), out_error);
let options = checked!(control_options(options_arg), out_error);
let handle = &*agent_arg;
let core = handle.core.clone();
@@ -613,6 +613,77 @@ pub unsafe extern "C" fn boxlite_agent_turn_wait(
callback_arg: CAgentJsonCb,
user_data_arg: *mut c_void,
out_error: *mut CBoxliteError,
+) -> BoxliteErrorCode {
+ unsafe {
+ submit_turn_wait(
+ turn_arg,
+ options_arg,
+ callback_arg,
+ user_data_arg,
+ out_error,
+ None,
+ )
+ }
+}
+
+/// One observation of a turn, owned by the caller.
+pub struct CAgentWait {
+ _cancel_on_drop: tokio::sync::oneshot::Sender<()>,
+}
+
+/// Start a wait and return its independently releasable handle. On synchronous
+/// refusal, out_wait is cleared and the callback is never queued. On acceptance,
+/// keep user_data valid through the single completion dispatched by runtime_drain.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn boxlite_agent_turn_wait_cancellable(
+ turn_arg: *mut CAgentTurn,
+ options_arg: *const CAgentWaitOptions,
+ callback_arg: CAgentJsonCb,
+ user_data_arg: *mut c_void,
+ out_wait: *mut *mut CAgentWait,
+ out_error: *mut CBoxliteError,
+) -> BoxliteErrorCode {
+ unsafe {
+ if out_wait.is_null() {
+ write_error(out_error, null_pointer_error("out_wait"));
+ return BoxliteErrorCode::InvalidArgument;
+ }
+ *out_wait = ptr::null_mut();
+ let (cancel, receiver) = tokio::sync::oneshot::channel();
+ let code = submit_turn_wait(
+ turn_arg,
+ options_arg,
+ callback_arg,
+ user_data_arg,
+ out_error,
+ Some(receiver),
+ );
+ if code == BoxliteErrorCode::Ok {
+ *out_wait = Box::into_raw(Box::new(CAgentWait {
+ _cancel_on_drop: cancel,
+ }));
+ }
+ code
+ }
+}
+
+/// Release once, including after normal completion. NULL is accepted.
+/// Release never blocks. If cancellation wins, the callback reports Stopped.
+/// The turn and other waiters continue.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn boxlite_agent_wait_free(wait: *mut CAgentWait) {
+ if !wait.is_null() {
+ unsafe { drop(Box::from_raw(wait)) };
+ }
+}
+
+unsafe fn submit_turn_wait(
+ turn_arg: *mut CAgentTurn,
+ options_arg: *const CAgentWaitOptions,
+ callback_arg: CAgentJsonCb,
+ user_data_arg: *mut c_void,
+ out_error: *mut CBoxliteError,
+ cancellation: Option<tokio::sync::oneshot::Receiver<()>>,
) -> BoxliteErrorCode {
unsafe {
if turn_arg.is_null() || callback_arg.is_none() {
@@ -643,9 +714,16 @@ pub unsafe extern "C" fn boxlite_agent_turn_wait(
handle.runtime.clone(),
handle.queue.clone(),
async move {
- core.wait(options)
- .await
- .map(|v| boxlite::agents::records::result(&v))
+ let wait = core.wait(options);
+ let result = match cancellation {
+ Some(receiver) => tokio::select! {
+ biased;
+ _ = receiver => Err(BoxliteError::Stopped("turn wait canceled".into())),
+ result = wait => result,
+ },
+ None => wait.await,
+ };
+ result.map(|v| boxlite::agents::records::result(&v))
},
move |result| deliver_json(result, callback, data),
);
@@ -979,7 +1057,7 @@ unsafe fn agent_getter(
unsafe fn write_json(
out: *mut *mut c_char,
out_error: *mut CBoxliteError,
- value: Result<serde_json::Value, BoxliteError>,
+ value: Result<impl std::fmt::Display, BoxliteError>,
) -> BoxliteErrorCode {
match value {
Ok(value) => {
@@ -1012,6 +1090,8 @@ pub unsafe extern "C" fn boxlite_agents_free(handle: *mut CAgents) {
#[unsafe(no_mangle)]
pub unsafe extern "C" fn boxlite_agent_free(handle: *mut CAgent) {
if !handle.is_null() {
+ #[cfg(feature = "test-support")]
+ go_test_support::record_free(false);
unsafe {
drop(Box::from_raw(handle));
}
@@ -1023,6 +1103,8 @@ pub unsafe extern "C" fn boxlite_agent_free(handle: *mut CAgent) {
#[unsafe(no_mangle)]
pub unsafe extern "C" fn boxlite_agent_turn_free(handle: *mut CAgentTurn) {
if !handle.is_null() {
+ #[cfg(feature = "test-support")]
+ go_test_support::record_free(true);
unsafe {
drop(Box::from_raw(handle));
}
diff --git a/sdks/c/src/agents/tests/go_support.rs b/sdks/c/src/agents/tests/go_support.rs
new file mode 100644
index 000000000..748db0a9a
--- /dev/null
+++ b/sdks/c/src/agents/tests/go_support.rs
@@ -0,0 +1,109 @@
+//! Test-only fixtures for Go's C/core boundary and real-VM acceptance tests.
+
+use super::*;
+use crate::runtime::{RuntimeHandle, RuntimeLiveness};
+use std::sync::atomic::AtomicUsize;
+use std::time::{Duration, Instant};
+
+static AGENTS_FREED: AtomicUsize = AtomicUsize::new(0);
+static TURNS_FREED: AtomicUsize = AtomicUsize::new(0);
+pub(super) fn record_free(turn: bool) {
+ let count = if turn { &TURNS_FREED } else { &AGENTS_FREED };
+ count.fetch_add(1, Ordering::SeqCst);
+}
+
+#[unsafe(no_mangle)]
+unsafe extern "C" fn boxlite_test_agents_new(
+ home: *const c_char,
+ out_runtime: *mut *mut RuntimeHandle,
+ out_agents: *mut *mut CAgents,
+ out_error: *mut CBoxliteError,
+) -> BoxliteErrorCode {
+ if home.is_null() || out_runtime.is_null() || out_agents.is_null() {
+ return BoxliteErrorCode::InvalidArgument;
+ }
+ unsafe {
+ *out_runtime = ptr::null_mut();
+ *out_agents = ptr::null_mut();
+ }
+ let build = || -> Result<_, BoxliteError> {
+ let home = unsafe { CStr::from_ptr(home) }
+ .to_str()
+ .map_err(|e| BoxliteError::InvalidArgument(e.to_string()))?;
+ let runtime = boxlite::BoxliteRuntime::new_for_test(boxlite::BoxliteOptions {
+ home_dir: home.into(),
+ ..Default::default()
+ })?;
+ let tokio_rt = Arc::new(
+ tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .map_err(|e| BoxliteError::Internal(e.to_string()))?,
+ );
+ let sandbox = tokio_rt.block_on(runtime.create(
+ boxlite::BoxOptions {
+ rootfs: boxlite::RootfsSpec::Image("alpine:latest".into()),
+ ..Default::default()
+ },
+ None,
+ ))?;
+ let queue = Arc::new(EventQueue::new());
+ let agents = CAgents {
+ core: sandbox.agents().with_test_backend(),
+ runtime: tokio_rt.clone(),
+ queue: queue.clone(),
+ };
+ let runtime = RuntimeHandle {
+ runtime,
+ tokio_rt,
+ queue,
+ liveness: Arc::new(RuntimeLiveness::new()),
+ };
+ Ok((runtime, agents))
+ };
+ match build() {
+ Ok((runtime, agents)) => {
+ unsafe {
+ *out_runtime = Box::into_raw(Box::new(runtime));
+ *out_agents = Box::into_raw(Box::new(agents));
+ }
+ BoxliteErrorCode::Ok
+ }
+ Err(e) => {
+ let code = error_to_code(&e);
+ unsafe { write_error(out_error, e) };
+ code
+ }
+ }
+}
+
+// Wait for a posted result without dispatching it, to control cancellation races.
+#[unsafe(no_mangle)]
+unsafe extern "C" fn boxlite_test_agents_wait_pending(runtime: *mut RuntimeHandle) -> bool {
+ unsafe { boxlite_test_agents_wait_queue(runtime, 1) }
+}
+
+#[unsafe(no_mangle)]
+unsafe extern "C" fn boxlite_test_agents_wait_queue(
+ runtime: *mut RuntimeHandle,
+ count: usize,
+) -> bool {
+ let queue = unsafe { &(*runtime).queue };
+ let deadline = Instant::now() + Duration::from_secs(5);
+ let mut events = queue.inner.lock().unwrap();
+ while events.len() < count {
+ let Some(remaining) = deadline.checked_duration_since(Instant::now()) else {
+ return false;
+ };
+ events = queue.cv.wait_timeout(events, remaining).unwrap().0;
+ }
+ true
+}
+
+#[unsafe(no_mangle)]
+unsafe extern "C" fn boxlite_test_agents_free_counts(agents: *mut usize, turns: *mut usize) {
+ unsafe {
+ *agents = AGENTS_FREED.load(Ordering::SeqCst);
+ *turns = TURNS_FREED.load(Ordering::SeqCst);
+ }
+}
diff --git a/sdks/c/src/agents/tests/mod.rs b/sdks/c/src/agents/tests/mod.rs
index b69191307..6f932e095 100644
--- a/sdks/c/src/agents/tests/mod.rs
+++ b/sdks/c/src/agents/tests/mod.rs
@@ -80,6 +80,80 @@ unsafe fn read_getter(
crate::boxlite_free_string(json);
parsed
}
+// A current-thread executor lets the test release before the first poll or
+// after the result has been queued, without racing a background worker.
+unsafe fn check_wait_release_order(turn: *mut CAgentTurn, runtime: *mut RuntimeHandle) {
+ let executor = Arc::new(
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap(),
+ );
+ let mut local = CAgentTurn {
+ core: (*turn).core.clone(),
+ queue: (*turn).queue.clone(),
+ runtime: executor.clone(),
+ };
+ for cancel_first in [true, false] {
+ let mut seen = Seen::default();
+ let data = &mut seen as *mut Seen as *mut c_void;
+ let mut handle = ptr::dangling_mut();
+ let cb: CAgentJsonCb = if cancel_first {
+ Some(error_json_cb)
+ } else {
+ Some(json_cb)
+ };
+ assert_eq!(
+ boxlite_agent_turn_wait_cancellable(
+ ptr::null_mut(),
+ ptr::null(),
+ cb,
+ data,
+ &mut handle,
+ ptr::null_mut()
+ ),
+ BoxliteErrorCode::InvalidArgument
+ );
+ assert!(handle.is_null());
+ assert_eq!(
+ boxlite_agent_turn_wait_cancellable(
+ &mut local,
+ ptr::null(),
+ cb,
+ data,
+ &mut handle,
+ ptr::null_mut()
+ ),
+ BoxliteErrorCode::Ok
+ );
+ assert!(!handle.is_null());
+ if cancel_first {
+ boxlite_agent_wait_free(handle);
+ }
+ executor.block_on(async {
+ tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ while local.queue.inner.lock().unwrap().is_empty() {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .unwrap();
+ });
+ if !cancel_first {
+ boxlite_agent_wait_free(handle);
+ }
+ assert!(!seen.done);
+ assert_eq!(crate::boxlite_runtime_drain(runtime, 0, ptr::null_mut()), 1);
+ assert!(seen.done);
+ if cancel_first {
+ assert_eq!(seen.error.unwrap().0, BoxliteErrorCode::Stopped);
+ } else {
+ assert_eq!(seen.json.unwrap()["text"], "hello");
+ }
+ assert_eq!(crate::boxlite_runtime_drain(runtime, 0, ptr::null_mut()), 0);
+ }
+}
+
#[test]
fn c_calls_and_getters_reach_core_through_drain() {
unsafe {
@@ -265,6 +339,7 @@ fn c_calls_and_getters_reach_core_through_drain() {
drain(runtime_ptr, &mut seen);
assert_eq!(seen.json.take().unwrap()["text"], "hello");
seen.done = false;
+ check_wait_release_order(turn, runtime_ptr);
let turn_id = CString::new("turn-1").unwrap();
assert_eq!(
boxlite_agent_get_turn(
diff --git a/sdks/c/src/agents/tests/opencode_vm.rs b/sdks/c/src/agents/tests/opencode_vm.rs
index 032d86fbe..f2f5f698c 100644
--- a/sdks/c/src/agents/tests/opencode_vm.rs
+++ b/sdks/c/src/agents/tests/opencode_vm.rs
@@ -125,7 +125,8 @@ fn c_opencode_vm_matches_rust() {
.iter()
.any(|op| op == "agent.send")
);
- let rust_result = boxlite::agents::records::result(&rust_result);
+ let rust_result: serde_json::Value =
+ serde_json::from_str(boxlite::agents::records::result(&rust_result).get()).unwrap();
for key in ["status", "outcome", "text", "data", "artifacts", "error"] {
assert_eq!(c_result[key], rust_result[key], "result field {key}");
}
diff --git a/sdks/go/README.md b/sdks/go/README.md
index acb7feb39..27299ef17 100644
--- a/sdks/go/README.md
+++ b/sdks/go/README.md
@@ -475,6 +475,22 @@ the box keeps running in the runtime.
## Development
+Agent calls and getters reach the C SDK and Rust core through the
+[shared JSON mapping](../../docs/reference/agents.md#go-json-mapping).
+`Box.Agents()` acquires its namespace lazily. Agent and turn wrappers must not be
+copied after first use; `Runtime.Close` releases their native handles.
+Canceling a call stops the Go wait without canceling submitted agent work;
+late returned handles are released. Canceling an `AgentTurn.Wait` or closing its
+runtime also releases that call’s native observer. Other waits on the same
+turn continue until their own completion, cancellation, or runtime shutdown. `Agent.Close` invokes the core operation
+rather than freeing the local handle. Both event methods return `Unsupported`.
+
+The Go unit and coverage targets enable C `test-support` and the
+`boxlite_agent_test` Go tag. Deterministic tests cross the C/core boundary without
+requiring a VM; normal SDK builds exclude these test entry points.
+Run `make test:unit:go FILTER=Agent` and add `RACE=1` for race checks.
+
+
Build from source (requires Rust toolchain):
```bash
diff --git a/sdks/go/agents.go b/sdks/go/agents.go
index 5cd8ab519..0b7d45c1f 100644
--- a/sdks/go/agents.go
+++ b/sdks/go/agents.go
@@ -3,6 +3,7 @@ package boxlite
import (
"context"
"encoding/json"
+ "sync"
"time"
)
@@ -180,62 +181,26 @@ type AgentEventStream interface {
}
// Agents, Agent and AgentTurn address agent conversations and work.
-type Agents struct{}
-type Agent struct{}
-type AgentTurn struct{}
+type Agents struct {
+ mu sync.Mutex
+ box *Box
+ native *agentNamespace
+}
-// Agents obtains the namespace without starting the Box.
-func (b *Box) Agents() *Agents { return &Agents{} }
+// Agent represents an agent session. Pass the *Agent returned by the SDK.
+// Do not copy the Agent value.
+type Agent struct{ native *agentSession }
-func agentNotImplemented(operation string) error {
- return &Error{Code: ErrUnsupported, Message: operation + " is not implemented"}
-}
+// AgentTurn represents one submitted task. Pass the *AgentTurn returned by the SDK.
+// Do not copy the AgentTurn value.
+type AgentTurn struct{ native *agentTurnHandle }
-func (a *Agents) Create(ctx context.Context, agent string, options AgentCreateOptions) (*Agent, error) {
- return nil, agentNotImplemented("agents.create")
-}
-func (a *Agents) Get(ctx context.Context, agentID string) (*Agent, error) {
- return nil, agentNotImplemented("agents.get")
-}
-func (s *Agent) Close(ctx context.Context, options AgentControlOptions) error {
- return agentNotImplemented("agent.close")
-}
-func (s *Agent) Send(ctx context.Context, text string, options AgentSendOptions) (*AgentTurn, error) {
- return nil, agentNotImplemented("agent.send")
-}
-func (s *Agent) GetTurn(ctx context.Context, turnID string) (*AgentTurn, error) {
- return nil, agentNotImplemented("agent.get_turn")
-}
-func (s *Agent) Events(ctx context.Context, options AgentEventsOptions) (AgentEventStream, error) {
- return nil, agentNotImplemented("agent.events")
-}
-func (s *Agent) Requests(ctx context.Context) ([]AgentRequest, error) {
- return nil, agentNotImplemented("agent.requests")
-}
-func (s *Agent) Respond(ctx context.Context, requestID string, response AgentResponse, options AgentControlOptions) (*AgentTurn, error) {
- return nil, agentNotImplemented("agent.respond")
-}
-func (s *Agent) State() (*AgentState, error) {
- return nil, agentNotImplemented("agent.state")
-}
-func (s *Agent) Config() (*AgentConfig, error) {
- return nil, agentNotImplemented("agent.config")
-}
-func (s *Agent) Capabilities() (*AgentCapabilities, error) {
- return nil, agentNotImplemented("agent.capabilities")
-}
-func (t *AgentTurn) Wait(ctx context.Context, options AgentWaitOptions) (*AgentResult, error) {
- return nil, agentNotImplemented("turn.wait")
-}
-func (t *AgentTurn) Events(ctx context.Context, options AgentEventsOptions) (AgentEventStream, error) {
- return nil, agentNotImplemented("turn.events")
-}
-func (t *AgentTurn) Steer(ctx context.Context, text string, options AgentControlOptions) (*AgentSteeringReceipt, error) {
- return nil, agentNotImplemented("turn.steer")
-}
-func (t *AgentTurn) Interrupt(ctx context.Context, options AgentControlOptions) error {
- return agentNotImplemented("turn.interrupt")
+// Agents obtains the namespace without starting the Box.
+func (b *Box) Agents() *Agents { return &Agents{box: b} }
+
+func (a *Agent) Events(context.Context, AgentEventsOptions) (AgentEventStream, error) {
+ return nil, &Error{Code: ErrUnsupported, Message: "agent.events is not implemented"}
}
-func (t *AgentTurn) State() (*AgentTurnState, error) {
- return nil, agentNotImplemented("turn.state")
+func (t *AgentTurn) Events(context.Context, AgentEventsOptions) (AgentEventStream, error) {
+ return nil, &Error{Code: ErrUnsupported, Message: "turn.events is not implemented"}
}
diff --git a/sdks/go/agents_bridge.c b/sdks/go/agents_bridge.c
new file mode 100644
index 000000000..031e759a6
--- /dev/null
+++ b/sdks/go/agents_bridge.c
@@ -0,0 +1,48 @@
+#include "agents_bridge.h"
+
+extern void goBoxliteAgentCreated(struct CAgent *, CBoxliteError *, uintptr_t);
+extern void goBoxliteAgentTurn(struct CAgentTurn *, CBoxliteError *, uintptr_t);
+extern void goBoxliteAgentJSON(char *, CBoxliteError *, uintptr_t);
+
+static void agent_created(struct CAgent *agent, const CBoxliteError *error, void *data) {
+ goBoxliteAgentCreated(agent, (CBoxliteError *)error, (uintptr_t)data);
+}
+static void agent_turn(struct CAgentTurn *turn, const CBoxliteError *error, void *data) {
+ goBoxliteAgentTurn(turn, (CBoxliteError *)error, (uintptr_t)data);
+}
+static void agent_json(const char *json, const CBoxliteError *error, void *data) {
+ goBoxliteAgentJSON((char *)json, (CBoxliteError *)error, (uintptr_t)data);
+}
+static void agent_done(const CBoxliteError *error, void *data) {
+ goBoxliteAgentJSON(NULL, (CBoxliteError *)error, (uintptr_t)data);
+}
+enum BoxliteErrorCode go_agent_create(struct CAgents *agents, const char *name, const struct CAgentCreateOptions *options, uintptr_t token, CBoxliteError *error) {
+ return boxlite_agents_create(agents, name, options, agent_created, (void *)token, error);
+}
+enum BoxliteErrorCode go_agent_get(struct CAgents *agents, const char *id, uintptr_t token, CBoxliteError *error) {
+ return boxlite_agents_get(agents, id, agent_created, (void *)token, error);
+}
+enum BoxliteErrorCode go_agent_close(struct CAgent *agent, const struct CAgentControlOptions *options, uintptr_t token, CBoxliteError *error) {
+ return boxlite_agent_close(agent, options, agent_done, (void *)token, error);
+}
+enum BoxliteErrorCode go_agent_send(struct CAgent *agent, const char *text, const struct CAgentSendOptions *options, uintptr_t token, CBoxliteError *error) {
+ return boxlite_agent_send(agent, text, options, agent_turn, (void *)token, error);
+}
+enum BoxliteErrorCode go_agent_get_turn(struct CAgent *agent, const char *id, uintptr_t token, CBoxliteError *error) {
+ return boxlite_agent_get_turn(agent, id, agent_turn, (void *)token, error);
+}
+enum BoxliteErrorCode go_agent_requests(struct CAgent *agent, uintptr_t token, CBoxliteError *error) {
+ return boxlite_agent_requests(agent, agent_json, (void *)token, error);
+}
+enum BoxliteErrorCode go_agent_respond(struct CAgent *agent, const char *id, const char *response, const struct CAgentControlOptions *options, uintptr_t token, CBoxliteError *error) {
+ return boxlite_agent_respond(agent, id, response, options, agent_turn, (void *)token, error);
+}
+enum BoxliteErrorCode go_agent_wait(struct CAgentTurn *turn, const struct CAgentWaitOptions *options, struct CAgentWait **wait, uintptr_t token, CBoxliteError *error) {
+ return boxlite_agent_turn_wait_cancellable(turn, options, agent_json, (void *)token, wait, error);
+}
+enum BoxliteErrorCode go_agent_steer(struct CAgentTurn *turn, const char *text, const struct CAgentControlOptions *options, uintptr_t token, CBoxliteError *error) {
+ return boxlite_agent_turn_steer(turn, text, options, agent_json, (void *)token, error);
+}
+enum BoxliteErrorCode go_agent_interrupt(struct CAgentTurn *turn, const struct CAgentControlOptions *options, uintptr_t token, CBoxliteError *error) {
+ return boxlite_agent_turn_interrupt(turn, options, agent_done, (void *)token, error);
+}
diff --git a/sdks/go/agents_bridge.h b/sdks/go/agents_bridge.h
new file mode 100644
index 000000000..58388f790
--- /dev/null
+++ b/sdks/go/agents_bridge.h
@@ -0,0 +1,16 @@
+#ifndef BOXLITE_GO_AGENTS_BRIDGE_H
+#define BOXLITE_GO_AGENTS_BRIDGE_H
+#include "boxlite.h"
+
+/* Keep cgo tokens as integers in Go; only C converts them to opaque user_data. */
+enum BoxliteErrorCode go_agent_create(struct CAgents *, const char *, const struct CAgentCreateOptions *, uintptr_t, CBoxliteError *);
+enum BoxliteErrorCode go_agent_get(struct CAgents *, const char *, uintptr_t, CBoxliteError *);
+enum BoxliteErrorCode go_agent_close(struct CAgent *, const struct CAgentControlOptions *, uintptr_t, CBoxliteError *);
+enum BoxliteErrorCode go_agent_send(struct CAgent *, const char *, const struct CAgentSendOptions *, uintptr_t, CBoxliteError *);
+enum BoxliteErrorCode go_agent_get_turn(struct CAgent *, const char *, uintptr_t, CBoxliteError *);
+enum BoxliteErrorCode go_agent_requests(struct CAgent *, uintptr_t, CBoxliteError *);
+enum BoxliteErrorCode go_agent_respond(struct CAgent *, const char *, const char *, const struct CAgentControlOptions *, uintptr_t, CBoxliteError *);
+enum BoxliteErrorCode go_agent_wait(struct CAgentTurn *, const struct CAgentWaitOptions *, struct CAgentWait **, uintptr_t, CBoxliteError *);
+enum BoxliteErrorCode go_agent_steer(struct CAgentTurn *, const char *, const struct CAgentControlOptions *, uintptr_t, CBoxliteError *);
+enum BoxliteErrorCode go_agent_interrupt(struct CAgentTurn *, const struct CAgentControlOptions *, uintptr_t, CBoxliteError *);
+#endif
diff --git a/sdks/go/agents_calls.go b/sdks/go/agents_calls.go
new file mode 100644
index 000000000..fb1299e70
--- /dev/null
+++ b/sdks/go/agents_calls.go
@@ -0,0 +1,227 @@
+package boxlite
+
+/*
+#include "agents_bridge.h"
+*/
+import "C"
+
+import (
+ "context"
+ "encoding/json"
+ "runtime"
+ "unicode/utf8"
+)
+
+func agentContextError(ctx context.Context) error {
+ if ctx == nil {
+ return agentJSONError(ErrInvalidArgument, "nil context")
+ }
+ return ctx.Err()
+}
+func agentFromResult(h *agentSession, err error) (*Agent, error) {
+ if err != nil {
+ return nil, err
+ }
+ return wrapAgent(h), nil
+}
+func turnFromResult(h *agentTurnHandle, err error) (*AgentTurn, error) {
+ if err != nil {
+ return nil, err
+ }
+ return wrapAgentTurn(h), nil
+}
+func agentJSONCall[T any, P comparable](ctx context.Context, h *agentHandle[P], submit func(P, C.uintptr_t, *C.CBoxliteError) C.enum_BoxliteErrorCode, parse func([]byte) (T, error)) (T, error) {
+ data, err := agentCall[[]byte](ctx, h, submit, nil)
+ if err != nil {
+ var zero T
+ return zero, err
+ }
+ return parse(data)
+}
+
+func (a *Agents) Create(ctx context.Context, agent string, options AgentCreateOptions) (*Agent, error) {
+ defer runtime.KeepAlive(a)
+ if err := agentContextError(ctx); err != nil {
+ return nil, err
+ }
+ config, err := agentConfigJSON(options.Config)
+ if err != nil {
+ return nil, err
+ }
+ var args agentArguments
+ defer args.free()
+ name := args.string(agent, "agent", false)
+ opts := C.struct_CAgentCreateOptions{cwd: args.string(options.Cwd, "cwd", true), config_json: args.string(string(config), "config", false), idempotency_key: args.string(options.IdempotencyKey, "idempotency_key", true)}
+ if args.err != nil {
+ return nil, args.err
+ }
+ h, err := a.namespace()
+ if err != nil {
+ return nil, err
+ }
+ return agentFromResult(agentCall[*agentSession](ctx, h, func(p *C.struct_CAgents, token C.uintptr_t, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.go_agent_create(p, name, &opts, token, e)
+ }, func(h *agentSession) { h.release() }))
+}
+
+func (a *Agents) Get(ctx context.Context, agentID string) (*Agent, error) {
+ defer runtime.KeepAlive(a)
+ if err := agentContextError(ctx); err != nil {
+ return nil, err
+ }
+ var args agentArguments
+ defer args.free()
+ id := args.string(agentID, "agent_id", false)
+ if args.err != nil {
+ return nil, args.err
+ }
+ h, err := a.namespace()
+ if err != nil {
+ return nil, err
+ }
+ return agentFromResult(agentCall[*agentSession](ctx, h, func(p *C.struct_CAgents, token C.uintptr_t, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.go_agent_get(p, id, token, e)
+ }, func(h *agentSession) { h.release() }))
+}
+
+func (s *Agent) Close(ctx context.Context, options AgentControlOptions) error {
+ defer runtime.KeepAlive(s)
+ var args agentArguments
+ defer args.free()
+ opts := args.control(options)
+ if args.err != nil {
+ return args.err
+ }
+ _, err := agentCall[[]byte](ctx, agentSessionOf(s), func(p *C.struct_CAgent, token C.uintptr_t, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.go_agent_close(p, &opts, token, e)
+ }, nil)
+ return err
+}
+
+func (s *Agent) Send(ctx context.Context, text string, options AgentSendOptions) (*AgentTurn, error) {
+ defer runtime.KeepAlive(s)
+ var mode C.int32_t
+ switch options.Mode {
+ case "", AgentSendQueue:
+ case AgentSendReject:
+ mode = 1
+ default:
+ return nil, agentJSONError(ErrInvalidArgument, "invalid send mode")
+ }
+ if len(options.Data) > 0 && (!utf8.Valid(options.Data) || !json.Valid(options.Data)) {
+ return nil, agentJSONError(ErrInvalidArgument, "invalid send data JSON")
+ }
+ var args agentArguments
+ defer args.free()
+ input := args.string(text, "text", false)
+ opts := C.struct_CAgentSendOptions{mode: mode, data_json: args.string(string(agentRaw(options.Data)), "data", true), idempotency_key: args.string(options.IdempotencyKey, "idempotency_key", true)}
+ if args.err != nil {
+ return nil, args.err
+ }
+ return turnFromResult(agentCall[*agentTurnHandle](ctx, agentSessionOf(s), func(p *C.struct_CAgent, token C.uintptr_t, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.go_agent_send(p, input, &opts, token, e)
+ }, func(h *agentTurnHandle) { h.release() }))
+}
+
+func (s *Agent) GetTurn(ctx context.Context, turnID string) (*AgentTurn, error) {
+ defer runtime.KeepAlive(s)
+ var args agentArguments
+ defer args.free()
+ id := args.string(turnID, "turn_id", false)
+ if args.err != nil {
+ return nil, args.err
+ }
+ return turnFromResult(agentCall[*agentTurnHandle](ctx, agentSessionOf(s), func(p *C.struct_CAgent, token C.uintptr_t, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.go_agent_get_turn(p, id, token, e)
+ }, func(h *agentTurnHandle) { h.release() }))
+}
+
+func (s *Agent) Requests(ctx context.Context) ([]AgentRequest, error) {
+ defer runtime.KeepAlive(s)
+ return agentJSONCall(ctx, agentSessionOf(s), func(p *C.struct_CAgent, token C.uintptr_t, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.go_agent_requests(p, token, e)
+ }, parseAgentRequests)
+}
+
+func (s *Agent) Respond(ctx context.Context, requestID string, response AgentResponse, options AgentControlOptions) (*AgentTurn, error) {
+ defer runtime.KeepAlive(s)
+ encoded, err := agentResponseJSON(response)
+ if err != nil {
+ return nil, err
+ }
+ var args agentArguments
+ defer args.free()
+ id := args.string(requestID, "request_id", false)
+ input := args.string(string(encoded), "response", false)
+ opts := args.control(options)
+ if args.err != nil {
+ return nil, args.err
+ }
+ return turnFromResult(agentCall[*agentTurnHandle](ctx, agentSessionOf(s), func(p *C.struct_CAgent, token C.uintptr_t, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.go_agent_respond(p, id, input, &opts, token, e)
+ }, func(h *agentTurnHandle) { h.release() }))
+}
+
+func (s *Agent) State() (*AgentState, error) {
+ defer runtime.KeepAlive(s)
+ return agentGetter(agentSessionOf(s), func(p *C.struct_CAgent, j **C.char, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.boxlite_agent_state(p, j, e)
+ }, parseAgentState)
+}
+func (s *Agent) Config() (*AgentConfig, error) {
+ defer runtime.KeepAlive(s)
+ return agentGetter(agentSessionOf(s), func(p *C.struct_CAgent, j **C.char, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.boxlite_agent_config(p, j, e)
+ }, parseAgentConfig)
+}
+func (s *Agent) Capabilities() (*AgentCapabilities, error) {
+ defer runtime.KeepAlive(s)
+ return agentGetter(agentSessionOf(s), func(p *C.struct_CAgent, j **C.char, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.boxlite_agent_capabilities(p, j, e)
+ }, parseAgentCapabilities)
+}
+func (t *AgentTurn) State() (*AgentTurnState, error) {
+ defer runtime.KeepAlive(t)
+ return agentGetter(agentTurnOf(t), func(p *C.struct_CAgentTurn, j **C.char, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.boxlite_agent_turn_state(p, j, e)
+ }, parseAgentTurnState)
+}
+
+func (t *AgentTurn) Wait(ctx context.Context, options AgentWaitOptions) (*AgentResult, error) {
+ defer runtime.KeepAlive(t)
+ opts := C.struct_CAgentWaitOptions{timeout_seconds: -1}
+ if options.Timeout != nil && *options.Timeout >= 0 {
+ opts.timeout_seconds = C.double(options.Timeout.Seconds())
+ }
+ var wait *C.struct_CAgentWait
+ defer func() { C.boxlite_agent_wait_free(wait) }()
+ return agentJSONCall(ctx, agentTurnOf(t), func(p *C.struct_CAgentTurn, token C.uintptr_t, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.go_agent_wait(p, &opts, &wait, token, e)
+ }, parseAgentResult)
+}
+func (t *AgentTurn) Steer(ctx context.Context, text string, options AgentControlOptions) (*AgentSteeringReceipt, error) {
+ defer runtime.KeepAlive(t)
+ var args agentArguments
+ defer args.free()
+ input := args.string(text, "text", false)
+ opts := args.control(options)
+ if args.err != nil {
+ return nil, args.err
+ }
+ return agentJSONCall(ctx, agentTurnOf(t), func(p *C.struct_CAgentTurn, token C.uintptr_t, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.go_agent_steer(p, input, &opts, token, e)
+ }, parseAgentReceipt)
+}
+func (t *AgentTurn) Interrupt(ctx context.Context, options AgentControlOptions) error {
+ defer runtime.KeepAlive(t)
+ var args agentArguments
+ defer args.free()
+ opts := args.control(options)
+ if args.err != nil {
+ return args.err
+ }
+ _, err := agentCall[[]byte](ctx, agentTurnOf(t), func(p *C.struct_CAgentTurn, token C.uintptr_t, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.go_agent_interrupt(p, &opts, token, e)
+ }, nil)
+ return err
+}
diff --git a/sdks/go/agents_json_test.go b/sdks/go/agents_json_test.go
index c96135530..033c824ee 100644
--- a/sdks/go/agents_json_test.go
+++ b/sdks/go/agents_json_test.go
@@ -1,6 +1,7 @@
package boxlite
import (
+ "bytes"
"encoding/json"
"errors"
"math"
@@ -29,18 +30,57 @@ func agentFixture(t *testing.T, name string) json.RawMessage {
func sameAgentJSON(t *testing.T, got, want []byte) {
t.Helper()
- var left, right any
- if err := json.Unmarshal(got, &left); err != nil {
- t.Fatal(err)
- }
- if err := json.Unmarshal(want, &right); err != nil {
+ equal, err := equalAgentJSON(got, want)
+ if err != nil {
t.Fatal(err)
}
- if !reflect.DeepEqual(left, right) {
+ if !equal {
t.Fatalf("JSON mismatch: got %s, want %s", got, want)
}
}
+func equalAgentJSON(got, want []byte) (bool, error) {
+ var values [2]any
+ for i, raw := range [][]byte{got, want} {
+ if !json.Valid(raw) {
+ return false, errors.New("invalid JSON")
+ }
+ decoder := json.NewDecoder(bytes.NewReader(raw))
+ // Compare numeric tokens exactly; only whitespace and object order are irrelevant.
+ decoder.UseNumber()
+ if err := decoder.Decode(&values[i]); err != nil {
+ return false, err
+ }
+ }
+ return reflect.DeepEqual(values[0], values[1]), nil
+}
+
+func TestAgentJSONComparisonPreservesNumbers(t *testing.T) {
+ for _, tc := range []struct {
+ left, right string
+ equal bool
+ }{
+ {`{"a":1,"b":[2]}`, ` {"b":[2],"a":1} `, true},
+ {`9007199254740992`, `9007199254740993`, false},
+ {`0.123456789012345678901`, `0.123456789012345678902`, false},
+ {`{"nested":[9223372036854775806]}`, `{"nested":[9223372036854775807]}`, false},
+ {`1e1000`, `2e1000`, false},
+ } {
+ equal, err := equalAgentJSON([]byte(tc.left), []byte(tc.right))
+ if err != nil || equal != tc.equal {
+ t.Errorf("compare %s and %s: %v, %v; want %v", tc.left, tc.right, equal, err, tc.equal)
+ }
+ }
+ for _, invalid := range []string{``, `{`, `1 2`} {
+ if _, err := equalAgentJSON([]byte(invalid), []byte(`null`)); err == nil {
+ t.Errorf("invalid left JSON accepted: %q", invalid)
+ }
+ if _, err := equalAgentJSON([]byte(`null`), []byte(invalid)); err == nil {
+ t.Errorf("invalid right JSON accepted: %q", invalid)
+ }
+ }
+}
+
func sameAgentValue(t *testing.T, got, want any) {
t.Helper()
left, err := json.Marshal(got)
@@ -218,6 +258,75 @@ func TestAgentRetentionDecimalBoundaries(t *testing.T) {
}
}
+func TestAgentRetentionBoundariesFromCore(t *testing.T) {
+ got, err := parseAgentCapabilities(agentFixture(t, "capabilities_max"))
+ if err != nil || got.IdempotencyRetention == nil || *got.IdempotencyRetention != time.Duration(math.MaxInt64) {
+ t.Fatalf("core maximum retention: %+v, %v", got, err)
+ }
+ if got, err := parseAgentCapabilities(agentFixture(t, "capabilities_overflow")); got != nil || err == nil {
+ t.Fatalf("core overflow retention: %+v, %v", got, err)
+ }
+}
+
+func TestAgentCapabilityIntegerBoundaries(t *testing.T) {
+ for _, field := range []string{"max_queued_turns", "max_pending_steering"} {
+ for _, want := range []uint{0, 1, ^uint(0)} {
+ raw, err := json.Marshal(want)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := parseAgentCapabilities(agentField(t, agentFixture(t, "capabilities"), field, raw))
+ if err != nil {
+ t.Fatal(err)
+ }
+ value := got.MaxQueuedTurns
+ if field == "max_pending_steering" {
+ value = got.MaxPendingSteering
+ }
+ if value == nil || *value != want {
+ t.Fatalf("%s: got %v, want %d", field, value, want)
+ }
+ }
+ for _, raw := range []string{"1.5", "18446744073709551616"} {
+ got, err := parseAgentCapabilities(agentField(t, agentFixture(t, "capabilities"), field, json.RawMessage(raw)))
+ if got != nil || err == nil {
+ t.Fatalf("%s accepted %s: %+v, %v", field, raw, got, err)
+ }
+ }
+ }
+}
+
+func TestAgentNumericPayloadsFromCore(t *testing.T) {
+ numbers := agentFixture(t, "numeric_data")
+ sameAgentJSON(t, numbers, []byte(`[9007199254740992,9007199254740993,-9223372036854775808,9223372036854775807,18446744073709551615,0.123456789012345678901,0.123456789012345678902]`))
+ config, err := parseAgentConfig(agentFixture(t, "numeric_config"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, data := range []json.RawMessage{config.Limits, config.Permissions, config.OutputSchema} {
+ sameAgentJSON(t, data, numbers)
+ }
+ encoded, err := agentConfigJSON(*config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sameAgentJSON(t, encoded, agentFixture(t, "numeric_config"))
+ result, err := parseAgentResult(agentFixture(t, "result"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var payload map[string]json.RawMessage
+ if err := json.Unmarshal(result.Data, &payload); err != nil {
+ t.Fatal(err)
+ }
+ sameAgentJSON(t, payload["numbers"], numbers)
+ encoded, err = agentResponseJSON(AgentAnswer{Text: "yes", Data: result.Data})
+ if err != nil {
+ t.Fatal(err)
+ }
+ sameAgentJSON(t, encoded, agentFixture(t, "answer"))
+}
+
func TestAgentRecordsFromCore(t *testing.T) {
state, err := parseAgentState(agentFixture(t, "state"))
if err != nil {
diff --git a/sdks/go/agents_native.go b/sdks/go/agents_native.go
new file mode 100644
index 000000000..84a2af83c
--- /dev/null
+++ b/sdks/go/agents_native.go
@@ -0,0 +1,305 @@
+package boxlite
+
+/*
+#include "agents_bridge.h"
+#include <stdlib.h>
+*/
+import "C"
+
+import (
+ "context"
+ "runtime"
+ "runtime/cgo"
+ "strings"
+ "sync"
+ "unicode/utf8"
+ "unsafe"
+)
+
+type agentResource interface{ release() }
+type agentNamespace = agentHandle[*C.struct_CAgents]
+type agentSession = agentHandle[*C.struct_CAgent]
+type agentTurnHandle = agentHandle[*C.struct_CAgentTurn]
+
+// Lock order is runtime admission, then handle. Both protect only the
+// synchronous C submission, never the wait for its completion callback.
+type agentHandle[P comparable] struct {
+ owner *Runtime
+ mu sync.RWMutex
+ ptr P
+ free func(P)
+}
+
+func (h *agentHandle[P]) acquire() (P, func(), error) {
+ var zero P
+ if h == nil || h.owner == nil {
+ return zero, nil, agentJSONError(ErrInvalidState, "agent handle is not initialized")
+ }
+ r := h.owner
+ r.agentMu.RLock()
+ if r.agentClosed || r.handle == nil {
+ r.agentMu.RUnlock()
+ return zero, nil, ErrRuntimeClosed
+ }
+ h.mu.RLock()
+ if h.ptr == zero {
+ h.mu.RUnlock()
+ r.agentMu.RUnlock()
+ return zero, nil, agentJSONError(ErrInvalidState, "agent handle is released")
+ }
+ return h.ptr, func() { h.mu.RUnlock(); r.agentMu.RUnlock() }, nil
+}
+
+func (h *agentHandle[P]) release() {
+ if h == nil {
+ return
+ }
+ r := h.owner
+ r.agentMu.Lock()
+ defer r.agentMu.Unlock()
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ var zero P
+ if h.ptr != zero {
+ h.free(h.ptr)
+ h.ptr = zero
+ delete(r.agentHandles, h)
+ }
+}
+
+func adoptAgentHandle[P comparable](r *Runtime, ptr P, free func(P)) (*agentHandle[P], error) {
+ r.agentMu.Lock()
+ defer r.agentMu.Unlock()
+ if r.agentClosed {
+ free(ptr)
+ return nil, ErrRuntimeClosed
+ }
+ return registerAgentHandle(r, ptr, free), nil
+}
+
+// The caller holds runtime admission exclusively.
+func registerAgentHandle[P comparable](r *Runtime, ptr P, free func(P)) *agentHandle[P] {
+ h := &agentHandle[P]{owner: r, ptr: ptr, free: free}
+ if r.agentHandles == nil {
+ r.agentHandles = make(map[agentResource]struct{})
+ }
+ r.agentHandles[h] = struct{}{}
+ return h
+}
+
+func (a *Agents) namespace() (*agentNamespace, error) {
+ if a == nil {
+ return nil, agentJSONError(ErrInvalidState, "agent namespace is not initialized")
+ }
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if a.native != nil {
+ return a.native, nil
+ }
+ if a.box == nil || a.box.runtime == nil {
+ return nil, agentJSONError(ErrInvalidState, "agent namespace has no Box")
+ }
+ box, unlock, err := a.box.acquire()
+ if err != nil {
+ return nil, err
+ }
+ defer unlock()
+ r := a.box.runtime
+ r.agentMu.Lock()
+ defer r.agentMu.Unlock()
+ if r.agentClosed || r.handle == nil {
+ return nil, ErrRuntimeClosed
+ }
+ var ptr *C.struct_CAgents
+ var cerr C.CBoxliteError
+ if C.boxlite_box_agents(box, &ptr, &cerr) != C.Ok {
+ return nil, freeError(&cerr)
+ }
+ a.native = registerAgentHandle(r, ptr, func(p *C.struct_CAgents) { C.boxlite_agents_free(p) })
+ runtime.AddCleanup(a, func(h *agentNamespace) { h.release() }, a.native)
+ return a.native, nil
+}
+
+func wrapAgent(h *agentSession) *Agent {
+ a := &Agent{native: h}
+ runtime.AddCleanup(a, func(h *agentSession) { h.release() }, h)
+ return a
+}
+func wrapAgentTurn(h *agentTurnHandle) *AgentTurn {
+ t := &AgentTurn{native: h}
+ runtime.AddCleanup(t, func(h *agentTurnHandle) { h.release() }, h)
+ return t
+}
+func agentSessionOf(a *Agent) *agentSession {
+ if a == nil {
+ return nil
+ }
+ return a.native
+}
+func agentTurnOf(t *AgentTurn) *agentTurnHandle {
+ if t == nil {
+ return nil
+ }
+ return t.native
+}
+
+type agentPending[T any] struct {
+ owner *Runtime
+ result chan handleResult[T]
+}
+
+func agentCall[T any, P comparable](ctx context.Context, h *agentHandle[P], submit func(P, C.uintptr_t, *C.CBoxliteError) C.enum_BoxliteErrorCode, dispose func(T)) (T, error) {
+ var zero T
+ if ctx == nil {
+ return zero, agentJSONError(ErrInvalidArgument, "nil context")
+ }
+ if err := ctx.Err(); err != nil {
+ return zero, err
+ }
+ ptr, unlock, err := h.acquire()
+ if err != nil {
+ return zero, err
+ }
+ r := h.owner
+ r.ensureDrainRunning()
+ pending := &agentPending[T]{owner: r, result: make(chan handleResult[T], 1)}
+ token := registerHandleForDispatch(cgo.NewHandle(pending))
+ var cerr C.CBoxliteError
+ code := submit(ptr, C.uintptr_t(token), &cerr)
+ unlock()
+ if code != C.Ok {
+ deleteHandleForDispatch(token)
+ return zero, freeError(&cerr)
+ }
+ discard := func(value T) {
+ if dispose != nil {
+ dispose(value)
+ }
+ }
+ select {
+ case result := <-pending.result:
+ select {
+ case <-r.closing:
+ discard(result.value)
+ return zero, ErrRuntimeClosed
+ default:
+ }
+ if err := ctx.Err(); err != nil {
+ discard(result.value)
+ return zero, err
+ }
+ return result.value, result.err
+ case <-ctx.Done():
+ abandonOwnedResult(pending.result, token, discard)
+ return zero, ctx.Err()
+ case <-r.closing:
+ abandonOwnedResult(pending.result, token, discard)
+ return zero, ErrRuntimeClosed
+ }
+}
+
+func agentGetter[T any, P comparable](h *agentHandle[P], get func(P, **C.char, *C.CBoxliteError) C.enum_BoxliteErrorCode, parse func([]byte) (T, error)) (T, error) {
+ var zero T
+ ptr, unlock, err := h.acquire()
+ if err != nil {
+ return zero, err
+ }
+ var json *C.char
+ var cerr C.CBoxliteError
+ code := get(ptr, &json, &cerr)
+ unlock()
+ if json != nil {
+ defer C.boxlite_free_string(json)
+ }
+ if code != C.Ok {
+ return zero, freeError(&cerr)
+ }
+ return parse([]byte(C.GoString(json)))
+}
+
+// Agent callback data is borrowed; freeError owns its input and cannot be
+// reused here. Copy the message before Rust frees it after callback return.
+func borrowedAgentError(err *C.CBoxliteError) error {
+ if err == nil || err.code == C.Ok {
+ return nil
+ }
+ return &Error{Code: ErrorCode(err.code), Message: cString(err.message)}
+}
+
+func agentHandleResult[P comparable](ptr P, err *C.CBoxliteError, token C.uintptr_t, free func(P)) {
+ h := cgo.Handle(token)
+ var zero P
+ if !claimHandleForDispatch(h) {
+ if ptr != zero {
+ free(ptr)
+ }
+ return
+ }
+ defer h.Delete()
+ op := h.Value().(*agentPending[*agentHandle[P]])
+ result := handleResult[*agentHandle[P]]{err: borrowedAgentError(err)}
+ if result.err == nil {
+ if ptr == zero {
+ result.err = agentJSONError(ErrInternal, "agent callback returned no handle")
+ } else {
+ result.value, result.err = adoptAgentHandle(op.owner, ptr, free)
+ }
+ } else if ptr != zero {
+ free(ptr)
+ }
+ op.result <- result
+}
+
+//export goBoxliteAgentCreated
+func goBoxliteAgentCreated(ptr *C.struct_CAgent, err *C.CBoxliteError, token C.uintptr_t) {
+ agentHandleResult(ptr, err, token, func(p *C.struct_CAgent) { C.boxlite_agent_free(p) })
+}
+
+//export goBoxliteAgentTurn
+func goBoxliteAgentTurn(ptr *C.struct_CAgentTurn, err *C.CBoxliteError, token C.uintptr_t) {
+ agentHandleResult(ptr, err, token, func(p *C.struct_CAgentTurn) { C.boxlite_agent_turn_free(p) })
+}
+
+//export goBoxliteAgentJSON
+func goBoxliteAgentJSON(json *C.char, err *C.CBoxliteError, token C.uintptr_t) {
+ h := cgo.Handle(token)
+ if !claimHandleForDispatch(h) {
+ return
+ }
+ defer h.Delete()
+ op := h.Value().(*agentPending[[]byte])
+ var data []byte
+ if json != nil {
+ data = []byte(C.GoString(json))
+ }
+ op.result <- handleResult[[]byte]{value: data, err: borrowedAgentError(err)}
+}
+
+type agentArguments struct {
+ strings []*C.char
+ err error
+}
+
+func (a *agentArguments) string(value, name string, optional bool) *C.char {
+ if a.err != nil {
+ return nil
+ }
+ if !utf8.ValidString(value) || strings.IndexByte(value, 0) >= 0 {
+ a.err = agentJSONError(ErrInvalidArgument, name+" contains invalid UTF-8 or NUL")
+ return nil
+ }
+ if optional && value == "" {
+ return nil
+ }
+ ptr := toCString(value)
+ a.strings = append(a.strings, ptr)
+ return ptr
+}
+func (a *agentArguments) control(options AgentControlOptions) C.struct_CAgentControlOptions {
+ return C.struct_CAgentControlOptions{idempotency_key: a.string(options.IdempotencyKey, "idempotency_key", true)}
+}
+func (a *agentArguments) free() {
+ for _, ptr := range a.strings {
+ C.free(unsafe.Pointer(ptr))
+ }
+}
diff --git a/sdks/go/agents_native_test.go b/sdks/go/agents_native_test.go
new file mode 100644
index 000000000..987cc1601
--- /dev/null
+++ b/sdks/go/agents_native_test.go
@@ -0,0 +1,697 @@
+//go:build boxlite_dev && boxlite_agent_test
+
+package boxlite
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "runtime"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+func testAgents(t *testing.T, manual bool) (*Runtime, *Agents) {
+ t.Helper()
+ r, a, err := newTestAgentNamespace(t.TempDir(), manual)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { r.Close(); runtime.KeepAlive(a) })
+ return r, a
+}
+func testCreateAgent(t *testing.T, a *Agents) *Agent {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ agent, err := a.Create(ctx, "test", AgentCreateOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { runtime.KeepAlive(agent) })
+ return agent
+}
+func agentHandleCount(r *Runtime) int {
+ r.agentMu.RLock()
+ defer r.agentMu.RUnlock()
+ return len(r.agentHandles)
+}
+func agentTokenCount() int {
+ n := 0
+ activeHandles.Range(func(_, _ any) bool { n++; return true })
+ return n
+}
+func receiveAgent[T any](t *testing.T, ch <-chan T) T {
+ t.Helper()
+ select {
+ case value := <-ch:
+ return value
+ case <-time.After(5 * time.Second):
+ t.Fatal("agent operation did not finish")
+ var zero T
+ return zero
+ }
+}
+
+func TestAgentCallsAndGettersReachCore(t *testing.T) {
+ _, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ adopted, err := a.Get(ctx, "agent-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer runtime.KeepAlive(adopted)
+ state, err := adopted.State()
+ if err != nil || state.ID != "agent-1" || state.Status != AgentReady || len(state.Requests) != 0 {
+ t.Fatalf("state=%+v err=%v", state, err)
+ }
+ config, err := agent.Config()
+ if err != nil || config.Model != "" || config.Tools == nil || config.MCP == nil || config.Permissions != nil {
+ t.Fatalf("config=%+v err=%v", config, err)
+ }
+ caps, err := agent.Capabilities()
+ if err != nil || !reflect.DeepEqual(caps.Operations, []string{"agent.send"}) || caps.MaxQueuedTurns != nil {
+ t.Fatalf("capabilities=%+v err=%v", caps, err)
+ }
+ for _, data := range []string{"false", "0", "[]", `{"nested":null}`} {
+ turn, err := agent.Send(ctx, "echo", AgentSendOptions{Mode: AgentSendReject, Data: json.RawMessage(data)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ state, err := turn.State()
+ if err != nil || state.ID != "turn-1" || state.AgentID != "agent-1" || state.Status != AgentTurnCompleted || state.Result.Text != "echo" || string(state.Result.Data) != data {
+ t.Fatalf("turn state=%+v err=%v", state, err)
+ }
+ loaded, err := agent.GetTurn(ctx, state.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ zero := time.Duration(0)
+ result, err := loaded.Wait(ctx, AgentWaitOptions{Timeout: &zero})
+ if err != nil || result.Status != AgentTurnCompleted || result.Text != "echo" || string(result.Data) != data {
+ t.Fatalf("result=%+v err=%v", result, err)
+ }
+ runtime.KeepAlive(turn)
+ runtime.KeepAlive(loaded)
+ }
+ requests, err := agent.Requests(ctx)
+ if err != nil || len(requests) != 1 || requests[0].ID != "request-1" {
+ t.Fatalf("requests=%+v err=%v", requests, err)
+ }
+ question, ok := requests[0].Kind.(AgentQuestion)
+ if !ok || question.Text != "continue?" {
+ t.Fatalf("question=%+v", requests[0].Kind)
+ }
+ answer, err := agent.Respond(ctx, requests[0].ID, &AgentAnswer{Text: "yes", Data: json.RawMessage(`{"approved":false,"n":0,"items":[],"child":null}`)}, AgentControlOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer runtime.KeepAlive(answer)
+ result, err := answer.Wait(ctx, AgentWaitOptions{})
+ if err != nil || result.Text != "yes" || string(result.Data) != `{"approved":false,"n":0,"items":[],"child":null}` {
+ t.Fatalf("answer=%+v err=%v", result, err)
+ }
+ denied, err := agent.Respond(ctx, "request-1", AgentPermissionResponse{Approved: false}, AgentControlOptions{})
+ checkAgentError(t, denied, err, ErrInvalidArgument)
+}
+
+func TestAgentOpaqueDataSurvivesNativeCalls(t *testing.T) {
+ _, namespace := testAgents(t, false)
+ agent := testCreateAgent(t, namespace)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ for _, data := range []string{
+ `1e400`, `-1e400`, `9007199254740993`, `-9223372036854775808`, `18446744073709551615`,
+ `{"$serde_json::private::Number":"42"}`,
+ `{"$serde_json::private::Number":"hello"}`,
+ `[{"$serde_json::private::Number":"42"},{"$serde_json::private::Number":"hello"}]`,
+ `0.123456789012345678901`, `[0.123456789012345678901,0.123456789012345678902]`,
+ } {
+ for _, operation := range []string{"send", "respond"} {
+ t.Run(operation+"/"+data, func(t *testing.T) {
+ var turn *AgentTurn
+ var err error
+ if operation == "send" {
+ turn, err = agent.Send(ctx, "echo", AgentSendOptions{Data: json.RawMessage(data)})
+ } else {
+ turn, err = agent.Respond(ctx, "request-1", AgentAnswer{Text: "echo", Data: json.RawMessage(data)}, AgentControlOptions{})
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer runtime.KeepAlive(turn)
+ state, err := turn.State()
+ if err != nil || state == nil || state.Result == nil {
+ t.Fatalf("state: %+v, %v", state, err)
+ }
+ if string(state.Result.Data) != data {
+ t.Fatalf("state payload changed: got %s, want %s", state.Result.Data, data)
+ }
+ loaded, err := agent.GetTurn(ctx, state.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer runtime.KeepAlive(loaded)
+ result, err := loaded.Wait(ctx, AgentWaitOptions{})
+ if err != nil || result == nil {
+ t.Fatalf("wait: %+v, %v", result, err)
+ }
+ if string(result.Data) != data {
+ t.Fatalf("payload changed: got %s, want %s", result.Data, data)
+ }
+ })
+ }
+ }
+}
+
+func TestAgentCoreErrorsAreCopied(t *testing.T) {
+ _, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ missing, err := agent.GetTurn(ctx, "unknown")
+ checkAgentError(t, missing, err, ErrNotFound)
+ if !strings.Contains(err.Error(), "unknown") {
+ t.Fatal(err)
+ }
+ savedError := err
+ turn, err := agent.Send(ctx, "work", AgentSendOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer runtime.KeepAlive(turn)
+ // Repeated failures force borrowed native messages to be allocated and freed.
+ for range 3 {
+ checkAgentError(t, nil, agent.Close(ctx, AgentControlOptions{}), ErrUnsupported)
+ receipt, err := turn.Steer(ctx, "next", AgentControlOptions{})
+ checkAgentError(t, receipt, err, ErrUnsupported)
+ checkAgentError(t, nil, turn.Interrupt(ctx, AgentControlOptions{}), ErrUnsupported)
+ }
+ if !strings.Contains(savedError.Error(), "unknown") {
+ t.Fatal("borrowed error changed after subsequent callbacks", savedError)
+ }
+ state, err := agent.State()
+ if err != nil || state.ID != "agent-1" {
+ t.Fatalf("semantic close invalidated handle: %v", err)
+ }
+}
+
+func TestAgentUninitializedAndReleasedHandles(t *testing.T) {
+ ctx := context.Background()
+ for _, namespace := range []*Agents{nil, {}, {box: &Box{}}} {
+ created, err := namespace.Create(ctx, "test", AgentCreateOptions{})
+ checkAgentError(t, created, err, ErrInvalidState)
+ loaded, err := namespace.Get(ctx, "agent-1")
+ checkAgentError(t, loaded, err, ErrInvalidState)
+ }
+ _, namespace := testAgents(t, false)
+ released := testCreateAgent(t, namespace)
+ released.native.release()
+ defer runtime.KeepAlive(released)
+ for _, agent := range []*Agent{nil, {}, released} {
+ state, err := agent.State()
+ checkAgentError(t, state, err, ErrInvalidState)
+ turn, err := agent.Send(ctx, "work", AgentSendOptions{})
+ checkAgentError(t, turn, err, ErrInvalidState)
+ }
+ for _, turn := range []*AgentTurn{nil, {}} {
+ state, err := turn.State()
+ checkAgentError(t, state, err, ErrInvalidState)
+ result, err := turn.Wait(ctx, AgentWaitOptions{})
+ checkAgentError(t, result, err, ErrInvalidState)
+ }
+}
+
+func TestAgentAdditionalArgumentsFailBeforeDispatch(t *testing.T) {
+ r, namespace := testAgents(t, false)
+ agent := testCreateAgent(t, namespace)
+ ctx := context.Background()
+ turn, err := agent.Send(ctx, "work", AgentSendOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer runtime.KeepAlive(turn)
+ tokens, handles := agentTokenCount(), agentHandleCount(r)
+ cases := []struct {
+ name string
+ call func() error
+ }{
+ {"get nil context", func() error { _, e := namespace.Get(nil, "agent-1"); return e }},
+ {"turn ID NUL", func() error { _, e := agent.GetTurn(ctx, "turn\x00"); return e }},
+ {"response ID NUL", func() error {
+ _, e := agent.Respond(ctx, "request\x00", AgentAnswer{}, AgentControlOptions{})
+ return e
+ }},
+ {"steer UTF8", func() error { _, e := turn.Steer(ctx, string([]byte{255}), AgentControlOptions{}); return e }},
+ {"interrupt key NUL", func() error { return turn.Interrupt(ctx, AgentControlOptions{IdempotencyKey: "key\x00"}) }},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ checkAgentError(t, nil, tc.call(), ErrInvalidArgument)
+ if agentTokenCount() != tokens || agentHandleCount(r) != handles {
+ t.Fatal("invalid argument changed native registrations")
+ }
+ })
+ }
+ canceled, cancel := context.WithCancel(ctx)
+ cancel()
+ result, err := agent.Requests(canceled)
+ if result != nil || !errors.Is(err, context.Canceled) {
+ t.Fatalf("canceled request: %v %v", result, err)
+ }
+}
+
+// Pause the result-side context check after native completion has been received.
+// The first check admits the call; the second lets the test cancel at return.
+type agentResultContext struct {
+ context.Context
+ checks int
+ returning chan struct{}
+ release chan struct{}
+}
+
+func (c *agentResultContext) Err() error {
+ c.checks++
+ if c.checks == 2 {
+ close(c.returning)
+ <-c.release
+ }
+ return c.Context.Err()
+}
+
+func TestAgentCancellationAfterNativeResultReleasesHandle(t *testing.T) {
+ r, namespace := testAgents(t, false)
+ agent := testCreateAgent(t, namespace)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ observed := &agentResultContext{Context: ctx, returning: make(chan struct{}), release: make(chan struct{})}
+ var once sync.Once
+ release := func() { once.Do(func() { close(observed.release) }) }
+ t.Cleanup(release)
+ _, before := testAgentFreeCounts()
+ handles := agentHandleCount(r)
+ completed := make(chan handleResult[*AgentTurn], 1)
+ go func() {
+ turn, err := agent.Send(observed, "work", AgentSendOptions{})
+ completed <- handleResult[*AgentTurn]{value: turn, err: err}
+ }()
+ receiveAgent(t, observed.returning)
+ cancel()
+ release()
+ result := receiveAgent(t, completed)
+ if result.value != nil || !errors.Is(result.err, context.Canceled) {
+ t.Fatalf("canceled result: %v %v", result.value, result.err)
+ }
+ _, after := testAgentFreeCounts()
+ if after-before != 1 || agentHandleCount(r) != handles {
+ t.Fatal("native result survived cancellation at return")
+ }
+}
+
+func TestAgentNativeSynchronousErrorsLeaveNoRegistrations(t *testing.T) {
+ r, namespace := testAgents(t, false)
+ agent := testCreateAgent(t, namespace)
+ tokens, handles := agentTokenCount(), agentHandleCount(r)
+ turn, err := testAgentNativeRejectedSend(context.Background(), agent)
+ checkAgentError(t, turn, err, ErrInvalidArgument)
+ state, err := testAgentNativeRejectedGetter(agent)
+ checkAgentError(t, state, err, ErrInvalidArgument)
+ if agentTokenCount() != tokens || agentHandleCount(r) != handles {
+ t.Fatal("synchronous C rejection leaked a registration")
+ }
+ // A rejected submission does not prevent later successful C/core dispatch.
+ loaded, err := agent.State()
+ if err != nil || loaded.ID != "agent-1" {
+ t.Fatalf("getter after rejection: %+v %v", loaded, err)
+ }
+}
+
+func TestAgentArgumentsFailBeforeDispatch(t *testing.T) {
+ r, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ ctx := context.Background()
+ before := agentTokenCount()
+ handles := agentHandleCount(r)
+ tests := []struct {
+ name string
+ call func() error
+ }{
+ {"name NUL", func() error { _, e := a.Create(ctx, "test\x00suffix", AgentCreateOptions{}); return e }},
+ {"cwd UTF8", func() error { _, e := a.Create(ctx, "test", AgentCreateOptions{Cwd: string([]byte{255})}); return e }},
+ {"config JSON", func() error {
+ _, e := a.Create(ctx, "test", AgentCreateOptions{Config: AgentConfig{Permissions: json.RawMessage("{")}})
+ return e
+ }},
+ {"ID NUL", func() error { _, e := a.Get(ctx, "agent\x00"); return e }},
+ {"mode", func() error { _, e := agent.Send(ctx, "work", AgentSendOptions{Mode: "invalid"}); return e }},
+ {"data JSON", func() error { _, e := agent.Send(ctx, "work", AgentSendOptions{Data: json.RawMessage("{")}); return e }},
+ {"text UTF8", func() error { _, e := agent.Send(ctx, string([]byte{255}), AgentSendOptions{}); return e }},
+ {"key NUL", func() error { return agent.Close(ctx, AgentControlOptions{IdempotencyKey: "k\x00"}) }},
+ {"answer JSON", func() error {
+ _, e := agent.Respond(ctx, "request-1", AgentAnswer{Data: json.RawMessage("{")}, AgentControlOptions{})
+ return e
+ }},
+ {"nil response", func() error {
+ _, e := agent.Respond(ctx, "request-1", (*AgentAnswer)(nil), AgentControlOptions{})
+ return e
+ }},
+ {"nil context", func() error { _, e := agent.Requests(nil); return e }},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ checkAgentError(t, nil, tt.call(), ErrInvalidArgument)
+ if agentTokenCount() != before || agentHandleCount(r) != handles {
+ t.Fatal("invalid input submitted native work")
+ }
+ })
+ }
+ canceled, cancel := context.WithCancel(ctx)
+ cancel()
+ empty := (&Box{}).Agents()
+ result, err := empty.Create(canceled, "test", AgentCreateOptions{})
+ if result != nil || !errors.Is(err, context.Canceled) || empty.native != nil {
+ t.Fatalf("canceled namespace: %v %v", result, err)
+ }
+}
+
+func TestAgentCancelBeforeDispatchFreesLateHandle(t *testing.T) {
+ r, a := testAgents(t, true)
+ before, _ := testAgentFreeCounts()
+ tokens := agentTokenCount()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ done := make(chan error, 1)
+ go func() {
+ value, err := a.Create(ctx, "test", AgentCreateOptions{})
+ if value != nil {
+ err = errors.New("canceled create returned a handle")
+ }
+ done <- err
+ }()
+ if !testAgentWaitPending(r) {
+ t.Fatal("no completion posted")
+ }
+ cancel()
+ if err := receiveAgent(t, done); !errors.Is(err, context.Canceled) {
+ t.Fatal(err)
+ }
+ if testAgentDrain(r) != 1 {
+ t.Fatal("late completion was not dispatched")
+ }
+ after, _ := testAgentFreeCounts()
+ if after-before != 1 || agentHandleCount(r) != 1 || agentTokenCount() != tokens {
+ t.Fatalf("late result leaked: frees=%d handles=%d", after-before, agentHandleCount(r))
+ }
+}
+
+func TestAgentCancelAfterDispatchDisposesBufferedHandle(t *testing.T) {
+ r, a := testAgents(t, true)
+ before, _ := testAgentFreeCounts()
+ tokens := agentTokenCount()
+ result, token, err := testAgentSubmitCreate(a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !testAgentWaitPending(r) || testAgentDrain(r) != 1 {
+ t.Fatal("completion missing")
+ }
+ done := make(chan struct{})
+ abandonOwnedResult(result, token, func(h *agentSession) { h.release(); close(done) })
+ receiveAgent(t, done)
+ after, _ := testAgentFreeCounts()
+ if after-before != 1 || agentHandleCount(r) != 1 || agentTokenCount() != tokens {
+ t.Fatal("buffered completion leaked")
+ }
+}
+
+func TestAgentRuntimeCloseWakesQueuedCall(t *testing.T) {
+ r, a := testAgents(t, true)
+ tokens := agentTokenCount()
+ done := make(chan error, 1)
+ go func() {
+ v, e := a.Create(context.Background(), "test", AgentCreateOptions{})
+ if v != nil {
+ e = errors.New("closed runtime returned a handle")
+ }
+ done <- e
+ }()
+ if !testAgentWaitPending(r) {
+ t.Fatal("completion missing")
+ }
+ r.Close()
+ if err := receiveAgent(t, done); !errors.Is(err, ErrRuntimeClosed) {
+ t.Fatal(err)
+ }
+ if agentHandleCount(r) != 0 || agentTokenCount() != tokens {
+ t.Fatal("close leaked agent resources")
+ }
+ v, e := a.Get(context.Background(), "agent-1")
+ if v != nil || !errors.Is(e, ErrRuntimeClosed) {
+ t.Fatalf("closed namespace: %v %v", v, e)
+ }
+}
+
+func TestAgentCanceledSendFreesOnlyLocalTurn(t *testing.T) {
+ r, a := testAgents(t, true)
+ // First create through the same C queue, under explicit dispatch ownership.
+ created := make(chan handleResult[*Agent], 1)
+ go func() {
+ v, e := a.Create(context.Background(), "test", AgentCreateOptions{})
+ created <- handleResult[*Agent]{value: v, err: e}
+ }()
+ if !testAgentWaitPending(r) || testAgentDrain(r) != 1 {
+ t.Fatal("create completion missing")
+ }
+ result := receiveAgent(t, created)
+ if result.err != nil {
+ t.Fatal(result.err)
+ }
+ agent := result.value
+ defer runtime.KeepAlive(agent)
+ _, before := testAgentFreeCounts()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ done := make(chan error, 1)
+ go func() {
+ v, e := agent.Send(ctx, "still completed", AgentSendOptions{})
+ if v != nil {
+ e = errors.New("canceled send returned a handle")
+ }
+ done <- e
+ }()
+ if !testAgentWaitPending(r) {
+ t.Fatal("send completion missing")
+ }
+ cancel()
+ if e := receiveAgent(t, done); !errors.Is(e, context.Canceled) {
+ t.Fatal(e)
+ }
+ if testAgentDrain(r) != 1 {
+ t.Fatal("late turn completion missing")
+ }
+ _, after := testAgentFreeCounts()
+ if after-before != 1 || agentHandleCount(r) != 2 {
+ t.Fatal("late turn handle leaked")
+ }
+ loaded := make(chan handleResult[*AgentTurn], 1)
+ go func() {
+ v, e := agent.GetTurn(context.Background(), "turn-1")
+ loaded <- handleResult[*AgentTurn]{value: v, err: e}
+ }()
+ if !testAgentWaitPending(r) || testAgentDrain(r) != 1 {
+ t.Fatal("get_turn completion missing")
+ }
+ turn := receiveAgent(t, loaded)
+ if turn.err != nil {
+ t.Fatal(turn.err)
+ }
+ state, err := turn.value.State()
+ if err != nil || state.Status != AgentTurnCompleted || state.Result.Text != "still completed" {
+ t.Fatalf("cancellation stopped core work: %+v %v", state, err)
+ }
+ runtime.KeepAlive(turn.value)
+}
+
+func TestAgentRuntimeCloseSerializesWithGetters(t *testing.T) {
+ r, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ turn, err := agent.Send(context.Background(), "work", AgentSendOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer runtime.KeepAlive(turn)
+ start := make(chan struct{})
+ var wg sync.WaitGroup
+ for range 4 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ for range 20 {
+ _, e := agent.State()
+ if e != nil && !errors.Is(e, ErrRuntimeClosed) {
+ t.Error(e)
+ }
+ }
+ }()
+ }
+ for range 2 {
+ wg.Add(1)
+ go func() { defer wg.Done(); <-start; r.Close() }()
+ }
+ close(start)
+ wg.Wait()
+ state, err := agent.State()
+ if state != nil || !errors.Is(err, ErrRuntimeClosed) {
+ t.Fatalf("state after close: %v %v", state, err)
+ }
+ config, err := agent.Config()
+ if config != nil || !errors.Is(err, ErrRuntimeClosed) {
+ t.Fatal(err)
+ }
+ caps, err := agent.Capabilities()
+ if caps != nil || !errors.Is(err, ErrRuntimeClosed) {
+ t.Fatal(err)
+ }
+ ts, err := turn.State()
+ if ts != nil || !errors.Is(err, ErrRuntimeClosed) {
+ t.Fatal(err)
+ }
+ if agentHandleCount(r) != 0 {
+ t.Fatal("close retained handles")
+ }
+}
+
+func TestAgentRemoteNamespacePropagatesServerNotFound(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet || r.URL.Path != "/v1/boxes/box1" {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, `{"box_id":"box1","name":"service","status":"configured","created_at":"2026-07-14T00:00:00Z","updated_at":"2026-07-14T00:00:00Z","pid":null,"image":"alpine:latest","cpus":1,"memory_mib":256}`)
+ }))
+ defer server.Close()
+ r, err := NewRest(BoxliteRestOptions{URL: server.URL})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer r.Close()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ box, err := r.Get(ctx, "box1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ namespace := box.Agents()
+ if namespace.native != nil {
+ t.Fatal("Agents must be lazy")
+ }
+ agent, err := namespace.Create(ctx, "opencode", AgentCreateOptions{})
+ checkAgentError(t, agent, err, ErrNotFound)
+ if strings.Contains(err.Error(), "not implemented") {
+ t.Fatal("stub error reached caller")
+ }
+ native := namespace.native
+ if native == nil {
+ t.Fatal("C namespace was not acquired")
+ }
+ if err := box.Close(); err != nil {
+ t.Fatal(err)
+ }
+ agent, err = namespace.Get(ctx, "ses_existing")
+ checkAgentError(t, agent, err, ErrNotFound)
+ if namespace.native != native {
+ t.Fatal("namespace did not retain its C handle")
+ }
+ closed := box.Agents()
+ agent, err = closed.Get(ctx, "ses_existing")
+ checkAgentError(t, agent, err, ErrInvalidState)
+}
+
+func TestAgentCancelWaitReleasesOnlyItsObserver(t *testing.T) {
+ _, namespace := testAgents(t, false)
+ agent := testCreateAgent(t, namespace)
+ turn, err := agent.Send(context.Background(), "hold wait observers", AgentSendOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ wait := func(ctx context.Context) <-chan error {
+ done := make(chan error, 1)
+ go func() {
+ result, err := turn.Wait(ctx, AgentWaitOptions{})
+ if err == nil && (result == nil || result.Text != "finish") {
+ err = errors.New("unexpected turn result")
+ }
+ done <- err
+ }()
+ return done
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ a := wait(ctx)
+ b := wait(context.Background())
+ defer func() {
+ _, _ = agent.Respond(context.Background(), "request-1", AgentAnswer{Text: "finish"}, AgentControlOptions{})
+ }()
+ waitForNativeObservers(t, agent, "2")
+ cancel()
+ if err := receiveAgent(t, a); !errors.Is(err, context.Canceled) {
+ t.Fatal(err)
+ }
+ waitForNativeObservers(t, agent, "1")
+ if _, err := agent.Respond(context.Background(), "request-1", AgentAnswer{Text: "finish"}, AgentControlOptions{}); err != nil {
+ t.Fatal(err)
+ }
+ if err := receiveAgent(t, b); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func waitForNativeObservers(t *testing.T, agent *Agent, want string) {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ state, err := agent.State()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if state.Cursor == want {
+ return
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("native wait observers = %s, want %s", state.Cursor, want)
+ }
+ runtime.Gosched()
+ }
+}
+
+func TestAgentWaitTimeoutAndRuntimeClose(t *testing.T) {
+ r, namespace := testAgents(t, false)
+ agent := testCreateAgent(t, namespace)
+ turn, err := agent.Send(context.Background(), "hold wait observers", AgentSendOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ zero := time.Duration(0)
+ result, err := turn.Wait(context.Background(), AgentWaitOptions{Timeout: &zero})
+ checkAgentError(t, result, err, ErrInvalidState)
+ done := make(chan error, 1)
+ go func() { _, err := turn.Wait(context.Background(), AgentWaitOptions{}); done <- err }()
+ waitForNativeObservers(t, agent, "1")
+ if err := r.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if err := receiveAgent(t, done); !errors.Is(err, ErrRuntimeClosed) {
+ t.Fatal(err)
+ }
+}
diff --git a/sdks/go/agents_test.go b/sdks/go/agents_test.go
index c842d061f..e92c4456f 100644
--- a/sdks/go/agents_test.go
+++ b/sdks/go/agents_test.go
@@ -4,63 +4,60 @@ import (
"context"
"errors"
"reflect"
- "strings"
"testing"
)
-func TestAgentsReturnUnsupported(t *testing.T) {
+func checkAgentError(t *testing.T, value any, err error, code ErrorCode) {
+ t.Helper()
+ var typed *Error
+ if !errors.As(err, &typed) || typed.Code != code {
+ t.Fatalf("got %v, %v; want error code %v", value, err, code)
+ }
+ if value != nil && !reflect.ValueOf(value).IsZero() {
+ t.Fatalf("error returned a value: %v", value)
+ }
+}
+
+func TestAgentsRequireNativeHandles(t *testing.T) {
ctx := context.Background()
- // A namespace operation must not touch the absent native Box/runtime.
agents := (&Box{}).Agents()
agent, turn := &Agent{}, &AgentTurn{}
- check := func(name string, value any, err error) {
- t.Helper()
- var typed *Error
- if !errors.As(err, &typed) || typed.Code != ErrUnsupported || !strings.Contains(typed.Message, name+" is not implemented") {
- t.Fatalf("%s returned %v, %v", name, value, err)
- }
- if value != nil && !reflect.ValueOf(value).IsZero() {
- t.Fatalf("%s returned a value with an error: %v", name, value)
- }
- }
- s, err := agents.Create(ctx, "agent", AgentCreateOptions{})
- check("agents.create", s, err)
- s, err = agents.Get(ctx, "agent")
- check("agents.get", s, err)
- check("agent.close", nil, agent.Close(ctx, AgentControlOptions{}))
+ a, err := agents.Create(ctx, "agent", AgentCreateOptions{})
+ checkAgentError(t, a, err, ErrInvalidState)
+ a, err = agents.Get(ctx, "agent")
+ checkAgentError(t, a, err, ErrInvalidState)
+ checkAgentError(t, nil, agent.Close(ctx, AgentControlOptions{}), ErrInvalidState)
for _, mode := range []AgentSendMode{"", AgentSendQueue, AgentSendReject} {
got, err := agent.Send(ctx, "task", AgentSendOptions{Mode: mode})
- check("agent.send", got, err)
+ checkAgentError(t, got, err, ErrInvalidState)
}
got, err := agent.GetTurn(ctx, "turn")
- check("agent.get_turn", got, err)
- events, err := agent.Events(ctx, AgentEventsOptions{After: "cursor"})
- check("agent.events", events, err)
- if events != nil {
- t.Fatal("failed event opening must not return a stream")
- }
+ checkAgentError(t, got, err, ErrInvalidState)
requests, err := agent.Requests(ctx)
- check("agent.requests", requests, err)
+ checkAgentError(t, requests, err, ErrInvalidState)
for _, response := range []AgentResponse{AgentAnswer{Text: "answer"}, AgentPermissionResponse{Approved: false}} {
got, err = agent.Respond(ctx, "request", response, AgentControlOptions{})
- check("agent.respond", got, err)
+ checkAgentError(t, got, err, ErrInvalidState)
}
state, err := agent.State()
- check("agent.state", state, err)
+ checkAgentError(t, state, err, ErrInvalidState)
config, err := agent.Config()
- check("agent.config", config, err)
+ checkAgentError(t, config, err, ErrInvalidState)
capabilities, err := agent.Capabilities()
- check("agent.capabilities", capabilities, err)
+ checkAgentError(t, capabilities, err, ErrInvalidState)
result, err := turn.Wait(ctx, AgentWaitOptions{})
- check("turn.wait", result, err)
- events, err = turn.Events(ctx, AgentEventsOptions{})
- check("turn.events", events, err)
- if events != nil {
- t.Fatal("failed event opening must not return a stream")
- }
+ checkAgentError(t, result, err, ErrInvalidState)
receipt, err := turn.Steer(ctx, "direction", AgentControlOptions{})
- check("turn.steer", receipt, err)
- check("turn.interrupt", nil, turn.Interrupt(ctx, AgentControlOptions{}))
+ checkAgentError(t, receipt, err, ErrInvalidState)
+ checkAgentError(t, nil, turn.Interrupt(ctx, AgentControlOptions{}), ErrInvalidState)
turnState, err := turn.State()
- check("turn.state", turnState, err)
+ checkAgentError(t, turnState, err, ErrInvalidState)
+}
+
+func TestAgentEventsRequireNativeHandles(t *testing.T) {
+ ctx := context.Background()
+ events, err := (&Agent{}).Events(ctx, AgentEventsOptions{})
+ checkAgentError(t, events, err, ErrUnsupported)
+ events, err = (&AgentTurn{}).Events(ctx, AgentEventsOptions{})
+ checkAgentError(t, events, err, ErrUnsupported)
}
diff --git a/sdks/go/runtime.go b/sdks/go/runtime.go
index 9446e7838..2b0b42533 100644
--- a/sdks/go/runtime.go
+++ b/sdks/go/runtime.go
@@ -28,7 +28,11 @@ const drainTimeoutMs = 100
// Runtime manages BoxLite boxes. Create one with NewRuntime.
type Runtime struct {
- handle *C.CBoxliteRuntime
+ handle *C.CBoxliteRuntime
+ closeOnce sync.Once
+ agentMu sync.RWMutex
+ agentClosed bool
+ agentHandles map[agentResource]struct{}
drainMu sync.Mutex
drainOnce sync.Once
@@ -99,23 +103,36 @@ func NewRuntime(opts ...RuntimeOption) (*Runtime, error) {
// Close releases the runtime. Implements io.Closer.
//
-// Order matters: closing the `r.closing` channel first wakes every in-flight
-// async caller that's parked on its result channel. They return
-// ErrRuntimeClosed and release their per-call resources before the drain
-// goroutine and native runtime are stopped.
+// Closing admission wakes pending agent calls before the drainer stops.
+// Native agent handles are released after dispatch joins and before the native
+// runtime is freed; detached cleanup state makes that release idempotent.
func (r *Runtime) Close() error {
- if r.handle == nil {
- return nil
- }
-
- r.closingOnce.Do(func() {
- if r.closing != nil {
- close(r.closing)
+ r.closeOnce.Do(func() {
+ r.agentMu.Lock()
+ r.agentClosed = true
+ r.closingOnce.Do(func() {
+ if r.closing != nil {
+ close(r.closing)
+ }
+ })
+ r.agentMu.Unlock()
+ r.stopDrain()
+ r.agentMu.Lock()
+ handles := make([]agentResource, 0, len(r.agentHandles))
+ for h := range r.agentHandles {
+ handles = append(handles, h)
+ }
+ r.agentMu.Unlock()
+ for _, h := range handles {
+ h.release()
+ }
+ r.agentMu.Lock()
+ if r.handle != nil {
+ C.boxlite_runtime_free(r.handle)
+ r.handle = nil
}
+ r.agentMu.Unlock()
})
- r.stopDrain()
- C.boxlite_runtime_free(r.handle)
- r.handle = nil
return nil
}
diff --git a/sdks/go/test_agents_cgo_support_dev.go b/sdks/go/test_agents_cgo_support_dev.go
new file mode 100644
index 000000000..04fab8a4d
--- /dev/null
+++ b/sdks/go/test_agents_cgo_support_dev.go
@@ -0,0 +1,107 @@
+//go:build boxlite_dev && boxlite_agent_test
+
+package boxlite
+
+/*
+#include "agents_bridge.h"
+#include <stdlib.h>
+BoxliteErrorCode boxlite_test_agents_new(const char*, CBoxliteRuntime**, struct CAgents**, CBoxliteError*);
+bool boxlite_test_agents_wait_pending(CBoxliteRuntime*);
+bool boxlite_test_agents_wait_queue(CBoxliteRuntime*, size_t);
+void boxlite_test_agents_free_counts(size_t*, size_t*);
+*/
+import "C"
+
+import (
+ "context"
+ "runtime"
+ "runtime/cgo"
+ "unsafe"
+)
+
+// Exercise shared call cleanup when C rejects a submission synchronously.
+// Public Send validates the mode in Go before reaching this C boundary.
+func testAgentNativeRejectedSend(ctx context.Context, agent *Agent) (*agentTurnHandle, error) {
+ text := toCString("work")
+ defer C.free(unsafe.Pointer(text))
+ return agentCall[*agentTurnHandle](ctx, agent.native, func(p *C.struct_CAgent, token C.uintptr_t, err *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ opts := C.struct_CAgentSendOptions{mode: 77}
+ return C.go_agent_send(p, text, &opts, token, err)
+ }, func(h *agentTurnHandle) { h.release() })
+}
+
+// A null native argument produces a real C getter error without transferring JSON.
+func testAgentNativeRejectedGetter(agent *Agent) (*AgentState, error) {
+ return agentGetter(agent.native, func(_ *C.struct_CAgent, json **C.char, err *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.boxlite_agent_state(nil, json, err)
+ }, parseAgentState)
+}
+
+// This file is built only by the Go unit target with the C test-support feature.
+func newTestAgentNamespace(home string, manualDrain bool) (*Runtime, *Agents, error) {
+ cHome := toCString(home)
+ defer C.free(unsafe.Pointer(cHome))
+ var ptr *C.CBoxliteRuntime
+ var agents *C.struct_CAgents
+ var cerr C.CBoxliteError
+ if C.boxlite_test_agents_new(cHome, &ptr, &agents, &cerr) != C.Ok {
+ return nil, nil, freeError(&cerr)
+ }
+ r := &Runtime{handle: ptr, closing: make(chan struct{})}
+ if manualDrain {
+ r.drainOnce.Do(func() {})
+ }
+ h, err := adoptAgentHandle(r, agents, func(p *C.struct_CAgents) { C.boxlite_agents_free(p) })
+ if err != nil {
+ r.Close()
+ return nil, nil, err
+ }
+ a := &Agents{native: h}
+ runtime.AddCleanup(a, func(h *agentNamespace) { h.release() }, h)
+ return r, a, nil
+}
+
+func testAgentWaitPending(r *Runtime) bool {
+ r.agentMu.RLock()
+ defer r.agentMu.RUnlock()
+ return C.boxlite_test_agents_wait_pending(r.handle) != false
+}
+func testAgentWaitQueue(r *Runtime, count int) bool {
+ r.agentMu.RLock()
+ defer r.agentMu.RUnlock()
+ return C.boxlite_test_agents_wait_queue(r.handle, C.size_t(count)) != false
+}
+func testAgentDrain(r *Runtime) int {
+ // These tests own the only drainer and call Close after it returns.
+ // Dispatch itself takes admission to adopt returned native handles.
+ return int(C.boxlite_runtime_drain(r.handle, 0, nil))
+}
+func testAgentFreeCounts() (int, int) {
+ var agents, turns C.size_t
+ C.boxlite_test_agents_free_counts(&agents, &turns)
+ return int(agents), int(turns)
+}
+
+// Expose a real buffered native completion to exercise cancellation after dispatch
+// has claimed its cgo token, before the public call consumes the returned handle.
+func testAgentSubmitCreate(a *Agents) (<-chan handleResult[*agentSession], cgo.Handle, error) {
+ h, err := a.namespace()
+ if err != nil {
+ return nil, 0, err
+ }
+ ptr, unlock, err := h.acquire()
+ if err != nil {
+ return nil, 0, err
+ }
+ defer unlock()
+ op := &agentPending[*agentSession]{owner: h.owner, result: make(chan handleResult[*agentSession], 1)}
+ token := registerHandleForDispatch(cgo.NewHandle(op))
+ name := toCString("buffered")
+ defer C.free(unsafe.Pointer(name))
+ var cerr C.CBoxliteError
+ if C.go_agent_create(ptr, name, nil, C.uintptr_t(token), &cerr) != C.Ok {
+ deleteHandleForDispatch(token)
+ return nil, 0, freeError(&cerr)
+ }
+ return op.result, token, nil
+}
diff --git a/sdks/go/testdata/agents.json b/sdks/go/testdata/agents.json
index 2ee4e01ba..b8c1fd606 100644
--- a/sdks/go/testdata/agents.json
+++ b/sdks/go/testdata/agents.json
@@ -6,7 +6,16 @@
"items": [],
"nested": {
"value": null
- }
+ },
+ "numbers": [
+ 9007199254740992,
+ 9007199254740993,
+ -9223372036854775808,
+ 9223372036854775807,
+ 18446744073709551615,
+ 0.123456789012345678901,
+ 0.123456789012345678902
+ ]
},
"text": "yes",
"type": "answer"
@@ -26,6 +35,28 @@
"agent.send"
]
},
+ "capabilities_max": {
+ "idempotency_retention_seconds": 9223372036.854775807,
+ "input_kinds": [
+ "text"
+ ],
+ "max_pending_steering": null,
+ "max_queued_turns": 0,
+ "operations": [
+ "agent.send"
+ ]
+ },
+ "capabilities_overflow": {
+ "idempotency_retention_seconds": 9223372036.854775808,
+ "input_kinds": [
+ "text"
+ ],
+ "max_pending_steering": null,
+ "max_queued_turns": 0,
+ "operations": [
+ "agent.send"
+ ]
+ },
"capabilities_unknown": {
"idempotency_retention_seconds": null,
"input_kinds": [],
@@ -66,7 +97,16 @@
"items": [],
"nested": {
"value": null
- }
+ },
+ "numbers": [
+ 9007199254740992,
+ 9007199254740993,
+ -9223372036854775808,
+ 9223372036854775807,
+ 18446744073709551615,
+ 0.123456789012345678901,
+ 0.123456789012345678902
+ ]
},
"kind": "progress",
"turn_id": null
@@ -78,6 +118,46 @@
"kind": "progress",
"turn_id": null
},
+ "numeric_config": {
+ "limits": [
+ 9007199254740992,
+ 9007199254740993,
+ -9223372036854775808,
+ 9223372036854775807,
+ 18446744073709551615,
+ 0.123456789012345678901,
+ 0.123456789012345678902
+ ],
+ "mcp": [],
+ "output_schema": [
+ 9007199254740992,
+ 9007199254740993,
+ -9223372036854775808,
+ 9223372036854775807,
+ 18446744073709551615,
+ 0.123456789012345678901,
+ 0.123456789012345678902
+ ],
+ "permissions": [
+ 9007199254740992,
+ 9007199254740993,
+ -9223372036854775808,
+ 9223372036854775807,
+ 18446744073709551615,
+ 0.123456789012345678901,
+ 0.123456789012345678902
+ ],
+ "tools": []
+ },
+ "numeric_data": [
+ 9007199254740992,
+ 9007199254740993,
+ -9223372036854775808,
+ 9223372036854775807,
+ 18446744073709551615,
+ 0.123456789012345678901,
+ 0.123456789012345678902
+ ],
"receipt": {
"id": "steer-1",
"status": "applied",
@@ -102,7 +182,16 @@
"items": [],
"nested": {
"value": null
- }
+ },
+ "numbers": [
+ 9007199254740992,
+ 9007199254740993,
+ -9223372036854775808,
+ 9223372036854775807,
+ 18446744073709551615,
+ 0.123456789012345678901,
+ 0.123456789012345678902
+ ]
},
"tool": "shell",
"type": "permission"
@@ -129,7 +218,16 @@
"items": [],
"nested": {
"value": null
- }
+ },
+ "numbers": [
+ 9007199254740992,
+ 9007199254740993,
+ -9223372036854775808,
+ 9223372036854775807,
+ 18446744073709551615,
+ 0.123456789012345678901,
+ 0.123456789012345678902
+ ]
},
"error": null,
"outcome": "answer",
@@ -176,7 +274,16 @@
"items": [],
"nested": {
"value": null
- }
+ },
+ "numbers": [
+ 9007199254740992,
+ 9007199254740993,
+ -9223372036854775808,
+ 9223372036854775807,
+ 18446744073709551615,
+ 0.123456789012345678901,
+ 0.123456789012345678902
+ ]
},
"tool": "shell",
"type": "permission"
@@ -225,7 +332,16 @@
"items": [],
"nested": {
"value": null
- }
+ },
+ "numbers": [
+ 9007199254740992,
+ 9007199254740993,
+ -9223372036854775808,
+ 9223372036854775807,
+ 18446744073709551615,
+ 0.123456789012345678901,
+ 0.123456789012345678902
+ ]
},
"tool": "shell",
"type": "permission"
@@ -241,7 +357,16 @@
"items": [],
"nested": {
"value": null
- }
+ },
+ "numbers": [
+ 9007199254740992,
+ 9007199254740993,
+ -9223372036854775808,
+ 9223372036854775807,
+ 18446744073709551615,
+ 0.123456789012345678901,
+ 0.123456789012345678902
+ ]
},
"error": null,
"outcome": "answer",
diff --git a/sdks/node/Cargo.toml b/sdks/node/Cargo.toml
index 29cf79423..f1c82a269 100644
--- a/sdks/node/Cargo.toml
+++ b/sdks/node/Cargo.toml
@@ -38,3 +38,9 @@ lto = true
strip = true # Strip symbols for smaller binaries
codegen-units = 1
opt-level = 3
+
+# Test-only addon with the real N-API agent classes and a deterministic backend.
+[[example]]
+name = "agent_record_fixture"
+path = "tests/fixtures/agent_record_fixture.rs"
+crate-type = ["cdylib"]
diff --git a/sdks/node/src/agents.rs b/sdks/node/src/agents.rs
index b256878ea..4f18b39ba 100644
--- a/sdks/node/src/agents.rs
+++ b/sdks/node/src/agents.rs
@@ -133,11 +133,21 @@ impl JsAgentEventStream {
return Ok(None);
}
let Some(stream) = guard.as_mut() else {
+ if let StreamState::Failed(error) = &*self.state.borrow() {
+ return Err(napi::Error::from_reason(error.clone()));
+ }
return Ok(None);
};
tokio::select! {
item = stream.next() => match item {
- Some(Ok(event)) => Ok(Some(records::event(&event))),
+ Some(Ok(event)) => match checked_record(records::event(&event)) {
+ Ok(record) => Ok(Some(record)),
+ Err(error) => {
+ *guard = None;
+ self.state.send_replace(StreamState::Failed(error.reason.clone()));
+ Err(error)
+ }
+ },
Some(Err(error)) => { *guard = None; Err(map_err(error)) },
None => { *guard = None; Ok(None) },
},
@@ -245,7 +255,12 @@ impl JsAgent {
Some("reject") => AgentSendMode::Reject,
Some(_) => return Err(invalid("unknown send mode")),
};
- let data = options.remove("data").filter(|value| !value.is_null());
+ let data = options
+ .remove("data")
+ .filter(|value| !value.is_null())
+ .map(|value| serde_json::value::to_raw_value(&value))
+ .transpose()
+ .map_err(|e| invalid(&e.to_string()))?;
let idempotency_key = optional_string(options.remove("idempotencyKey"), "idempotencyKey")?;
no_unknown(options)?;
let turn = self
@@ -283,7 +298,7 @@ impl JsAgent {
#[napi]
pub async fn requests(&self) -> Result<Vec<Value>> {
let requests = self.agent.requests().await.map_err(map_err)?;
- Ok(records::requests(&requests)
+ Ok(checked_record(records::requests(&requests))?
.as_array()
.cloned()
.unwrap_or_default())
@@ -296,7 +311,7 @@ impl JsAgent {
response: Value,
options: Option<Value>,
) -> Result<JsAgentTurn> {
- let response = records::parse_response(response).map_err(map_err)?;
+ let response = records::parse_response(&response.to_string()).map_err(map_err)?;
let turn = self
.agent
.respond(&request_id, response, control_options(options)?)
@@ -307,17 +322,17 @@ impl JsAgent {
#[napi(getter)]
pub fn state(&self) -> Result<Value> {
- Ok(records::agent_state(&self.agent.state().map_err(map_err)?))
+ checked_record(records::agent_state(&self.agent.state().map_err(map_err)?))
}
#[napi(getter)]
pub fn config(&self) -> Result<Value> {
- Ok(records::config(&self.agent.config().map_err(map_err)?))
+ checked_record(records::config(&self.agent.config().map_err(map_err)?))
}
#[napi(getter)]
pub fn capabilities(&self) -> Result<Value> {
- Ok(records::capabilities(
+ checked_record(records::capabilities(
&self.agent.capabilities().map_err(map_err)?,
))
}
@@ -339,13 +354,14 @@ impl JsAgentTurn {
_ => return Err(invalid("invalid timeout")),
};
no_unknown(options)?;
- Ok(records::result(
+ let result = records::result(
&self
.turn
.wait(AgentWaitOptions { timeout })
.await
.map_err(map_err)?,
- ))
+ );
+ native_json_record(&result, 0).and_then(checked_record)
}
#[napi]
@@ -359,7 +375,7 @@ impl JsAgentTurn {
#[napi]
pub async fn steer(&self, text: String, options: Option<Value>) -> Result<Value> {
- Ok(records::receipt(
+ checked_record(records::receipt(
&self
.turn
.steer(&text, control_options(options)?)
@@ -378,7 +394,71 @@ impl JsAgentTurn {
#[napi(getter)]
pub fn state(&self) -> Result<Value> {
- Ok(records::turn_state(&self.turn.state().map_err(map_err)?))
+ let state = records::turn_state(&self.turn.state().map_err(map_err)?);
+ native_json_record(&state, 0).and_then(checked_record)
+ }
+}
+
+// napi 3.16 converts JSON numbers through i64, finite f64, or u64. Its
+// last branch unwraps the u64, so reject unsupported tokens before dispatch.
+fn checked_record(record: Value) -> Result<Value> {
+ fn check(value: &Value, depth: usize) -> Result<()> {
+ if depth > 128 {
+ return Err(invalid("agent record exceeds the N-API JSON depth limit"));
+ }
+ match value {
+ Value::Number(n) if !(n.is_i64() || n.is_f64() || n.is_u64()) => {
+ Err(napi::Error::from_reason(
+ "agent JSON number exceeds the Node binding's numeric range",
+ ))
+ }
+ Value::Number(n) if n.is_f64() && n.as_f64() == Some(0.0) => {
+ let token = n.to_string();
+ let mantissa = token.split(['e', 'E']).next().unwrap_or_default();
+ if mantissa.bytes().any(|b| matches!(b, b'1'..=b'9')) {
+ return Err(napi::Error::from_reason(
+ "nonzero agent JSON number underflows the Node binding's numeric range",
+ ));
+ }
+ Ok(())
+ }
+ Value::Array(items) => items.iter().try_for_each(|item| check(item, depth + 1)),
+ Value::Object(fields) => fields.values().try_for_each(|item| check(item, depth + 1)),
+ _ => Ok(()),
+ }
+ }
+ check(&record, 0)?;
+ Ok(record)
+}
+
+// N-API requires a value tree. Decode JSON objects as literal maps so user keys
+// cannot be mistaken for the arbitrary-precision number marker.
+fn native_json_record(raw: &serde_json::value::RawValue, depth: usize) -> Result<Value> {
+ use serde_json::value::RawValue;
+ if depth > 128 {
+ return Err(invalid("agent record exceeds the N-API JSON depth limit"));
+ }
+ let json = raw.get();
+ let parse_error = |e: serde_json::Error| invalid(&e.to_string());
+ match json.as_bytes()[0] {
+ b'{' => {
+ let fields: std::collections::BTreeMap<String, &RawValue> =
+ serde_json::from_str(json).map_err(parse_error)?;
+ fields
+ .into_iter()
+ .map(|(key, value)| Ok((key, native_json_record(value, depth + 1)?)))
+ .collect::<Result<_>>()
+ .map(Value::Object)
+ }
+ b'[' => {
+ let items: Vec<&RawValue> = serde_json::from_str(json).map_err(parse_error)?;
+ items
+ .into_iter()
+ .map(|item| native_json_record(item, depth + 1))
+ .collect::<Result<_>>()
+ .map(Value::Array)
+ }
+ _ => serde_json::from_str(json).map_err(parse_error),
}
}
diff --git a/sdks/node/src/agents/tests/forwarding.rs b/sdks/node/src/agents/tests/forwarding.rs
index 43551dad0..2843cd25c 100644
--- a/sdks/node/src/agents/tests/forwarding.rs
+++ b/sdks/node/src/agents/tests/forwarding.rs
@@ -80,6 +80,43 @@ fn agent_bindings_forward_to_core_test_backend() {
.await
.unwrap();
assert_eq!(reply.wait(None).await.unwrap()["text"], "yes");
+ let payload = json!([{"$serde_json::private::Number":"hello"}]);
+ let turn = agent
+ .send("echo".into(), Some(json!({"data": payload})))
+ .await
+ .unwrap();
+ assert_eq!(turn.wait(None).await.unwrap()["data"], payload);
+ assert_eq!(turn.state().unwrap()["result"]["data"], payload);
+ for token in [
+ "18446744073709551615",
+ "-9223372036854775808",
+ "0.125",
+ "0e-999",
+ "5e-324",
+ ] {
+ let payload: Value = serde_json::from_str(token).unwrap();
+ let turn = agent
+ .send("echo".into(), Some(json!({"data":payload})))
+ .await
+ .unwrap();
+ assert_eq!(turn.wait(None).await.unwrap()["data"], payload);
+ }
+ for token in [
+ "18446744073709551616",
+ "-9223372036854775809",
+ "1e400",
+ "1e-999",
+ "-1e-999",
+ ] {
+ let options =
+ serde_json::from_str(&format!(r#"{{"data":[{{"n":{token}}}]}}"#)).unwrap();
+ let turn = agent.send("echo".into(), Some(options)).await.unwrap();
+ assert!(
+ turn.wait(None).await.is_err(),
+ "wait exposed {token} to N-API"
+ );
+ assert!(turn.state().is_err(), "turn state exposed {token} to N-API");
+ }
assert!(
agent
.send("bad".into(), Some(json!({"mode":"bad"})))
@@ -134,3 +171,21 @@ fn agent_bindings_forward_to_core_test_backend() {
let _ = std::fs::remove_dir_all(home);
});
}
+
+#[tokio::test]
+async fn agent_stream_keeps_conversion_failure_on_retry() {
+ let stream = JsAgentEventStream::start(async {
+ let events = ["1e400", "1"].map(|token| {
+ Ok(boxlite::agents::AgentEvent {
+ cursor: None,
+ agent_id: "test".into(),
+ turn_id: None,
+ kind: "data".into(),
+ data: serde_json::from_str(token).unwrap(),
+ })
+ });
+ Ok(Box::pin(futures::stream::iter(events)) as AgentEventStream)
+ });
+ let first = stream.next_event().await.unwrap_err();
+ assert_eq!(stream.next_event().await.unwrap_err().reason, first.reason);
+}
diff --git a/sdks/node/tests/agent-native-numbers.test.ts b/sdks/node/tests/agent-native-numbers.test.ts
new file mode 100644
index 000000000..cd5a3a66d
--- /dev/null
+++ b/sdks/node/tests/agent-native-numbers.test.ts
@@ -0,0 +1,50 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { expect, test } from "vitest";
+import { wrapAgents, type NativeAgents } from "../lib/agents.js";
+
+const directory = process.env.BOXLITE_AGENT_FIXTURE_DIR;
+
+test.skipIf(!directory)(
+ "agent numbers cross the native JavaScript boundary",
+ async () => {
+ const library =
+ process.platform === "darwin"
+ ? "libagent_record_fixture.dylib"
+ : process.platform === "win32"
+ ? "agent_record_fixture.dll"
+ : "libagent_record_fixture.so";
+ const addon = { exports: {} };
+ process.dlopen(addon, join(directory!, library));
+ const { seedAgent } = addon.exports as {
+ seedAgent: (
+ home: string,
+ token: string,
+ ) => ReturnType<NativeAgents["get"]>;
+ };
+ const home = mkdtempSync(join(tmpdir(), "boxlite-js-agent-"));
+ try {
+ for (const [index, token] of [
+ "18446744073709551616",
+ "1e-999",
+ "0.125",
+ ].entries()) {
+ const agent = await seedAgent(join(home, String(index)), token);
+ const namespace = wrapAgents({
+ get: async () => agent,
+ create: async () => agent,
+ });
+ const turn = await (await namespace.get("agent-1")).getTurn("turn-1");
+ if (token === "0.125") {
+ expect((await turn.wait()).data).toBe(0.125);
+ } else {
+ await expect(turn.wait()).rejects.toThrow(/numeric range/);
+ expect(() => turn.state).toThrow(/numeric range/);
+ }
+ }
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ },
+);
diff --git a/sdks/node/tests/fixtures/agent_record_fixture.rs b/sdks/node/tests/fixtures/agent_record_fixture.rs
new file mode 100644
index 000000000..967877d80
--- /dev/null
+++ b/sdks/node/tests/fixtures/agent_record_fixture.rs
@@ -0,0 +1,37 @@
+#[path = "../../src/agents.rs"]
+mod agents;
+#[path = "../../src/util.rs"]
+mod util;
+
+use agents::{JsAgent, JsAgents};
+use boxlite::{BoxOptions, BoxliteOptions, BoxliteRuntime, RootfsSpec};
+use napi_derive::napi;
+
+/// Seed the backend on the Rust side, before JavaScript can round the token.
+#[napi]
+pub async fn seed_agent(home: String, token: String) -> napi::Result<JsAgent> {
+ let runtime = BoxliteRuntime::new_for_test(BoxliteOptions {
+ home_dir: home.into(),
+ ..Default::default()
+ })
+ .map_err(util::map_err)?;
+ let sandbox = runtime
+ .create(
+ BoxOptions {
+ rootfs: RootfsSpec::Image("alpine:latest".into()),
+ ..Default::default()
+ },
+ None,
+ )
+ .await
+ .map_err(util::map_err)?;
+ let agent = JsAgents::from_core(sandbox.agents().with_test_backend())
+ .create("test".into(), None)
+ .await?;
+ let data: serde_json::Value =
+ serde_json::from_str(&token).map_err(|e| napi::Error::from_reason(e.to_string()))?;
+ agent
+ .send("echo".into(), Some(serde_json::json!({"data":data})))
+ .await?;
+ Ok(agent)
+}
diff --git a/sdks/python/src/agents.rs b/sdks/python/src/agents.rs
index 7fb150bf3..5bfb0707e 100644
--- a/sdks/python/src/agents.rs
+++ b/sdks/python/src/agents.rs
@@ -153,7 +153,8 @@ impl PyAgent {
))));
}
};
- let data = json(&data)?;
+ let data = serde_json::from_str(&data)
+ .map_err(|e| map_err(boxlite::BoxliteError::InvalidArgument(e.to_string())))?;
let agent = self.agent.clone();
pyo3_async_runtimes::tokio::future_into_py(py, async move {
let turn = agent
@@ -161,7 +162,7 @@ impl PyAgent {
&text,
AgentSendOptions {
mode,
- data: if data.is_null() { None } else { Some(data) },
+ data,
idempotency_key: key,
},
)
@@ -194,7 +195,7 @@ impl PyAgent {
response: String,
key: Option<String>,
) -> PyResult<Bound<'py, PyAny>> {
- let response = records::parse_response(json(&response)?).map_err(map_err)?;
+ let response = records::parse_response(&response).map_err(map_err)?;
let agent = self.agent.clone();
pyo3_async_runtimes::tokio::future_into_py(py, async move {
Ok(PyAgentTurn {
diff --git a/sdks/python/src/agents/tests/forwarding.rs b/sdks/python/src/agents/tests/forwarding.rs
index ea6219976..5549113ff 100644
--- a/sdks/python/src/agents/tests/forwarding.rs
+++ b/sdks/python/src/agents/tests/forwarding.rs
@@ -49,6 +49,16 @@ async def main():
assert json.loads(await agent.requests())[0]['id'] == 'request-1'
reply = await agent.respond('request-1', '{"type":"answer","text":"yes"}', None)
assert json.loads(await reply.wait(None))['text'] == 'yes'
+ payload = '[9007199254740993,1e400,-1e400]'
+ answer = '{"type":"answer","text":"echo","data":' + payload + '}'
+ for observed in (await agent.send('echo', 'queue', payload, None),
+ await agent.respond('request-1', answer, None)):
+ for record in (await observed.wait(None), observed.state):
+ data = json.loads(record, parse_int=str, parse_float=str)
+ if 'result' in data:
+ data = data['result']
+ assert data['data'] == ['9007199254740993', '1e400', '-1e400']
+
for operation, error in (
(lambda: agent.send('bad', 'bad', 'null', None), InvalidArgumentError),
(lambda: agent.send('bad', 'queue', '{', None), InvalidArgumentError),
diff --git a/src/boxlite/Cargo.toml b/src/boxlite/Cargo.toml
index 07204c68f..c0f517503 100644
--- a/src/boxlite/Cargo.toml
+++ b/src/boxlite/Cargo.toml
@@ -45,7 +45,7 @@ serde = { version = "1.0", features = ["derive"] }
dirs = "5.0"
tokio = { version = "1.37", features = ["rt", "rt-multi-thread", "macros", "sync", "net", "time", "process", "io-util", "signal"] }
tokio-util = "0.7"
-serde_json = "1.0"
+serde_json = { version = "1.0", features = ["arbitrary_precision", "raw_value"] }
futures = "0.3"
async-stream = "0.3"
tonic = "0.12"
diff --git a/src/boxlite/src/agents/opencode/mod.rs b/src/boxlite/src/agents/opencode/mod.rs
index a90752370..d44f895f4 100644
--- a/src/boxlite/src/agents/opencode/mod.rs
+++ b/src/boxlite/src/agents/opencode/mod.rs
@@ -933,7 +933,13 @@ fn prompt_body(turn_id: &str, text: &str, options: &AgentSendOptions) -> Boxlite
&[
("idempotency_key", options.idempotency_key.is_some()),
("mode reject", options.mode == AgentSendMode::Reject),
- ("data", is_present(&options.data)),
+ (
+ "data",
+ options
+ .data
+ .as_ref()
+ .is_some_and(|data| data.get() != "null"),
+ ),
],
)?;
Ok(json!({ "id": turn_id, "text": text, "delivery": "queue" }))
diff --git a/src/boxlite/src/agents/records.rs b/src/boxlite/src/agents/records.rs
index a92b13075..73125d698 100644
--- a/src/boxlite/src/agents/records.rs
+++ b/src/boxlite/src/agents/records.rs
@@ -4,12 +4,13 @@
//! `docs/reference/agents.md`.
use super::{
- AgentCapabilities, AgentConfig, AgentEvent, AgentOutcome, AgentRequest, AgentRequestKind,
- AgentResponse, AgentResult, AgentState, AgentStatus, AgentSteeringReceipt, AgentSteeringStatus,
+ AgentCapabilities, AgentConfig, AgentEvent, AgentRequest, AgentRequestKind, AgentResponse,
+ AgentResult, AgentState, AgentStatus, AgentSteeringReceipt, AgentSteeringStatus,
AgentTurnState, AgentTurnStatus,
};
use crate::{BoxliteError, BoxliteResult};
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
+use serde_json::value::{RawValue, to_raw_value};
use serde_json::{Value, json};
pub fn agent_state(state: &AgentState) -> Value {
@@ -24,29 +25,31 @@ pub fn agent_state(state: &AgentState) -> Value {
})
}
-pub fn turn_state(state: &AgentTurnState) -> Value {
- json!({
- "id": state.id,
- "agent_id": state.agent_id,
- "status": turn_status(state.status),
- "cursor": state.cursor,
- "result": state.result.as_ref().map(result),
- "requests": requests(&state.requests),
- "steering": state.steering.iter().map(receipt).collect::<Vec<_>>(),
+pub fn turn_state(state: &AgentTurnState) -> Box<RawValue> {
+ #[derive(Serialize)]
+ struct Record<'a> {
+ id: &'a str,
+ agent_id: &'a str,
+ status: AgentTurnStatus,
+ cursor: Option<&'a str>,
+ result: Option<&'a AgentResult>,
+ requests: Value,
+ steering: Vec<Value>,
+ }
+ to_raw_value(&Record {
+ id: &state.id,
+ agent_id: &state.agent_id,
+ status: state.status,
+ cursor: state.cursor.as_deref(),
+ result: state.result.as_ref(),
+ requests: requests(&state.requests),
+ steering: state.steering.iter().map(receipt).collect(),
})
+ .expect("agent turn fields are JSON-serializable")
}
-pub fn result(result: &AgentResult) -> Value {
- json!({
- "turn_id": result.turn_id,
- "status": turn_status(result.status),
- "outcome": result.outcome.map(outcome_name),
- "text": result.text,
- "data": result.data,
- "artifacts": result.artifacts,
- "usage": result.usage,
- "error": result.error,
- })
+pub fn result(result: &AgentResult) -> Box<RawValue> {
+ to_raw_value(result).expect("agent result fields are JSON-serializable")
}
pub fn receipt(receipt: &AgentSteeringReceipt) -> Value {
@@ -97,7 +100,13 @@ pub fn capabilities(capabilities: &AgentCapabilities) -> Value {
"max_queued_turns": capabilities.max_queued_turns,
"max_pending_steering": capabilities.max_pending_steering,
"idempotency_retention_seconds":
- capabilities.idempotency_retention.map(|retention| retention.as_secs_f64()),
+ capabilities.idempotency_retention.map(|retention| {
+ // Keep nanoseconds exact even beyond f64's integer precision.
+ let seconds = format!("{}.{:09}", retention.as_secs(), retention.subsec_nanos());
+ seconds.trim_end_matches('0').trim_end_matches('.')
+ .parse::<serde_json::Number>()
+ .expect("integer seconds and nanoseconds form a valid JSON number")
+ }),
})
}
@@ -142,19 +151,47 @@ pub fn parse_config(value: Value) -> BoxliteResult<AgentConfig> {
}
/// Parse the `respond` argument: an answer or a permission decision.
-pub fn parse_response(value: Value) -> BoxliteResult<AgentResponse> {
+pub fn parse_response(json: &str) -> BoxliteResult<AgentResponse> {
#[derive(Deserialize)]
- #[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
- enum ResponseRecord {
- Answer { text: String, data: Option<Value> },
- Permission { approved: bool },
+ #[serde(rename_all = "snake_case")]
+ enum Kind {
+ Answer,
+ Permission,
+ }
+ #[derive(Deserialize)]
+ struct Tag {
+ #[serde(rename = "type")]
+ kind: Kind,
+ }
+
+ #[derive(Deserialize)]
+ #[serde(deny_unknown_fields)]
+ struct Answer {
+ #[serde(rename = "type")]
+ _kind: Kind,
+ text: String,
+ data: Option<Box<RawValue>>,
+ }
+ #[derive(Deserialize)]
+ #[serde(deny_unknown_fields)]
+ struct Permission {
+ #[serde(rename = "type")]
+ _kind: Kind,
+ approved: bool,
+ }
+ let invalid = |e| BoxliteError::InvalidArgument(format!("response: {e}"));
+ // Internally tagged enums buffer the payload before selecting the variant.
+ // Read the tag first so the selected record can borrow its original JSON input.
+ match serde_json::from_str::<Tag>(json).map_err(invalid)?.kind {
+ Kind::Answer => {
+ let Answer { text, data, .. } = serde_json::from_str(json).map_err(invalid)?;
+ Ok(AgentResponse::Answer { text, data })
+ }
+ Kind::Permission => {
+ let Permission { approved, .. } = serde_json::from_str(json).map_err(invalid)?;
+ Ok(AgentResponse::Permission { approved })
+ }
}
- let record: ResponseRecord = serde_json::from_value(value)
- .map_err(|error| BoxliteError::InvalidArgument(format!("response: {error}")))?;
- Ok(match record {
- ResponseRecord::Answer { text, data } => AgentResponse::Answer { text, data },
- ResponseRecord::Permission { approved } => AgentResponse::Permission { approved },
- })
}
macro_rules! record_enum {
@@ -173,19 +210,24 @@ 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",
-});
+#[cfg(feature = "rest")]
+fn parse_turn_status(value: &str) -> BoxliteResult<super::AgentTurnStatus> {
+ super::AgentTurnStatus::deserialize(
+ serde::de::value::StrDeserializer::<serde::de::value::Error>::new(value),
+ )
+ .map_err(|_| invalid("turn status", value))
+}
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")]
+fn parse_outcome(value: &str) -> BoxliteResult<super::AgentOutcome> {
+ super::AgentOutcome::deserialize(
+ serde::de::value::StrDeserializer::<serde::de::value::Error>::new(value),
+ )
+ .map_err(|_| invalid("outcome", value))
+}
#[cfg(feature = "rest")]
#[derive(Deserialize)]
@@ -291,7 +333,7 @@ pub(super) struct ResultRecord {
pub(super) status: String,
pub(super) outcome: Option<String>,
pub(super) text: Option<String>,
- pub(super) data: Option<Value>,
+ pub(super) data: Option<Box<RawValue>>,
pub(super) artifacts: Vec<String>,
pub(super) usage: Option<Value>,
pub(super) error: Option<String>,
diff --git a/src/boxlite/src/agents/records/tests/rest.rs b/src/boxlite/src/agents/records/tests/rest.rs
index d661823e6..71cafc3ff 100644
--- a/src/boxlite/src/agents/records/tests/rest.rs
+++ b/src/boxlite/src/agents/records/tests/rest.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::agents::AgentOutcome;
fn sample_turn(status: AgentTurnStatus) -> AgentTurnState {
AgentTurnState {
@@ -11,7 +12,9 @@ fn sample_turn(status: AgentTurnStatus) -> AgentTurnState {
status,
outcome: Some(AgentOutcome::Question),
text: Some("answer".into()),
- data: Some(json!({"nested": null})),
+ data: Some(
+ RawValue::from_string(r#"{ "nested": null, "big": 1e400 }"#.into()).unwrap(),
+ ),
artifacts: vec!["file".into()],
usage: Some(json!({"tokens": 1})),
error: None,
@@ -46,7 +49,10 @@ fn shared_enum_mappings_are_bidirectional_and_reject_unknown_values() {
);
}
for value in [AgentOutcome::Answer, AgentOutcome::Question] {
- assert_eq!(parse_outcome(outcome_name(value)).unwrap(), value);
+ assert_eq!(
+ parse_outcome(serde_json::to_value(value).unwrap().as_str().unwrap()).unwrap(),
+ value
+ );
}
assert!(parse_agent_status("invalid").is_err());
assert!(parse_turn_status("invalid").is_err());
@@ -68,11 +74,11 @@ fn shared_records_round_trip_turns_and_nested_values() {
] {
let original = sample_turn(status);
let encoded = turn_state(&original);
- let decoded: AgentTurnState = serde_json::from_value::<Turn>(encoded.clone())
+ let decoded: AgentTurnState = serde_json::from_str::<Turn>(encoded.get())
.unwrap()
.try_into()
.unwrap();
- assert_eq!(turn_state(&decoded), encoded);
+ assert_eq!(turn_state(&decoded).get(), encoded.get());
}
}
@@ -122,10 +128,13 @@ fn turn_decoders_reject_invalid_enum_values() {
("/result/outcome", "outcome"),
("/steering/0/status", "steering status"),
] {
- let mut wire = turn_state(&sample_turn(AgentTurnStatus::Running));
+ let mut wire: Value =
+ serde_json::from_str(turn_state(&sample_turn(AgentTurnStatus::Running)).get()).unwrap();
*wire.pointer_mut(path).unwrap() = json!("not-an-enum-value");
let decoded: BoxliteResult<AgentTurnState> =
- serde_json::from_value::<Turn>(wire).unwrap().try_into();
+ serde_json::from_str::<Turn>(&wire.to_string())
+ .unwrap()
+ .try_into();
assert!(decoded.unwrap_err().to_string().contains(field), "{path}");
}
}
@@ -137,10 +146,13 @@ fn turn_decoders_reject_mismatched_child_ids() {
"/requests/0/turn_id",
"/steering/0/turn_id",
] {
- let mut wire = turn_state(&sample_turn(AgentTurnStatus::Running));
+ let mut wire: Value =
+ serde_json::from_str(turn_state(&sample_turn(AgentTurnStatus::Running)).get()).unwrap();
*wire.pointer_mut(path).unwrap() = json!("another-turn");
let decoded: BoxliteResult<AgentTurnState> =
- serde_json::from_value::<Turn>(wire).unwrap().try_into();
+ serde_json::from_str::<Turn>(&wire.to_string())
+ .unwrap()
+ .try_into();
assert!(
decoded
.unwrap_err()
@@ -158,11 +170,11 @@ fn turn_decoders_accept_absent_result_and_empty_children() {
original.requests.clear();
original.steering.clear();
let wire = turn_state(&original);
- let decoded: AgentTurnState = serde_json::from_value::<Turn>(wire.clone())
+ let decoded: AgentTurnState = serde_json::from_str::<Turn>(wire.get())
.unwrap()
.try_into()
.unwrap();
- assert_eq!(turn_state(&decoded), wire);
+ assert_eq!(turn_state(&decoded).get(), wire.get());
}
#[test]
diff --git a/src/boxlite/src/agents/rest.rs b/src/boxlite/src/agents/rest.rs
index e70b1e3ae..0239faa9c 100644
--- a/src/boxlite/src/agents/rest.rs
+++ b/src/boxlite/src/agents/rest.rs
@@ -157,17 +157,25 @@ impl AgentBackend for RestAgent {
.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()));
+ #[derive(serde::Serialize)]
+ struct Options<'a> {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ mode: Option<&'static str>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ data: Option<&'a serde_json::value::RawValue>,
}
- 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);
+ #[derive(serde::Serialize)]
+ struct Send<'a> {
+ text: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ options: Option<Options<'a>>,
}
+ let mode = (options.mode == AgentSendMode::Reject).then_some("reject");
+ let data = options.data.as_deref();
+ let body = Send {
+ text,
+ options: (mode.is_some() || data.is_some()).then_some(Options { mode, data }),
+ };
let result: Turn = self
.client
.post_agent(
@@ -208,24 +216,16 @@ impl AgentBackend for RestAgent {
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})
- }
- };
+ #[derive(serde::Serialize)]
+ struct Respond {
+ response: AgentResponse,
+ }
let path = format!("{}/requests/{}/respond", self.path, segment(request_id)?);
let result: Turn = self
.client
.post_agent(
&path,
- &serde_json::json!({"response": response}),
+ &Respond { response },
options.idempotency_key.as_deref(),
)
.await?;
diff --git a/src/boxlite/src/agents/test_support.rs b/src/boxlite/src/agents/test_support.rs
index 1ac33eeb5..51d3538b5 100644
--- a/src/boxlite/src/agents/test_support.rs
+++ b/src/boxlite/src/agents/test_support.rs
@@ -6,11 +6,16 @@ use std::sync::Mutex;
#[derive(Debug, Default)]
pub(super) struct TestBackend {
config: AgentConfig,
+ wait_gate: tokio::sync::watch::Sender<bool>,
turn: Mutex<Option<AgentTurnState>>,
}
impl TestBackend {
- fn complete(&self, text: &str) -> AgentTurnState {
+ fn complete(
+ &self,
+ text: &str,
+ data: Option<Box<serde_json::value::RawValue>>,
+ ) -> AgentTurnState {
let state = AgentTurnState {
id: "turn-1".into(),
agent_id: "agent-1".into(),
@@ -21,7 +26,7 @@ impl TestBackend {
status: AgentTurnStatus::Completed,
outcome: Some(AgentOutcome::Answer),
text: Some(text.into()),
- data: None,
+ data,
artifacts: vec![],
usage: None,
error: None,
@@ -61,17 +66,28 @@ impl AgentBackend for TestBackend {
Ok(AgentState {
id: self.id().into(),
status: AgentStatus::Ready,
- cursor: None,
+ cursor: (*self.wait_gate.borrow()).then(|| self.wait_gate.receiver_count().to_string()),
active_turn_id: None,
queued_turn_ids: vec![],
requests: vec![],
steering: vec![],
})
}
- async fn send(&self, text: &str, _: &AgentSendOptions) -> BoxliteResult<AgentTurnState> {
- Ok(self.complete(text))
+ async fn send(&self, text: &str, options: &AgentSendOptions) -> BoxliteResult<AgentTurnState> {
+ let mut state = self.complete(text, options.data.clone());
+ if text == "hold wait observers" {
+ state.status = AgentTurnStatus::Running;
+ state.result = None;
+ *self.turn.lock().unwrap() = Some(state.clone());
+ self.wait_gate.send_replace(true);
+ }
+ Ok(state)
}
async fn turn(&self, id: &str) -> BoxliteResult<AgentTurnState> {
+ let mut gate = self.wait_gate.subscribe();
+ gate.wait_for(|held| !held)
+ .await
+ .expect("backend owns sender");
self.turn
.lock()
.unwrap()
@@ -96,7 +112,11 @@ impl AgentBackend for TestBackend {
_: &AgentControlOptions,
) -> BoxliteResult<AgentTurnState> {
match (id, response) {
- ("request-1", AgentResponse::Answer { text, .. }) => Ok(self.complete(&text)),
+ ("request-1", AgentResponse::Answer { text, data }) => {
+ let state = self.complete(&text, data);
+ self.wait_gate.send_replace(false);
+ Ok(state)
+ }
_ => Err(BoxliteError::InvalidArgument(
"expected answer to request-1".into(),
)),
diff --git a/src/boxlite/src/agents/tests/go_records.rs b/src/boxlite/src/agents/tests/go_records.rs
index 7040965e8..ba4d66e57 100644
--- a/src/boxlite/src/agents/tests/go_records.rs
+++ b/src/boxlite/src/agents/tests/go_records.rs
@@ -1,9 +1,79 @@
use super::*;
use serde_json::json;
+const NUMERIC_DATA: &str = r#"[9007199254740992,9007199254740993,-9223372036854775808,9223372036854775807,18446744073709551615,0.123456789012345678901,0.123456789012345678902]"#;
+
+#[test]
+fn opaque_agent_numbers_round_trip() {
+ let config = records::parse_config(
+ serde_json::from_str(&format!(r#"{{"limits":{NUMERIC_DATA}}}"#)).unwrap(),
+ )
+ .unwrap();
+ assert_eq!(records::config(&config)["limits"].to_string(), NUMERIC_DATA);
+ let response = records::parse_response(&format!(
+ r#"{{"type":"answer","text":"yes","data":{NUMERIC_DATA}}}"#
+ ))
+ .unwrap();
+ let AgentResponse::Answer {
+ data: Some(data), ..
+ } = response
+ else {
+ panic!("expected answer data")
+ };
+ assert_eq!(data.to_string(), NUMERIC_DATA);
+}
+
+#[test]
+fn capabilities_retention_preserves_nanoseconds() {
+ for (duration, expected) in [
+ (
+ Duration::from_nanos(i64::MAX as u64),
+ "9223372036.854775807",
+ ),
+ (Duration::ZERO, "0"),
+ (Duration::from_nanos(1), "0.000000001"),
+ (Duration::from_millis(1500), "1.5"),
+ (
+ Duration::from_nanos(9_007_199_254_740_991),
+ "9007199.254740991",
+ ),
+ (
+ Duration::from_nanos(9_007_199_254_740_992),
+ "9007199.254740992",
+ ),
+ (
+ Duration::from_nanos(9_007_199_254_740_993),
+ "9007199.254740993",
+ ),
+ (
+ Duration::from_nanos(i64::MAX as u64 - 1),
+ "9223372036.854775806",
+ ),
+ (
+ Duration::from_nanos(i64::MAX as u64 + 1),
+ "9223372036.854775808",
+ ),
+ (Duration::MAX, "18446744073709551615.999999999"),
+ ] {
+ let capabilities = AgentCapabilities {
+ operations: vec![],
+ input_kinds: vec![],
+ max_queued_turns: None,
+ max_pending_steering: None,
+ idempotency_retention: Some(duration),
+ };
+ assert_eq!(
+ records::capabilities(&capabilities)["idempotency_retention_seconds"].to_string(),
+ expected,
+ "duration {duration:?} must retain its nanoseconds in the JSON number"
+ );
+ }
+}
+
#[test]
fn go_json_fixture_matches_core_records() {
- let data = json!({"enabled": false, "count": 0, "items": [], "nested": {"value": null}});
+ let numeric_data: serde_json::Value = serde_json::from_str(NUMERIC_DATA).unwrap();
+ let data = json!({"enabled": false, "count": 0, "items": [], "nested": {"value": null}, "numbers": numeric_data});
let requests = vec![
AgentRequest {
id: "question-1".into(),
@@ -32,7 +102,7 @@ fn go_json_fixture_matches_core_records() {
status: AgentTurnStatus::Completed,
outcome: Some(AgentOutcome::Answer),
text: Some("done".into()),
- data: Some(data.clone()),
+ data: Some(serde_json::value::to_raw_value(&data).unwrap()),
artifacts: vec![],
usage: Some(json!({"tokens": 0})),
error: None,
@@ -107,6 +177,18 @@ fn go_json_fixture_matches_core_records() {
max_pending_steering: None,
idempotency_retention: None,
};
+ let max_capabilities = AgentCapabilities {
+ idempotency_retention: Some(Duration::from_nanos(i64::MAX as u64)),
+ ..capabilities.clone()
+ };
+ let overflow_capabilities = AgentCapabilities {
+ idempotency_retention: Some(Duration::from_nanos(i64::MAX as u64 + 1)),
+ ..capabilities.clone()
+ };
+ let numeric_config = records::parse_config(json!({
+ "limits": numeric_data, "permissions": numeric_data, "output_schema": numeric_data,
+ }))
+ .unwrap();
let event = AgentEvent {
cursor: None,
agent_id: "agent-1".into(),
@@ -130,18 +212,21 @@ fn go_json_fixture_matches_core_records() {
let denial = json!({"type": "permission", "approved": false});
let approval = json!({"type": "permission", "approved": true});
assert!(matches!(
- records::parse_response(answer.clone()).unwrap(),
+ records::parse_response(&answer.to_string()).unwrap(),
AgentResponse::Answer { .. }
));
assert!(matches!(
- records::parse_response(denial.clone()).unwrap(),
+ records::parse_response(&denial.to_string()).unwrap(),
AgentResponse::Permission { approved: false }
));
assert!(matches!(
- records::parse_response(approval.clone()).unwrap(),
+ records::parse_response(&approval.to_string()).unwrap(),
AgentResponse::Permission { approved: true }
));
let fixture = json!({
+ "numeric_data": numeric_data, "numeric_config": records::config(&numeric_config),
+ "capabilities_max": records::capabilities(&max_capabilities),
+ "capabilities_overflow": records::capabilities(&overflow_capabilities),
"config": records::config(&config), "config_default": records::config(&AgentConfig::default()),
"capabilities": records::capabilities(&capabilities), "capabilities_unknown": records::capabilities(&unknown_capabilities),
"state": records::agent_state(&state), "state_empty": records::agent_state(&empty_state),
diff --git a/src/boxlite/src/agents/tests/mod.rs b/src/boxlite/src/agents/tests/mod.rs
index 8d06f2591..f32364872 100644
--- a/src/boxlite/src/agents/tests/mod.rs
+++ b/src/boxlite/src/agents/tests/mod.rs
@@ -131,7 +131,7 @@ async fn unsupported_operations_fail_before_reaching_the_box() {
..Default::default()
},
AgentSendOptions {
- data: Some(serde_json::json!({ "k": 1 })),
+ data: Some(serde_json::value::to_raw_value(&serde_json::json!({ "k": 1 })).unwrap()),
..Default::default()
},
AgentSendOptions {
@@ -155,7 +155,7 @@ async fn unsupported_operations_fail_before_reaching_the_box() {
async fn null_send_data_means_no_data() {
let agent = offline_agent();
let options = AgentSendOptions {
- data: Some(serde_json::Value::Null),
+ data: Some(serde_json::value::RawValue::NULL.to_owned()),
..Default::default()
};
// Validation accepts null, so the call proceeds to the Box and hits the test network.
@@ -249,7 +249,7 @@ fn agents_records_use_documented_json_shapes() {
steering: vec![],
};
assert_eq!(
- records::turn_state(&turn),
+ serde_json::from_str::<serde_json::Value>(records::turn_state(&turn).get()).unwrap(),
json!({
"id": "msg", "agent_id": "ses", "status": "waiting_input", "cursor": "c1",
"result": {"turn_id": "msg", "status": "waiting_input", "outcome": "question",
@@ -292,11 +292,11 @@ fn agents_respond_parses_answers_and_permissions_and_rejects_other_shapes() {
use crate::agents::AgentResponse;
use serde_json::json;
assert!(matches!(
- records::parse_response(json!({"type": "answer", "text": "yes", "data": {"n": 1}})),
- Ok(AgentResponse::Answer { text, data: Some(data) }) if text == "yes" && data == json!({"n": 1})
+ records::parse_response(&json!({"type": "answer", "text": "yes", "data": {"n": 1}}).to_string()),
+ Ok(AgentResponse::Answer { text, data: Some(data) }) if text == "yes" && data.get() == r#"{"n":1}"#
));
assert!(matches!(
- records::parse_response(json!({"type": "permission", "approved": false})),
+ records::parse_response(&json!({"type": "permission", "approved": false}).to_string()),
Ok(AgentResponse::Permission { approved: false })
));
for invalid in [
@@ -308,7 +308,7 @@ fn agents_respond_parses_answers_and_permissions_and_rejects_other_shapes() {
] {
assert!(
matches!(
- records::parse_response(invalid.clone()),
+ records::parse_response(&invalid.to_string()),
Err(BoxliteError::InvalidArgument(_))
),
"accepted {invalid}"
@@ -351,7 +351,7 @@ fn agent_records_reject_wrong_field_types() {
);
}
assert!(matches!(
- records::parse_response(json!({"type": "answer", "text": false})),
+ records::parse_response(&json!({"type": "answer", "text": false}).to_string()),
Err(BoxliteError::InvalidArgument(_))
));
}
diff --git a/src/boxlite/src/agents/types.rs b/src/boxlite/src/agents/types.rs
index b25e221e0..0540f6ded 100644
--- a/src/boxlite/src/agents/types.rs
+++ b/src/boxlite/src/agents/types.rs
@@ -4,7 +4,7 @@ use std::pin::Pin;
use std::time::Duration;
use futures::Stream;
-use serde_json::Value;
+use serde_json::{Value, value::RawValue};
use crate::BoxliteResult;
@@ -44,7 +44,7 @@ pub enum AgentSendMode {
#[derive(Debug, Clone, Default)]
pub struct AgentSendOptions {
pub mode: AgentSendMode,
- pub data: Option<Value>,
+ pub data: Option<Box<RawValue>>,
pub idempotency_key: Option<String>,
}
@@ -75,7 +75,9 @@ pub enum AgentStatus {
Unknown,
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "rest", derive(serde::Deserialize))]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
pub enum AgentTurnStatus {
Queued,
Running,
@@ -137,10 +139,17 @@ pub enum AgentRequestKind {
}
/// Text can answer a question; only the Permission variant can grant authority.
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
pub enum AgentResponse {
- Answer { text: String, data: Option<Value> },
- Permission { approved: bool },
+ Answer {
+ text: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ data: Option<Box<RawValue>>,
+ },
+ Permission {
+ approved: bool,
+ },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -159,20 +168,22 @@ pub struct AgentSteeringReceipt {
pub status: AgentSteeringStatus,
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "rest", derive(serde::Deserialize))]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
pub enum AgentOutcome {
Answer,
Question,
}
/// Result provenance and optional adapter-reported usage; unavailable usage is not zero.
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, serde::Serialize)]
pub struct AgentResult {
pub turn_id: String,
pub status: AgentTurnStatus,
pub outcome: Option<AgentOutcome>,
pub text: Option<String>,
- pub data: Option<Value>,
+ pub data: Option<Box<RawValue>>,
pub artifacts: Vec<String>,
pub usage: Option<Value>,
pub error: Option<String>,
diff --git a/src/boxlite/src/rest/client.rs b/src/boxlite/src/rest/client.rs
index 783268468..ea67b389e 100644
--- a/src/boxlite/src/rest/client.rs
+++ b/src/boxlite/src/rest/client.rs
@@ -353,7 +353,7 @@ impl ApiClient {
pub(crate) async fn post_agent<T: DeserializeOwned>(
&self,
path: &str,
- body: &serde_json::Value,
+ body: &impl serde::Serialize,
key: Option<&str>,
) -> BoxliteResult<T> {
let mut builder = self.agent_writes.post(self.url(path)).json(body);
diff --git a/src/boxlite/src/rest/litebox/tests/agents.rs b/src/boxlite/src/rest/litebox/tests/agents.rs
index 4a88d1dbf..3b3f464be 100644
--- a/src/boxlite/src/rest/litebox/tests/agents.rs
+++ b/src/boxlite/src/rest/litebox/tests/agents.rs
@@ -105,13 +105,14 @@ async fn remote_agent_create_send_and_get_turn() {
#[tokio::test]
async fn remote_agent_send_preserves_optional_request_values() {
use crate::agents::{AgentSendMode, AgentSendOptions};
+ const RAW_DATA: &str = r#"{ "$serde_json::private::Number": "ordinary key", "number": 1e400 }"#;
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] {
+ for response in [resource, turn, turn, turn, turn] {
let (mut socket, _) = listener.accept().await.unwrap();
let mut header = Vec::new();
while !header.ends_with(b"\r\n\r\n") {
@@ -128,10 +129,7 @@ async fn remote_agent_send_preserves_optional_request_values() {
.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(),
- ));
+ requests.push((header, String::from_utf8(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
@@ -150,7 +148,7 @@ async fn remote_agent_send_preserves_optional_request_values() {
"hello",
AgentSendOptions {
mode: AgentSendMode::Queue,
- data: Some(serde_json::Value::Null),
+ data: Some(serde_json::value::to_raw_value(&serde_json::Value::Null).unwrap()),
..Default::default()
},
)
@@ -161,23 +159,35 @@ async fn remote_agent_send_preserves_optional_request_values() {
"hello",
AgentSendOptions {
mode: AgentSendMode::Reject,
- data: Some(serde_json::json!(false)),
+ data: Some(serde_json::value::to_raw_value(&serde_json::json!(false)).unwrap()),
idempotency_key: Some("retry-1".into()),
},
)
.await
.unwrap();
+ agent
+ .send(
+ "raw",
+ AgentSendOptions {
+ data: Some(serde_json::value::RawValue::from_string(RAW_DATA.into()).unwrap()),
+ ..Default::default()
+ },
+ )
+ .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!(requests[4].1.contains(RAW_DATA));
+ let body = |i: usize| serde_json::from_str::<serde_json::Value>(&requests[i].1).unwrap();
+ assert_eq!(body(1), serde_json::json!({"text":"hello"}));
assert_eq!(
- requests[2].1,
+ body(2),
serde_json::json!({"text":"hello", "options":{"data":null}})
);
assert_eq!(
- requests[3].1,
+ body(3),
serde_json::json!({"text":"hello", "options":{"mode":"reject","data":false}})
);
assert!(
@@ -292,7 +302,7 @@ async fn remote_controls_forward_typed_responses_and_confirm_shutdown() {
.unwrap();
let answer = AgentResponse::Answer {
text: "yes".into(),
- data: Some(json!(42)),
+ data: Some(serde_json::value::to_raw_value(&json!(42)).unwrap()),
};
let turn = agent
.respond("question", answer, Default::default())
diff --git a/src/cli/src/commands/agent/mod.rs b/src/cli/src/commands/agent/mod.rs
index e816203d4..38ec2c2c1 100644
--- a/src/cli/src/commands/agent/mod.rs
+++ b/src/cli/src/commands/agent/mod.rs
@@ -76,8 +76,8 @@ pub enum AgentCommand {
#[arg(long, value_name = "REQUEST")]
request: String,
/// Typed answer or permission response
- #[arg(value_name = "JSON", value_parser = parse_json)]
- response: Value,
+ #[arg(value_name = "JSON", value_parser = parse_raw_json)]
+ response: Box<serde_json::value::RawValue>,
#[command(flatten)]
options: AgentControlOptions,
},
@@ -164,8 +164,8 @@ pub struct AgentSendOptions {
#[arg(long, value_enum, default_value = "queue")]
mode: SendMode,
/// Additional JSON input
- #[arg(long, value_name = "JSON", value_parser = parse_json)]
- data: Option<Value>,
+ #[arg(long, value_name = "JSON", value_parser = parse_raw_json)]
+ data: Option<Box<serde_json::value::RawValue>>,
#[command(flatten)]
control: AgentControlOptions,
}
@@ -205,6 +205,10 @@ pub enum AgentView {
Requests,
}
+fn parse_raw_json(input: &str) -> serde_json::Result<Box<serde_json::value::RawValue>> {
+ serde_json::from_str(input)
+}
+
fn parse_json(input: &str) -> serde_json::Result<Value> {
serde_json::from_str(input)
}
@@ -247,7 +251,7 @@ pub async fn execute(args: AgentArgs, global: &GlobalFlags) -> Result<()> {
options,
} => {
let agent = open_agent(&runtime, &target).await?;
- let response = records::parse_response(response)?;
+ let response = records::parse_response(response.get())?;
let turn = agent
.respond(&request, response, options.into_core())
.await?;
@@ -256,7 +260,9 @@ pub async fn execute(args: AgentArgs, global: &GlobalFlags) -> Result<()> {
AgentCommand::Inspect { target, options } => {
let agent = open_agent(&runtime, &target.agent).await?;
let record = match (target.turn, options.view) {
- (Some(turn), _) => records::turn_state(&agent.get_turn(&turn).await?.state()?),
+ (Some(turn), _) => {
+ return print(&records::turn_state(&agent.get_turn(&turn).await?.state()?));
+ }
(None, None) => records::agent_state(&agent.state()?),
(None, Some(AgentView::Config)) => records::config(&agent.config()?),
(None, Some(AgentView::Capabilities)) => {
@@ -318,7 +324,7 @@ async fn open_turn(runtime: &BoxliteRuntime, target: &TurnTarget) -> Result<Agen
Ok(agent.get_turn(&target.turn).await?)
}
-fn print(record: &Value) -> Result<()> {
+fn print(record: &impl std::fmt::Display) -> Result<()> {
println!("{record}");
Ok(())
}
diff --git a/src/cli/src/commands/agent/tests/mod.rs b/src/cli/src/commands/agent/tests/mod.rs
index a5c0fbd02..ffdb4470a 100644
--- a/src/cli/src/commands/agent/tests/mod.rs
+++ b/src/cli/src/commands/agent/tests/mod.rs
@@ -63,7 +63,7 @@ fn agents_send_defaults_to_queue_and_accepts_reject_and_json() {
panic!("expected send")
};
assert_eq!(options.mode, SendMode::Queue);
- assert_eq!(options.data, None);
+ assert!(options.data.is_none());
assert_eq!(options.control.idempotency_key, None);
let AgentCommand::Send {
@@ -79,7 +79,7 @@ fn agents_send_defaults_to_queue_and_accepts_reject_and_json() {
"--mode",
"reject",
"--data",
- r#"{"value":1}"#,
+ r#"{"values": [9007199254740993, 1e400]}"#,
"--idempotency-key",
"retry",
])
@@ -90,7 +90,10 @@ fn agents_send_defaults_to_queue_and_accepts_reject_and_json() {
assert_eq!(target.agent_id, "agent");
assert_eq!(text, "hello");
assert_eq!(options.mode, SendMode::Reject);
- assert_eq!(options.data, Some(json!({"value": 1})));
+ assert_eq!(
+ options.data.unwrap().get(),
+ r#"{"values": [9007199254740993, 1e400]}"#
+ );
assert_eq!(options.control.idempotency_key.as_deref(), Some("retry"));
}
@@ -171,7 +174,7 @@ fn agents_responses_keep_answer_and_permission_json_distinct() {
panic!("expected respond")
};
assert_eq!(request, "request");
- assert_eq!(parsed, serde_json::from_str::<Value>(response).unwrap());
+ assert_eq!(parsed.get(), response);
assert_eq!(options.idempotency_key.as_deref(), Some("retry"));
}
}