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 event subscriptions and VM acceptance (#3093)

Jiaqiang Wong6c22254e5658
diff --git a/docs/reference/agents.md b/docs/reference/agents.md
index 4fd34f33b..cb71006e4 100644
--- a/docs/reference/agents.md
+++ b/docs/reference/agents.md
@@ -253,7 +253,7 @@ 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.
+Both event methods return a stream after the native subscription connects.
Agent namespaces are acquired lazily. Closing a Box releases its local Box handle;
an acquired namespace, agent or turn remains usable until `Runtime.Close`.
@@ -265,6 +265,41 @@ Cancellation stops the Go wait, not submitted agent work. Late native handles
are released, including results already buffered when cancellation wins.
`Runtime.Close` wakes pending calls with `ErrRuntimeClosed` and rejects new calls.
+### Go event streams
+
+Open events before sending work: `agent.Events(ctx, AgentEventsOptions{})` waits
+for native `on_open`. Opening errors return a nil stream. The opening context
+also controls the subscription after connection.
+
+`Next(ctx)` permits one reader; concurrent reads return `ErrInvalidState`.
+Canceling that read returns its context error without consuming an event or
+canceling the subscription. A stream retains at most 64 events and 4 MiB of
+copied JSON. Oversized records are rejected before copying. Count or byte overflow
+cancels the subscription with `ErrResourceExhausted`, preserving its accepted prefix.
+Callbacks never wait for a reader, so a slow stream cannot block other calls.
+
+An invalid event record is consumed once. `Next` returns a nil event and
+an `*AgentEventDecodeError` identifiable with `errors.As`. Missing or mistyped
+fields are named in the error without including the payload. All five outer
+fields are required. Cursor and turn ID accept null, unfamiliar string kinds
+are accepted, and `data` preserves any JSON value, including null. Call
+`Next` again to read the following event, or close the stream.
+
+A native end returns buffered events followed by sticky `io.EOF` or the native
+error. Canceling the subscription context preserves buffered events, followed by
+its context error. The first recorded error wins; completed native EOF is final.
+`Close` discards unread events, wakes readers and requests native cancellation
+without waiting. It preserves an earlier error and otherwise produces `io.EOF`.
+Closing a stream does not interrupt agent work.
+
+`Runtime.Close` discards buffers and makes reads return `ErrRuntimeClosed`, including when
+the read context is also canceled at the read decision.
+It cancels connected subscriptions before joining the ordinary drainer, then
+dispatches only subscription callbacks until their terminals arrive. Other queued callbacks are discarded during teardown. Pending connects do not hold shutdown
+open; their callback state is released after native runtime destruction.
+Garbage collection requests stream closure as a fallback; deterministic cleanup
+uses stream or runtime `Close`.
+
### Example: handle operation errors
Python (the Box may already exist; this call starts no work):
diff --git a/make/coverage.mk b/make/coverage.mk
index a9fbdd0c3..3aff51c15 100644
--- a/make/coverage.mk
+++ b/make/coverage.mk
@@ -93,11 +93,11 @@ coverage\:go:
@$(MAKE) dev:go GO_CARGO_FEATURES="--features test-support"
@mkdir -p target/coverage
@rc=0; \
- (cd sdks/go && go test -a -count=1 -tags boxlite_dev,boxlite_agent_test -covermode=atomic -coverpkg=./... \
+ (cd sdks/go && $(GO_DEV_ENV) go test -a -count=1 -tags $(GO_DEV_TAGS),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=$$?; \
- (cd apps/runner && GOFLAGS=-tags=boxlite_dev go test -covermode=atomic -coverpkg=./... \
+ (cd apps/runner && $(GO_DEV_ENV) GOFLAGS=-tags=$(GO_DEV_TAGS) go test -covermode=atomic -coverpkg=./... \
-coverprofile="$(PROJECT_ROOT)/target/coverage/runner.out" $(GOTEST_FILTER) ./...) || rc=$$?; \
(cd apps/image-service && go test -covermode=atomic -coverpkg=./... \
-coverprofile="$(PROJECT_ROOT)/target/coverage/image-service.out" $(GOTEST_FILTER) ./...) || rc=$$?; \
diff --git a/make/dev.mk b/make/dev.mk
index 00d8fc314..d6dc3941b 100644
--- a/make/dev.mk
+++ b/make/dev.mk
@@ -49,12 +49,19 @@ dev\:node: $(if $(SETUP_DONE),,runtime\:debug)
@cd examples/node && npm install --silent
@echo "✅ Node.js SDK built and linked to examples"
+GO_DEBUG_DIR = $(abspath $(or $(CARGO_TARGET_DIR),$(PROJECT_ROOT)/target))/debug
+GO_DEV_TAGS = boxlite_dev
+ifneq ($(strip $(CARGO_TARGET_DIR)),)
+GO_DEV_TAGS = boxlite_dev,boxlite_external_archive
+GO_DEV_ENV = CGO_LDFLAGS='$(CGO_LDFLAGS) "$(GO_DEBUG_DIR)/libboxlite.a"'
+endif
+
# 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 $(GO_CARGO_FEATURES)
- @bash $(SCRIPT_DIR)/build/fix-go-symbols.sh target/debug/libboxlite.a
- @cd sdks/go && go build -tags boxlite_dev ./...
+ @bash $(SCRIPT_DIR)/build/fix-go-symbols.sh "$(GO_DEBUG_DIR)/libboxlite.a"
+ @cd sdks/go && $(GO_DEV_ENV) go build -tags $(GO_DEV_TAGS) ./...
@echo "✅ Go SDK built. You can now run: cd sdks/go && go test -tags boxlite_dev -v ./..."
# Native REST acceptance clients. SETUP_DONE=1 with BOXLITE_DEPS_STUB=1
@@ -62,7 +69,7 @@ dev\:go: $(if $(SETUP_DONE),,runtime\:debug)
build\:e2e\:drivers: dev\:go
@mkdir -p target/e2e
$(CC) -std=c11 -Wall -Wextra -Werror -Isdks/c/include apps/e2e/sdks/c/e2e_domains.c -Ltarget/debug -lboxlite -Wl,-rpath,$(PROJECT_ROOT)/target/debug -o target/e2e/domain-c
- @cd sdks/go && go build -tags boxlite_dev -o ../../target/e2e/domain-go ../../apps/e2e/sdks/go/e2e_domains.go
+ @cd sdks/go && $(GO_DEV_ENV) go build -tags $(GO_DEV_TAGS) -o ../../target/e2e/domain-go ../../apps/e2e/sdks/go/e2e_domains.go
@cargo build --locked -p boxlite-e2e-rust --bin domain-rust
# The workflow checks out the selected release separately. Driver sources stay
diff --git a/make/help.mk b/make/help.mk
index 717199316..c6f4dc612 100644
--- a/make/help.mk
+++ b/make/help.mk
@@ -104,6 +104,8 @@ help:
@echo " make test:all:node - Run all Node.js SDK tests"
@echo " make test:unit:go - Run Go SDK unit tests"
@echo " make test:integration:go - Run Go SDK archive round-trip test (requires VM, FILTER=<pattern>)"
+ @echo " make test:integration:go:agents - Compare Go, C and Rust OpenCode agent behavior (requires VM)"
+ @echo " make test:integration:go:agents:parity - Run Go equivalents of the Rust agent VM scenarios"
@echo " make test:integration:runner - Run runner native archive recovery tests (FILTER=<pattern>)"
@echo " make test:all:go - Run all Go SDK tests"
@echo " make test:unit:c - Run C SDK unit tests (no VM required)"
diff --git a/make/test.mk b/make/test.mk
index c3599b140..1987a7ec3 100644
--- a/make/test.mk
+++ b/make/test.mk
@@ -552,6 +552,31 @@ test\:integration\:c\:agents:
@BOXLITE_C_AGENT_VM_BIN="$(PROJECT_ROOT)/sdks/c/tests/build/test_agents_opencode" \
cargo test -p boxlite-c --lib c_opencode_vm_matches_rust -- --ignored --test-threads=1 --nocapture
+# Local, three-language acceptance with the shared scripted OpenCode model.
+# Kept separate from archive integration and hosted CI.
+test\:integration\:go\:agents:
+ @test -n "$$BOXLITE_TEST_OPENCODE_BINARY" || { \
+ echo "❌ Set BOXLITE_TEST_OPENCODE_BINARY to the OpenCode 2.2.2 glibc Linux binary"; exit 1; }
+ @$(MAKE) dev:go GO_CARGO_FEATURES="--features test-support"
+ @mkdir -p sdks/c/tests/build
+ @cd sdks/c/tests/build && cmake .. -DBOXLITE_LIB_DIR="$(if $(CARGO_TARGET_DIR),$(abspath $(CARGO_TARGET_DIR)),$(PROJECT_ROOT)/target)/debug"
+ @cd sdks/c/tests/build && cmake --build . --target test_agents_opencode -j
+ @cd sdks/go && $(GO_DEV_ENV) go test -c -tags $(GO_DEV_TAGS),boxlite_agent_vm -o "$(GO_DEBUG_DIR)/go-agent-vm"
+ @BOXLITE_C_AGENT_VM_BIN="$(PROJECT_ROOT)/sdks/c/tests/build/test_agents_opencode" \
+ BOXLITE_GO_AGENT_VM_BIN="$(GO_DEBUG_DIR)/go-agent-vm" \
+ cargo test -p boxlite-c --lib go_opencode_vm_matches_rust -- --ignored --test-threads=1 --nocapture
+ @BOXLITE_GO_AGENT_VM_BIN="$(GO_DEBUG_DIR)/go-agent-vm" \
+ cargo test -p boxlite-c --lib go_opencode_vm_parity -- --ignored --test-threads=1 --nocapture
+
+# Rerun the scenario matrix without repeating the C/Go/Rust result comparison.
+test\:integration\:go\:agents\:parity:
+ @test -n "$$BOXLITE_TEST_OPENCODE_BINARY" || { \
+ echo "❌ Set BOXLITE_TEST_OPENCODE_BINARY to the OpenCode 2.2.2 glibc Linux binary"; exit 1; }
+ @$(MAKE) dev:go GO_CARGO_FEATURES="--features test-support"
+ @cd sdks/go && $(GO_DEV_ENV) go test -c -tags $(GO_DEV_TAGS),boxlite_agent_vm -o "$(GO_DEBUG_DIR)/go-agent-vm"
+ @BOXLITE_GO_AGENT_VM_BIN="$(GO_DEBUG_DIR)/go-agent-vm" \
+ cargo test -p boxlite-c --lib go_opencode_vm_parity -- --ignored --test-threads=1 --nocapture
+
# Run the same OpenCode scenario in Rust, Python and Node, comparing each SDK
# result with the Rust result produced in this invocation.
test\:integration\:agent-sdk-parity: $(if $(SETUP_DONE),,runtime\:debug)
@@ -705,7 +730,7 @@ test\:all\:c:
test\:unit\:go:
@echo "🧪 Running Go SDK unit tests..."
@$(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) ./...
+ @cd sdks/go && $(GO_DEV_ENV) go test -a -count=1 -tags $(GO_DEV_TAGS),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/sdks/c/cbindgen.toml b/sdks/c/cbindgen.toml
index 82c7d3401..818debbc3 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", "boxlite_test_agents_new", "boxlite_test_agents_wait_pending", "boxlite_test_agents_wait_queue", "boxlite_test_agents_free_counts"]
+exclude = ["boxlite_go_drain_subscription", "sockaddr_storage", "boxlite_test_agents_new", "boxlite_test_agents_wait_pending", "boxlite_test_agents_wait_queue", "boxlite_test_agents_free_counts", "boxlite_test_agents_event_frees", "boxlite_test_agents_barrier", "boxlite_test_agents_install"]
[export.rename]
sockaddr_storage = "struct sockaddr_storage"
diff --git a/sdks/c/src/agents.rs b/sdks/c/src/agents.rs
index 8b045f0da..584b790c9 100644
--- a/sdks/c/src/agents.rs
+++ b/sdks/c/src/agents.rs
@@ -894,7 +894,7 @@ fn open_subscription(
Err(error) => {
push_event(
&queue,
- RuntimeEvent::AgentCompletion(Box::new(move || unsafe {
+ RuntimeEvent::AgentSubscription(Box::new(move || unsafe {
deliver::<()>(Err(error), |_, error| {
on_open(ptr::null_mut(), error, data as *mut c_void)
});
@@ -913,7 +913,7 @@ fn open_subscription(
});
push_event(
&queue,
- RuntimeEvent::AgentCompletion(Box::new(move || unsafe {
+ RuntimeEvent::AgentSubscription(Box::new(move || unsafe {
on_open(Box::into_raw(handle), ptr::null(), data as *mut c_void);
})),
)
@@ -934,7 +934,7 @@ fn open_subscription(
item = stream.next() => match item {
Some(Ok(event)) => {
let value = boxlite::agents::records::event(&event);
- push_event(&queue, RuntimeEvent::AgentCompletion(Box::new(move || unsafe {
+ push_event(&queue, RuntimeEvent::AgentSubscription(Box::new(move || unsafe {
deliver_json(Ok(value), on_event, data);
}))).await;
}
@@ -945,7 +945,7 @@ fn open_subscription(
};
push_event(
&queue,
- RuntimeEvent::AgentCompletion(Box::new(move || unsafe {
+ RuntimeEvent::AgentSubscription(Box::new(move || unsafe {
match terminal {
Some(error) => deliver::<()>(Err(error), |_, error| {
on_event(ptr::null(), error, data as *mut c_void)
@@ -1117,6 +1117,8 @@ pub unsafe extern "C" fn boxlite_agent_turn_free(handle: *mut CAgentTurn) {
#[unsafe(no_mangle)]
pub unsafe extern "C" fn boxlite_agent_events_free(handle: *mut CAgentEvents) {
if !handle.is_null() {
+ #[cfg(feature = "test-support")]
+ go_test_support::record_events_free();
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
index 748db0a9a..bf7064d2a 100644
--- a/sdks/c/src/agents/tests/go_support.rs
+++ b/sdks/c/src/agents/tests/go_support.rs
@@ -5,8 +5,77 @@ use crate::runtime::{RuntimeHandle, RuntimeLiveness};
use std::sync::atomic::AtomicUsize;
use std::time::{Duration, Instant};
+// Installation is a Rust test-only operation, not part of the public C/Go API.
+// This fixture prepares the same delivered-agent state as the Rust VM tests.
+#[unsafe(no_mangle)]
+unsafe extern "C" fn boxlite_test_agents_install(
+ handle: *mut CBoxHandle,
+ name: *const c_char,
+ path: *const c_char,
+ out_error: *mut CBoxliteError,
+) -> BoxliteErrorCode {
+ let result = || -> Result<(), BoxliteError> {
+ if handle.is_null() || name.is_null() || path.is_null() {
+ return Err(BoxliteError::InvalidArgument(
+ "null installation fixture argument".into(),
+ ));
+ }
+ let handle = unsafe { &*handle };
+ let name = unsafe { CStr::from_ptr(name) }
+ .to_str()
+ .map_err(|e| BoxliteError::InvalidArgument(e.to_string()))?;
+ let path = unsafe { CStr::from_ptr(path) }
+ .to_str()
+ .map_err(|e| BoxliteError::InvalidArgument(e.to_string()))?;
+ handle.tokio_rt.block_on(
+ handle
+ .handle
+ .agents()
+ .install_from_host(name, std::path::Path::new(path)),
+ )
+ };
+ match result() {
+ Ok(()) => BoxliteErrorCode::Ok,
+ Err(error) => {
+ let code = error_to_code(&error);
+ unsafe { write_error(out_error, error) };
+ code
+ }
+ }
+}
+
static AGENTS_FREED: AtomicUsize = AtomicUsize::new(0);
static TURNS_FREED: AtomicUsize = AtomicUsize::new(0);
+static EVENTS_FREED: AtomicUsize = AtomicUsize::new(0);
+
+pub(super) fn record_events_free() {
+ EVENTS_FREED.fetch_add(1, Ordering::SeqCst);
+}
+
+#[unsafe(no_mangle)]
+extern "C" fn boxlite_test_agents_event_frees() -> usize {
+ EVENTS_FREED.load(Ordering::SeqCst)
+}
+
+// Deliberately pause one real drainer while tests exercise another runtime or
+// queue an opening/cancellation behind it. The test owns callback/token lifetime.
+#[unsafe(no_mangle)]
+unsafe extern "C" fn boxlite_test_agents_barrier(
+ runtime: *mut RuntimeHandle,
+ callback: unsafe extern "C" fn(usize),
+ token: usize,
+) {
+ let queue = unsafe { &(*runtime).queue };
+ queue
+ .inner
+ .lock()
+ .unwrap()
+ .push_back(RuntimeEvent::AgentCompletion(Box::new(move || unsafe {
+ callback(token)
+ })));
+ queue.cv.notify_one();
+}
+
pub(super) fn record_free(turn: bool) {
let count = if turn { &TURNS_FREED } else { &AGENTS_FREED };
count.fetch_add(1, Ordering::SeqCst);
diff --git a/sdks/c/src/agents/tests/opencode_vm.rs b/sdks/c/src/agents/tests/opencode_vm.rs
index f2f5f698c..ff1f1b05d 100644
--- a/sdks/c/src/agents/tests/opencode_vm.rs
+++ b/sdks/c/src/agents/tests/opencode_vm.rs
@@ -1,4 +1,4 @@
-//! Real OpenCode comparison between a compiled C caller and Rust agent API.
+//! Real OpenCode comparison across native SDK callers and the Rust agent API.
#[path = "../../../../../src/boxlite/tests/common/opencode.rs"]
mod opencode;
@@ -12,17 +12,28 @@ fn json_line(output: &str, prefix: &str) -> serde_json::Value {
let line = output
.lines()
.find_map(|line| line.strip_prefix(prefix))
- .expect("C acceptance output missing JSON");
+ .expect("native acceptance output missing JSON");
serde_json::from_str(line).unwrap()
}
#[test]
#[ignore = "requires a VM and BOXLITE_TEST_OPENCODE_BINARY"]
fn c_opencode_vm_matches_rust() {
+ let program = std::env::var("BOXLITE_C_AGENT_VM_BIN").expect("set BOXLITE_C_AGENT_VM_BIN");
+ compare_vm_callers(&[("C", program)]);
+}
+
+#[test]
+#[ignore = "requires a VM, OpenCode and compiled C/Go acceptance callers"]
+fn go_opencode_vm_matches_rust() {
+ let c = std::env::var("BOXLITE_C_AGENT_VM_BIN").expect("set BOXLITE_C_AGENT_VM_BIN");
+ let go = std::env::var("BOXLITE_GO_AGENT_VM_BIN").expect("set BOXLITE_GO_AGENT_VM_BIN");
+ compare_vm_callers(&[("C", c), ("GO", go)]);
+}
+
+fn compare_vm_callers(programs: &[(&str, String)]) {
let binary = std::env::var(opencode::BINARY_ENV).expect("set BOXLITE_TEST_OPENCODE_BINARY");
- let c_program = std::env::var("BOXLITE_C_AGENT_VM_BIN").expect("set BOXLITE_C_AGENT_VM_BIN");
let home = boxlite_test_utils::home::PerTestBoxHome::new();
- let c_home = boxlite_test_utils::home::PerTestBoxHome::new();
let tokio_rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
@@ -98,57 +109,117 @@ fn c_opencode_vm_matches_rust() {
(first, result, id)
});
tokio_rt.block_on(runtime.shutdown(Some(30))).unwrap();
- let output = std::process::Command::new(c_program)
- .arg(&binary)
- .arg(&config)
- .arg(&c_home.path)
- .arg(&registry.host)
- .output()
- .expect("run compiled C agent acceptance");
- assert!(
- output.status.success(),
- "C acceptance failed: {}\n{}",
- String::from_utf8_lossy(&output.stdout),
- String::from_utf8_lossy(&output.stderr)
- );
- let stdout = String::from_utf8(output.stdout).unwrap();
- let c_event = json_line(&stdout, "C_EVENT=");
- let c_result = json_line(&stdout, "C_RESULT=");
- let c_turn = json_line(&stdout, "C_TURN=");
- let c_config = json_line(&stdout, "C_CONFIG=");
- let c_capabilities = json_line(&stdout, "C_CAPABILITIES=");
- assert_eq!(c_config["model"], "fake/fake-model");
- assert!(
- c_capabilities["operations"]
- .as_array()
- .unwrap()
- .iter()
- .any(|op| op == "agent.send")
- );
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}");
- }
- let mut c_usage = c_result["usage"].clone();
- let mut rust_usage = rust_result["usage"].clone();
- for usage in [&mut c_usage, &mut rust_usage] {
- if let Some(entries) = usage.as_array_mut() {
- for entry in entries {
- let id = entry.as_object_mut().unwrap().remove("message_id").unwrap();
- assert!(!id.as_str().unwrap().is_empty());
+ for (label, program) in programs {
+ let caller_home = boxlite_test_utils::home::PerTestBoxHome::new();
+ let mut command = std::process::Command::new(program);
+ if *label == "GO" {
+ command.args(["-test.run=^TestGoAgentVMDriver$", "-test.v", "--"]);
+ }
+ let output = command
+ .arg(&binary)
+ .arg(&config)
+ .arg(&caller_home.path)
+ .arg(&registry.host)
+ .output()
+ .expect("run compiled native agent acceptance");
+ assert!(
+ output.status.success(),
+ "{label} acceptance failed: {}\n{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let stdout = String::from_utf8(output.stdout).unwrap();
+ let actual_event = json_line(&stdout, &format!("{label}_EVENT="));
+ let actual_result = json_line(&stdout, &format!("{label}_RESULT="));
+ let actual_turn = json_line(&stdout, &format!("{label}_TURN="));
+ let actual_config = json_line(&stdout, &format!("{label}_CONFIG="));
+ let actual_capabilities = json_line(&stdout, &format!("{label}_CAPABILITIES="));
+ assert_eq!(actual_config["model"], "fake/fake-model");
+ assert!(
+ actual_capabilities["operations"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|op| op == "agent.send")
+ );
+ for key in ["status", "outcome", "text", "data", "artifacts", "error"] {
+ assert_eq!(actual_result[key], rust_result[key], "result field {key}");
+ }
+ let mut actual_usage = actual_result["usage"].clone();
+ let mut rust_usage = rust_result["usage"].clone();
+ for usage in [&mut actual_usage, &mut rust_usage] {
+ if let Some(entries) = usage.as_array_mut() {
+ for entry in entries {
+ let id = entry.as_object_mut().unwrap().remove("message_id").unwrap();
+ assert!(!id.as_str().unwrap().is_empty());
+ }
}
}
+ assert_eq!(
+ actual_usage, rust_usage,
+ "usage apart from per-session message IDs"
+ );
+ assert_eq!(actual_result["turn_id"], actual_turn["id"]);
+ assert_eq!(actual_event["kind"], rust_event.kind);
+ assert_eq!(
+ actual_event["turn_id"].as_str() == actual_turn["id"].as_str(),
+ rust_event.turn_id.as_deref() == Some(rust_turn_id.as_str())
+ );
+ assert_eq!(
+ actual_event["turn_id"].is_null(),
+ rust_event.turn_id.is_none()
+ );
+ eprintln!(
+ "{label}/Rust match: result fields, normalized usage, first-event kind and turn association"
+ );
}
- assert_eq!(
- c_usage, rust_usage,
- "usage apart from per-session message IDs"
+}
+
+#[test]
+#[ignore = "requires VM and the compiled Go agent parity suite"]
+fn go_opencode_vm_parity() {
+ let program = std::env::var("BOXLITE_GO_AGENT_VM_BIN").expect("set BOXLITE_GO_AGENT_VM_BIN");
+ let binary = std::env::var(opencode::BINARY_ENV).expect("set BOXLITE_TEST_OPENCODE_BINARY");
+ let home = boxlite_test_utils::home::PerTestBoxHome::new();
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ let (port, _log) = runtime.block_on(opencode::start_fake_model());
+ let config = home.path.join("opencode.json");
+ std::fs::write(
+ &config,
+ serde_json::to_vec(&opencode::provider_config(port)).unwrap(),
+ )
+ .unwrap();
+ let registry = boxlite_test_utils::registry::local_registry().search_registry();
+ let filter = std::env::var("BOXLITE_GO_AGENT_VM_FILTER")
+ .unwrap_or_else(|_| "^TestGoAgentVMParity$".into());
+ let output = std::process::Command::new(program)
+ .arg(format!("-test.run={filter}"))
+ .args(["-test.timeout=25m", "-test.v", "--"])
+ .args([
+ std::path::Path::new(&binary),
+ &config,
+ &home.path,
+ std::path::Path::new(&registry.host),
+ ])
+ .stderr(std::process::Stdio::inherit())
+ .output()
+ .expect("run Go equivalents of Rust OpenCode tests");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ print!("{stdout}");
+ assert!(
+ output.status.success(),
+ "Go parity suite failed: {}",
+ output.status
);
- assert_eq!(c_result["turn_id"], c_turn["id"]);
- assert_eq!(c_event["kind"], rust_event.kind);
- assert_eq!(
- c_event["turn_id"].as_str() == c_turn["id"].as_str(),
- rust_event.turn_id.as_deref() == Some(rust_turn_id.as_str())
+ assert!(
+ stdout.lines().any(|line| line
+ .trim_start()
+ .starts_with("--- PASS: TestGoAgentVMParity/")),
+ "no Go VM scenario passed for {filter}"
);
- assert_eq!(c_event["turn_id"].is_null(), rust_event.turn_id.is_none());
}
diff --git a/sdks/c/src/agents/tests/subscriptions.rs b/sdks/c/src/agents/tests/subscriptions.rs
index 60add1964..a0a43f5b6 100644
--- a/sdks/c/src/agents/tests/subscriptions.rs
+++ b/sdks/c/src/agents/tests/subscriptions.rs
@@ -593,3 +593,36 @@ fn single_drainer_serializes_open_events_and_terminal() {
crate::boxlite_runtime_free(runtime);
}
}
+
+#[test]
+fn go_shutdown_drains_terminal_without_dispatching_stdout() {
+ extern "C" fn stdout(_: *const u8, _: usize, data: *mut c_void) {
+ unsafe { *data.cast::<bool>() = true };
+ }
+ unsafe {
+ let (rt, agent, queue) = fixture();
+ let mut seen = EventsSeen::default();
+ assert_eq!(
+ open(agent, Some("pending"), &mut seen),
+ BoxliteErrorCode::Ok
+ );
+ drain_until(rt, &mut seen, |s| s.opened);
+ let mut wrote = false;
+ queue.inner.lock().unwrap().push_back(RuntimeEvent::Stdout {
+ cb: stdout,
+ user_data: (&raw mut wrote) as usize,
+ data: vec![1],
+ });
+ boxlite_agent_events_free(seen.handle);
+ for _ in 0..100 {
+ crate::runtime::boxlite_go_drain_subscription(rt, 50);
+ if seen.terminal == 1 {
+ break;
+ }
+ }
+ assert_eq!(seen.terminal, 1);
+ assert!(!wrote, "shutdown dispatched queued stdout");
+ boxlite_agent_free(agent);
+ crate::boxlite_runtime_free(rt);
+ }
+}
diff --git a/sdks/c/src/event_queue.rs b/sdks/c/src/event_queue.rs
index a36aa3f2f..084684a08 100644
--- a/sdks/c/src/event_queue.rs
+++ b/sdks/c/src/event_queue.rs
@@ -400,6 +400,7 @@ impl<T> Drop for OwnedFfiPtr<T> {
pub enum RuntimeEvent {
AgentCompletion(Box<dyn FnOnce() + Send>),
+ AgentSubscription(Box<dyn FnOnce() + Send>),
AgentCreate {
callback: unsafe extern "C" fn(
*mut crate::agents::CAgent,
diff --git a/sdks/c/src/runtime.rs b/sdks/c/src/runtime.rs
index 02095f788..ff95656c8 100644
--- a/sdks/c/src/runtime.rs
+++ b/sdks/c/src/runtime.rs
@@ -206,7 +206,7 @@ pub unsafe extern "C" fn boxlite_runtime_drain(
timeout_ms: c_int,
out_error: *mut CBoxliteError,
) -> c_int {
- drain(runtime, timeout_ms, out_error)
+ drain(runtime, timeout_ms, out_error, false)
}
unsafe fn runtime_new(
@@ -512,7 +512,23 @@ unsafe fn runtime_free(runtime: *mut RuntimeHandle) {
}
}
-unsafe fn drain(rt: *mut RuntimeHandle, timeout_ms: c_int, out_error: *mut FFIError) -> c_int {
+/// Internal Go shutdown entry point. The ordinary drainer has joined and the
+/// runtime is being destroyed. Discard unrelated events as runtime_free would,
+/// making room even when a subscription producer is blocked on a full queue.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn boxlite_go_drain_subscription(
+ runtime: *mut CBoxliteRuntime,
+ timeout_ms: c_int,
+) {
+ unsafe { drain(runtime, timeout_ms, ptr::null_mut(), true) };
+}
+
+unsafe fn drain(
+ rt: *mut RuntimeHandle,
+ timeout_ms: c_int,
+ out_error: *mut FFIError,
+ subscription_only: bool,
+) -> c_int {
if rt.is_null() {
unsafe { write_error(out_error, null_pointer_error("runtime")) };
return -1;
@@ -567,6 +583,13 @@ unsafe fn drain(rt: *mut RuntimeHandle, timeout_ms: c_int, out_error: *mut FFIEr
};
// ─── Lock RELEASED — dispatch to user callback ───
+ if subscription_only {
+ if let RuntimeEvent::AgentSubscription(dispatch) = event {
+ dispatch();
+ return 1;
+ }
+ continue;
+ }
unsafe { dispatch_event(event) };
count = count.saturating_add(1);
}
@@ -575,7 +598,9 @@ unsafe fn drain(rt: *mut RuntimeHandle, timeout_ms: c_int, out_error: *mut FFIEr
unsafe fn dispatch_event(event: RuntimeEvent) {
unsafe {
match event {
- RuntimeEvent::AgentCompletion(dispatch) => dispatch(),
+ RuntimeEvent::AgentCompletion(dispatch) | RuntimeEvent::AgentSubscription(dispatch) => {
+ dispatch()
+ }
RuntimeEvent::AgentCreate {
callback,
user_data,
diff --git a/sdks/go/README.md b/sdks/go/README.md
index 312a2bc4b..6c4059c6d 100644
--- a/sdks/go/README.md
+++ b/sdks/go/README.md
@@ -498,21 +498,37 @@ 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.
+Agent record conversion uses the [shared JSON mapping](../../docs/reference/agents.md#go-json-mapping).
+The fixture in `testdata/agents.json` comes from the Rust core's record functions;
+the Rust test checks it for drift and the Go tests check conversion against it.
+Agent calls, getters and subscriptions reach the C SDK and Rust core.
+Open events before sending; `Events` returns only after connection. Streams allow
+one `Next` reader and bound buffered JSON to 64 events/4 MiB; overflow preserves
+the accepted prefix and ends with `ErrResourceExhausted`. Stream `Close` is
+non-blocking and does not interrupt work. See [Go event streams](../../docs/reference/agents.md#go-event-streams).
+
+`Box.Agents()` acquires its native namespace on first use. Agent and turn wrappers
+must not be copied after first use; `Runtime.Close` releases all their native handles.
+`Agent.Close` requests the core close operation, which may return `ErrUnsupported`;
+it does not free the local handle. Canceling a context stops the wait without
+canceling submitted work. Canceling an `AgentTurn.Wait` also releases its native
+observer while other waits on the same turn continue. See [Go ownership and cancellation](../../docs/reference/agents.md#go-json-mapping).
+
+The Go unit and coverage targets build the C SDK with its `test-support` feature and add
+the `boxlite_agent_test` Go build tag. These tests cross the real C/core boundary
+using a deterministic backend, without a VM. Normal `make dev:go` builds exclude
+these test entry points; hosted tests do not verify OpenCode in a real VM.
+```bash
+make test:unit:go FILTER=Agent
+make test:unit:rust FILTER=go_json_fixture_matches_core_records
+# Race checks for agent calls, streams and ownership
+make test:unit:go FILTER=Agent RACE=1
+```
+
+After an intentional core format change, regenerate the fixture with
+`BOXLITE_UPDATE_AGENT_FIXTURES=1 make test:unit:rust FILTER=go_json_fixture_matches_core_records`,
+then review the JSON diff and rerun both suites.
Build from source (requires Rust toolchain):
@@ -547,3 +563,56 @@ runtime create operation saves the option; `Box.Start(ctx)` keeps that saved val
Runner reads its feature ENV at startup and chooses this creation option only for
eligible Cloud requests on supported hosts. This adds no start options or change
to default local creation. Changing organization policy affects future creates.
+
+Local agent VM acceptance uses the same scripted model and OpenCode 2.2.2 binary
+as the C/Rust tests, comparing normalized results, usage and first-event
+identity relationships. It checks unsupported operations, getters and a running
+turn completing after its local handle is released. It is outside hosted CI.
+
+```bash
+BOXLITE_TEST_OPENCODE_BINARY=/absolute/path/to/linux/opencode make test:integration:go:agents
+```
+
+The target builds C and Go callers, then runs the Rust comparison harness.
+The OpenCode binary must match the VM architecture and use glibc Linux; the
+Debian test image, VM support and complete runtime artifacts must be available.
+
+### Agent VM parity with Rust
+
+`make test:integration:go:agents` runs the three-language result comparison and
+Go equivalents of all 15 cases in
+[`agents_opencode.rs`](../../src/boxlite/tests/agents_opencode.rs).
+`TestGoAgentVMParity` uses the Rust test names as Go subtest names, so a failed
+scenario can be traced directly to its source contract.
+
+| Rust VM scenario | Go assertions |
+|---|---|
+| Concurrent creates, send/events/wait | One registered service, configuration, matching turn event, lookup through another handle |
+| Old turn beyond the first history page | Thirty turns outgrow the 50-message page; the first turn remains readable |
+| Restart with running and queued turns | Reacquire the Box and agent; both original turns complete |
+| Foreign server on the agent port | `ErrInvalidState` identifies the occupied port |
+| Missing OpenCode binary | `ErrExecution` identifies the required version |
+| User-owned ready or frozen service | Refuse takeover; preserve the service URL and PID |
+| Stale service registration | Recover the service without signalling the unrelated PID |
+| Environment reads and questions | `.env.example` is readable, `.env`/`.env.local` stay secret, denied questions do not block later work |
+| Frozen BoxLite service | Report unresponsiveness; after thawing, reuse its PID |
+| Remote service configuration | Refuse local startup and leave no local registration |
+| Delivered binary outside the image PATH | Agent runs from a read-only mount without adding an image executable |
+| Repeated installation | Reuse a single mount |
+| Installation after a failed file lookup | The new executable becomes visible on the existing mount |
+| Restart of a delivered agent | First Go lookup restores its recorded mount |
+| Failed mount after restart | Surface the error, keep the VM running, and retry after removing the blocker |
+
+The five installation scenarios use a `test-support` C fixture that calls the
+existing Rust-only `install_from_host` setup method. It is excluded from
+`boxlite.h` and normal builds; it adds no Go installation API. Subsequent agent
+calls, visibility checks and restart recovery use the real Go SDK and VM.
+
+The security cases observe the shared model's reply, which includes `SECRET`
+only when a tool actually returned it. Service assertions inspect the guest's
+registration and process state. These tests run outside hosted CI and require
+the same complete runtime artifacts and OpenCode binary as the comparison.
+
+For a scenario-only rerun, use `make test:integration:go:agents:parity` with the
+same binary/runtime environment. `BOXLITE_GO_AGENT_VM_FILTER` optionally selects
+a Go test/subtest pattern; omit it for the complete 15-scenario matrix.
diff --git a/sdks/go/agents.go b/sdks/go/agents.go
index 0b7d45c1f..05bea1ddb 100644
--- a/sdks/go/agents.go
+++ b/sdks/go/agents.go
@@ -197,10 +197,3 @@ type AgentTurn struct{ native *agentTurnHandle }
// 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) 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
index 031e759a6..8e38bdc41 100644
--- a/sdks/go/agents_bridge.c
+++ b/sdks/go/agents_bridge.c
@@ -3,6 +3,8 @@
extern void goBoxliteAgentCreated(struct CAgent *, CBoxliteError *, uintptr_t);
extern void goBoxliteAgentTurn(struct CAgentTurn *, CBoxliteError *, uintptr_t);
extern void goBoxliteAgentJSON(char *, CBoxliteError *, uintptr_t);
+extern void goBoxliteAgentOpened(struct CAgentEvents *, CBoxliteError *, uintptr_t);
+extern void goBoxliteAgentEvent(char *, CBoxliteError *, uintptr_t);
static void agent_created(struct CAgent *agent, const CBoxliteError *error, void *data) {
goBoxliteAgentCreated(agent, (CBoxliteError *)error, (uintptr_t)data);
@@ -46,3 +48,21 @@ enum BoxliteErrorCode go_agent_steer(struct CAgentTurn *turn, const char *text,
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);
}
+static void agent_opened(struct CAgentEvents *events, const CBoxliteError *error, void *data) {
+ goBoxliteAgentOpened(events, (CBoxliteError *)error, (uintptr_t)data);
+}
+static void agent_event(const char *json, const CBoxliteError *error, void *data) {
+ goBoxliteAgentEvent((char *)json, (CBoxliteError *)error, (uintptr_t)data);
+}
+enum BoxliteErrorCode go_agent_events(struct CAgent *agent, const struct CAgentEventsOptions *options, uintptr_t token, CBoxliteError *error) {
+ return boxlite_agent_events(agent, options, agent_opened, agent_event, (void *)token, error);
+}
+enum BoxliteErrorCode go_agent_turn_events(struct CAgentTurn *turn, const struct CAgentEventsOptions *options, uintptr_t token, CBoxliteError *error) {
+ return boxlite_agent_turn_events(turn, options, agent_opened, agent_event, (void *)token, error);
+}
+/* Inspect at most limit + 1 bytes before Go decides whether to allocate a copy. */
+size_t go_agent_event_length(const char *json, size_t limit) {
+ size_t length = 0;
+ while (length <= limit && json[length] != '\0') length++;
+ return length;
+}
diff --git a/sdks/go/agents_bridge.h b/sdks/go/agents_bridge.h
index 58388f790..f974a8e7e 100644
--- a/sdks/go/agents_bridge.h
+++ b/sdks/go/agents_bridge.h
@@ -13,4 +13,8 @@ enum BoxliteErrorCode go_agent_respond(struct CAgent *, const char *, const char
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 *);
+enum BoxliteErrorCode go_agent_events(struct CAgent *, const struct CAgentEventsOptions *, uintptr_t, CBoxliteError *);
+enum BoxliteErrorCode go_agent_turn_events(struct CAgentTurn *, const struct CAgentEventsOptions *, uintptr_t, CBoxliteError *);
+void boxlite_go_drain_subscription(CBoxliteRuntime *, int);
+size_t go_agent_event_length(const char *, size_t);
#endif
diff --git a/sdks/go/agents_json_test.go b/sdks/go/agents_json_test.go
index 033c824ee..786111676 100644
--- a/sdks/go/agents_json_test.go
+++ b/sdks/go/agents_json_test.go
@@ -7,6 +7,7 @@ import (
"math"
"os"
"reflect"
+ "strings"
"testing"
"time"
)
@@ -475,3 +476,39 @@ func TestAgentFutureStatusesAndFields(t *testing.T) {
t.Fatalf("future steering status: %+v, %v", receipt, err)
}
}
+
+func TestAgentEventRequiredFields(t *testing.T) {
+ for _, field := range []string{"cursor", "turn_id", "agent_id", "kind", "data"} {
+ t.Run(field, func(t *testing.T) {
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(agentFixture(t, "event"), &fields); err != nil {
+ t.Fatal(err)
+ }
+ delete(fields, field)
+ wire, err := json.Marshal(fields)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var decode *AgentEventDecodeError
+ if event, err := parseAgentEvent(wire); !errors.As(err, &decode) || event != nil || !strings.Contains(err.Error(), "missing required field "+field) {
+ t.Fatalf("accepted event missing %s", field)
+ }
+ })
+ }
+}
+
+func TestAgentEventMistypedMetadata(t *testing.T) {
+ for _, field := range []string{"kind", "agent_id", "cursor", "turn_id"} {
+ for _, value := range []string{`{"sensitive-payload":true}`, "null"} {
+ if value == "null" && (field == "turn_id" || field == "cursor") {
+ continue
+ }
+ wire := agentField(t, agentFixture(t, "event_null"), field, json.RawMessage(value))
+ var decode *AgentEventDecodeError
+ event, err := parseAgentEvent(wire)
+ if event != nil || !errors.As(err, &decode) || !strings.Contains(err.Error(), field+" must be a string") || strings.Contains(err.Error(), "sensitive-payload") {
+ t.Fatalf("unexpected error for %s: %v", field, err)
+ }
+ }
+ }
+}
diff --git a/sdks/go/agents_native_test.go b/sdks/go/agents_native_test.go
index 987cc1601..8692cdec1 100644
--- a/sdks/go/agents_native_test.go
+++ b/sdks/go/agents_native_test.go
@@ -221,6 +221,8 @@ func TestAgentUninitializedAndReleasedHandles(t *testing.T) {
checkAgentError(t, state, err, ErrInvalidState)
turn, err := agent.Send(ctx, "work", AgentSendOptions{})
checkAgentError(t, turn, err, ErrInvalidState)
+ stream, err := agent.Events(ctx, AgentEventsOptions{})
+ checkAgentError(t, stream, err, ErrInvalidState)
}
for _, turn := range []*AgentTurn{nil, {}} {
state, err := turn.State()
diff --git a/sdks/go/agents_records.go b/sdks/go/agents_records.go
index 4f0f1f924..c28c1153d 100644
--- a/sdks/go/agents_records.go
+++ b/sdks/go/agents_records.go
@@ -162,20 +162,55 @@ func parseAgentRequests(data []byte) ([]AgentRequest, error) {
return agentRequests(records)
}
+// AgentEventDecodeError reports an invalid outer event record. Next consumes
+// the record; callers may continue reading from the same subscription.
+type AgentEventDecodeError struct {
+ cause Error
+}
+
+func (e *AgentEventDecodeError) Error() string { return e.cause.Error() }
+func (e *AgentEventDecodeError) Unwrap() error { return &e.cause }
+
+func eventDecodeError(reason string) error {
+ return &AgentEventDecodeError{cause: Error{Code: ErrInternal, Message: "agent event: " + reason}}
+}
+
func parseAgentEvent(data []byte) (*AgentEvent, error) {
- var record struct {
- Cursor string `json:"cursor"`
- AgentID string `json:"agent_id"`
- TurnID string `json:"turn_id"`
- Kind string `json:"kind"`
- Data json.RawMessage `json:"data"`
+ var fields map[string]json.RawMessage
+ if !utf8.Valid(data) || json.Unmarshal(data, &fields) != nil || fields == nil {
+ return nil, eventDecodeError("expected a valid UTF-8 JSON object")
+ }
+ event := &AgentEvent{}
+ for _, field := range []struct {
+ name string
+ dest *string
+ nullable bool
+ }{
+ {"cursor", &event.Cursor, true},
+ {"agent_id", &event.AgentID, false},
+ {"turn_id", &event.TurnID, true},
+ {"kind", &event.Kind, false},
+ } {
+ raw, ok := fields[field.name]
+ if !ok {
+ return nil, eventDecodeError("missing required field " + field.name)
+ }
+ if field.nullable && bytes.Equal(raw, []byte("null")) {
+ continue
+ }
+ if raw[0] != '"' || json.Unmarshal(raw, field.dest) != nil {
+ reason := " must be a string"
+ if field.nullable {
+ reason += " or null"
+ }
+ return nil, eventDecodeError(field.name + reason)
+ }
}
- if err := decodeAgentRecord(data, &record); err != nil {
- return nil, err
+ event.Data = fields["data"]
+ if event.Data == nil {
+ return nil, eventDecodeError("missing required field data")
}
- return &AgentEvent{
- Cursor: record.Cursor, AgentID: record.AgentID, TurnID: record.TurnID, Kind: record.Kind, Data: record.Data,
- }, nil
+ return event, nil
}
func agentTurnStatus(value string) AgentTurnStatus {
diff --git a/sdks/go/agents_stream.go b/sdks/go/agents_stream.go
new file mode 100644
index 000000000..abfa5c279
--- /dev/null
+++ b/sdks/go/agents_stream.go
@@ -0,0 +1,420 @@
+package boxlite
+
+/*
+#include "agents_bridge.h"
+*/
+import "C"
+
+import (
+ "context"
+ "io"
+ "runtime"
+ "runtime/cgo"
+ "sync"
+ "unsafe"
+)
+
+const (
+ agentStreamCount = 64
+ agentStreamBytes = 4 * 1024 * 1024
+)
+
+// The runtime retains callback state until terminal delivery, and buffered
+// records until the wrapper closes, becomes unreachable, or its runtime closes.
+// Public wrappers can become unreachable without keeping the subscription open.
+// No lock is held while invoking a native release or stopping a context watcher.
+type agentSubscription struct {
+ owner *Runtime
+ token cgo.Handle
+ mu sync.Mutex
+ ptr *C.struct_CAgentEvents
+ opened bool
+ terminal bool
+ retired bool
+ canceled bool
+ closed bool
+ reading bool
+ runtimeClosed bool
+ openErr error
+ err error
+ queue [][]byte
+ bytes int
+ changed chan struct{}
+ openDone chan struct{}
+ done chan struct{}
+ ctx context.Context
+ stopWatch func() bool
+}
+type agentEventStream struct{ state *agentSubscription }
+
+func (s *agentSubscription) signalLocked() { close(s.changed); s.changed = make(chan struct{}) }
+func (s *agentSubscription) takeLocked() *C.struct_CAgentEvents { p := s.ptr; s.ptr = nil; return p }
+func freeAgentEvents(p *C.struct_CAgentEvents) {
+ if p != nil {
+ C.boxlite_agent_events_free(p)
+ }
+}
+func (s *agentSubscription) stopWatching() {
+ s.mu.Lock()
+ stop := s.stopWatch
+ s.stopWatch = nil
+ s.ctx = nil
+ s.mu.Unlock()
+ if stop != nil {
+ stop()
+ }
+}
+func (s *agentSubscription) watch(ctx context.Context) {
+ stop := context.AfterFunc(ctx, func() { s.cancel(ctx.Err()) })
+ s.mu.Lock()
+ if s.terminal || s.closed || s.runtimeClosed {
+ s.mu.Unlock()
+ stop()
+ return
+ }
+ s.stopWatch = stop
+ s.mu.Unlock()
+}
+func (s *agentSubscription) cancel(err error) {
+ s.mu.Lock()
+ if s.terminal || s.closed || s.runtimeClosed {
+ s.mu.Unlock()
+ return
+ }
+ if s.err == nil {
+ s.err = err
+ }
+ s.canceled = true
+ p := s.takeLocked()
+ s.signalLocked()
+ s.mu.Unlock()
+ freeAgentEvents(p)
+}
+func (s *agentSubscription) close() {
+ s.mu.Lock()
+ s.closed = true
+ s.canceled = true
+ s.queue = nil
+ s.bytes = 0
+ p := s.takeLocked()
+ s.signalLocked()
+ s.mu.Unlock()
+ s.stopWatching()
+ freeAgentEvents(p)
+ s.forgetBuffer()
+}
+func (s *agentSubscription) shutdown() {
+ s.mu.Lock()
+ s.runtimeClosed = true
+ s.canceled = true
+ s.queue = nil
+ s.bytes = 0
+ p := s.takeLocked()
+ s.signalLocked()
+ s.mu.Unlock()
+ s.stopWatching()
+ freeAgentEvents(p)
+ s.forgetBuffer()
+}
+func (s *agentSubscription) forgetBuffer() {
+ s.owner.agentStreamsMu.Lock()
+ delete(s.owner.agentBuffers, s)
+ s.owner.agentStreamsMu.Unlock()
+}
+func (s *agentSubscription) retire() {
+ s.mu.Lock()
+ if s.retired {
+ s.mu.Unlock()
+ return
+ }
+ s.retired = true
+ forget := s.closed || s.runtimeClosed || s.openErr != nil
+ s.mu.Unlock()
+ s.owner.agentStreamsMu.Lock()
+ delete(s.owner.agentStreams, uintptr(s.token))
+ s.owner.agentStreamsMu.Unlock()
+ if forget {
+ s.forgetBuffer()
+ }
+ s.token.Delete()
+ close(s.done)
+}
+func (s *agentSubscription) finish(err error) {
+ s.mu.Lock()
+ s.terminal = true
+ if s.err == nil && !s.closed {
+ s.err = err
+ if err == nil && s.ctx != nil {
+ s.err = s.ctx.Err()
+ }
+ }
+ p := s.takeLocked()
+ s.signalLocked()
+ s.mu.Unlock()
+ s.stopWatching()
+ freeAgentEvents(p)
+ s.retire()
+}
+func (s *agentSubscription) runtimeEnded() {
+ s.shutdown()
+ s.mu.Lock()
+ s.terminal = true
+ s.mu.Unlock()
+ s.retire()
+}
+func runtimeAgentClosed(r *Runtime) bool {
+ select {
+ case <-r.closing:
+ return true
+ default:
+ return false
+ }
+}
+
+func openAgentEvents[P comparable](ctx context.Context, h *agentHandle[P], options AgentEventsOptions, submit func(P, *C.struct_CAgentEventsOptions, C.uintptr_t, *C.CBoxliteError) C.enum_BoxliteErrorCode) (AgentEventStream, error) {
+ if err := agentContextError(ctx); err != nil {
+ return nil, err
+ }
+ var args agentArguments
+ defer args.free()
+ opts := C.struct_CAgentEventsOptions{after: args.string(options.After, "after", true)}
+ if args.err != nil {
+ return nil, args.err
+ }
+ p, unlock, err := h.acquire()
+ if err != nil {
+ return nil, err
+ }
+ r := h.owner
+ s := &agentSubscription{owner: r, changed: make(chan struct{}), openDone: make(chan struct{}), done: make(chan struct{}), ctx: ctx}
+ s.token = cgo.NewHandle(s)
+ r.agentStreamsMu.Lock()
+ if r.agentStreams == nil {
+ r.agentStreams = make(map[uintptr]*agentSubscription)
+ }
+ if r.agentBuffers == nil {
+ r.agentBuffers = make(map[*agentSubscription]struct{})
+ }
+ r.agentStreams[uintptr(s.token)] = s
+ r.agentBuffers[s] = struct{}{}
+ r.agentStreamsMu.Unlock()
+ s.watch(ctx)
+ r.ensureDrainRunning()
+ var cerr C.CBoxliteError
+ code := submit(p, &opts, C.uintptr_t(s.token), &cerr)
+ unlock()
+ if code != C.Ok {
+ s.close()
+ s.finish(nil)
+ return nil, freeError(&cerr)
+ }
+ select {
+ case <-s.openDone:
+ if runtimeAgentClosed(r) {
+ s.shutdown()
+ return nil, ErrRuntimeClosed
+ }
+ if err := ctx.Err(); err != nil {
+ s.cancel(err)
+ s.close()
+ return nil, err
+ }
+ s.mu.Lock()
+ err := s.openErr
+ s.mu.Unlock()
+ if err != nil {
+ return nil, err
+ }
+ stream := &agentEventStream{state: s}
+ runtime.AddCleanup(stream, func(state *agentSubscription) { state.close() }, s)
+ return stream, nil
+ case <-ctx.Done():
+ s.cancel(ctx.Err())
+ s.close()
+ return nil, ctx.Err()
+ case <-r.closing:
+ s.shutdown()
+ return nil, ErrRuntimeClosed
+ }
+}
+func (a *Agent) Events(ctx context.Context, options AgentEventsOptions) (AgentEventStream, error) {
+ defer runtime.KeepAlive(a)
+ return openAgentEvents(ctx, agentSessionOf(a), options, func(p *C.struct_CAgent, o *C.struct_CAgentEventsOptions, t C.uintptr_t, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.go_agent_events(p, o, t, e)
+ })
+}
+func (t *AgentTurn) Events(ctx context.Context, options AgentEventsOptions) (AgentEventStream, error) {
+ defer runtime.KeepAlive(t)
+ return openAgentEvents(ctx, agentTurnOf(t), options, func(p *C.struct_CAgentTurn, o *C.struct_CAgentEventsOptions, t C.uintptr_t, e *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.go_agent_turn_events(p, o, t, e)
+ })
+}
+
+func (stream *agentEventStream) Close() error {
+ defer runtime.KeepAlive(stream)
+ stream.state.close()
+ return nil
+}
+
+// Shutdown takes precedence when both cancellation signals are observable.
+func (s *agentSubscription) readContextErrorLocked(ctx context.Context) error {
+ readErr := ctx.Err()
+ if s.runtimeClosed || runtimeAgentClosed(s.owner) {
+ return ErrRuntimeClosed
+ }
+ return readErr
+}
+
+func (stream *agentEventStream) Next(ctx context.Context) (*AgentEvent, error) {
+ defer runtime.KeepAlive(stream)
+ if ctx == nil {
+ return nil, agentJSONError(ErrInvalidArgument, "nil context")
+ }
+ s := stream.state
+ s.mu.Lock()
+ if err := s.readContextErrorLocked(ctx); err != nil {
+ s.mu.Unlock()
+ return nil, err
+ }
+ if s.reading {
+ s.mu.Unlock()
+ return nil, agentJSONError(ErrInvalidState, "concurrent event reader")
+ }
+ s.reading = true
+ s.mu.Unlock()
+ defer func() { s.mu.Lock(); s.reading = false; s.mu.Unlock() }()
+ for {
+ s.mu.Lock()
+ if err := s.readContextErrorLocked(ctx); err != nil {
+ s.mu.Unlock()
+ return nil, err
+ }
+ if len(s.queue) > 0 {
+ raw := s.queue[0]
+ s.queue[0] = nil
+ s.queue = s.queue[1:]
+ s.bytes -= len(raw)
+ s.mu.Unlock()
+ return parseAgentEvent(raw)
+ }
+ if s.err != nil {
+ err := s.err
+ s.mu.Unlock()
+ return nil, err
+ }
+ if s.terminal || s.closed {
+ s.mu.Unlock()
+ return nil, io.EOF
+ }
+ changed := s.changed
+ s.mu.Unlock()
+ select {
+ case <-changed:
+ case <-ctx.Done():
+ case <-s.owner.closing:
+ }
+ }
+}
+
+//export goBoxliteAgentOpened
+func goBoxliteAgentOpened(ptr *C.struct_CAgentEvents, cerr *C.CBoxliteError, token C.uintptr_t) {
+ s := cgo.Handle(token).Value().(*agentSubscription)
+ err := borrowedAgentError(cerr)
+ if ptr == nil && err == nil {
+ err = agentJSONError(ErrInternal, "event opening returned no handle")
+ }
+ s.mu.Lock()
+ s.opened = ptr != nil
+ s.ptr = ptr
+ s.openErr = err
+ if runtimeAgentClosed(s.owner) {
+ s.runtimeClosed = true
+ s.canceled = true
+ }
+ if s.ctx != nil && s.ctx.Err() != nil && !s.closed && !s.terminal {
+ if s.err == nil {
+ s.err = s.ctx.Err()
+ }
+ s.canceled = true
+ }
+ var release *C.struct_CAgentEvents
+ if s.canceled {
+ release = s.takeLocked()
+ }
+ close(s.openDone)
+ s.signalLocked()
+ s.mu.Unlock()
+ freeAgentEvents(release)
+ if err != nil {
+ s.finish(err)
+ }
+}
+
+//export goBoxliteAgentEvent
+func goBoxliteAgentEvent(json *C.char, cerr *C.CBoxliteError, token C.uintptr_t) {
+ s := cgo.Handle(token).Value().(*agentSubscription)
+ if json == nil {
+ s.finish(borrowedAgentError(cerr))
+ return
+ }
+ s.mu.Lock()
+ if s.canceled || s.closed || s.terminal || s.runtimeClosed {
+ s.mu.Unlock()
+ return
+ }
+ // Admission precedes Go allocation; oversized borrowed records are never copied.
+ length := int(C.go_agent_event_length(json, C.size_t(agentStreamBytes)))
+ if len(s.queue) >= agentStreamCount || length > agentStreamBytes-s.bytes {
+ if s.err == nil {
+ s.err = agentJSONError(ErrResourceExhausted, "agent event buffer exhausted")
+ }
+ s.canceled = true
+ p := s.takeLocked()
+ s.signalLocked()
+ s.mu.Unlock()
+ freeAgentEvents(p)
+ return
+ }
+ s.queue = append(s.queue, C.GoBytes(unsafe.Pointer(json), C.int(length)))
+ s.bytes += length
+ s.signalLocked()
+ s.mu.Unlock()
+}
+
+func (r *Runtime) agentStreamSnapshot() []*agentSubscription {
+ r.agentStreamsMu.Lock()
+ defer r.agentStreamsMu.Unlock()
+ streams := make([]*agentSubscription, 0, len(r.agentStreams))
+ for _, s := range r.agentStreams {
+ streams = append(streams, s)
+ }
+ return streams
+}
+func (r *Runtime) agentBufferSnapshot() []*agentSubscription {
+ r.agentStreamsMu.Lock()
+ defer r.agentStreamsMu.Unlock()
+ streams := make([]*agentSubscription, 0, len(r.agentBuffers))
+ for s := range r.agentBuffers {
+ streams = append(streams, s)
+ }
+ return streams
+}
+func (r *Runtime) connectedAgentStreams() int {
+ n := 0
+ for _, s := range r.agentStreamSnapshot() {
+ s.mu.Lock()
+ if s.opened && !s.terminal {
+ n++
+ }
+ s.mu.Unlock()
+ }
+ return n
+}
+
+// Called only after the ordinary drainer has joined. Pending native connects
+// without a transferred handle remain C-owned and do not delay runtime free.
+func (r *Runtime) drainAgentTerminals() {
+ for r.connectedAgentStreams() > 0 {
+ C.boxlite_go_drain_subscription(r.handle, C.int(drainTimeoutMs))
+ }
+}
diff --git a/sdks/go/agents_stream_test.go b/sdks/go/agents_stream_test.go
new file mode 100644
index 000000000..508e8ad34
--- /dev/null
+++ b/sdks/go/agents_stream_test.go
@@ -0,0 +1,759 @@
+//go:build boxlite_dev && boxlite_agent_test
+
+package boxlite
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "runtime"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// Done is observed only after the caller has reached the relevant wait/registration.
+// This gives tests an interleaving barrier without sleeping or polling goroutines.
+type agentObservedContext struct {
+ context.Context
+ observed chan struct{}
+ once sync.Once
+}
+
+func (c *agentObservedContext) Done() <-chan struct{} {
+ c.once.Do(func() { close(c.observed) })
+ return c.Context.Done()
+}
+func observedAgentContext(ctx context.Context) *agentObservedContext {
+ return &agentObservedContext{Context: ctx, observed: make(chan struct{})}
+}
+func openTestAgentStream(t *testing.T, a *Agent, ctx context.Context, after string) *agentEventStream {
+ t.Helper()
+ stream, err := a.Events(ctx, AgentEventsOptions{After: after})
+ if err != nil {
+ t.Fatal(err)
+ }
+ s := stream.(*agentEventStream)
+ t.Cleanup(func() { s.Close(); runtime.KeepAlive(a) })
+ return s
+}
+func waitAgentStream(t *testing.T, s *agentSubscription, predicate func(*agentSubscription) bool) {
+ t.Helper()
+ deadline := time.NewTimer(5 * time.Second)
+ defer deadline.Stop()
+ for {
+ s.mu.Lock()
+ ready := predicate(s)
+ changed := s.changed
+ s.mu.Unlock()
+ if ready {
+ return
+ }
+ select {
+ case <-changed:
+ case <-deadline.C:
+ t.Fatal("stream state did not arrive")
+ }
+ }
+}
+func nextAgent(t *testing.T, s AgentEventStream) *AgentEvent {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ e, err := s.Next(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return e
+}
+func stopTestDrainer(t *testing.T, r *Runtime) func() {
+ t.Helper()
+ b := testAgentBlockDrainer(r)
+ receiveAgent(t, b.entered)
+ var once sync.Once
+ release := func() { once.Do(func() { close(b.release) }) }
+ t.Cleanup(release)
+ return release
+}
+
+func TestAgentStreamWaitsForOpen(t *testing.T) {
+ r, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ release := stopTestDrainer(t, r)
+ defer release()
+ ctx := observedAgentContext(context.Background())
+ result := make(chan handleResult[AgentEventStream], 1)
+ go func() {
+ s, e := agent.Events(ctx, AgentEventsOptions{After: "pending"})
+ result <- handleResult[AgentEventStream]{value: s, err: e}
+ }()
+ receiveAgent(t, ctx.observed)
+ if !testAgentWaitPending(r) {
+ t.Fatal("opening not posted")
+ }
+ select {
+ case <-result:
+ t.Fatal("Events returned before on_open")
+ default:
+ }
+ release()
+ got := receiveAgent(t, result)
+ if got.err != nil {
+ t.Fatal(got.err)
+ }
+ stream := got.value.(*agentEventStream)
+ before := testAgentEventFrees()
+ if err := stream.Close(); err != nil {
+ t.Fatal(err)
+ }
+ receiveAgent(t, stream.state.done)
+ stream.Close()
+ if testAgentEventFrees()-before != 1 {
+ t.Fatal("subscription was not freed exactly once")
+ }
+ if len(r.agentStreamSnapshot()) != 0 {
+ t.Fatal("terminal retained callback token")
+ }
+ stream.state.mu.Lock()
+ watch := stream.state.stopWatch
+ stream.state.mu.Unlock()
+ if watch != nil {
+ t.Fatal("terminal retained subscription context watcher")
+ }
+}
+
+func TestAgentStreamNativeEndAndErrors(t *testing.T) {
+ for _, after := range []string{"", "read-error", "open-error"} {
+ t.Run(after, func(t *testing.T) {
+ r, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ raw, err := agent.Events(ctx, AgentEventsOptions{After: after})
+ if after == "open-error" {
+ checkAgentError(t, raw, err, ErrNetwork)
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ stream := raw.(*agentEventStream)
+ defer stream.Close()
+ receiveAgent(t, stream.state.done)
+ if after == "read-error" {
+ first := nextAgent(t, stream)
+ if first.Kind != "first" || first.AgentID != "agent-1" {
+ t.Fatalf("event=%+v", first)
+ }
+ e, err := stream.Next(context.Background())
+ checkAgentError(t, e, err, ErrNetwork)
+ stream.Close()
+ e, err = stream.Next(context.Background())
+ checkAgentError(t, e, err, ErrNetwork)
+ } else {
+ cancel() // Native completion wins over later subscription-context cancellation.
+ for range 2 {
+ e, err := stream.Next(context.Background())
+ if e != nil || !errors.Is(err, io.EOF) {
+ t.Fatalf("end=%v %v", e, err)
+ }
+ }
+ }
+ if len(r.agentStreamSnapshot()) != 0 {
+ t.Fatal("terminal retained callback state")
+ }
+ })
+ }
+}
+
+func TestAgentTurnStreamReachesNative(t *testing.T) {
+ _, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ turn, err := agent.Send(context.Background(), "task", AgentSendOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, err := turn.Events(context.Background(), AgentEventsOptions{After: "read-error"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ stream := raw.(*agentEventStream)
+ defer stream.Close()
+ first := nextAgent(t, stream)
+ if first.Kind != "first" {
+ t.Fatalf("event=%+v", first)
+ }
+ e, err := stream.Next(context.Background())
+ checkAgentError(t, e, err, ErrNetwork)
+ runtime.KeepAlive(turn)
+}
+
+func TestAgentStreamReaderCancellationDoesNotConsume(t *testing.T) {
+ _, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ stream := openTestAgentStream(t, agent, context.Background(), "events")
+ waitAgentStream(t, stream.state, func(s *agentSubscription) bool { return len(s.queue) == 2 })
+ canceled, cancel := context.WithCancel(context.Background())
+ cancel()
+ e, err := stream.Next(canceled)
+ if e != nil || !errors.Is(err, context.Canceled) {
+ t.Fatalf("read=%v %v", e, err)
+ }
+ if nextAgent(t, stream).Kind != "first" || nextAgent(t, stream).Kind != "second" {
+ t.Fatal("canceled read lost an event")
+ }
+}
+
+func TestAgentStreamRejectsConcurrentReaders(t *testing.T) {
+ _, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ stream := openTestAgentStream(t, agent, context.Background(), "pending")
+ parent, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ ctx := observedAgentContext(parent)
+ done := make(chan error, 1)
+ go func() { _, e := stream.Next(ctx); done <- e }()
+ receiveAgent(t, ctx.observed)
+ e, err := stream.Next(context.Background())
+ checkAgentError(t, e, err, ErrInvalidState)
+ cancel()
+ if err := receiveAgent(t, done); !errors.Is(err, context.Canceled) {
+ t.Fatal(err)
+ }
+ stream.state.mu.Lock()
+ canceled := stream.state.canceled
+ ptr := stream.state.ptr
+ stream.state.mu.Unlock()
+ if canceled || ptr == nil {
+ t.Fatal("read cancellation canceled native subscription")
+ }
+ stream.Close()
+ e, err = stream.Next(context.Background())
+ if e != nil || !errors.Is(err, io.EOF) {
+ t.Fatalf("close=%v %v", e, err)
+ }
+ receiveAgent(t, stream.state.done)
+}
+
+func TestAgentStreamContextCancellationPreservesPrefix(t *testing.T) {
+ _, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ stream := openTestAgentStream(t, agent, ctx, "events")
+ waitAgentStream(t, stream.state, func(s *agentSubscription) bool { return len(s.queue) == 2 })
+ cancel()
+ receiveAgent(t, stream.state.done)
+ if nextAgent(t, stream).Kind != "first" || nextAgent(t, stream).Kind != "second" {
+ t.Fatal("prefix lost")
+ }
+ for range 2 {
+ e, err := stream.Next(context.Background())
+ if e != nil || !errors.Is(err, context.Canceled) {
+ t.Fatalf("end=%v %v", e, err)
+ }
+ }
+ stream.Close()
+ e, err := stream.Next(context.Background())
+ if e != nil || !errors.Is(err, context.Canceled) {
+ t.Fatalf("close erased error: %v", err)
+ }
+}
+
+func TestAgentStreamLateOpeningAfterCancellation(t *testing.T) {
+ for _, after := range []string{"pending", "open-error"} {
+ t.Run(after, func(t *testing.T) {
+ r, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ release := stopTestDrainer(t, r)
+ defer release()
+ parent, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ ctx := observedAgentContext(parent)
+ done := make(chan handleResult[AgentEventStream], 1)
+ go func() {
+ v, e := agent.Events(ctx, AgentEventsOptions{After: after})
+ done <- handleResult[AgentEventStream]{value: v, err: e}
+ }()
+ receiveAgent(t, ctx.observed)
+ if !testAgentWaitPending(r) {
+ t.Fatal("native open not queued")
+ }
+ states := r.agentStreamSnapshot()
+ if len(states) != 1 {
+ t.Fatal("missing opening state")
+ }
+ before := testAgentEventFrees()
+ cancel()
+ result := receiveAgent(t, done)
+ if result.value != nil || !errors.Is(result.err, context.Canceled) {
+ t.Fatalf("opening=%+v", result)
+ }
+ release()
+ receiveAgent(t, states[0].done)
+ want := 0
+ if after == "pending" {
+ want = 1
+ }
+ if testAgentEventFrees()-before != want {
+ t.Fatal("late opening ownership mismatch")
+ }
+ if len(r.agentStreamSnapshot()) != 0 {
+ t.Fatal("late opening retained callback token")
+ }
+ })
+ }
+}
+
+func TestAgentStreamCountOverflowKeepsPrefixAndDrainerResponsive(t *testing.T) {
+ _, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ stream := openTestAgentStream(t, agent, context.Background(), "many")
+ receiveAgent(t, stream.state.done)
+ stream.state.mu.Lock()
+ count := len(stream.state.queue)
+ stream.state.mu.Unlock()
+ if count != agentStreamCount {
+ t.Fatalf("buffered %d events", count)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ requests, err := agent.Requests(ctx)
+ if err != nil || len(requests) != 1 {
+ t.Fatalf("slow reader blocked request: %v", err)
+ }
+ for i := range agentStreamCount {
+ if e := nextAgent(t, stream); e.Kind != fmt.Sprint(i) {
+ t.Fatalf("event %d=%+v", i, e)
+ }
+ }
+ for range 2 {
+ e, err := stream.Next(context.Background())
+ checkAgentError(t, e, err, ErrResourceExhausted)
+ }
+}
+
+func TestAgentStreamByteBoundaries(t *testing.T) {
+ tests := []struct {
+ name, after string
+ count, bytes int
+ overflow bool
+ }{
+ {"exact record", fmt.Sprintf("bytes:%d", agentStreamBytes), 1, agentStreamBytes, false},
+ {"oversize record", fmt.Sprintf("bytes:%d", agentStreamBytes+1), 0, 0, true},
+ {"exact aggregate", fmt.Sprintf("bytes:%d,%d", agentStreamBytes/2, agentStreamBytes/2), 2, agentStreamBytes, false},
+ {"aggregate one over", fmt.Sprintf("bytes:%d,%d", agentStreamBytes/2, agentStreamBytes/2+1), 1, agentStreamBytes / 2, true},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ r, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ release := stopTestDrainer(t, r)
+ defer release()
+ ctx := observedAgentContext(context.Background())
+ result := make(chan handleResult[AgentEventStream], 1)
+ go func() {
+ v, e := agent.Events(ctx, AgentEventsOptions{After: tt.after})
+ result <- handleResult[AgentEventStream]{value: v, err: e}
+ }()
+ receiveAgent(t, ctx.observed)
+ if !testAgentWaitPending(r) {
+ t.Fatal("native open missing")
+ }
+ var before runtime.MemStats
+ runtime.ReadMemStats(&before)
+ release()
+ got := receiveAgent(t, result)
+ if got.err != nil {
+ t.Fatal(got.err)
+ }
+ stream := got.value.(*agentEventStream)
+ defer stream.Close()
+ receiveAgent(t, stream.state.done)
+ var after runtime.MemStats
+ runtime.ReadMemStats(&after)
+ stream.state.mu.Lock()
+ count, bytes, err := len(stream.state.queue), stream.state.bytes, stream.state.err
+ stream.state.mu.Unlock()
+ if count != tt.count || bytes != tt.bytes {
+ t.Fatalf("buffer count=%d bytes=%d", count, bytes)
+ }
+ if tt.overflow {
+ checkAgentError(t, nil, err, ErrResourceExhausted)
+ } else if err != nil {
+ t.Fatal(err)
+ }
+ if tt.count == 0 && after.TotalAlloc-before.TotalAlloc >= 1024*1024 {
+ t.Fatalf("oversized record allocated %d Go bytes before rejection", after.TotalAlloc-before.TotalAlloc)
+ }
+ })
+ }
+}
+
+func TestAgentStreamRuntimeCloseOverridesBufferAndError(t *testing.T) {
+ r, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ stream := openTestAgentStream(t, agent, context.Background(), "read-error")
+ receiveAgent(t, stream.state.done) // Preserve a native error and buffered prefix first.
+ r.Close()
+ stream.state.mu.Lock()
+ buffered := len(stream.state.queue)
+ stream.state.mu.Unlock()
+ if buffered != 0 {
+ t.Fatal("runtime retained a completed stream's buffered events")
+ }
+ e, err := stream.Next(context.Background())
+ if e != nil || !errors.Is(err, ErrRuntimeClosed) {
+ t.Fatalf("runtime end=%v %v", e, err)
+ }
+}
+
+func TestAgentStreamRuntimeCloseWithPendingConnect(t *testing.T) {
+ r, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ ctx := observedAgentContext(context.Background())
+ done := make(chan error, 1)
+ go func() {
+ s, e := agent.Events(ctx, AgentEventsOptions{After: "open-pending"})
+ if s != nil {
+ e = errors.New("closed opening returned a stream")
+ }
+ done <- e
+ }()
+ receiveAgent(t, ctx.observed)
+ states := r.agentStreamSnapshot()
+ if len(states) != 1 {
+ t.Fatal("pending opening missing")
+ }
+ closed := make(chan struct{})
+ go func() { r.Close(); close(closed) }()
+ receiveAgent(t, closed)
+ if e := receiveAgent(t, done); !errors.Is(e, ErrRuntimeClosed) {
+ t.Fatal(e)
+ }
+ receiveAgent(t, states[0].done)
+ if len(r.agentStreamSnapshot()) != 0 {
+ t.Fatal("pending open leaked token")
+ }
+}
+
+func TestAgentStreamRuntimeCloseWithFullQueueAndLateOpen(t *testing.T) {
+ r, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ release := stopTestDrainer(t, r)
+ defer release()
+ ctx := observedAgentContext(context.Background())
+ done := make(chan error, 1)
+ go func() {
+ s, e := agent.Events(ctx, AgentEventsOptions{After: "continuous"})
+ if s != nil {
+ e = errors.New("closed opening returned a stream")
+ }
+ done <- e
+ }()
+ receiveAgent(t, ctx.observed)
+ // The real C queue is full while its drainer is held before on_open.
+ if !testAgentWaitQueue(r, 4096) {
+ t.Fatal("native producer did not fill queue")
+ }
+ states := r.agentStreamSnapshot()
+ if len(states) != 1 {
+ t.Fatal("missing opening")
+ }
+ closed := make(chan struct{})
+ go func() { r.Close(); close(closed) }()
+ receiveAgent(t, r.closing)
+ if e := receiveAgent(t, done); !errors.Is(e, ErrRuntimeClosed) {
+ t.Fatal(e)
+ }
+ release()
+ receiveAgent(t, closed)
+ receiveAgent(t, states[0].done)
+ if len(r.agentStreamSnapshot()) != 0 {
+ t.Fatal("late-open terminal tracking leaked")
+ }
+}
+
+func TestAgentStreamTwoRuntimesDrainIndependently(t *testing.T) {
+ first, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ stream := openTestAgentStream(t, agent, context.Background(), "pending")
+ release := stopTestDrainer(t, first)
+ defer release()
+ second, b := testAgents(t, false)
+ other := testCreateAgent(t, b)
+ closed := make(chan struct{})
+ go func() { first.Close(); close(closed) }()
+ receiveAgent(t, first.closing)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ turn, err := other.Send(ctx, "independent", AgentSendOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ result, err := turn.Wait(ctx, AgentWaitOptions{})
+ if err != nil || result.Text != "independent" {
+ t.Fatalf("second runtime blocked: %+v %v", result, err)
+ }
+ release()
+ receiveAgent(t, closed)
+ receiveAgent(t, stream.state.done)
+ second.Close()
+ runtime.KeepAlive(turn)
+}
+
+func TestAgentStreamInvalidOpeningNeverRegisters(t *testing.T) {
+ r, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ for _, cursor := range []string{"bad\x00cursor", string([]byte{255})} {
+ stream, err := agent.Events(context.Background(), AgentEventsOptions{After: cursor})
+ checkAgentError(t, stream, err, ErrInvalidArgument)
+ }
+ stream, err := agent.Events(nil, AgentEventsOptions{})
+ checkAgentError(t, stream, err, ErrInvalidArgument)
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ stream, err = agent.Events(ctx, AgentEventsOptions{})
+ if stream != nil || !errors.Is(err, context.Canceled) {
+ t.Fatalf("canceled open=%v %v", stream, err)
+ }
+ if len(r.agentStreamSnapshot()) != 0 {
+ t.Fatal("invalid opening registered native callback state")
+ }
+}
+
+func TestAgentStreamCloseDiscardsUnreadEvents(t *testing.T) {
+ _, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ stream := openTestAgentStream(t, agent, ctx, "events")
+ waitAgentStream(t, stream.state, func(s *agentSubscription) bool { return len(s.queue) == 2 })
+ stream.Close()
+ stream.Close()
+ receiveAgent(t, stream.state.done)
+ cancel()
+ e, err := stream.Next(context.Background())
+ if e != nil || !errors.Is(err, io.EOF) {
+ t.Fatalf("close=%v %v", e, err)
+ }
+ stream.state.mu.Lock()
+ count, bytes := len(stream.state.queue), stream.state.bytes
+ stream.state.mu.Unlock()
+ if count != 0 || bytes != 0 {
+ t.Fatal("Close retained unread records")
+ }
+}
+
+func TestAgentStreamConcurrentCloseNextAndRuntime(t *testing.T) {
+ for range 8 {
+ r, a := testAgents(t, false)
+ agent := testCreateAgent(t, a)
+ stream := openTestAgentStream(t, agent, context.Background(), "pending")
+ ctx := observedAgentContext(context.Background())
+ read := make(chan error, 1)
+ go func() { _, e := stream.Next(ctx); read <- e }()
+ receiveAgent(t, ctx.observed)
+ before := testAgentEventFrees()
+ start := make(chan struct{})
+ var wg sync.WaitGroup
+ for range 2 {
+ wg.Add(1)
+ go func() { defer wg.Done(); <-start; stream.Close() }()
+ }
+ wg.Add(1)
+ go func() { defer wg.Done(); <-start; r.Close() }()
+ close(start)
+ wg.Wait()
+ e := receiveAgent(t, read)
+ if !errors.Is(e, io.EOF) && !errors.Is(e, ErrRuntimeClosed) {
+ t.Fatal(e)
+ }
+ receiveAgent(t, stream.state.done)
+ if testAgentEventFrees()-before != 1 {
+ t.Fatal("concurrent close double-freed native subscription")
+ }
+ }
+}
+
+func TestAgentStreamDecodeRecovery(t *testing.T) {
+ _, ns := testAgents(t, false)
+ agent := testCreateAgent(t, ns)
+ stream := openTestAgentStream(t, agent, context.Background(), "after-response")
+ if first := nextAgent(t, stream); first.Kind != "first" {
+ t.Fatalf("first event: %+v", first)
+ }
+ testDeliverAgentRecord(stream.state, `{"agent_id":"a","turn_id":null,"kind":7,"cursor":null,"data":"sensitive-payload"}`)
+ event, err := stream.Next(context.Background())
+ var decode *AgentEventDecodeError
+ if event != nil || !errors.As(err, &decode) || !strings.Contains(err.Error(), "kind") || strings.Contains(err.Error(), "sensitive-payload") {
+ t.Fatalf("unexpected decode result: %v %v", event, err)
+ }
+ stream.state.mu.Lock()
+ active := !stream.state.canceled && stream.state.ptr != nil
+ stream.state.mu.Unlock()
+ if !active {
+ t.Fatal("decode error released the native subscription")
+ }
+ if _, err := agent.Respond(context.Background(), "request-1", AgentAnswer{Text: "continue"}, AgentControlOptions{}); err != nil {
+ t.Fatal(err)
+ }
+ got := nextAgent(t, stream)
+ if got.Kind != "future" || string(got.Data) != "1e+400" {
+ t.Fatalf("later event: %+v", got)
+ }
+ receiveAgent(t, stream.state.done)
+ if _, err := stream.Next(context.Background()); !errors.Is(err, io.EOF) {
+ t.Fatal(err)
+ }
+
+}
+
+func TestAgentStreamDecodeRuntimePrecedence(t *testing.T) {
+ r, ns := testAgents(t, false)
+ stream := openTestAgentStream(t, testCreateAgent(t, ns), context.Background(), "pending")
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ r.Close()
+ if _, err := stream.Next(ctx); !errors.Is(err, ErrRuntimeClosed) {
+ t.Fatalf("both closed: %v", err)
+ }
+}
+
+// Pause the first Err observation until shutdown and read cancellation overlap.
+type agentReadBarrierContext struct {
+ context.Context
+ entered chan struct{}
+ once sync.Once
+}
+
+func (c *agentReadBarrierContext) Err() error {
+ c.once.Do(func() {
+ close(c.entered)
+ <-c.Done()
+ })
+ return c.Context.Err()
+}
+
+func TestAgentStreamRuntimeClosesDuringReadErrorCheck(t *testing.T) {
+ r, ns := testAgents(t, false)
+ stream := openTestAgentStream(t, testCreateAgent(t, ns), context.Background(), "pending")
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ read := &agentReadBarrierContext{Context: ctx, entered: make(chan struct{})}
+ result := make(chan error, 1)
+ go func() {
+ _, err := stream.Next(read)
+ result <- err
+ }()
+ receiveAgent(t, read.entered)
+ closed := make(chan error, 1)
+ go func() { closed <- r.Close() }()
+ receiveAgent(t, r.closing)
+ cancel()
+ if err := receiveAgent(t, result); !errors.Is(err, ErrRuntimeClosed) {
+ t.Errorf("Next during runtime shutdown returned %v, want ErrRuntimeClosed", err)
+ }
+ if err := receiveAgent(t, closed); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestAgentStreamDecodeClose(t *testing.T) {
+ _, ns := testAgents(t, false)
+ stream := openTestAgentStream(t, testCreateAgent(t, ns), context.Background(), "pending")
+ testDeliverAgentRecord(stream.state, "{}")
+ var decode *AgentEventDecodeError
+ if _, err := stream.Next(context.Background()); !errors.As(err, &decode) {
+ t.Fatal(err)
+ }
+ if err := stream.Close(); err != nil {
+ t.Fatal(err)
+ }
+ receiveAgent(t, stream.state.done)
+ if _, err := stream.Next(context.Background()); !errors.Is(err, io.EOF) {
+ t.Fatal(err)
+ }
+}
+
+func TestAgentStreamDecodePreservesNativeError(t *testing.T) {
+ _, ns := testAgents(t, false)
+ stream := openTestAgentStream(t, testCreateAgent(t, ns), context.Background(), "read-error")
+ receiveAgent(t, stream.state.done)
+ // Corrupt the one buffered record after the real native terminal arrives.
+ s := stream.state
+ s.mu.Lock()
+ s.queue[0] = []byte("{}")
+ s.bytes = len(s.queue[0])
+ s.mu.Unlock()
+ var decode *AgentEventDecodeError
+ if _, err := stream.Next(context.Background()); !errors.As(err, &decode) {
+ t.Fatal(err)
+ }
+ e, err := stream.Next(context.Background())
+ checkAgentError(t, e, err, ErrNetwork)
+}
+
+func TestAgentStreamShutdownDispatchesOnlySubscriptions(t *testing.T) {
+ r, ns := testAgents(t, false)
+ stream := openTestAgentStream(t, testCreateAgent(t, ns), context.Background(), "pending")
+ r.stopDrain()
+ b, token := testQueueUnrelatedCallback(r)
+ if err := r.Close(); err != nil {
+ t.Fatal(err)
+ }
+ receiveAgent(t, stream.state.done)
+ select {
+ case <-b.entered:
+ t.Fatal("shutdown dispatched an unrelated callback")
+ default:
+ token.Delete()
+ }
+}
+
+func TestAgentStreamCanceledBeforeNativeEOF(t *testing.T) {
+ _, ns := testAgents(t, false)
+ a := testCreateAgent(t, ns)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ s := openTestAgentStream(t, a, ctx, "after-response")
+ // Hold back AfterFunc delivery while the real native terminal arrives.
+ if !s.state.stopWatch() {
+ t.Fatal("subscription watcher already ran")
+ }
+ cancel()
+ if _, err := a.Respond(context.Background(), "request-1", AgentAnswer{Text: "continue"}, AgentControlOptions{}); err != nil {
+ t.Fatal(err)
+ }
+ receiveAgent(t, s.state.done)
+ for _, kind := range []string{"first", "future"} {
+ if e := nextAgent(t, s); e.Kind != kind {
+ t.Fatalf("event = %v, want %s", e, kind)
+ }
+ }
+ if _, err := s.Next(context.Background()); !errors.Is(err, context.Canceled) {
+ t.Fatalf("native EOF after subscription cancellation returned %v", err)
+ }
+}
+
+func TestAgentStreamNativeRejectsOpen(t *testing.T) {
+ r, ns := testAgents(t, false)
+ a := testCreateAgent(t, ns)
+ stream, err := testAgentRejectedOpen(a)
+ checkAgentError(t, stream, err, ErrInvalidArgument)
+ if len(r.agentStreamSnapshot()) != 0 || len(r.agentBufferSnapshot()) != 0 {
+ t.Fatal("synchronous rejection retained subscription state")
+ }
+}
+
+func TestAgentStreamNilReadContextPreservesEvent(t *testing.T) {
+ _, ns := testAgents(t, false)
+ stream := openTestAgentStream(t, testCreateAgent(t, ns), context.Background(), "after-response")
+ event, err := stream.Next(nil)
+ checkAgentError(t, event, err, ErrInvalidArgument)
+ if first := nextAgent(t, stream); first.Kind != "first" {
+ t.Fatalf("after invalid read: %+v", first)
+ }
+}
diff --git a/sdks/go/agents_test.go b/sdks/go/agents_test.go
index e92c4456f..af3de1f69 100644
--- a/sdks/go/agents_test.go
+++ b/sdks/go/agents_test.go
@@ -57,7 +57,7 @@ func TestAgentsRequireNativeHandles(t *testing.T) {
func TestAgentEventsRequireNativeHandles(t *testing.T) {
ctx := context.Background()
events, err := (&Agent{}).Events(ctx, AgentEventsOptions{})
- checkAgentError(t, events, err, ErrUnsupported)
+ checkAgentError(t, events, err, ErrInvalidState)
events, err = (&AgentTurn{}).Events(ctx, AgentEventsOptions{})
- checkAgentError(t, events, err, ErrUnsupported)
+ checkAgentError(t, events, err, ErrInvalidState)
}
diff --git a/sdks/go/agents_vm_integration_test.go b/sdks/go/agents_vm_integration_test.go
new file mode 100644
index 000000000..ad160a0e4
--- /dev/null
+++ b/sdks/go/agents_vm_integration_test.go
@@ -0,0 +1,209 @@
+//go:build boxlite_dev && boxlite_agent_vm
+
+package boxlite
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Invoked only by the Rust VM runner, which supplies the same model and inputs
+// to C and Go. Getter/handle checks use production C/core, without a fake backend.
+func TestGoAgentVMDriver(t *testing.T) {
+ if len(os.Args) < 5 {
+ t.Fatal("Rust runner must supply binary, config, home and registry")
+ }
+ args := os.Args[len(os.Args)-4:]
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ defer cancel()
+ r, err := NewRuntime(WithHomeDir(args[2]), WithImageRegistries(ImageRegistry{Host: args[3], Transport: RegistryTransportHTTP, Search: true}))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer r.Close()
+ box, err := r.Create(ctx, "debian:bookworm-slim", WithAutoDeleteInterval(0))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer box.Close()
+ if err := box.Start(ctx); err != nil {
+ t.Fatal(err)
+ }
+ stopped := false
+ defer func() {
+ if !stopped {
+ if err := box.Stop(ctx); err != nil {
+ t.Error(err)
+ }
+ }
+ }()
+ shell := func(command string) {
+ t.Helper()
+ result, e := box.Exec(ctx, "sh", "-c", command)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if result.ExitCode != 0 {
+ t.Fatalf("shell: %+v", result)
+ }
+ }
+ shell("mkdir -p /root/.config/opencode")
+ for _, copy := range [][2]string{{args[0], "/usr/local/bin/opencode"}, {args[1], "/root/.config/opencode/opencode.json"}} {
+ if e := box.CopyInto(ctx, copy[0], copy[1]); e != nil {
+ t.Fatal(e)
+ }
+ }
+ shell("chmod 755 /usr/local/bin/opencode")
+ agent, err := box.Agents().Create(ctx, "opencode", AgentCreateOptions{Config: AgentConfig{Model: "fake/fake-model"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer runtime.KeepAlive(agent)
+ state, err := agent.State()
+ checkAgentError(t, state, err, ErrUnsupported)
+ config, err := agent.Config()
+ if err != nil || config.Model != "fake/fake-model" {
+ t.Fatalf("config=%+v %v", config, err)
+ }
+ capabilities, err := agent.Capabilities()
+ if err != nil {
+ t.Fatal(err)
+ }
+ printVMRecord(t, "CONFIG", map[string]any{"model": config.Model})
+ printVMRecord(t, "CAPABILITIES", map[string]any{"operations": capabilities.Operations})
+ // Opening completes before send; the first record is retained for comparison.
+ events, err := agent.Events(ctx, AgentEventsOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer events.Close()
+ turn, err := agent.Send(ctx, "hello", AgentSendOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ ts, err := turn.State()
+ if err != nil {
+ t.Fatal(err)
+ }
+ printVMRecord(t, "TURN", map[string]any{"id": ts.ID, "agent_id": ts.AgentID, "status": ts.Status})
+ timeout := 120 * time.Second
+ result, err := turn.Wait(ctx, AgentWaitOptions{Timeout: &timeout})
+ if err != nil {
+ t.Fatal(err)
+ }
+ first, err := events.Next(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ nullable := func(s string) any {
+ if s == "" {
+ return nil
+ }
+ return s
+ }
+ printVMRecord(t, "EVENT", map[string]any{"agent_id": first.AgentID, "turn_id": nullable(first.TurnID), "kind": first.Kind, "data": first.Data})
+ printVMRecord(t, "RESULT", map[string]any{"turn_id": result.TurnID, "status": result.Status, "outcome": nullable(string(result.Outcome)), "text": nullable(result.Text), "data": result.Data, "artifacts": result.Artifacts, "usage": result.Usage, "error": nullable(result.Error)})
+ receipt, err := turn.Steer(ctx, "continue", AgentControlOptions{})
+ checkAgentError(t, receipt, err, ErrUnsupported)
+ if !strings.Contains(err.Error(), "OpenCode 2.2") {
+ t.Fatal(err)
+ }
+ adopted, err := box.Agents().Get(ctx, ts.AgentID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer runtime.KeepAlive(adopted)
+ if _, err := adopted.Config(); err != nil {
+ t.Fatal(err)
+ }
+ requests, err := agent.Requests(ctx)
+ checkAgentError(t, requests, err, ErrUnsupported)
+ slow, err := agent.Send(ctx, "SLOW", AgentSendOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ slowState, err := slow.State()
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Real progress events provide the rendezvous; no sleeps or GC timing.
+ for {
+ event, e := events.Next(ctx)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if event.TurnID != slowState.ID {
+ continue
+ }
+ probe, e := agent.GetTurn(ctx, slowState.ID)
+ if e != nil {
+ t.Fatal(e)
+ }
+ running, e := probe.State()
+ probe.native.release()
+ if e != nil {
+ t.Fatal(e)
+ }
+ if running.Status == AgentTurnRunning {
+ break
+ }
+ if running.Status == AgentTurnCompleted {
+ t.Fatal("slow turn completed before release check")
+ }
+ }
+ slow.native.release()
+ released, err := slow.State()
+ checkAgentError(t, released, err, ErrInvalidState)
+ recovered, err := agent.GetTurn(ctx, slowState.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ completed, err := recovered.Wait(ctx, AgentWaitOptions{Timeout: &timeout})
+ if err != nil || completed.Status != AgentTurnCompleted {
+ t.Fatalf("released turn stopped: %+v %v", completed, err)
+ }
+ runtime.KeepAlive(recovered)
+ runtime.KeepAlive(slow)
+ runtime.KeepAlive(turn)
+ events.Close()
+ if err := box.Stop(ctx); err != nil {
+ t.Fatal(err)
+ }
+ stopped = true
+ if err := r.Shutdown(ctx, 30*time.Second); err != nil {
+ t.Fatal(err)
+ }
+ r.Close()
+ config, err = agent.Config()
+ if config != nil || !errors.Is(err, ErrRuntimeClosed) {
+ t.Fatalf("getter after runtime close=%+v %v", config, err)
+ }
+ caps, err := agent.Capabilities()
+ if caps != nil || !errors.Is(err, ErrRuntimeClosed) {
+ t.Fatal(err)
+ }
+ state, err = agent.State()
+ if state != nil || !errors.Is(err, ErrRuntimeClosed) {
+ t.Fatal(err)
+ }
+ finalState, err := turn.State()
+ if finalState != nil || !errors.Is(err, ErrRuntimeClosed) {
+ t.Fatal(err)
+ }
+}
+
+func printVMRecord(t *testing.T, name string, value any) {
+ t.Helper()
+ data, err := json.Marshal(value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fmt.Printf("GO_%s=%s\n", name, data)
+}
diff --git a/sdks/go/agents_vm_parity_test.go b/sdks/go/agents_vm_parity_test.go
new file mode 100644
index 000000000..ba33f4b00
--- /dev/null
+++ b/sdks/go/agents_vm_parity_test.go
@@ -0,0 +1,474 @@
+//go:build boxlite_dev && boxlite_agent_vm
+
+package boxlite
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+const goAgentServiceRecord = "/root/.local/state/opencode/service.json"
+
+type goAgentVMFixture struct {
+ t *testing.T
+ ctx context.Context
+ rt *Runtime
+ box *Box
+ binary string
+}
+
+// Subtest names match src/boxlite/tests/agents_opencode.rs exactly.
+func TestGoAgentVMParity(t *testing.T) {
+ tests := []struct {
+ name string
+ run func(*goAgentVMFixture)
+ }{
+ {"opencode_agent_creates_sends_streams_and_waits", goAgentConcurrentCreate},
+ {"an_old_turn_is_read_beyond_the_first_history_page", goAgentHistoryPagination},
+ {"a_box_restart_resumes_the_running_turn_and_delivers_the_queued_one", goAgentRunningRestart},
+ {"a_foreign_server_on_the_agent_port_is_reported", goAgentForeignServer},
+ {"a_box_without_opencode_is_reported", goAgentMissingBinary},
+ {"a_user_service_is_refused_ready_or_frozen_and_left_running", goAgentUserService},
+ {"a_stale_registration_is_dropped_without_signalling_its_pid", goAgentStaleRegistration},
+ {"sessions_deny_env_reads_and_questions_and_keep_running", goAgentPermissionBoundaries},
+ {"a_frozen_agent_service_is_reported_and_left_alone", goAgentFrozenService},
+ {"remote_access_is_refused_before_a_service_starts", goAgentRemoteService},
+ {"an_installed_opencode_runs_in_an_image_without_one", goAgentInstalledBinary},
+ {"installing_again_reuses_the_one_mount", goAgentRepeatedInstall},
+ {"an_agent_installed_after_a_failed_lookup_is_found_at_once", goAgentInstallAfterLookup},
+ {"a_restart_mounts_the_recorded_agent_on_first_use", goAgentInstalledRestart},
+ {"a_failed_mount_after_a_restart_is_reported_and_retried", goAgentMountRetry},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) { test.run(newGoAgentVMFixture(t)) })
+ }
+}
+
+func newGoAgentVMFixture(t *testing.T) *goAgentVMFixture {
+ t.Helper()
+ if len(os.Args) < 5 {
+ t.Fatal("run through make test:integration:go:agents")
+ }
+ args := os.Args[len(os.Args)-4:]
+ ctx, cancel := context.WithTimeout(context.Background(), 6*time.Minute)
+ t.Cleanup(cancel)
+ r, err := NewRuntime(WithHomeDir(t.TempDir()), WithImageRegistries(ImageRegistry{Host: args[3], Transport: RegistryTransportHTTP, Search: true}))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { r.Close() })
+ box, err := r.Create(ctx, "debian:bookworm-slim", WithAutoDeleteInterval(0), WithEnv("OPENCODE_PASSWORD", "inherited-from-the-box"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ f := &goAgentVMFixture{t: t, ctx: ctx, rt: r, box: box, binary: args[0]}
+ t.Cleanup(func() {
+ shutdown, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := r.Shutdown(shutdown, 30*time.Second); err != nil {
+ t.Error(err)
+ }
+ f.box.Close()
+ })
+ if err := box.Start(ctx); err != nil {
+ t.Fatal(err)
+ }
+ f.shell("mkdir -p /root/.config/opencode")
+ for _, copy := range [][2]string{{args[0], "/usr/local/bin/opencode"}, {args[1], "/root/.config/opencode/opencode.json"}} {
+ if err := box.CopyInto(ctx, copy[0], copy[1]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ f.shell("chmod 755 /usr/local/bin/opencode")
+ return f
+}
+func (f *goAgentVMFixture) shell(script string) string {
+ f.t.Helper()
+ r, err := f.box.Exec(f.ctx, "sh", "-c", script)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ if r.ExitCode != 0 {
+ f.t.Fatalf("script %q failed: %+v", script, r)
+ }
+ return strings.TrimSpace(r.Stdout)
+}
+func (f *goAgentVMFixture) create() *Agent {
+ f.t.Helper()
+ a, err := f.box.Agents().Create(f.ctx, "opencode", AgentCreateOptions{Config: AgentConfig{Model: "fake/fake-model"}})
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ return a
+}
+func (f *goAgentVMFixture) send(a *Agent, text string) *AgentTurn {
+ f.t.Helper()
+ turn, err := a.Send(f.ctx, text, AgentSendOptions{})
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ return turn
+}
+func (f *goAgentVMFixture) snapshot(turn *AgentTurn) *AgentTurnState {
+ f.t.Helper()
+ s, err := turn.State()
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ return s
+}
+func (f *goAgentVMFixture) wait(turn *AgentTurn) *AgentResult {
+ f.t.Helper()
+ timeout := 120 * time.Second
+ result, err := turn.Wait(f.ctx, AgentWaitOptions{Timeout: &timeout})
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ if result.Status != AgentTurnCompleted {
+ f.t.Fatalf("turn failed: %+v", result)
+ }
+ return result
+}
+func (f *goAgentVMFixture) get(a *Agent, id string) *AgentTurn {
+ f.t.Helper()
+ turn, err := a.GetTurn(f.ctx, id)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ return turn
+}
+func (f *goAgentVMFixture) pid() string {
+ f.t.Helper()
+ pid := f.shell("sed -n 's/.*\"pid\":\\([0-9][0-9]*\\).*/\\1/p' " + goAgentServiceRecord)
+ n, err := strconv.Atoi(pid)
+ if err != nil || n <= 0 {
+ f.t.Fatalf("invalid service pid %q", pid)
+ }
+ return pid
+}
+func (f *goAgentVMFixture) expectCreateError(code ErrorCode, message string) {
+ f.t.Helper()
+ a, err := f.box.Agents().Create(f.ctx, "opencode", AgentCreateOptions{Config: AgentConfig{Model: "fake/fake-model"}})
+ checkAgentError(f.t, a, err, code)
+ if !strings.Contains(err.Error(), message) {
+ f.t.Fatalf("error %q lacks %q", err, message)
+ }
+}
+func (f *goAgentVMFixture) restart() {
+ f.t.Helper()
+ id := f.box.ID()
+ if err := f.box.Stop(f.ctx); err != nil {
+ f.t.Fatal(err)
+ }
+ f.box.Close()
+ box, err := f.rt.Get(f.ctx, id)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ f.box = box
+ if err := box.Start(f.ctx); err != nil {
+ f.t.Fatal(err)
+ }
+}
+func (f *goAgentVMFixture) install(name, path string) {
+ f.t.Helper()
+ if err := installVMTestAgent(f.box, name, path); err != nil {
+ f.t.Fatal(err)
+ }
+}
+func (f *goAgentVMFixture) delivered() {
+ f.shell("rm /usr/local/bin/opencode")
+ f.install("opencode", f.binary)
+}
+func (f *goAgentVMFixture) mounts() string {
+ return f.shell(`awk '$2 == "/opt/boxlite/agents"' /proc/mounts | wc -l`)
+}
+func (f *goAgentVMFixture) completedAgentID() string {
+ f.t.Helper()
+ a := f.create()
+ turn := f.send(a, "ping")
+ f.wait(turn)
+ return f.snapshot(turn).AgentID
+}
+
+func goAgentConcurrentCreate(f *goAgentVMFixture) {
+ start := make(chan struct{})
+ var wg sync.WaitGroup
+ result := make(chan handleResult[*Agent], 2)
+ for range 2 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ a, e := f.box.Agents().Create(f.ctx, "opencode", AgentCreateOptions{Config: AgentConfig{Model: "fake/fake-model"}})
+ result <- handleResult[*Agent]{value: a, err: e}
+ }()
+ }
+ close(start)
+ wg.Wait()
+ close(result)
+ var agents []*Agent
+ for r := range result {
+ if r.err != nil {
+ f.t.Fatal(r.err)
+ }
+ agents = append(agents, r.value)
+ }
+ services := f.shell(`for p in /proc/[0-9]*; do case "$(tr '\0' ' ' <"$p/cmdline" 2>/dev/null)" in *[o]pencode*serve*--service*) echo "${p#/proc/}";; esac; done`)
+ if services != f.pid() {
+ f.t.Fatalf("multiple services: %q", services)
+ }
+ for _, a := range agents {
+ config, e := a.Config()
+ if e != nil || config.Model != "fake/fake-model" {
+ f.t.Fatalf("config=%+v %v", config, e)
+ }
+ }
+ state, e := agents[0].State()
+ checkAgentError(f.t, state, e, ErrUnsupported)
+ events, e := agents[0].Events(f.ctx, AgentEventsOptions{})
+ if e != nil {
+ f.t.Fatal(e)
+ }
+ defer events.Close()
+ turn := f.send(agents[0], "hello")
+ resultValue := f.wait(turn)
+ if resultValue.Text != "pong: hello" {
+ f.t.Fatal(resultValue)
+ }
+ id := f.snapshot(turn).ID
+ for {
+ event, e := events.Next(f.ctx)
+ if e != nil {
+ f.t.Fatal(e)
+ }
+ if event.Kind == "session.inbox.enqueued" {
+ if event.TurnID != id {
+ f.t.Fatal(event)
+ }
+ adopted, e := f.box.Agents().Get(f.ctx, event.AgentID)
+ if e != nil {
+ f.t.Fatal(e)
+ }
+ if f.snapshot(f.get(adopted, id)).Status != AgentTurnCompleted {
+ f.t.Fatal("adopted turn incomplete")
+ }
+ break
+ }
+ }
+ runtime.KeepAlive(agents)
+}
+func goAgentHistoryPagination(f *goAgentVMFixture) {
+ a := f.create()
+ var ids []string
+ for i := range 30 {
+ ids = append(ids, f.snapshot(f.send(a, fmt.Sprintf("turn %d", i))).ID)
+ }
+ f.wait(f.get(a, ids[len(ids)-1]))
+ if f.snapshot(f.get(a, ids[0])).Status != AgentTurnCompleted {
+ f.t.Fatal("old turn not found beyond first page")
+ }
+}
+func goAgentRunningRestart(f *goAgentVMFixture) {
+ a := f.create()
+ events, e := a.Events(f.ctx, AgentEventsOptions{})
+ if e != nil {
+ f.t.Fatal(e)
+ }
+ defer events.Close()
+ running := f.snapshot(f.send(a, "SLOW please"))
+ for {
+ event, e := events.Next(f.ctx)
+ if e != nil {
+ f.t.Fatal(e)
+ }
+ if event.TurnID == running.ID && f.snapshot(f.get(a, running.ID)).Status == AgentTurnRunning {
+ break
+ }
+ }
+ queued := f.snapshot(f.send(a, "after the restart"))
+ if queued.Status != AgentTurnQueued {
+ f.t.Fatalf("expected queued turn: %+v", queued)
+ }
+ if status := f.snapshot(f.get(a, running.ID)).Status; status != AgentTurnRunning {
+ f.t.Fatalf("turn before restart = %v, want running", status)
+ }
+ events.Close()
+ f.restart()
+ adopted, e := f.box.Agents().Get(f.ctx, running.AgentID)
+ if e != nil {
+ f.t.Fatal(e)
+ }
+ for _, id := range []string{running.ID, queued.ID} {
+ f.wait(f.get(adopted, id))
+ }
+}
+func goAgentForeignServer(f *goAgentVMFixture) {
+ execution, e := f.box.StartExecution(f.ctx, "sh", []string{"-c", "OPENCODE_PASSWORD=foreign exec opencode serve --hostname 0.0.0.0 --port 47096 >/tmp/foreign.log 2>&1"}, nil)
+ if e != nil {
+ f.t.Fatal(e)
+ }
+ defer execution.Close()
+ f.shell("for _ in $(seq 1 100); do grep -q listening /tmp/foreign.log && exit 0; sleep 0.2; done; exit 1")
+ f.expectCreateError(ErrInvalidState, "held by another server")
+}
+func goAgentMissingBinary(f *goAgentVMFixture) {
+ f.shell("rm /usr/local/bin/opencode")
+ f.expectCreateError(ErrExecution, "must provide OpenCode 2.2.2")
+}
+func goAgentUserService(f *goAgentVMFixture) {
+ url := f.shell("opencode service start 2>&1 | tail -n 1")
+ pid := f.pid()
+ f.t.Cleanup(func() { f.shell("kill -CONT " + pid) })
+ for _, signal := range []string{"", "kill -STOP "} {
+ if signal != "" {
+ f.shell(signal + pid)
+ }
+ f.expectCreateError(ErrInvalidState, "runs at "+url)
+ }
+ f.shell("kill -CONT " + pid)
+ if f.shell("opencode service status") != url || f.pid() != pid {
+ f.t.Fatal("user service was replaced")
+ }
+}
+func goAgentStaleRegistration(f *goAgentVMFixture) {
+ f.shell("opencode service start >/dev/null 2>&1")
+ dead := f.pid()
+ f.shell("cp " + goAgentServiceRecord + " /root/stale.json && kill -9 " + dead)
+ holder := f.shell("sleep 600 >/dev/null 2>&1 & echo $!")
+ if _, e := strconv.Atoi(holder); e != nil {
+ f.t.Fatal(e)
+ }
+ f.shell(fmt.Sprintf(`sed 's/"pid":%s/"pid":%s/' /root/stale.json > %s`, dead, holder, goAgentServiceRecord))
+ a := f.create()
+ if f.wait(f.send(a, "hello")).Text != "pong: hello" {
+ f.t.Fatal("stale service was not recovered")
+ }
+ state := f.shell("sed -n 's/^State:[[:space:]]*//p' /proc/" + holder + "/status")
+ if !strings.HasPrefix(state, "S") {
+ f.t.Fatalf("unrelated process was signalled: %q", state)
+ }
+}
+func goAgentPermissionBoundaries(f *goAgentVMFixture) {
+ f.shell("mkdir -p /root/work && cd /root/work && for f in .env .env.local .env.example; do echo SECRET=1 > $f; done")
+ a, e := f.box.Agents().Create(f.ctx, "opencode", AgentCreateOptions{Cwd: "/root/work", Config: AgentConfig{Model: "fake/fake-model"}})
+ if e != nil {
+ f.t.Fatal(e)
+ }
+ // The shared model echoes SECRET only when it actually receives it in a tool result.
+ if text := f.wait(f.send(a, "READ .env.example")).Text; !strings.Contains(text, "SECRET") {
+ f.t.Fatalf("allowed read=%q", text)
+ }
+ for _, file := range []string{".env", ".env.local"} {
+ if text := f.wait(f.send(a, "READ "+file)).Text; strings.Contains(text, "SECRET") {
+ f.t.Fatalf("denied read %s leaked: %q", file, text)
+ }
+ }
+ f.wait(f.send(a, "ASK please"))
+ if text := f.wait(f.send(a, "and then")).Text; text != "pong: and then" {
+ f.t.Fatalf("question blocked later work: %q", text)
+ }
+}
+func goAgentFrozenService(f *goAgentVMFixture) {
+ f.create()
+ pid := f.pid()
+ f.shell("kill -STOP " + pid)
+ f.t.Cleanup(func() { f.shell("kill -CONT " + pid) })
+ f.expectCreateError(ErrInvalidState, "not responding")
+ f.shell("kill -CONT " + pid)
+ f.create()
+ if f.pid() != pid {
+ f.t.Fatal("frozen service was replaced")
+ }
+}
+func goAgentRemoteService(f *goAgentVMFixture) {
+ f.shell(`printf '{"remote":{"route":"test"}}' > /root/.config/opencode/service.json`)
+ f.expectCreateError(ErrInvalidState, "remote access is on")
+ if f.shell("test -e "+goAgentServiceRecord+" && echo registered || echo none") != "none" {
+ f.t.Fatal("remote configuration started a local service")
+ }
+}
+func goAgentInstalledBinary(f *goAgentVMFixture) {
+ f.delivered()
+ f.completedAgentID()
+ if f.shell("command -v opencode || echo none") != "none" {
+ f.t.Fatal("installation changed image PATH")
+ }
+ if out := f.shell("touch /opt/boxlite/agents/x 2>&1 && echo written || true"); !strings.Contains(out, "Read-only file system") {
+ f.t.Fatal(out)
+ }
+}
+func goAgentRepeatedInstall(f *goAgentVMFixture) {
+ f.delivered()
+ f.install("opencode", f.binary)
+ f.create()
+ if f.mounts() != "1" {
+ f.t.Fatal("repeated install duplicated mount")
+ }
+}
+func goAgentInstallAfterLookup(f *goAgentVMFixture) {
+ f.delivered()
+ if f.shell("stat /opt/boxlite/agents/probe >/dev/null 2>&1 || echo missing") != "missing" {
+ f.t.Fatal("probe already exists")
+ }
+ probe := filepath.Join(f.t.TempDir(), "probe")
+ if e := os.WriteFile(probe, []byte("#!/bin/sh\necho probe-ran\n"), 0700); e != nil {
+ f.t.Fatal(e)
+ }
+ f.install("probe", probe)
+ if f.shell("stat /opt/boxlite/agents/probe >/dev/null && /opt/boxlite/agents/probe/*/probe") != "probe-ran" {
+ f.t.Fatal("negative lookup hid newly installed file")
+ }
+ if f.mounts() != "1" {
+ f.t.Fatal("probe duplicated mount")
+ }
+}
+func goAgentInstalledRestart(f *goAgentVMFixture) {
+ f.delivered()
+ id := f.completedAgentID()
+ f.restart()
+ if f.mounts() != "0" || f.shell("ls -A /opt/boxlite/agents") != "" {
+ f.t.Fatal("mount survived stop")
+ }
+ a, e := f.box.Agents().Get(f.ctx, id)
+ if e != nil {
+ f.t.Fatal(e)
+ }
+ if f.mounts() != "1" {
+ f.t.Fatal("first Go lookup did not restore mount")
+ }
+ f.wait(f.send(a, "ping"))
+}
+func goAgentMountRetry(f *goAgentVMFixture) {
+ f.delivered()
+ id := f.completedAgentID()
+ f.restart()
+ f.shell("touch /opt/boxlite/agents/blocker")
+ a, e := f.box.Agents().Get(f.ctx, id)
+ if a != nil || e == nil || !strings.Contains(e.Error(), "/opt/boxlite/agents") {
+ f.t.Fatalf("mount error=%v %v", a, e)
+ }
+ if f.mounts() != "0" {
+ f.t.Fatal("failed mount was installed")
+ }
+ info, e := f.box.Info(f.ctx)
+ if e != nil || info.State != StateRunning {
+ f.t.Fatalf("mount failure stopped VM: %+v %v", info, e)
+ }
+ f.shell("rm /opt/boxlite/agents/blocker")
+ a, e = f.box.Agents().Get(f.ctx, id)
+ if e != nil || a == nil {
+ f.t.Fatal(e)
+ }
+ if f.mounts() != "1" {
+ f.t.Fatal("mount retry did not succeed")
+ }
+}
diff --git a/sdks/go/bridge_cgo_coverage.go b/sdks/go/bridge_cgo_coverage.go
index 1f6ebb258..a9493c4b7 100644
--- a/sdks/go/bridge_cgo_coverage.go
+++ b/sdks/go/bridge_cgo_coverage.go
@@ -1,9 +1,9 @@
-//go:build boxlite_dev && boxlite_coverage
+//go:build boxlite_dev && (boxlite_coverage || boxlite_external_archive)
package boxlite
-// The coverage collector supplies the instrumented library and its matching
-// LLVM profile runtime through CGO_LDFLAGS instead of the fixed dev archive.
+// External builds supply the archive through CGO_LDFLAGS. Coverage builds
+// also supply the matching LLVM profile runtime.
/*
#cgo CFLAGS: -I${SRCDIR}/../c/include
diff --git a/sdks/go/bridge_cgo_dev.go b/sdks/go/bridge_cgo_dev.go
index 8a40e9ae8..8d18083cf 100644
--- a/sdks/go/bridge_cgo_dev.go
+++ b/sdks/go/bridge_cgo_dev.go
@@ -1,4 +1,4 @@
-//go:build boxlite_dev && !boxlite_coverage
+//go:build boxlite_dev && !boxlite_coverage && !boxlite_external_archive
package boxlite
diff --git a/sdks/go/runtime.go b/sdks/go/runtime.go
index 2b0b42533..af4ee1b45 100644
--- a/sdks/go/runtime.go
+++ b/sdks/go/runtime.go
@@ -28,11 +28,14 @@ const drainTimeoutMs = 100
// Runtime manages BoxLite boxes. Create one with NewRuntime.
type Runtime struct {
- handle *C.CBoxliteRuntime
- closeOnce sync.Once
- agentMu sync.RWMutex
- agentClosed bool
- agentHandles map[agentResource]struct{}
+ handle *C.CBoxliteRuntime
+ closeOnce sync.Once
+ agentMu sync.RWMutex
+ agentClosed bool
+ agentHandles map[agentResource]struct{}
+ agentStreamsMu sync.Mutex
+ agentStreams map[uintptr]*agentSubscription
+ agentBuffers map[*agentSubscription]struct{}
drainMu sync.Mutex
drainOnce sync.Once
@@ -116,7 +119,16 @@ func (r *Runtime) Close() error {
}
})
r.agentMu.Unlock()
+ // Cancel connected producers before joining: a continuously nonempty C
+ // queue can keep drain running past its timeout until producers stop.
+ for _, s := range r.agentStreamSnapshot() {
+ s.shutdown()
+ }
+ for _, s := range r.agentBufferSnapshot() {
+ s.shutdown()
+ }
r.stopDrain()
+ r.drainAgentTerminals()
r.agentMu.Lock()
handles := make([]agentResource, 0, len(r.agentHandles))
for h := range r.agentHandles {
@@ -132,6 +144,11 @@ func (r *Runtime) Close() error {
r.handle = nil
}
r.agentMu.Unlock()
+ // Native destruction drops untransferred opens; their tokens are safe
+ // to release only after no further native callback can be dispatched.
+ for _, s := range r.agentStreamSnapshot() {
+ s.runtimeEnded()
+ }
})
return nil
}
diff --git a/sdks/go/test_agents_cgo_support_dev.go b/sdks/go/test_agents_cgo_support_dev.go
index 04fab8a4d..6860d9ac1 100644
--- a/sdks/go/test_agents_cgo_support_dev.go
+++ b/sdks/go/test_agents_cgo_support_dev.go
@@ -9,6 +9,12 @@ BoxliteErrorCode boxlite_test_agents_new(const char*, CBoxliteRuntime**, struct
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*);
+size_t boxlite_test_agents_event_frees(void);
+void boxlite_test_agents_barrier(CBoxliteRuntime*, void (*)(uintptr_t), uintptr_t);
+extern void goBoxliteAgentTestBarrier(uintptr_t);
+static inline void test_agent_barrier(CBoxliteRuntime *rt, uintptr_t token) {
+ boxlite_test_agents_barrier(rt, goBoxliteAgentTestBarrier, token);
+}
*/
import "C"
@@ -82,6 +88,32 @@ func testAgentFreeCounts() (int, int) {
return int(agents), int(turns)
}
+func testAgentEventFrees() int { return int(C.boxlite_test_agents_event_frees()) }
+
+type agentTestBarrier struct {
+ entered chan struct{}
+ release chan struct{}
+}
+
+func testAgentBlockDrainer(r *Runtime) *agentTestBarrier {
+ b := &agentTestBarrier{entered: make(chan struct{}), release: make(chan struct{})}
+ token := cgo.NewHandle(b)
+ r.agentMu.RLock()
+ r.ensureDrainRunning()
+ C.test_agent_barrier(r.handle, C.uintptr_t(token))
+ r.agentMu.RUnlock()
+ return b
+}
+
+//export goBoxliteAgentTestBarrier
+func goBoxliteAgentTestBarrier(token C.uintptr_t) {
+ h := cgo.Handle(token)
+ b := h.Value().(*agentTestBarrier)
+ close(b.entered)
+ <-b.release
+ h.Delete()
+}
+
// 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) {
@@ -105,3 +137,27 @@ func testAgentSubmitCreate(a *Agents) (<-chan handleResult[*agentSession], cgo.H
}
return op.result, token, nil
}
+
+// Feed a wire record through the production callback. The typed Rust fixture
+// cannot generate a malformed outer record.
+func testDeliverAgentRecord(s *agentSubscription, record string) {
+ value := C.CString(record)
+ defer C.free(unsafe.Pointer(value))
+ goBoxliteAgentEvent(value, nil, C.uintptr_t(s.token))
+}
+
+// Queue an unrelated callback after the ordinary drainer has joined.
+func testQueueUnrelatedCallback(r *Runtime) (*agentTestBarrier, cgo.Handle) {
+ b := &agentTestBarrier{entered: make(chan struct{}), release: make(chan struct{})}
+ close(b.release)
+ token := cgo.NewHandle(b)
+ C.test_agent_barrier(r.handle, C.uintptr_t(token))
+ return b, token
+}
+
+// Invalid native arguments exercise synchronous rejection after Go registers a token.
+func testAgentRejectedOpen(a *Agent) (AgentEventStream, error) {
+ return openAgentEvents(context.Background(), a.native, AgentEventsOptions{}, func(_ *C.struct_CAgent, opts *C.struct_CAgentEventsOptions, token C.uintptr_t, err *C.CBoxliteError) C.enum_BoxliteErrorCode {
+ return C.go_agent_events(nil, opts, token, err)
+ })
+}
diff --git a/sdks/go/test_agents_vm_fixture_dev.go b/sdks/go/test_agents_vm_fixture_dev.go
new file mode 100644
index 000000000..43528f052
--- /dev/null
+++ b/sdks/go/test_agents_vm_fixture_dev.go
@@ -0,0 +1,32 @@
+//go:build boxlite_dev && boxlite_agent_vm
+
+package boxlite
+
+/*
+#include "agents_bridge.h"
+BoxliteErrorCode boxlite_test_agents_install(CBoxHandle*, const char*, const char*, CBoxliteError*);
+*/
+import "C"
+import "runtime"
+
+// Install only prepares a VM test fixture through the existing Rust test API.
+// Subsequent visibility, mounting and restart checks use public Go operations.
+func installVMTestAgent(box *Box, name, path string) error {
+ defer runtime.KeepAlive(box)
+ var args agentArguments
+ defer args.free()
+ n, p := args.string(name, "agent", false), args.string(path, "path", false)
+ if args.err != nil {
+ return args.err
+ }
+ handle, unlock, err := box.acquire()
+ if err != nil {
+ return err
+ }
+ defer unlock()
+ var cerr C.CBoxliteError
+ if C.boxlite_test_agents_install(handle, n, p, &cerr) != C.Ok {
+ return freeError(&cerr)
+ }
+ return nil
+}
diff --git a/src/boxlite/src/agents/test_support.rs b/src/boxlite/src/agents/test_support.rs
index 51d3538b5..6d156b66d 100644
--- a/src/boxlite/src/agents/test_support.rs
+++ b/src/boxlite/src/agents/test_support.rs
@@ -124,7 +124,59 @@ impl AgentBackend for TestBackend {
}
async fn events(&self, options: &AgentEventsOptions) -> BoxliteResult<AgentEventStream> {
use futures::StreamExt;
+ let event = |kind: String| AgentEvent {
+ cursor: None,
+ agent_id: self.id().into(),
+ turn_id: None,
+ kind,
+ data: serde_json::json!({}),
+ };
+ if let Some(size) = options
+ .after
+ .as_deref()
+ .and_then(|s| s.strip_prefix("bytes:"))
+ {
+ let mut items = Vec::new();
+ for size in size.split(',') {
+ let size: usize = size
+ .parse()
+ .map_err(|_| BoxliteError::InvalidArgument("invalid test size".into()))?;
+ let mut item = event("sized".into());
+ item.data = serde_json::json!("");
+ let overhead = records::event(&item).to_string().len();
+ let padding = size.checked_sub(overhead).ok_or_else(|| {
+ BoxliteError::InvalidArgument("test size below record overhead".into())
+ })?;
+ item.data = serde_json::json!("x".repeat(padding));
+ items.push(Ok(item));
+ }
+ return Ok(Box::pin(futures::stream::iter(items)));
+ }
match options.after.as_deref() {
+ Some("after-response") => {
+ let first = event("first".into());
+ let mut last = event("future".into());
+ last.data = serde_json::from_str("1e+400").unwrap();
+ let mut response = self.wait_gate.subscribe();
+ Ok(Box::pin(futures::stream::iter([Ok(first)]).chain(
+ futures::stream::once(async move {
+ response.changed().await.expect("backend owns sender");
+ Ok(last)
+ }),
+ )))
+ }
+ Some("open-pending") => std::future::pending().await,
+ Some("many") => Ok(Box::pin(futures::stream::iter(
+ (0..128)
+ .map(|n| Ok(event(n.to_string())))
+ .collect::<Vec<_>>(),
+ ))),
+ Some("continuous") => {
+ let item = event("tick".into());
+ Ok(Box::pin(futures::stream::repeat_with(move || {
+ Ok(item.clone())
+ })))
+ }
Some("open-error") => Err(BoxliteError::Network("test open failed".into())),
Some("pending") => Ok(Box::pin(futures::stream::pending())),
Some("read-error") => Ok(Box::pin(futures::stream::iter(vec![