Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,128 @@
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use futures::FutureExt;
use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;
use tracing::warn;
use super::CellHost;
use super::CellToolCall;
use crate::TaskFailureHandler;
use crate::runtime::RuntimeCommand;
#[derive(Clone, Copy)]
pub(super) enum CallbackCompletion {
DrainNotifications,
Cancel,
}
pub(super) fn spawn_notification<H: CellHost>(
tasks: &mut JoinSet<()>,
host: Arc<H>,
call_id: String,
text: String,
cancellation_token: CancellationToken,
task_failure_handler: Option<TaskFailureHandler>,
) {
tasks.spawn(async move {
let callback =
AssertUnwindSafe(async move { host.notify(call_id, text, cancellation_token).await })
.catch_unwind()
.await;
match callback {
Ok(Ok(())) => {}
Ok(Err(err)) => warn!("failed to deliver code mode notification: {err}"),
Err(_) => report_task_failure(
task_failure_handler.as_ref(),
"code mode notification task panicked".to_string(),
),
}
});
}
pub(super) fn spawn_tool<H: CellHost>(
tasks: &mut JoinSet<()>,
host: Arc<H>,
invocation: CellToolCall,
runtime_tx: std::sync::mpsc::Sender<RuntimeCommand>,
cancellation_token: CancellationToken,
task_failure_handler: Option<TaskFailureHandler>,
) {
tasks.spawn(async move {
let id = invocation.id.clone();
let callback =
AssertUnwindSafe(async move { host.invoke_tool(invocation, cancellation_token).await })
.catch_unwind()
.await;
let (command, failure_reason) = match callback {
Ok(Ok(result)) => (RuntimeCommand::ToolResponse { id, result }, None),
Ok(Err(error_text)) => (RuntimeCommand::ToolError { id, error_text }, None),
Err(_) => {
let failure_reason = "code mode tool task panicked".to_string();
(
RuntimeCommand::ToolError {
id,
error_text: failure_reason.clone(),
},
Some(failure_reason),
)
}
};
let _ = runtime_tx.send(command);
if let Some(failure_reason) = failure_reason {
report_task_failure(task_failure_handler.as_ref(), failure_reason);
}
});
}
pub(super) async fn finish_callbacks(
cancellation_token: &CancellationToken,
notification_tasks: &mut JoinSet<()>,
tool_tasks: &mut JoinSet<()>,
completion: CallbackCompletion,
task_failure_handler: Option<&TaskFailureHandler>,
) {
if matches!(completion, CallbackCompletion::Cancel) {
cancellation_token.cancel();
}
drain_tasks(notification_tasks, "notification", task_failure_handler).await;
cancellation_token.cancel();
drain_tasks(tool_tasks, "tool", task_failure_handler).await;
}
pub(super) fn report_task_result(
task_result: Option<Result<(), tokio::task::JoinError>>,
description: &str,
task_failure_handler: Option<&TaskFailureHandler>,
) {
if let Some(Err(err)) = task_result
&& !err.is_cancelled()
{
report_task_failure(
task_failure_handler,
format!("code mode {description} task failed: {err}"),
);
}
}
fn report_task_failure(task_failure_handler: Option<&TaskFailureHandler>, failure_reason: String) {
warn!("{failure_reason}");
if let Some(task_failure_handler) = task_failure_handler {
task_failure_handler(failure_reason);
}
}
async fn drain_tasks(
tasks: &mut JoinSet<()>,
description: &str,
task_failure_handler: Option<&TaskFailureHandler>,
) {
while let Some(result) = tasks.join_next().await {
report_task_result(Some(result), description, task_failure_handler);
}
}
#[cfg(test)]
#[path = "callbacks_tests.rs"]
mod tests;

View File

@@ -0,0 +1,131 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::mpsc as std_mpsc;
use std::time::Duration;
use pretty_assertions::assert_eq;
use serde_json::Value as JsonValue;
use tokio::sync::mpsc;
use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;
use super::*;
use crate::cell_actor::CellState;
use crate::cell_actor::CompletionCommit;
use crate::runtime::RuntimeCommand;
use crate::session_runtime::CellEvent;
use crate::session_runtime::ToolKind;
use crate::session_runtime::ToolName;
struct PanickingCallbackHost;
impl CellHost for PanickingCallbackHost {
async fn invoke_tool(
&self,
_invocation: CellToolCall,
_cancellation_token: CancellationToken,
) -> Result<JsonValue, String> {
panic!("tool callback panic probe");
}
async fn notify(
&self,
_call_id: String,
_text: String,
_cancellation_token: CancellationToken,
) -> Result<(), String> {
panic!("notification callback panic probe");
}
async fn commit_completion(
&self,
_stored_value_writes: HashMap<String, Arc<JsonValue>>,
_event: impl FnOnce() -> CellEvent + Send,
_cell_state: Arc<CellState>,
) -> CompletionCommit {
panic!("unexpected completion commit");
}
async fn closed(&self) {}
}
#[tokio::test]
async fn tool_callback_panic_rejects_the_js_promise_and_reports_failure() {
let mut tasks = JoinSet::new();
let (runtime_tx, runtime_rx) = std_mpsc::channel();
let (failure_tx, mut failure_rx) = mpsc::unbounded_channel();
spawn_tool(
&mut tasks,
Arc::new(PanickingCallbackHost),
CellToolCall {
id: "tool-1".to_string(),
name: ToolName {
name: "panic".to_string(),
namespace: None,
},
kind: ToolKind::Function,
input: None,
},
runtime_tx,
CancellationToken::new(),
Some(Arc::new(move |reason| {
let _ = failure_tx.send(reason);
})),
);
tasks
.join_next()
.await
.expect("tool callback task")
.expect("tool callback wrapper");
let command = runtime_rx
.recv_timeout(Duration::from_secs(1))
.expect("tool error command");
let RuntimeCommand::ToolError { id, error_text } = command else {
panic!("expected a tool error command");
};
assert_eq!(id, "tool-1");
assert_eq!(error_text, "code mode tool task panicked");
assert_eq!(failure_rx.recv().await, Some(error_text));
}
#[tokio::test]
async fn notification_callback_panic_reports_failure() {
let mut tasks = JoinSet::new();
let (failure_tx, mut failure_rx) = mpsc::unbounded_channel();
spawn_notification(
&mut tasks,
Arc::new(PanickingCallbackHost),
"notify-1".to_string(),
"hello".to_string(),
CancellationToken::new(),
Some(Arc::new(move |reason| {
let _ = failure_tx.send(reason);
})),
);
tasks
.join_next()
.await
.expect("notification callback task")
.expect("notification callback wrapper");
let failure_reason = failure_rx.recv().await.expect("notification failure");
assert_eq!(failure_reason, "code mode notification task panicked");
}
#[tokio::test]
async fn callback_wrapper_join_error_reports_failure() {
let task_result = tokio::spawn(async {
panic!("callback wrapper panic probe");
})
.await;
let (failure_tx, mut failure_rx) = mpsc::unbounded_channel();
let task_failure_handler: TaskFailureHandler = Arc::new(move |reason| {
let _ = failure_tx.send(reason);
});
report_task_result(Some(task_result), "tool", Some(&task_failure_handler));
let failure_reason = failure_rx.recv().await.expect("wrapper failure");
assert!(failure_reason.contains("code mode tool task failed"));
}

View File

@@ -0,0 +1,42 @@
use akode_code_mode_protocol::CodeModeToolKind;
use akode_code_mode_protocol::ExecuteRequest;
use akode_code_mode_protocol::ToolDefinition;
use akode_protocol::ToolName;
use crate::session_runtime::CreateCellRequest as CellRequest;
use crate::session_runtime::ToolKind as CellToolKind;
pub(super) fn runtime_request(request: CellRequest) -> ExecuteRequest {
ExecuteRequest {
tool_call_id: request.tool_call_id,
enabled_tools: request
.enabled_tools
.into_iter()
.map(|definition| ToolDefinition {
name: definition.name,
tool_name: ToolName {
name: definition.tool_name.name,
namespace: definition.tool_name.namespace,
},
description: definition.description,
kind: match definition.kind {
CellToolKind::Function => CodeModeToolKind::Function,
CellToolKind::Freeform => CodeModeToolKind::Freeform,
},
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
})
.collect(),
source: request.source,
yield_time_ms: None,
max_output_tokens: None,
}
}
pub(super) fn cell_tool_kind(kind: CodeModeToolKind) -> CellToolKind {
match kind {
CodeModeToolKind::Function => CellToolKind::Function,
CodeModeToolKind::Freeform => CellToolKind::Freeform,
}
}

View File

@@ -0,0 +1,590 @@
mod callbacks;
mod conversions;
mod types;
use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
use serde_json::Value as JsonValue;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;
use self::callbacks::CallbackCompletion;
use self::callbacks::finish_callbacks;
use self::callbacks::report_task_result;
use self::callbacks::spawn_notification;
use self::callbacks::spawn_tool;
use self::conversions::cell_tool_kind;
use self::conversions::runtime_request;
use self::types::CellCommand;
pub(crate) use self::types::CellError;
pub(crate) use self::types::CellEventFuture;
pub(crate) use self::types::CellHandle;
pub(crate) use self::types::CellHost;
pub(crate) use self::types::CellState;
pub(crate) use self::types::CellToolCall;
pub(crate) use self::types::CompletionCommit;
use self::types::CompletionDelivery;
use self::types::ObservationDelivery;
use crate::TaskFailureHandler;
use crate::output::OutputCollector;
use crate::runtime::PendingRuntimeMode;
use crate::runtime::RuntimeCommand;
use crate::runtime::RuntimeControlCommand;
use crate::runtime::RuntimeEvent;
use crate::runtime::RuntimeEventReceiver;
use crate::runtime::runtime_event_channel;
use crate::runtime::spawn_runtime;
use crate::session_runtime::CellEvent;
use crate::session_runtime::CreateCellRequest as CellRequest;
use crate::session_runtime::Observation;
use crate::session_runtime::ObserveMode;
use crate::session_runtime::ToolName as CellToolName;
pub(crate) struct CellActor;
impl CellActor {
pub(crate) fn prepare<H: CellHost>(
request: CellRequest,
stored_values: HashMap<String, Arc<JsonValue>>,
host: Arc<H>,
initial_observation: Observation,
cell_state: Arc<CellState>,
task_failure_handler: Option<TaskFailureHandler>,
) -> Result<
(
CellHandle,
CellEventFuture,
impl Future<Output = ()> + Send + 'static,
),
String,
> {
let (event_tx, event_rx) = runtime_event_channel(request.output_truncation);
let output = OutputCollector::new(request.output_truncation);
let (command_tx, command_rx) = mpsc::unbounded_channel();
let (initial_response_tx, initial_response_rx) = oneshot::channel();
let (runtime_tx, runtime_control_tx, runtime_terminate_handle) = spawn_runtime(
stored_values,
runtime_request(request),
event_tx,
PendingRuntimeMode::PauseUntilResumed,
task_failure_handler.clone(),
)?;
let handle = CellHandle::new(command_tx, Arc::clone(&cell_state));
let task = run_cell(
host,
CellContext {
runtime_tx,
runtime_control_tx,
runtime_terminate_handle,
cell_state,
output,
},
event_rx,
command_rx,
Observer {
observation: initial_observation,
response_tx: initial_response_tx,
},
task_failure_handler,
);
let initial_response =
Box::pin(async move { initial_response_rx.await.unwrap_or(Err(CellError::Closed)) });
Ok((handle, initial_response, task))
}
}
struct CellContext {
runtime_tx: std::sync::mpsc::Sender<RuntimeCommand>,
runtime_control_tx: std::sync::mpsc::Sender<RuntimeControlCommand>,
runtime_terminate_handle: v8::IsolateHandle,
cell_state: Arc<CellState>,
output: OutputCollector,
}
struct Observer {
observation: Observation,
response_tx: oneshot::Sender<Result<CellEvent, CellError>>,
}
async fn run_cell<H: CellHost>(
host: Arc<H>,
context: CellContext,
mut event_rx: RuntimeEventReceiver,
command_rx: mpsc::UnboundedReceiver<CellCommand>,
initial_observer: Observer,
task_failure_handler: Option<TaskFailureHandler>,
) {
let CellContext {
runtime_tx,
runtime_control_tx,
runtime_terminate_handle,
cell_state,
mut output,
} = context;
let cancellation_token = cell_state.cancellation_token();
let callback_cancellation_token = cancellation_token.child_token();
let mut pending_tool_call_ids = Vec::new();
let mut pending_frontier_ready = false;
let mut yield_signal = Some(initial_observer.observation.yield_signal.clone());
let mut observer = Some(initial_observer);
let mut termination = false;
let mut runtime_closed = false;
let mut runtime_paused = false;
let mut runtime_failure_reported = false;
let mut yield_timer: Option<std::pin::Pin<Box<tokio::time::Sleep>>> = None;
let mut notification_tasks = JoinSet::new();
let mut tool_tasks = JoinSet::new();
let mut command_rx = Some(command_rx);
loop {
let yield_deadline_elapsed = yield_timer
.as_ref()
.is_some_and(|yield_timer| yield_timer.deadline() <= tokio::time::Instant::now());
tokio::select! {
biased;
_ = cancellation_token.cancelled(), if !termination => {
termination = true;
yield_timer = None;
yield_signal = None;
drop(command_rx.take());
begin_termination(
&runtime_tx,
&runtime_control_tx,
&runtime_terminate_handle,
&cancellation_token,
);
if runtime_closed {
finish_callbacks(
&callback_cancellation_token,
&mut notification_tasks,
&mut tool_tasks,
CallbackCompletion::Cancel,
task_failure_handler.as_ref(),
).await;
finish_termination(
&cell_state,
observer.take().map(|observer| observer.response_tx),
CellEvent::Terminated {
content_items: output.take(),
},
);
break;
}
}
maybe_command = async {
match command_rx.as_mut() {
Some(command_rx) => command_rx.recv().await,
None => std::future::pending::<Option<CellCommand>>().await,
}
} => {
let Some(CellCommand::Observe { observation, response_tx }) = maybe_command else {
cancellation_token.cancel();
continue;
};
let mode = observation.mode;
if response_tx.is_closed() {
continue;
}
let response_tx = match cell_state.route_observation(response_tx) {
ObservationDelivery::Running(response_tx) => response_tx,
ObservationDelivery::Delivered => break,
ObservationDelivery::Buffered | ObservationDelivery::Closed => continue,
};
if observer
.as_ref()
.is_some_and(|observer| observer.response_tx.is_closed())
{
observer = None;
yield_timer = None;
yield_signal = None;
}
if observer.is_some() || termination {
let _ = response_tx.send(Err(CellError::Busy));
continue;
}
if matches!(mode, ObserveMode::PendingFrontier) && pending_frontier_ready {
pending_frontier_ready =
!send_pending(&mut output, response_tx, &mut pending_tool_call_ids);
continue;
}
yield_signal = Some(observation.yield_signal.clone());
observer = Some(Observer { observation, response_tx });
yield_timer = observer.as_ref().and_then(observer_timer);
if runtime_paused && matches!(mode, ObserveMode::YieldAfter(_)) {
pending_frontier_ready = false;
pending_tool_call_ids.clear();
}
resume_for_observation(
mode,
&mut runtime_paused,
&runtime_tx,
&runtime_control_tx,
);
}
_ = async {
tokio::select! {
_ = async {
if let Some(yield_timer) = yield_timer.as_mut() {
yield_timer.await;
} else {
std::future::pending::<()>().await;
}
} => {}
_ = async {
if let Some(yield_signal) = yield_signal.as_ref() {
yield_signal.cancelled().await;
} else {
std::future::pending::<()>().await;
}
} => {}
}
} => {
yield_timer = None;
yield_signal = None;
if let Some(observer) = observer.take() {
send_yield(&mut output, observer.response_tx);
}
}
maybe_event = async {
if runtime_closed {
std::future::pending().await
} else {
event_rx.recv().await
}
}, if !yield_deadline_elapsed => {
let Some(event) = maybe_event else {
runtime_closed = true;
yield_timer = None;
yield_signal = None;
if termination || cancellation_token.is_cancelled() {
finish_callbacks(
&callback_cancellation_token,
&mut notification_tasks,
&mut tool_tasks,
CallbackCompletion::Cancel,
task_failure_handler.as_ref(),
).await;
finish_termination(
&cell_state,
observer.take().map(|observer| observer.response_tx),
CellEvent::Terminated {
content_items: output.take(),
},
);
break;
}
if !runtime_failure_reported
&& let Some(task_failure_handler) = &task_failure_handler
{
runtime_failure_reported = true;
task_failure_handler(
"code-mode V8 runtime thread ended unexpectedly".to_string(),
);
}
finish_callbacks(
&callback_cancellation_token,
&mut notification_tasks,
&mut tool_tasks,
CallbackCompletion::DrainNotifications,
task_failure_handler.as_ref(),
)
.await;
host
.commit_completion(
HashMap::new(),
|| {
take_completed_event(&mut output, Some(
"exec runtime ended unexpectedly".to_string(),
))
},
Arc::clone(&cell_state),
)
.await;
match cell_state.deliver_completion(
observer.take().map(|observer| observer.response_tx),
) {
CompletionDelivery::Delivered => break,
CompletionDelivery::Buffered => {}
CompletionDelivery::Rejected(response_tx) => {
finish_termination(
&cell_state,
response_tx,
CellEvent::Terminated {
content_items: output.take(),
},
);
break;
}
}
continue;
};
match event {
// Keep the observer attached until termination has drained the output.
RuntimeEvent::Started | RuntimeEvent::Pending | RuntimeEvent::YieldRequested
if termination => {}
RuntimeEvent::Started => {
yield_timer = observer.as_ref().and_then(observer_timer);
}
RuntimeEvent::Pending => {
runtime_paused = true;
if let Some(observer) = observer.take_if(|observer| {
matches!(observer.observation.mode, ObserveMode::PendingFrontier)
}) {
yield_timer = None;
yield_signal = None;
pending_frontier_ready =
!send_pending(&mut output, observer.response_tx, &mut pending_tool_call_ids);
} else {
pending_tool_call_ids.clear();
let _ = runtime_control_tx.send(RuntimeControlCommand::Continue);
runtime_paused = false;
}
}
RuntimeEvent::ContentItem(item) => {
output.push(item);
}
RuntimeEvent::YieldRequested => {
if let Some(observer) = observer.take_if(|observer| {
matches!(observer.observation.mode, ObserveMode::YieldAfter(_))
}) {
yield_timer = None;
yield_signal = None;
send_yield(&mut output, observer.response_tx);
}
}
RuntimeEvent::Notify { call_id, text } => {
spawn_notification(
&mut notification_tasks,
Arc::clone(&host),
call_id,
text,
callback_cancellation_token.child_token(),
task_failure_handler.clone(),
);
}
RuntimeEvent::ToolCall { id, name, kind, input } => {
pending_tool_call_ids.push(id.clone());
spawn_tool(
&mut tool_tasks,
Arc::clone(&host),
CellToolCall {
id,
name: CellToolName {
name: name.name,
namespace: name.namespace,
},
kind: cell_tool_kind(kind),
input,
},
runtime_tx.clone(),
callback_cancellation_token.child_token(),
task_failure_handler.clone(),
);
}
RuntimeEvent::Result { stored_value_writes, error_text } => {
runtime_closed = true;
yield_timer = None;
yield_signal = None;
if termination || cancellation_token.is_cancelled() {
finish_callbacks(
&callback_cancellation_token,
&mut notification_tasks,
&mut tool_tasks,
CallbackCompletion::Cancel,
task_failure_handler.as_ref(),
).await;
finish_termination(
&cell_state,
observer.take().map(|observer| observer.response_tx),
CellEvent::Terminated {
content_items: output.take(),
},
);
break;
}
finish_callbacks(
&callback_cancellation_token,
&mut notification_tasks,
&mut tool_tasks,
CallbackCompletion::DrainNotifications,
task_failure_handler.as_ref(),
)
.await;
host
.commit_completion(
stored_value_writes,
|| take_completed_event(&mut output, error_text),
Arc::clone(&cell_state),
)
.await;
match cell_state.deliver_completion(
observer.take().map(|observer| observer.response_tx),
) {
CompletionDelivery::Delivered => break,
CompletionDelivery::Buffered => {}
CompletionDelivery::Rejected(response_tx) => {
finish_termination(
&cell_state,
response_tx,
CellEvent::Terminated {
content_items: output.take(),
},
);
break;
}
}
}
RuntimeEvent::ThreadPanicked => {
runtime_failure_reported = true;
}
}
}
task_result = notification_tasks.join_next(), if !notification_tasks.is_empty() => {
report_task_result(
task_result,
"notification",
task_failure_handler.as_ref(),
);
}
task_result = tool_tasks.join_next(), if !tool_tasks.is_empty() => {
report_task_result(task_result, "tool", task_failure_handler.as_ref());
}
}
}
// Reject requests that arrive while asynchronous terminal cleanup runs.
cell_state.tombstone();
drop(command_rx.take());
begin_termination(
&runtime_tx,
&runtime_control_tx,
&runtime_terminate_handle,
&cancellation_token,
);
finish_callbacks(
&callback_cancellation_token,
&mut notification_tasks,
&mut tool_tasks,
CallbackCompletion::Cancel,
task_failure_handler.as_ref(),
)
.await;
host.closed().await;
}
/// Construct completion only after the terminal outcome is settled.
pub(crate) fn take_completed_event(
output: &mut OutputCollector,
error_text: Option<String>,
) -> CellEvent {
let error_text = error_text.map(|error_text| output.collect_error(error_text));
CellEvent::Completed {
content_items: output.take(),
error_text,
result_buffered_for: std::time::Duration::ZERO,
}
}
fn send_cell_event(
response_tx: oneshot::Sender<Result<CellEvent, CellError>>,
event: CellEvent,
) -> Result<(), CellEvent> {
match response_tx.send(Ok(event)) {
Ok(()) => Ok(()),
Err(Ok(event)) => Err(event),
Err(Err(error)) => panic!("cell event delivery returned an actor error: {error:?}"),
}
}
fn send_yield(
output: &mut OutputCollector,
response_tx: oneshot::Sender<Result<CellEvent, CellError>>,
) {
output.try_deliver(|content_items| {
send_cell_event(response_tx, CellEvent::Yielded { content_items }).map_err(|event| {
let CellEvent::Yielded { content_items } = event else {
unreachable!("yield delivery returned a different event");
};
content_items
})
});
}
fn send_pending(
output: &mut OutputCollector,
response_tx: oneshot::Sender<Result<CellEvent, CellError>>,
pending_tool_call_ids: &mut Vec<String>,
) -> bool {
output.try_deliver(|content_items| {
let pending = CellEvent::Pending {
content_items,
pending_tool_call_ids: std::mem::take(pending_tool_call_ids),
};
send_cell_event(response_tx, pending).map_err(|event| {
let CellEvent::Pending {
content_items,
pending_tool_call_ids: returned_ids,
} = event
else {
unreachable!("pending delivery returned a different event");
};
*pending_tool_call_ids = returned_ids;
content_items
})
})
}
fn finish_termination(
cell_state: &CellState,
observer_tx: Option<oneshot::Sender<Result<CellEvent, CellError>>>,
event: CellEvent,
) {
if let Some(event) = cell_state.finish_termination(event)
&& let Some(observer_tx) = observer_tx
{
let _ = observer_tx.send(Ok(event));
}
}
fn observer_timer(observer: &Observer) -> Option<std::pin::Pin<Box<tokio::time::Sleep>>> {
match observer.observation.mode {
ObserveMode::YieldAfter(duration) => Some(Box::pin(tokio::time::sleep(duration))),
ObserveMode::PendingFrontier => None,
}
}
fn resume_for_observation(
mode: ObserveMode,
runtime_paused: &mut bool,
runtime_tx: &std::sync::mpsc::Sender<RuntimeCommand>,
runtime_control_tx: &std::sync::mpsc::Sender<RuntimeControlCommand>,
) {
if *runtime_paused {
let control = match mode {
ObserveMode::YieldAfter(_) => RuntimeControlCommand::Continue,
ObserveMode::PendingFrontier => RuntimeControlCommand::Resume,
};
let _ = runtime_control_tx.send(control);
*runtime_paused = false;
} else if matches!(mode, ObserveMode::PendingFrontier) {
let _ = runtime_tx.send(RuntimeCommand::ObservePendingFrontier);
}
}
fn begin_termination(
runtime_tx: &std::sync::mpsc::Sender<RuntimeCommand>,
runtime_control_tx: &std::sync::mpsc::Sender<RuntimeControlCommand>,
runtime_terminate_handle: &v8::IsolateHandle,
cancellation_token: &CancellationToken,
) {
cancellation_token.cancel();
let _ = runtime_tx.send(RuntimeCommand::Terminate);
let _ = runtime_control_tx.send(RuntimeControlCommand::Terminate);
let _ = runtime_terminate_handle.terminate_execution();
}
#[cfg(test)]
#[path = "tests.rs"]
mod tests;

View File

@@ -0,0 +1,766 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::mpsc as std_mpsc;
use std::time::Duration;
use akode_code_mode_protocol::CodeModeOutputTruncation;
use akode_code_mode_protocol::ExecuteRequest;
use akode_code_mode_protocol::host::BOUNDED_OUTPUT_MAX_IMAGE_BYTES;
use pretty_assertions::assert_eq;
use serde_json::Value as JsonValue;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use super::*;
use crate::runtime::RuntimeEventSender;
use crate::session_runtime::OutputItem;
#[derive(Default)]
struct TestHost {
commit_started: CancellationToken,
resume_commit: Option<CancellationToken>,
}
#[derive(Default)]
struct RecordingHost {
notified: AtomicBool,
}
impl CellHost for TestHost {
async fn invoke_tool(
&self,
_invocation: CellToolCall,
_cancellation_token: CancellationToken,
) -> Result<JsonValue, String> {
Err("unexpected tool call".to_string())
}
async fn notify(
&self,
_call_id: String,
_text: String,
_cancellation_token: CancellationToken,
) -> Result<(), String> {
Ok(())
}
async fn commit_completion(
&self,
_stored_value_writes: HashMap<String, Arc<JsonValue>>,
event: impl FnOnce() -> CellEvent + Send,
cell_state: Arc<CellState>,
) -> CompletionCommit {
self.commit_started.cancel();
if let Some(resume) = &self.resume_commit {
resume.cancelled().await;
}
cell_state.commit_completion(event, || {})
}
async fn closed(&self) {}
}
impl CellHost for RecordingHost {
async fn invoke_tool(
&self,
_invocation: CellToolCall,
_cancellation_token: CancellationToken,
) -> Result<JsonValue, String> {
Err("unexpected tool call".to_string())
}
async fn notify(
&self,
_call_id: String,
_text: String,
_cancellation_token: CancellationToken,
) -> Result<(), String> {
self.notified.store(true, Ordering::Release);
Ok(())
}
async fn commit_completion(
&self,
_stored_value_writes: HashMap<String, Arc<JsonValue>>,
event: impl FnOnce() -> CellEvent + Send,
cell_state: Arc<CellState>,
) -> CompletionCommit {
cell_state.commit_completion(event, || {})
}
async fn closed(&self) {}
}
struct CellActorHarness {
event_tx: RuntimeEventSender,
handle: CellHandle,
yield_signal: CancellationToken,
initial_event_rx: oneshot::Receiver<Result<CellEvent, CellError>>,
task: tokio::task::JoinHandle<()>,
runtime_control_rx: std_mpsc::Receiver<RuntimeControlCommand>,
_runtime_event_rx: mpsc::UnboundedReceiver<RuntimeEvent>,
}
fn spawn_cell_actor_harness(initial_observe_mode: ObserveMode) -> CellActorHarness {
spawn_cell_actor_harness_with_host(initial_observe_mode, Arc::new(TestHost::default()))
}
fn spawn_cell_actor_harness_with_host<H: CellHost>(
initial_observe_mode: ObserveMode,
host: Arc<H>,
) -> CellActorHarness {
spawn_cell_actor_harness_with_host_and_failure_handler(
initial_observe_mode,
host,
CodeModeOutputTruncation::Client,
/*task_failure_handler*/ None,
)
}
fn spawn_cell_actor_harness_with_host_and_failure_handler<H: CellHost>(
initial_observe_mode: ObserveMode,
host: Arc<H>,
output_truncation: CodeModeOutputTruncation,
task_failure_handler: Option<TaskFailureHandler>,
) -> CellActorHarness {
let (event_tx, event_rx) = runtime_event_channel(output_truncation);
let output = OutputCollector::new(output_truncation);
let (command_tx, command_rx) = mpsc::unbounded_channel();
let (initial_event_tx, initial_event_rx) = oneshot::channel();
let (runtime_event_tx, runtime_event_rx) = mpsc::unbounded_channel();
let (runtime_tx, _runtime_control_tx, runtime_terminate_handle) = spawn_runtime(
HashMap::new(),
ExecuteRequest {
tool_call_id: "call-1".to_string(),
enabled_tools: Vec::new(),
source: "await new Promise(() => {});".to_string(),
yield_time_ms: None,
max_output_tokens: None,
},
runtime_event_tx,
PendingRuntimeMode::PauseUntilResumed,
/*task_failure_handler*/ None,
)
.unwrap();
let (runtime_control_tx, runtime_control_rx) = std_mpsc::channel();
let cell_state = Arc::new(CellState::new(CancellationToken::new()));
let handle = CellHandle::new(command_tx, Arc::clone(&cell_state));
let yield_signal = CancellationToken::new();
let task = tokio::spawn(run_cell(
host,
CellContext {
runtime_tx,
runtime_control_tx,
runtime_terminate_handle,
cell_state,
output,
},
event_rx,
command_rx,
Observer {
observation: initial_observe_mode.with_yield_signal(yield_signal.clone()),
response_tx: initial_event_tx,
},
task_failure_handler,
));
CellActorHarness {
event_tx,
handle,
yield_signal,
initial_event_rx,
task,
runtime_control_rx,
_runtime_event_rx: runtime_event_rx,
}
}
#[tokio::test]
async fn termination_drains_a_send_already_blocked_by_backpressure() {
let harness = spawn_cell_actor_harness_with_host_and_failure_handler(
ObserveMode::YieldAfter(Duration::from_secs(60)),
Arc::new(TestHost::default()),
CodeModeOutputTruncation::Server,
/*task_failure_handler*/ None,
);
let (termination, capacity) = {
let RuntimeEventSender::Bounded(tx) = &harness.event_tx else {
panic!("server runtime must use a bounded sender");
};
// This test owns the V8-side events. The current-thread actor cannot run
// before our first await; fill its actual FIFO and register a sender.
for _ in 0..tx.max_capacity() {
tx.try_send(RuntimeEvent::ContentItem(OutputItem::InputText {
text: "queued".to_string(),
}))
.unwrap();
}
let mut send = std::pin::pin!(tx.send(RuntimeEvent::ContentItem(OutputItem::InputText {
text: "blocked".to_string(),
})));
assert!(futures::poll!(send.as_mut()).is_pending());
// terminate() synchronously cancels. No event was consumed between the
// Pending poll and cancellation; run_cell must drain while terminating.
let termination = harness.handle.terminate();
tokio::time::timeout(Duration::from_secs(1), send)
.await
.expect("termination must release the registered sender")
.expect("actor must drain the blocked item");
(termination, tx.max_capacity())
};
drop(harness.event_tx);
let event = tokio::time::timeout(Duration::from_secs(1), termination)
.await
.expect("termination must finish after draining")
.expect("termination event");
let mut expected = OutputCollector::new(CodeModeOutputTruncation::Server);
for _ in 0..capacity {
expected.push(OutputItem::InputText {
text: "queued".to_string(),
});
}
expected.push(OutputItem::InputText {
text: "blocked".to_string(),
});
assert_eq!(
event,
CellEvent::Terminated {
content_items: expected,
}
);
assert_eq!(harness.initial_event_rx.await.unwrap(), Ok(event));
tokio::time::timeout(Duration::from_secs(1), harness.task)
.await
.expect("actor must close")
.unwrap();
}
#[tokio::test]
async fn unexpected_runtime_thread_exit_is_reported_to_the_session_owner() {
let (failure_tx, mut failure_rx) = mpsc::unbounded_channel();
let harness = spawn_cell_actor_harness_with_host_and_failure_handler(
ObserveMode::YieldAfter(Duration::from_secs(60)),
Arc::new(TestHost::default()),
CodeModeOutputTruncation::Client,
Some(Arc::new(move |reason| {
let _ = failure_tx.send(reason);
})),
);
drop(harness.event_tx);
assert_eq!(
tokio::time::timeout(Duration::from_secs(1), failure_rx.recv())
.await
.expect("runtime failure timeout")
.expect("runtime failure"),
"code-mode V8 runtime thread ended unexpectedly"
);
assert!(
harness
.initial_event_rx
.await
.expect("initial event")
.is_ok()
);
harness.task.await.expect("cell task");
}
#[tokio::test]
async fn termination_during_completion_commit_preserves_output_and_discards_losing_error() {
for mode in [
CodeModeOutputTruncation::Client,
CodeModeOutputTruncation::Server,
] {
// The actor has received Result but cannot commit until the host releases
// the session store. Termination must decide which output is published.
let resume_commit = CancellationToken::new();
let host = Arc::new(TestHost {
resume_commit: Some(resume_commit.clone()),
..TestHost::default()
});
let harness = spawn_cell_actor_harness_with_host_and_failure_handler(
ObserveMode::YieldAfter(Duration::from_secs(60)),
Arc::clone(&host),
mode,
/*task_failure_handler*/ None,
);
// Simulate V8's dedicated thread, where server-mode sends can block
// while the event queue is full.
let event_tx = harness.event_tx.clone();
tokio::task::spawn_blocking(move || {
event_tx
.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputText {
text: "output that must survive termination".to_string(),
}))
.expect("output");
event_tx
.blocking_send(RuntimeEvent::Result {
stored_value_writes: HashMap::new(),
error_text: Some("uncommitted error".repeat(128 * 1024)),
})
.expect("completion");
})
.await
.expect("runtime producer");
tokio::time::timeout(Duration::from_secs(5), host.commit_started.cancelled())
.await
.expect("commit reached");
let termination = harness.handle.terminate();
resume_commit.cancel();
let mut expected_output = OutputCollector::new(mode);
expected_output.push(OutputItem::InputText {
text: "output that must survive termination".to_string(),
});
let expected = Ok(CellEvent::Terminated {
content_items: expected_output,
});
assert_eq!(termination.await, expected, "{mode:?}");
assert_eq!(harness.initial_event_rx.await.expect("observer"), expected);
harness.task.await.expect("cell task");
}
}
#[tokio::test]
async fn runtime_thread_panic_remains_a_cell_error_without_owner_supervision() {
let harness = spawn_cell_actor_harness(ObserveMode::YieldAfter(Duration::from_secs(60)));
harness
.event_tx
.blocking_send(RuntimeEvent::ThreadPanicked)
.expect("runtime panic event");
drop(harness.event_tx);
assert_eq!(
harness.initial_event_rx.await.expect("initial event"),
Ok(CellEvent::Completed {
content_items: OutputCollector::Client(Vec::new()),
result_buffered_for: Duration::ZERO,
error_text: Some("exec runtime ended unexpectedly".to_string()),
})
);
harness.task.await.expect("cell task");
}
async fn wait_for_notification(host: &RecordingHost) {
tokio::time::timeout(Duration::from_secs(1), async {
while !host.notified.load(Ordering::Acquire) {
tokio::task::yield_now().await;
}
})
.await
.expect("notification barrier timed out");
}
#[tokio::test]
async fn yield_timer_preempts_buffered_runtime_output() {
let harness = spawn_cell_actor_harness(ObserveMode::YieldAfter(Duration::ZERO));
harness
.event_tx
.blocking_send(RuntimeEvent::Started)
.unwrap();
harness
.event_tx
.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputText {
text: "queued output".to_string(),
}))
.unwrap();
assert_eq!(
harness.initial_event_rx.await.unwrap(),
Ok(CellEvent::Yielded {
content_items: OutputCollector::Client(Vec::new()),
})
);
let termination = harness.handle.terminate();
drop(harness.event_tx);
assert_eq!(
termination.await,
Ok(CellEvent::Terminated {
content_items: OutputCollector::Client(vec![OutputItem::InputText {
text: "queued output".to_string(),
}]),
})
);
harness.task.await.unwrap();
}
#[tokio::test]
async fn queued_termination_preempts_unobserved_runtime_completion() {
let harness = spawn_cell_actor_harness(ObserveMode::YieldAfter(Duration::ZERO));
harness
.event_tx
.blocking_send(RuntimeEvent::Started)
.unwrap();
harness
.event_tx
.blocking_send(RuntimeEvent::YieldRequested)
.unwrap();
harness
.event_tx
.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputText {
text: "queued output".to_string(),
}))
.unwrap();
harness
.event_tx
.blocking_send(RuntimeEvent::Result {
stored_value_writes: HashMap::new(),
error_text: None,
})
.unwrap();
harness.yield_signal.cancel();
let termination = harness.handle.terminate();
let terminated = Ok(CellEvent::Terminated {
content_items: OutputCollector::Client(vec![OutputItem::InputText {
text: "queued output".to_string(),
}]),
});
assert_eq!(termination.await, terminated.clone());
assert_eq!(harness.initial_event_rx.await.unwrap(), terminated);
harness.task.await.unwrap();
}
#[tokio::test]
async fn observation_dropped_before_dequeue_does_not_consume_output() {
let host = Arc::new(RecordingHost::default());
let harness = spawn_cell_actor_harness_with_host(
ObserveMode::YieldAfter(Duration::from_secs(60)),
Arc::clone(&host),
);
harness
.event_tx
.blocking_send(RuntimeEvent::YieldRequested)
.unwrap();
assert!(harness.initial_event_rx.await.unwrap().is_ok());
drop(
harness
.handle
.observe(ObserveMode::YieldAfter(Duration::from_secs(60))),
);
harness
.event_tx
.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputText {
text: "survives pre-dequeue cancellation".to_string(),
}))
.unwrap();
harness
.event_tx
.blocking_send(RuntimeEvent::YieldRequested)
.unwrap();
harness
.event_tx
.blocking_send(RuntimeEvent::Notify {
call_id: "after-dropped-command".to_string(),
text: "barrier".to_string(),
})
.unwrap();
wait_for_notification(&host).await;
assert_eq!(
harness
.handle
.observe(ObserveMode::YieldAfter(Duration::ZERO))
.await,
Ok(CellEvent::Yielded {
content_items: OutputCollector::Client(vec![OutputItem::InputText {
text: "survives pre-dequeue cancellation".to_string(),
}]),
})
);
let termination = harness.handle.terminate();
drop(harness.event_tx);
assert_eq!(
termination.await,
Ok(CellEvent::Terminated {
content_items: OutputCollector::Client(Vec::new()),
})
);
harness.task.await.unwrap();
}
#[tokio::test]
async fn dropped_yield_observer_preserves_output_for_the_next_observation() {
let host = Arc::new(RecordingHost::default());
let harness = spawn_cell_actor_harness_with_host(
ObserveMode::YieldAfter(Duration::from_secs(60)),
Arc::clone(&host),
);
harness
.event_tx
.blocking_send(RuntimeEvent::YieldRequested)
.unwrap();
assert!(harness.initial_event_rx.await.unwrap().is_ok());
let dropped_observation = harness
.handle
.observe(ObserveMode::YieldAfter(Duration::from_secs(60)));
assert_eq!(
harness
.handle
.observe(ObserveMode::YieldAfter(Duration::ZERO))
.await,
Err(CellError::Busy)
);
drop(dropped_observation);
harness
.event_tx
.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputText {
text: "survives active cancellation".to_string(),
}))
.unwrap();
harness
.event_tx
.blocking_send(RuntimeEvent::YieldRequested)
.unwrap();
harness
.event_tx
.blocking_send(RuntimeEvent::Notify {
call_id: "after-dropped-observer".to_string(),
text: "barrier".to_string(),
})
.unwrap();
wait_for_notification(&host).await;
assert_eq!(
harness
.handle
.observe(ObserveMode::YieldAfter(Duration::ZERO))
.await,
Ok(CellEvent::Yielded {
content_items: OutputCollector::Client(vec![OutputItem::InputText {
text: "survives active cancellation".to_string(),
}]),
})
);
let termination = harness.handle.terminate();
drop(harness.event_tx);
assert_eq!(
termination.await,
Ok(CellEvent::Terminated {
content_items: OutputCollector::Client(Vec::new()),
})
);
harness.task.await.unwrap();
}
#[tokio::test]
async fn dropped_pending_observer_preserves_the_frontier_for_the_next_observation() {
let host = Arc::new(RecordingHost::default());
let harness = spawn_cell_actor_harness_with_host(
ObserveMode::YieldAfter(Duration::from_secs(60)),
Arc::clone(&host),
);
harness
.event_tx
.blocking_send(RuntimeEvent::YieldRequested)
.unwrap();
assert!(harness.initial_event_rx.await.unwrap().is_ok());
let dropped_observation = harness.handle.observe(ObserveMode::PendingFrontier);
assert_eq!(
harness.handle.observe(ObserveMode::PendingFrontier).await,
Err(CellError::Busy)
);
drop(dropped_observation);
let item = OutputItem::InputText {
text: "before frontier".to_owned(),
};
harness
.event_tx
.blocking_send(RuntimeEvent::ContentItem(item.clone()))
.unwrap();
harness
.event_tx
.blocking_send(RuntimeEvent::ToolCall {
id: "tool-1".to_string(),
name: akode_protocol::ToolName {
name: "echo".to_string(),
namespace: None,
},
kind: akode_code_mode_protocol::CodeModeToolKind::Function,
input: Some(serde_json::json!({})),
})
.unwrap();
harness
.event_tx
.blocking_send(RuntimeEvent::Pending)
.unwrap();
harness
.event_tx
.blocking_send(RuntimeEvent::Notify {
call_id: "after-dropped-pending".to_string(),
text: "barrier".to_string(),
})
.unwrap();
wait_for_notification(&host).await;
assert_eq!(
harness.handle.observe(ObserveMode::PendingFrontier).await,
Ok(CellEvent::Pending {
content_items: OutputCollector::Client(vec![item]),
pending_tool_call_ids: vec!["tool-1".to_string()],
})
);
assert!(matches!(
harness.runtime_control_rx.try_recv(),
Err(std_mpsc::TryRecvError::Empty)
));
let termination = harness.handle.terminate();
drop(harness.event_tx);
assert_eq!(
termination.await,
Ok(CellEvent::Terminated {
content_items: OutputCollector::Client(Vec::new()),
})
);
harness.task.await.unwrap();
}
#[tokio::test(start_paused = true)]
async fn only_the_first_termination_claims_a_buffered_completion() {
let cell_state = CellState::new(CancellationToken::new());
let completion = CellEvent::Completed {
content_items: OutputCollector::Client(Vec::new()),
result_buffered_for: Duration::ZERO,
error_text: None,
};
assert_eq!(
cell_state.commit_completion(|| completion.clone(), || {}),
CompletionCommit::Committed
);
assert!(matches!(
cell_state.deliver_completion(/*response_tx*/ None),
CompletionDelivery::Buffered
));
let first_termination = cell_state.request_termination();
assert_eq!(
cell_state.request_termination().await,
Err(CellError::AlreadyTerminating)
);
assert_eq!(first_termination.await, Ok(completion.clone()));
assert_eq!(
cell_state.finish_termination(CellEvent::Terminated {
content_items: OutputCollector::Client(Vec::new()),
}),
Some(completion)
);
}
#[tokio::test]
async fn termination_claim_prevents_stored_value_commit() {
let cell_state = CellState::new(CancellationToken::new());
let termination = cell_state.request_termination();
let mut commit_ran = false;
assert_eq!(
cell_state.commit_completion(
|| panic!("terminated cell must not construct completion output"),
|| commit_ran = true
),
CompletionCommit::Rejected
);
assert!(!commit_ran);
let terminated = CellEvent::Terminated {
content_items: OutputCollector::Client(Vec::new()),
};
assert_eq!(
cell_state.finish_termination(terminated.clone()),
Some(terminated.clone())
);
assert_eq!(termination.await, Ok(terminated));
}
#[tokio::test(start_paused = true)]
async fn failed_completion_delivery_rebuffers_the_event() {
let cell_state = CellState::new(CancellationToken::new());
let completion = |result_buffered_for| CellEvent::Completed {
content_items: OutputCollector::Client(vec![OutputItem::InputText {
text: "done".to_string(),
}]),
result_buffered_for,
error_text: None,
};
assert_eq!(
cell_state.commit_completion(|| completion(Duration::ZERO), || {}),
CompletionCommit::Committed
);
let (response_tx, response_rx) = oneshot::channel();
drop(response_rx);
assert!(matches!(
cell_state.deliver_completion(Some(response_tx)),
CompletionDelivery::Buffered
));
assert!(cell_state.accepting_observations());
let interval = Duration::from_secs(5);
tokio::time::advance(interval).await;
let (response_tx, response_rx) = oneshot::channel();
drop(response_rx);
assert!(matches!(
cell_state.route_observation(response_tx),
ObservationDelivery::Buffered
));
tokio::time::advance(interval).await;
let (response_tx, mut response_rx) = oneshot::channel();
assert!(matches!(
cell_state.route_observation(response_tx),
ObservationDelivery::Delivered
));
assert_eq!(response_rx.try_recv(), Ok(Ok(completion(2 * interval))));
}
#[test]
fn a_failed_yield_restores_image_allocation_and_omission_order() {
let mut output = OutputCollector::new(CodeModeOutputTruncation::Server);
let image_url = "i".repeat(BOUNDED_OUTPUT_MAX_IMAGE_BYTES);
let pointer = image_url.as_ptr();
output.push(OutputItem::InputImage {
image_url,
detail: None,
});
output.push(OutputItem::InputImage {
image_url: "excess".to_string(),
detail: None,
});
let (tx, rx) = oneshot::channel();
drop(rx);
send_yield(&mut output, tx);
output.push(OutputItem::InputText {
text: "after".to_string(),
});
let (tx, mut rx) = oneshot::channel();
send_yield(&mut output, tx);
let CellEvent::Yielded { content_items } = rx.try_recv().unwrap().unwrap() else {
panic!("expected a yield");
};
let items = crate::output::render_output(
content_items.into_collected_output(),
/*max_output_tokens*/ None,
);
let [
OutputItem::InputImage { image_url, .. },
OutputItem::InputText { text: notice },
OutputItem::InputText { text },
] = items.as_slice()
else {
panic!("expected image, omission notice, and subsequent text");
};
assert_eq!(image_url.as_ptr(), pointer);
assert!(notice.contains("1 images"), "{notice}");
assert_eq!(text, "after");
assert_eq!(
output.take(),
OutputCollector::new(CodeModeOutputTruncation::Server)
);
}

View File

@@ -0,0 +1,376 @@
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Mutex;
use tokio::time::Instant;
use serde_json::Value as JsonValue;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use super::send_cell_event;
use crate::session_runtime::CellEvent;
use crate::session_runtime::Observation;
use crate::session_runtime::ToolKind;
use crate::session_runtime::ToolName;
pub(crate) type CellEventFuture =
Pin<Box<dyn Future<Output = Result<CellEvent, CellError>> + Send + 'static>>;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum CellError {
Busy,
AlreadyTerminating,
Closed,
}
pub(crate) struct CellToolCall {
pub(crate) id: String,
pub(crate) name: ToolName,
pub(crate) kind: ToolKind,
pub(crate) input: Option<JsonValue>,
}
/// Connects a cell actor to session-owned callbacks and stored values.
///
/// Implementations should forward callback cancellation to downstream work.
/// Implementations must not return from `closed` until the session can no longer
/// route requests to the cell.
pub(crate) trait CellHost: Send + Sync + 'static {
fn invoke_tool(
&self,
invocation: CellToolCall,
cancellation_token: CancellationToken,
) -> impl Future<Output = Result<JsonValue, String>> + Send;
fn notify(
&self,
call_id: String,
text: String,
cancellation_token: CancellationToken,
) -> impl Future<Output = Result<(), String>> + Send;
fn commit_completion(
&self,
stored_value_writes: HashMap<String, Arc<JsonValue>>,
event: impl FnOnce() -> CellEvent + Send,
cell_state: Arc<CellState>,
) -> impl Future<Output = CompletionCommit> + Send;
fn closed(&self) -> impl Future<Output = ()> + Send;
}
#[derive(Clone)]
pub(crate) struct CellHandle {
command_tx: mpsc::UnboundedSender<CellCommand>,
state: Arc<CellState>,
}
impl CellHandle {
pub(super) fn new(
command_tx: mpsc::UnboundedSender<CellCommand>,
state: Arc<CellState>,
) -> Self {
Self { command_tx, state }
}
pub(crate) fn observe(&self, observation: impl Into<Observation>) -> CellEventFuture {
if !self.state.accepting_observations() {
return closed_event();
}
let (response_tx, response_rx) = oneshot::channel();
if self
.command_tx
.send(CellCommand::Observe {
observation: observation.into(),
response_tx,
})
.is_err()
{
return closed_event();
}
response_event(response_rx)
}
pub(crate) fn terminate(&self) -> CellEventFuture {
self.state.request_termination()
}
}
/// The single linearization point for a cell's terminal outcome.
///
/// The cancellation token is a child of the owning session token. Callback
/// tokens are children of this token, so cancellation flows strictly from the
/// session to the cell and then to its callbacks.
///
/// The mutex is held only for synchronous phase transitions and terminal
/// delivery. Runtime execution, observation waits, and callbacks never run
/// while it is held.
pub(crate) struct CellState {
phase: Mutex<CellPhase>,
cancellation_token: CancellationToken,
}
enum CellPhase {
Running,
Terminating {
response_tx: oneshot::Sender<Result<CellEvent, CellError>>,
},
Completed {
event: CellEvent,
completed_at: Instant,
},
CompletionClaimed(CellEvent),
Tombstone,
}
pub(crate) enum CompletionDelivery {
Delivered,
Buffered,
Rejected(Option<oneshot::Sender<Result<CellEvent, CellError>>>),
}
/// Result of atomically publishing a completed cell and its session side effects.
#[derive(Debug, PartialEq)]
pub(crate) enum CompletionCommit {
Committed,
Rejected,
}
pub(crate) enum ObservationDelivery {
Running(oneshot::Sender<Result<CellEvent, CellError>>),
Delivered,
Buffered,
Closed,
}
impl CellState {
pub(crate) fn new(cancellation_token: CancellationToken) -> Self {
Self {
phase: Mutex::new(CellPhase::Running),
cancellation_token,
}
}
pub(crate) fn accepting_observations(&self) -> bool {
let accepting_phase = matches!(
*self
.phase
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
CellPhase::Running | CellPhase::Completed { .. }
);
accepting_phase && !self.cancellation_token.is_cancelled()
}
pub(crate) fn request_termination(&self) -> CellEventFuture {
let mut phase = self
.phase
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match std::mem::replace(&mut *phase, CellPhase::Tombstone) {
CellPhase::Running => {
let (response_tx, response_rx) = oneshot::channel();
*phase = CellPhase::Terminating { response_tx };
self.cancellation_token.cancel();
response_event(response_rx)
}
CellPhase::Terminating { response_tx } => {
*phase = CellPhase::Terminating { response_tx };
Box::pin(async { Err(CellError::AlreadyTerminating) })
}
CellPhase::Completed {
event,
completed_at,
} => {
let event = buffered_completion(event, completed_at);
*phase = CellPhase::CompletionClaimed(event.clone());
self.cancellation_token.cancel();
ready_event(event)
}
CellPhase::CompletionClaimed(event) => {
*phase = CellPhase::CompletionClaimed(event);
Box::pin(async { Err(CellError::AlreadyTerminating) })
}
CellPhase::Tombstone => closed_event(),
}
}
pub(crate) fn commit_completion(
&self,
event: impl FnOnce() -> CellEvent,
commit: impl FnOnce(),
) -> CompletionCommit {
let mut phase = self
.phase
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !matches!(*phase, CellPhase::Running) || self.cancellation_token.is_cancelled() {
return CompletionCommit::Rejected;
}
commit();
*phase = CellPhase::Completed {
// Construct terminal output only after completion wins. In bounded
// mode, an error may evict user output; termination must not see it.
event: event(),
completed_at: Instant::now(),
};
CompletionCommit::Committed
}
pub(crate) fn deliver_completion(
&self,
response_tx: Option<oneshot::Sender<Result<CellEvent, CellError>>>,
) -> CompletionDelivery {
let mut phase = self
.phase
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let (event, completed_at) = match std::mem::replace(&mut *phase, CellPhase::Tombstone) {
CellPhase::Completed {
event,
completed_at,
} => (event, completed_at),
previous => {
*phase = previous;
return CompletionDelivery::Rejected(response_tx);
}
};
let Some(response_tx) = response_tx else {
*phase = CellPhase::Completed {
event,
completed_at,
};
return CompletionDelivery::Buffered;
};
match send_cell_event(response_tx, event) {
Ok(()) => {
self.cancellation_token.cancel();
CompletionDelivery::Delivered
}
Err(event) => {
*phase = CellPhase::Completed {
event,
completed_at,
};
CompletionDelivery::Buffered
}
}
}
pub(crate) fn route_observation(
&self,
response_tx: oneshot::Sender<Result<CellEvent, CellError>>,
) -> ObservationDelivery {
let mut phase = self
.phase
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match std::mem::replace(&mut *phase, CellPhase::Tombstone) {
CellPhase::Running => {
*phase = CellPhase::Running;
ObservationDelivery::Running(response_tx)
}
CellPhase::Completed {
event,
completed_at,
} => match send_cell_event(response_tx, buffered_completion(event, completed_at)) {
Ok(()) => {
self.cancellation_token.cancel();
ObservationDelivery::Delivered
}
Err(event) => {
*phase = CellPhase::Completed {
event,
completed_at,
};
ObservationDelivery::Buffered
}
},
CellPhase::Terminating {
response_tx: termination_tx,
} => {
*phase = CellPhase::Terminating {
response_tx: termination_tx,
};
let _ = response_tx.send(Err(CellError::Closed));
ObservationDelivery::Closed
}
CellPhase::CompletionClaimed(event) => {
*phase = CellPhase::CompletionClaimed(event);
let _ = response_tx.send(Err(CellError::Closed));
ObservationDelivery::Closed
}
CellPhase::Tombstone => {
let _ = response_tx.send(Err(CellError::Closed));
ObservationDelivery::Closed
}
}
}
pub(crate) fn finish_termination(&self, event: CellEvent) -> Option<CellEvent> {
let mut phase = self
.phase
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let observer_event = match std::mem::replace(&mut *phase, CellPhase::Tombstone) {
CellPhase::Running => Some(event),
CellPhase::Terminating { response_tx } => {
let _ = response_tx.send(Ok(event.clone()));
Some(event)
}
CellPhase::Completed {
event,
completed_at,
} => Some(buffered_completion(event, completed_at)),
CellPhase::CompletionClaimed(completed_event) => Some(completed_event),
CellPhase::Tombstone => None,
};
self.cancellation_token.cancel();
observer_event
}
pub(crate) fn tombstone(&self) {
*self
.phase
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = CellPhase::Tombstone;
self.cancellation_token.cancel();
}
pub(crate) fn cancellation_token(&self) -> CancellationToken {
self.cancellation_token.clone()
}
}
fn buffered_completion(mut event: CellEvent, completed_at: Instant) -> CellEvent {
if let CellEvent::Completed {
result_buffered_for,
..
} = &mut event
{
*result_buffered_for = completed_at.elapsed();
}
event
}
pub(super) enum CellCommand {
Observe {
observation: Observation,
response_tx: oneshot::Sender<Result<CellEvent, CellError>>,
},
}
fn response_event(response_rx: oneshot::Receiver<Result<CellEvent, CellError>>) -> CellEventFuture {
Box::pin(async move { response_rx.await.unwrap_or(Err(CellError::Closed)) })
}
fn ready_event(event: CellEvent) -> CellEventFuture {
Box::pin(async move { Ok(event) })
}
fn closed_event() -> CellEventFuture {
Box::pin(async { Err(CellError::Closed) })
}

View File

@@ -0,0 +1,15 @@
mod cell_actor;
mod output;
mod runtime;
mod service;
mod session_runtime;
mod ui;
mod v8_init;
pub(crate) type TaskFailureHandler = std::sync::Arc<dyn Fn(String) + Send + Sync>;
pub use akode_code_mode_protocol::*;
pub use service::InProcessCodeModeSession;
pub use ui::run as run_ui_sandbox;
pub use v8_init::V8JitMode;
pub use v8_init::initialize_v8;

View File

@@ -0,0 +1,149 @@
//! Bounded retention and per-observation rendering for Code Mode output.
//!
//! Keeps omission accounting inside this module until rendered. No actor or
//! transport state belongs here.
use akode_code_mode_protocol::CodeModeOutputTruncation;
use akode_code_mode_protocol::FunctionCallOutputContentItem as OutputItem;
use akode_utils_output_truncation::OutputBoundary;
use akode_utils_string::truncate_middle_with_marker;
mod output_collection;
mod output_render;
pub(crate) use output_collection::BoundedOutput;
#[cfg(test)]
pub(crate) use output_collection::MAX_OUTPUT_ITEMS;
pub(crate) use output_render::render_output;
/// Bound the buffered server diagnostic independently of model-visible output.
pub(crate) const MAX_SERVER_DIAGNOSTIC_BYTES: usize = 64 * 1024;
/// The actor transfers the whole collector at each observation, so a failed
/// synchronous send can restore the original state, including any omissions.
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub(crate) enum OutputCollector {
Client(Vec<OutputItem>),
/// Allocate storage only when the observation receives output.
Server(Option<Box<BoundedOutput>>),
}
impl OutputCollector {
pub(crate) fn new(mode: CodeModeOutputTruncation) -> Self {
match mode {
CodeModeOutputTruncation::Client => Self::Client(Vec::new()),
CodeModeOutputTruncation::Server => Self::Server(None),
}
}
pub(crate) fn push(&mut self, item: OutputItem) {
match self {
Self::Client(items) => items.push(item),
Self::Server(output) => output.get_or_insert_with(Box::default).push(item),
}
}
/// Server errors share the observation's output budget; their diagnostic
/// has an independent bound. Client errors retain their original formatting.
pub(crate) fn collect_error(&mut self, error_text: String) -> String {
match self {
Self::Client(_) => error_text,
Self::Server(output) => {
output
.get_or_insert_with(Box::default)
.push_error(&error_text);
// Reuse small errors without retaining oversized backing storage.
if error_text.capacity() <= MAX_SERVER_DIAGNOSTIC_BYTES {
error_text
} else {
truncate_middle_with_marker(&error_text, MAX_SERVER_DIAGNOSTIC_BYTES, "…")
}
}
}
}
pub(crate) fn take(&mut self) -> Self {
match self {
Self::Client(items) => Self::Client(std::mem::take(items)),
Self::Server(output) => Self::Server(output.take()),
}
}
pub(crate) fn try_deliver(&mut self, send: impl FnOnce(Self) -> Result<(), Self>) -> bool {
if let Err(undelivered) = send(self.take()) {
*self = undelivered;
return false;
}
true
}
/// Flatten the retained state only after the observer owns it.
pub(crate) fn into_collected_output(self) -> CollectedOutput {
match self {
Self::Client(items) => items.into(),
Self::Server(Some(output)) => output.into_collected_output(),
Self::Server(None) => CollectedOutput::default(),
}
}
}
/// Retained content and where the collector had to drop data. Loss is private
/// to the runtime until it is rendered as text after the observation's budget.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct CollectedOutput {
items: Vec<OutputItem>,
gaps: Vec<OutputGap>,
}
impl From<Vec<OutputItem>> for CollectedOutput {
fn from(items: Vec<OutputItem>) -> Self {
Self {
items,
gaps: Vec::new(),
}
}
}
impl CollectedOutput {
fn push_gap(&mut self, boundary: OutputBoundary, omitted: OutputOmission) {
if let Some(gap) = self.gaps.last_mut()
&& gap.boundary == boundary
{
gap.omitted.combine(omitted);
} else {
self.gaps.push(OutputGap { boundary, omitted });
}
}
/// Takes the unformatted items. Only for client-side observations, where
/// the caller already owns truncation and the input was not bounded.
pub(crate) fn into_untruncated_items(self) -> Vec<OutputItem> {
self.items
}
}
/// Missing output at a boundary in the retained logical items. A nonzero
/// UTF-8 byte offset marks loss inside a single text item.
#[derive(Clone, Copy, Debug, PartialEq)]
struct OutputGap {
boundary: OutputBoundary,
omitted: OutputOmission,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct OutputOmission {
text_bytes: u64,
text_items: u64,
image_items: u64,
audio_items: u64,
}
impl OutputOmission {
fn combine(&mut self, other: Self) {
self.text_bytes = self.text_bytes.saturating_add(other.text_bytes);
self.text_items = self.text_items.saturating_add(other.text_items);
self.image_items = self.image_items.saturating_add(other.image_items);
self.audio_items = self.audio_items.saturating_add(other.audio_items);
}
}

View File

@@ -0,0 +1,535 @@
//! Bounded head/tail retention for raw Code Mode output. Text has a rolling
//! byte allowance. Admit whole images and audio clips in source order against
//! independent byte allowances. Item pressure can free space for later media.
use std::collections::VecDeque;
use super::CollectedOutput;
use super::OutputOmission;
use akode_code_mode_protocol::FunctionCallOutputContentItem as OutputItem;
use akode_utils_output_truncation::OutputBoundary;
pub(super) use akode_code_mode_protocol::host::BOUNDED_OUTPUT_MAX_AUDIO_BYTES as MAX_AUDIO_BYTES;
pub(super) use akode_code_mode_protocol::host::BOUNDED_OUTPUT_MAX_BYTES as MAX_OUTPUT_BYTES;
pub(super) use akode_code_mode_protocol::host::BOUNDED_OUTPUT_MAX_IMAGE_BYTES as MAX_IMAGE_BYTES;
/// Limit logical items independently of payload bytes. An observation that
/// fits this limit must keep its item boundaries even if our storage layout changes.
pub(crate) const MAX_OUTPUT_ITEMS: usize = 32 * 1024;
const TEXT_BLOCK_BYTES: usize = 4096;
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
enum RetainedItem {
Content(OutputItem),
Partial(Box<PartialText>),
Gap(OutputOmission),
}
/// Store a partially evicted suffix in blocks so later writes can release
/// its oldest bytes without copying the rest. Only the first block has an offset.
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
struct PartialText {
blocks: VecDeque<String>,
front_offset: usize,
bytes: usize,
omitted: u64,
continues_prefix: bool,
}
impl RetainedItem {
fn retain(mut item: OutputItem) -> Self {
let payload = match &mut item {
OutputItem::InputImage { image_url, .. } => image_url,
OutputItem::InputAudio { audio_url } => audio_url,
OutputItem::InputText { text } if text.len() > MAX_OUTPUT_BYTES => {
// Eviction copies only the head and suffix that can survive.
return Self::Content(item);
}
OutputItem::InputText { text } => text,
};
payload.shrink_to_fit();
Self::Content(item)
}
/// Evict bytes after the retained prefix and keep any surviving suffix.
fn text_suffix(text: &str, prefix_len: usize, bytes_to_evict: usize) -> Self {
let tail = &text[prefix_len..];
let omitted = tail.ceil_char_boundary(bytes_to_evict.min(tail.len()));
let mut suffix = &tail[omitted..];
if suffix.is_empty() {
return Self::Gap(OutputOmission {
text_bytes: omitted as u64,
text_items: 1,
..OutputOmission::default()
});
}
let bytes = suffix.len();
let mut blocks = VecDeque::new();
while !suffix.is_empty() {
let end = suffix.floor_char_boundary(suffix.len().min(TEXT_BLOCK_BYTES));
blocks.push_back(suffix[..end].to_owned());
suffix = &suffix[end..];
}
Self::Partial(Box::new(PartialText {
blocks,
front_offset: 0,
bytes,
omitted: omitted as u64,
continues_prefix: prefix_len > 0,
}))
}
fn content_bytes(&self) -> usize {
match self {
Self::Content(OutputItem::InputText { text }) => text.len(),
Self::Partial(text) => text.bytes,
Self::Content(OutputItem::InputImage { .. } | OutputItem::InputAudio { .. })
| Self::Gap(_) => 0,
}
}
fn omission(&self) -> OutputOmission {
let mut loss = OutputOmission::default();
match self {
Self::Content(OutputItem::InputText { text }) => {
loss.text_bytes = text.len() as u64;
loss.text_items = 1;
}
Self::Content(OutputItem::InputImage { .. }) => loss.image_items = 1,
Self::Content(OutputItem::InputAudio { .. }) => loss.audio_items = 1,
Self::Partial(text) => {
loss.text_bytes = text.omitted.saturating_add(text.bytes as u64);
loss.text_items = 1;
}
Self::Gap(omitted) => loss = *omitted,
}
loss
}
fn move_into(self, output: &mut CollectedOutput) {
match self {
Self::Content(item) => output.items.push(item),
Self::Gap(loss) => output.push_gap(
OutputBoundary {
item_index: output.items.len(),
text_offset: 0,
},
loss,
),
Self::Partial(text) => {
// A split suffix continues the preceding prefix. A suffix whose
// prefix was discarded starts its own logical item.
if !text.continues_prefix {
output.items.push(OutputItem::InputText {
text: String::new(),
});
}
let item_index = output.items.len() - 1;
let OutputItem::InputText { text: retained } = &mut output.items[item_index] else {
unreachable!("a split suffix follows its text prefix");
};
let text_offset = retained.len();
retained.reserve_exact(text.bytes);
for (i, block) in text.blocks.into_iter().enumerate() {
let start = if i == 0 { text.front_offset } else { 0 };
retained.push_str(&block[start..]);
}
if text.omitted > 0 {
output.push_gap(
OutputBoundary {
item_index,
text_offset,
},
OutputOmission {
text_bytes: text.omitted,
..OutputOmission::default()
},
);
}
}
}
}
}
#[derive(Clone, Debug, Default)]
#[cfg_attr(test, derive(PartialEq))]
struct OpenOutput {
items: VecDeque<RetainedItem>,
content_bytes: usize,
}
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub(crate) struct BoundedOutput {
state: Retention,
media: MediaBytes,
}
#[derive(Clone, Debug, Default)]
#[cfg_attr(test, derive(PartialEq))]
struct MediaBytes {
images: usize,
audio: usize,
}
impl MediaBytes {
fn admit(&mut self, item: &OutputItem) -> Result<(), OutputOmission> {
let (len, used, limit, omission) = match item {
OutputItem::InputText { .. } => return Ok(()),
OutputItem::InputImage { image_url, .. } => (
image_url.len(),
&mut self.images,
MAX_IMAGE_BYTES,
OutputOmission {
image_items: 1,
..OutputOmission::default()
},
),
OutputItem::InputAudio { audio_url } => (
audio_url.len(),
&mut self.audio,
MAX_AUDIO_BYTES,
OutputOmission {
audio_items: 1,
..OutputOmission::default()
},
),
};
if len > limit - *used {
return Err(omission);
}
*used += len;
Ok(())
}
}
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
enum Retention {
/// All individually fitting items are intact, in source order.
Open(OpenOutput),
/// A fixed prefix and a rolling tail with omissions in source order.
HeadTail(HeadTailOutput),
}
impl Default for BoundedOutput {
fn default() -> Self {
Self {
state: Retention::Open(OpenOutput::default()),
media: MediaBytes::default(),
}
}
}
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
struct HeadTailOutput {
head: Vec<RetainedItem>,
head_bytes: usize,
tail: VecDeque<RetainedItem>,
// The first tail item that might still have text bytes.
cursor: usize,
// Adjacent tail gaps occupy one logical item. Repack their physical slots in batches.
adjacent_gaps: usize,
// Text bytes retained in the entire observation, including the head.
content_bytes: usize,
// Gaps at the front of the tail no longer need their own slots.
middle: OutputOmission,
}
impl HeadTailOutput {
fn from_open(open: OpenOutput) -> Self {
let mut output = Self {
head: Vec::new(),
head_bytes: 0,
tail: open.items,
cursor: 0,
adjacent_gaps: 0,
content_bytes: open.content_bytes,
middle: OutputOmission::default(),
};
while output.head.len() < MAX_OUTPUT_ITEMS / 2 {
let Some(item) = output.tail.pop_front() else {
break;
};
let bytes = item.content_bytes();
let remaining = MAX_OUTPUT_BYTES / 2 - output.head_bytes;
if bytes <= remaining {
output.head_bytes += bytes;
output.head.push(item);
} else if output.content_bytes <= MAX_OUTPUT_BYTES {
// Under item pressure a whole item may borrow unused tail bytes.
output.head_bytes += bytes;
output.head.push(item);
break;
} else {
output.tail.push_front(item);
output.split_front(remaining);
break;
}
}
output
}
/// Preserve a text prefix and copy only suffix bytes that could still fit.
fn split_front(&mut self, remaining: usize) {
let Some(RetainedItem::Content(OutputItem::InputText { text })) = self.tail.front() else {
return;
};
let split = text.floor_char_boundary(remaining);
if split == 0 {
return;
}
self.head.push(RetainedItem::Content(OutputItem::InputText {
text: text[..split].to_owned(),
}));
self.head_bytes += split;
let excess = self.content_bytes - MAX_OUTPUT_BYTES;
let suffix = RetainedItem::text_suffix(text, split, excess);
self.content_bytes -= text.len() - split - suffix.content_bytes();
if matches!(suffix, RetainedItem::Gap(_))
&& matches!(self.tail.get(1), Some(RetainedItem::Gap(_)))
{
self.adjacent_gaps += 1;
}
self.tail[0] = suffix;
}
fn advance_front(&mut self) -> RetainedItem {
self.cursor = self.cursor.saturating_sub(1);
let Some(item) = self.tail.pop_front() else {
unreachable!("eviction requires a nonempty tail");
};
if matches!(item, RetainedItem::Gap(_))
&& matches!(self.tail.front(), Some(RetainedItem::Gap(_)))
{
self.adjacent_gaps -= 1;
}
item
}
fn trim(&mut self, media: &mut MediaBytes) {
if self.content_bytes > MAX_OUTPUT_BYTES && self.head_bytes > MAX_OUTPUT_BYTES / 2 {
// Only the last prefix item can have borrowed space. Reconsider it
// before the middle gap, whose source position follows that item.
let Some(item) = self.head.pop() else {
unreachable!("borrowed bytes require a prefix item");
};
self.head_bytes -= item.content_bytes();
if self.middle != OutputOmission::default() {
self.tail
.push_front(RetainedItem::Gap(std::mem::take(&mut self.middle)));
}
self.tail.push_front(item);
self.cursor = 0;
let remaining = MAX_OUTPUT_BYTES / 2 - self.head_bytes;
self.split_front(remaining);
}
// Skip retained media and preserve each gap between its source neighbors.
let used = &mut self.content_bytes;
let cursor = &mut self.cursor;
while *used > MAX_OUTPUT_BYTES {
let slot = &mut self.tail[*cursor];
let old_bytes = slot.content_bytes();
if old_bytes > 0 {
let excess = *used - MAX_OUTPUT_BYTES;
let remaining = old_bytes.saturating_sub(excess);
match slot {
RetainedItem::Content(OutputItem::InputText { text }) if remaining > 0 => {
*slot = RetainedItem::text_suffix(text, /*prefix_len*/ 0, excess);
}
RetainedItem::Partial(text) if remaining > 0 => {
// Later writes may evict more of this same suffix.
while text.bytes > remaining {
let front = &text.blocks[0][text.front_offset..];
let removed =
front.ceil_char_boundary((text.bytes - remaining).min(front.len()));
text.bytes -= removed;
text.omitted = text.omitted.saturating_add(removed as u64);
if removed == front.len() {
text.blocks.pop_front();
text.front_offset = 0;
} else {
text.front_offset += removed;
}
}
if text.bytes == 0 {
*slot = RetainedItem::Gap(slot.omission());
}
}
_ => *slot = RetainedItem::Gap(slot.omission()),
}
let new_bytes = slot.content_bytes();
*used -= old_bytes - new_bytes;
if new_bytes > 0 {
break;
}
self.adjacent_gaps += usize::from(
*cursor > 0 && matches!(self.tail[*cursor - 1], RetainedItem::Gap(_)),
) + usize::from(matches!(
self.tail.get(*cursor + 1),
Some(RetainedItem::Gap(_))
));
}
*cursor += 1;
}
// Each sweep removes at least this many slots. Tiny writes cannot
// repeatedly scan the tail, even when a live image brackets many gaps.
if self.adjacent_gaps >= MAX_OUTPUT_ITEMS.div_ceil(8) {
let slots = self.tail.make_contiguous();
for i in 1..slots.len() {
let (prior, rest) = slots.split_at_mut(i);
if let (RetainedItem::Gap(left), RetainedItem::Gap(right)) =
(&mut prior[i - 1], &mut rest[0])
{
right.combine(std::mem::take(left));
}
}
self.tail.retain(|item| !matches!(item, RetainedItem::Gap(loss) if *loss == OutputOmission::default()));
self.cursor = 0;
self.adjacent_gaps = 0;
}
let split_suffix = if matches!(self.tail.front(), Some(RetainedItem::Partial(text)) if text.continues_prefix)
{
// The suffix shares its head item's slot, and no middle gap exists yet.
if self.head.len() + self.tail.len() - self.adjacent_gaps <= MAX_OUTPUT_ITEMS + 1 {
return;
}
Some(self.advance_front())
} else {
None
};
// A middle gap costs a slot only once it exists. The first eviction
// creates that gap, so recompute the logical item count on each pass.
while self.head.len() + self.tail.len() - self.adjacent_gaps
+ usize::from(self.middle != OutputOmission::default())
> MAX_OUTPUT_ITEMS
{
let item = self.advance_front();
self.content_bytes -= item.content_bytes();
match &item {
RetainedItem::Content(OutputItem::InputImage { image_url, .. }) => {
media.images -= image_url.len();
}
RetainedItem::Content(OutputItem::InputAudio { audio_url }) => {
media.audio -= audio_url.len();
}
_ => {}
}
self.middle.combine(item.omission());
}
while matches!(self.tail.front(), Some(RetainedItem::Gap(_))) {
let item = self.advance_front();
self.middle.combine(item.omission());
}
if let Some(suffix) = split_suffix {
self.tail
.push_front(RetainedItem::Gap(std::mem::take(&mut self.middle)));
self.tail.push_front(suffix);
self.cursor = 0;
}
}
}
impl BoundedOutput {
/// A completed error is one logical text item, including its label. Do not
/// allocate an arbitrarily large formatted copy before selecting its output.
pub(crate) fn push_error(&mut self, error: &str) {
const LABEL: &str = "Script error:\n";
// No selection can retain more than MAX_OUTPUT_BYTES from either end
// of this item. Keep both possible spans until push() decides how the
// existing head, tail and item pressure affect them. Round outward so
// a UTF-8 boundary cannot pull bytes from the prefix across the gap.
let head_end = error.ceil_char_boundary(error.len().min(MAX_OUTPUT_BYTES - LABEL.len()));
let tail_start =
error.floor_char_boundary(error.len().saturating_sub(MAX_OUTPUT_BYTES).max(head_end));
self.push(OutputItem::InputText {
text: format!("{LABEL}{}{}", &error[..head_end], &error[tail_start..]),
});
let skipped = tail_start - head_end;
if skipped > 0 {
// This item alone exceeds the content budget. Its newest, retained
// suffix owns the gap, even when an image separates it from older loss.
let Retention::HeadTail(output) = &mut self.state else {
unreachable!("an oversized error must enter head/tail retention");
};
let Some(RetainedItem::Partial(text)) = output.tail.back_mut() else {
unreachable!("the tail retains the end of the oversized error");
};
text.omitted = text.omitted.saturating_add(skipped as u64);
}
}
pub(crate) fn push(&mut self, item: OutputItem) {
if let Err(loss) = self.media.admit(&item) {
self.push_retained(RetainedItem::Gap(loss));
// Adding the loss marker can evict earlier media from a full observation.
// Replace only this item's marker if that freed enough space.
if let Retention::HeadTail(split) = &mut self.state
&& let Some(slot) = split.tail.back_mut()
&& matches!(slot, RetainedItem::Gap(omitted) if *omitted == loss)
&& self.media.admit(&item).is_ok()
{
*slot = RetainedItem::retain(item);
}
return;
}
self.push_retained(RetainedItem::retain(item));
}
fn push_retained(&mut self, item: RetainedItem) {
let bytes = item.content_bytes();
let (tail, retained) = match &mut self.state {
Retention::Open(open) => (&mut open.items, &mut open.content_bytes),
Retention::HeadTail(split) => (&mut split.tail, &mut split.content_bytes),
};
if let RetainedItem::Gap(loss) = &item
&& let Some(RetainedItem::Gap(last)) = tail.back_mut()
{
last.combine(*loss);
return;
}
tail.push_back(item);
*retained += bytes;
if let Retention::Open(open) = &mut self.state {
if open.content_bytes <= MAX_OUTPUT_BYTES && open.items.len() <= MAX_OUTPUT_ITEMS {
return;
}
self.state = Retention::HeadTail(HeadTailOutput::from_open(std::mem::take(open)));
}
if let Retention::HeadTail(split) = &mut self.state {
split.trim(&mut self.media);
}
}
fn collect(items: impl Iterator<Item = RetainedItem>) -> CollectedOutput {
let mut output = CollectedOutput::default();
for item in items {
item.move_into(&mut output);
}
output
}
pub(crate) fn into_collected_output(self) -> CollectedOutput {
match self.state {
Retention::Open(open) => Self::collect(open.items.into_iter()),
Retention::HeadTail(split) => Self::collect(
split
.head
.into_iter()
.chain(
(split.middle != OutputOmission::default())
.then_some(RetainedItem::Gap(split.middle)),
)
.chain(split.tail),
),
}
}
}
#[cfg(test)]
#[path = "output_collection_tests.rs"]
mod tests;

View File

@@ -0,0 +1,332 @@
//! Regression coverage for bounded output retention.
#![cfg(test)]
use super::*;
use crate::output::OutputCollector;
use akode_code_mode_protocol::CodeModeOutputTruncation;
use akode_code_mode_protocol::ImageDetail;
use pretty_assertions::assert_eq;
fn text(value: &str) -> OutputItem {
OutputItem::InputText {
text: value.to_owned(),
}
}
fn image(image_url: String) -> OutputItem {
OutputItem::InputImage {
image_url,
detail: Some(ImageDetail::Original),
}
}
fn audio(audio_url: String) -> OutputItem {
OutputItem::InputAudio { audio_url }
}
fn collect(items: impl IntoIterator<Item = OutputItem>) -> BoundedOutput {
let mut output = BoundedOutput::default();
for item in items {
output.push(item);
}
output
}
fn retained_capacity(collector: &BoundedOutput) -> usize {
let capacity = |item: &RetainedItem| match item {
RetainedItem::Content(OutputItem::InputText { text }) => text.capacity(),
RetainedItem::Content(OutputItem::InputImage { image_url, .. }) => image_url.capacity(),
RetainedItem::Content(OutputItem::InputAudio { audio_url }) => audio_url.capacity(),
RetainedItem::Gap(_) => 0,
RetainedItem::Partial(text) => text.blocks.iter().map(String::capacity).sum(),
};
match &collector.state {
Retention::Open(open) => open.items.iter().map(capacity).sum(),
Retention::HeadTail(split) => split.head.iter().chain(&split.tail).map(capacity).sum(),
}
}
#[test]
fn all_32k_empty_writes_fit_before_the_item_limit_creates_a_gap() {
let mut output = collect((0..32_768).map(|_| text("")));
assert!(output.clone().into_collected_output() == vec![text(""); 32_768].into());
output.push(text("last"));
let snapshot = output.into_collected_output();
assert_eq!(snapshot.items.len(), 32_767);
assert_eq!(snapshot.items.last(), Some(&text("last")));
let [gap] = snapshot.gaps.as_slice() else {
panic!("expected one item-limit gap")
};
assert_eq!(gap.boundary.item_index, 16_384);
assert_eq!(gap.omitted.text_items, 2);
}
#[test]
fn item_pressure_keeps_a_split_head_items_suffix() {
let half = "x".repeat(MAX_OUTPUT_BYTES / 2);
let retained = text(&half.repeat(2));
let mut output = collect([text(&format!("{half}y{half}"))]);
for _ in 0..MAX_OUTPUT_ITEMS - 1 {
output.push(text(""));
}
assert!(output.clone().into_collected_output().items.first() == Some(&retained));
output.push(text(""));
let snapshot = output.into_collected_output();
assert!(snapshot.items.first() == Some(&retained));
assert_eq!(snapshot.items.len(), MAX_OUTPUT_ITEMS - 1);
assert_eq!(snapshot.gaps.len(), 2);
assert_eq!(snapshot.gaps[1].boundary.item_index, 1);
assert_eq!(snapshot.gaps[1].omitted.text_items, 2);
}
#[test]
fn fitting_items_release_spare_capacity() {
let items = [text("first"), image("image".into()), audio("audio".into())];
let output = collect(items.iter().cloned().map(|mut item| {
let payload = match &mut item {
OutputItem::InputText { text } => text,
OutputItem::InputImage { image_url, .. } => image_url,
OutputItem::InputAudio { audio_url } => audio_url,
};
payload.reserve(2 * MAX_OUTPUT_BYTES);
item
}));
assert!(retained_capacity(&output) <= MAX_OUTPUT_BYTES);
assert_eq!(output.into_collected_output(), items.to_vec().into());
}
#[test]
fn rolling_unicode_suffix_survives_tiny_writes_without_unbounded_backing() {
let half = MAX_OUTPUT_BYTES / 2;
let original = format!("{}{}z", "a".repeat(half - 1), "😀".repeat(half));
let mut output = collect([text(&original)]);
let mut last_block = None;
for _ in 0..10_001 {
output.push(text("z"));
let Retention::HeadTail(split) = &output.state else {
panic!("expected truncated output")
};
let Some(RetainedItem::Partial(front)) = split.tail.front() else {
panic!("expected a partial suffix")
};
let ptr = front.blocks.back().unwrap().as_ptr();
assert_eq!(*last_block.get_or_insert(ptr), ptr);
assert!(retained_capacity(&output) < MAX_OUTPUT_BYTES + TEXT_BLOCK_BYTES);
}
let head = original.floor_char_boundary(half);
let tail = original.ceil_char_boundary(original.len() - (MAX_OUTPUT_BYTES - head - 10_001));
let snapshot = output.into_collected_output();
assert_eq!(snapshot.items.len(), 10_002);
assert!(snapshot.items[0] == text(&[&original[..head], &original[tail..]].concat()));
let [gap] = snapshot.gaps.as_slice() else {
panic!("expected one split")
};
assert_eq!(
gap.boundary,
OutputBoundary {
item_index: 0,
text_offset: head
}
);
assert_eq!(gap.omitted.text_bytes, (tail - head) as u64);
}
#[test]
fn byte_pressure_reclaims_space_borrowed_by_the_first_item() {
let half = MAX_OUTPUT_BYTES / 2;
let suffix = text(&"z".repeat(half));
let first = text(&"a".repeat(half + 8));
let mut output = collect([first.clone()]);
for _ in 0..MAX_OUTPUT_ITEMS {
output.push(text(""));
}
assert!(output.clone().into_collected_output().items[0] == first);
output.push(suffix.clone());
let snapshot = output.into_collected_output();
assert_eq!(snapshot.items.last(), Some(&suffix));
let [gap] = snapshot.gaps.as_slice() else {
panic!("expected one middle gap")
};
assert!(snapshot.items[0] == text(&"a".repeat(half)));
assert_eq!(gap.boundary.item_index, 1);
assert_eq!(gap.omitted.text_bytes, 8);
}
#[test]
fn image_admission_uses_remaining_bytes_and_reclaims_them_on_eviction() {
let half = MAX_OUTPUT_ITEMS / 2;
let mut output = collect((0..half).map(|_| text("")));
let first = image("i".repeat(MAX_IMAGE_BYTES - 2));
let last = image("zz".into());
for item in [first.clone(), image("xxx".into()), last.clone()] {
output.push(item);
}
let snapshot = output.clone().into_collected_output();
assert!(snapshot.items.ends_with(&[first, last]));
let [gap] = snapshot.gaps.as_slice() else {
panic!("expected one rejected image")
};
assert_eq!(gap.boundary.item_index, half + 1);
assert_eq!(gap.omitted.image_items, 1);
for _ in 0..MAX_OUTPUT_ITEMS {
output.push(text(""));
}
let full = image("j".repeat(MAX_IMAGE_BYTES));
output.push(full.clone());
assert!(output.into_collected_output().items.last() == Some(&full));
}
#[test]
fn image_admission_reuses_space_freed_by_the_same_write() {
let half = MAX_OUTPUT_ITEMS / 2;
let mut output = collect((0..half).map(|_| text("")));
output.push(image("i".repeat(MAX_IMAGE_BYTES)));
for _ in 0..half - 1 {
output.push(text(""));
}
let replacement = image("replacement".into());
output.push(replacement.clone());
let snapshot = output.into_collected_output();
assert_eq!(snapshot.items.last(), Some(&replacement));
assert_eq!(snapshot.gaps.len(), 1);
assert_eq!(snapshot.gaps[0].omitted.image_items, 1);
}
#[test]
fn one_extra_text_byte_keeps_a_large_image_in_either_order() {
let half = MAX_OUTPUT_BYTES / 2;
let original = format!("{}b{}", "a".repeat(half), "c".repeat(half - 1));
let retained = text(&[&original[..half], &original[half + 1..]].concat());
let large_image = image("i".repeat(MAX_IMAGE_BYTES / 2 + 1));
for image_index in [0, 1] {
let mut items = vec![text(&original)];
items.insert(image_index, large_image.clone());
items.push(text("z"));
let snapshot = collect(items).into_collected_output();
let mut expected = vec![retained.clone(), text("z")];
expected.insert(image_index, large_image.clone());
assert!(snapshot.items == expected);
let [gap] = snapshot.gaps.as_slice() else {
panic!("expected one omitted byte")
};
assert_eq!(
gap.boundary,
OutputBoundary {
item_index: 1 - image_index,
text_offset: MAX_OUTPUT_BYTES / 2
}
);
assert_eq!(gap.omitted.text_bytes, 1);
}
}
#[test]
fn output_item_types_have_independent_byte_allowances() {
let items = vec![
text(&"t".repeat(MAX_OUTPUT_BYTES)),
image("i".repeat(MAX_IMAGE_BYTES)),
audio("a".into()),
];
assert_eq!(collect(items.clone()).into_collected_output(), items.into());
}
#[test]
fn failed_delivery_keeps_the_observation_until_success() {
// An intact image can move through a failed send and a retry without copying.
let url = "i".repeat(MAX_IMAGE_BYTES);
let ptr = url.as_ptr();
let mut output = OutputCollector::new(CodeModeOutputTruncation::Server);
output.push(image(url));
assert!(!output.try_deliver(Err));
assert!(output.try_deliver(|snapshot| {
let snapshot = snapshot.into_collected_output();
let [OutputItem::InputImage { image_url, .. }] = snapshot.items.as_slice() else {
panic!("expected the original image")
};
assert_eq!(image_url.as_ptr(), ptr);
Ok(())
}));
// The image allowance has reset. A failed send must also preserve a loss notice.
let full = image("j".repeat(MAX_IMAGE_BYTES));
output.push(full.clone());
output.push(text(&"x".repeat(2 * MAX_OUTPUT_BYTES)));
let mut expected = output.clone().into_collected_output();
assert!(expected.items.first() == Some(&full));
assert_eq!(expected.gaps.len(), 1);
assert!(!output.try_deliver(Err));
output.push(text(""));
expected.items.push(text(""));
assert!(output.try_deliver(|snapshot| {
assert!(snapshot.into_collected_output() == expected);
Ok(())
}));
assert_eq!(output.into_collected_output(), CollectedOutput::default());
}
#[test]
fn repeated_eviction_keeps_recent_writes_and_gaps_on_each_side_of_an_image() {
let half = "p".repeat(MAX_OUTPUT_BYTES / 2);
let image = image("i".repeat(2 * MAX_OUTPUT_BYTES));
let mut output = collect([text(&half), text("b"), image.clone(), text(&half)]);
let chunk = "x".repeat(64);
let writes = 2 * MAX_OUTPUT_ITEMS;
for _ in 0..writes {
output.push(text(&chunk));
}
let snapshot = output.into_collected_output();
let recent = MAX_OUTPUT_BYTES / 2 / chunk.len();
assert_eq!(snapshot.items.len(), 2 + recent);
assert!(snapshot.items.starts_with(&[text(&half), image]));
assert!(
snapshot.items[2..]
.iter()
.all(|item| matches!(item, OutputItem::InputText { text } if text == &chunk))
);
let [before, after] = snapshot.gaps.as_slice() else {
panic!("expected gaps around the image")
};
assert_eq!(
(before.boundary.item_index, after.boundary.item_index),
(1, 2)
);
assert_eq!(before.omitted.text_bytes, 1);
assert_eq!(after.omitted.text_bytes, (writes * chunk.len()) as u64);
assert_eq!(after.omitted.text_items, (1 + writes - recent) as u64);
}
#[test]
fn terminal_error_matches_ordinary_text_across_loss_boundaries() {
let label = "Script error:\n";
// Rounding inward at the emoji can wrongly pull XYZ into the retained suffix.
let error = format!(
"{}XYZ{}💡{}",
"p".repeat(MAX_OUTPUT_BYTES - label.len() - 3),
"m".repeat(22),
"s".repeat(MAX_OUTPUT_BYTES - 3),
);
let half = text(&"p".repeat(MAX_OUTPUT_BYTES / 2));
for (prefix, gap_count) in [
(Vec::new(), 1),
(vec![text(""); MAX_OUTPUT_ITEMS / 2], 1),
(vec![half.clone(), text("lost"), image("i".into()), half], 2),
] {
let mut terminal = BoundedOutput::default();
let mut ordinary = BoundedOutput::default();
for item in prefix {
terminal.push(item.clone());
ordinary.push(item);
}
terminal.push_error(&error);
ordinary.push(text(&format!("{label}{error}")));
assert!(retained_capacity(&terminal) < MAX_OUTPUT_BYTES + TEXT_BLOCK_BYTES);
let actual = terminal.into_collected_output();
assert_eq!(actual.gaps.len(), gap_count);
assert!(actual == ordinary.into_collected_output());
}
}

View File

@@ -0,0 +1,198 @@
//! Applies the outer Code Mode response budget at an observation boundary.
use akode_code_mode_protocol::DEFAULT_MAX_OUTPUT_TOKENS_PER_EXEC_CALL;
use akode_code_mode_protocol::FunctionCallOutputContentItem as OutputItem;
use akode_code_mode_protocol::ImageDetail;
use akode_protocol::models::FunctionCallOutputContentItem;
use akode_protocol::models::ImageDetail as ProtocolImageDetail;
use akode_protocol::models::ImageReference;
use akode_utils_audio::estimate_audio_token_count_without_cache;
use akode_utils_output_truncation::OutputBoundary;
use akode_utils_output_truncation::formatted_output_at_token_boundaries;
use akode_utils_output_truncation::mixed_output_at_token_boundaries;
use crate::output::CollectedOutput;
use crate::output::OutputGap;
use crate::output::OutputOmission;
// Even with four full-width u64 counts per notice, this adds less than 1 KiB.
const MAX_POSITIONED_NOTICES: usize = 4;
/// Renders the output since the preceding observation, using that request's
/// own budget. The terminal error participates in the same budget as text
/// emitted by the script; the response still carries its error status separately.
///
/// Image fidelity is preserved here. Model-specific image detail selection
/// still belongs to the caller and does not affect the truncation budget.
///
/// This is the same output Core would render as long as the session collector
/// has retained the whole observation. Collector omissions stay outside this
/// budget: Core's warning describes the retained text alone. The shared
/// formatter moves collector boundaries along with their source content.
/// If losses are too scattered for individual notices, report their totals once.
pub(crate) fn render_output(
output: CollectedOutput,
max_output_tokens: Option<usize>,
) -> Vec<OutputItem> {
let CollectedOutput { items, gaps } = output;
let mut boundaries: Vec<_> = gaps.iter().map(|gap| gap.boundary).collect();
let mut content = Vec::with_capacity(items.len());
for item in items {
match item {
OutputItem::InputText { text } => {
content.push(FunctionCallOutputContentItem::InputText { text });
}
OutputItem::InputImage { image_url, detail } => {
content.push(FunctionCallOutputContentItem::InputImage {
image: ImageReference::Inline { image_url },
detail: detail.map(|detail| match detail {
ImageDetail::Auto => ProtocolImageDetail::Auto,
ImageDetail::Low => ProtocolImageDetail::Low,
ImageDetail::High => ProtocolImageDetail::High,
ImageDetail::Original => ProtocolImageDetail::Original,
}),
});
}
OutputItem::InputAudio { audio_url } => {
content.push(FunctionCallOutputContentItem::InputAudio { audio_url });
}
}
}
let max_tokens = max_output_tokens.unwrap_or(DEFAULT_MAX_OUTPUT_TOKENS_PER_EXEC_CALL);
// Core budgets mixed output in order. Keep that policy even if the
// collector removed every image or audio item in the observation.
let formatted = if gaps
.iter()
.any(|gap| gap.omitted.image_items > 0 || gap.omitted.audio_items > 0)
{
mixed_output_at_token_boundaries(
content,
max_tokens,
estimate_audio_token_count_without_cache,
&mut boundaries,
)
} else {
formatted_output_at_token_boundaries(
content,
max_tokens,
estimate_audio_token_count_without_cache,
&mut boundaries,
)
};
insert_loss_notices(formatted, boundaries, gaps)
}
fn insert_loss_notices(
mut formatted: Vec<FunctionCallOutputContentItem>,
boundaries: Vec<OutputBoundary>,
gaps: Vec<OutputGap>,
) -> Vec<OutputItem> {
if gaps.is_empty() {
return formatted.into_iter().map(into_code_mode_output).collect();
}
// One extra slot detects when an observation-wide summary is needed.
let mut notices = [((0, 0), OutputOmission::default()); MAX_POSITIONED_NOTICES + 1];
let mut notice_count = 0;
let mut total = OutputOmission::default();
let mut summary_position = (formatted.len(), 0);
for (gap, boundary) in gaps.into_iter().zip(boundaries) {
total.combine(gap.omitted);
let OutputBoundary {
item_index,
text_offset,
} = boundary;
// The end of a text item and the start of its successor are one position.
let position = if text_offset != 0
&& let Some(FunctionCallOutputContentItem::InputText { text }) =
formatted.get(item_index)
&& text_offset == text.len()
{
(item_index + 1, 0)
} else {
(item_index, text_offset)
};
// The collector can split one original text item. Even an observation-wide
// summary must keep its two fragments from reading as contiguous text.
if gap.boundary.text_offset != 0 {
summary_position = position;
}
if notice_count == notices.len() {
continue;
}
if let Some((last, omitted)) = notices[..notice_count].last_mut()
&& *last == position
{
omitted.combine(gap.omitted);
} else {
notices[notice_count] = (position, gap.omitted);
notice_count += 1;
}
}
let scope = if notice_count == notices.len() {
notices[0] = (summary_position, total);
notice_count = 1;
"across this observation, "
} else {
""
};
// Drain from the end so earlier positions stay valid as text is split.
let mut reversed = Vec::with_capacity(formatted.len() + 2 * notice_count);
for &((index, offset), omission) in notices[..notice_count].iter().rev() {
let after = index + usize::from(offset != 0);
reversed.extend(formatted.drain(after..).rev().map(into_code_mode_output));
if offset != 0 {
let FunctionCallOutputContentItem::InputText { text } = &mut formatted[index] else {
unreachable!("only text has an inner byte position");
};
if offset < text.len() {
reversed.push(OutputItem::InputText {
text: text.split_off(offset),
});
}
}
reversed.push(OutputItem::InputText {
text: format!(
"[Code Mode session output limit reached: {scope}omitted {} text bytes; discarded {} text segments, {} images, {} audio items]",
omission.text_bytes,
omission.text_items,
omission.image_items,
omission.audio_items
),
});
}
reversed.extend(formatted.into_iter().rev().map(into_code_mode_output));
reversed.reverse();
reversed
}
fn into_code_mode_output(item: FunctionCallOutputContentItem) -> OutputItem {
match item {
FunctionCallOutputContentItem::InputText { text } => OutputItem::InputText { text },
FunctionCallOutputContentItem::InputImage {
image: ImageReference::Inline { image_url },
detail,
} => OutputItem::InputImage {
image_url,
detail: detail.map(|detail| match detail {
ProtocolImageDetail::Auto => ImageDetail::Auto,
ProtocolImageDetail::Low => ImageDetail::Low,
ProtocolImageDetail::High => ImageDetail::High,
ProtocolImageDetail::Original => ImageDetail::Original,
}),
},
FunctionCallOutputContentItem::InputAudio { audio_url } => {
OutputItem::InputAudio { audio_url }
}
FunctionCallOutputContentItem::EncryptedContent { .. }
| FunctionCallOutputContentItem::InputImage {
image: ImageReference::File { .. },
..
} => {
unreachable!("output truncation must not introduce new content types")
}
}
}
#[cfg(test)]
#[path = "output_render_tests.rs"]
mod tests;

View File

@@ -0,0 +1,285 @@
#![cfg(test)]
use super::render_output;
use crate::output::CollectedOutput;
use crate::output::OutputGap;
use crate::output::OutputOmission;
use crate::output::output_collection::BoundedOutput;
use crate::output::output_collection::MAX_AUDIO_BYTES;
use crate::output::output_collection::MAX_OUTPUT_BYTES;
use akode_code_mode_protocol::DEFAULT_MAX_OUTPUT_TOKENS_PER_EXEC_CALL;
use akode_code_mode_protocol::FunctionCallOutputContentItem as Item;
use akode_code_mode_protocol::ImageDetail;
use akode_code_mode_protocol::host::BOUNDED_OUTPUT_MAX_IMAGE_BYTES;
use akode_utils_output_truncation::OutputBoundary;
use pretty_assertions::assert_eq;
fn text(value: &str) -> Item {
Item::InputText {
text: value.to_owned(),
}
}
#[test]
fn missing_budget_uses_the_protocol_default() {
let limit = DEFAULT_MAX_OUTPUT_TOKENS_PER_EXEC_CALL;
for (extra, count) in [(0, 2), (1, 1)] {
let items = vec![text("a"), text(&"b".repeat(4 * limit - 2 + extra))];
let rendered = render_output(items.clone().into(), /*max_output_tokens*/ None);
assert_eq!(rendered.len(), count);
assert_eq!(rendered, render_output(items.into(), Some(limit)));
}
}
#[tokio::test]
async fn typed_media_round_trips_with_the_audio_estimate() {
let mut images: Vec<_> = [
None,
Some(ImageDetail::Auto),
Some(ImageDetail::Low),
Some(ImageDetail::High),
Some(ImageDetail::Original),
]
.map(|detail| Item::InputImage {
image_url: "img:one".to_owned(),
detail,
})
.into();
// One 16-bit PCM sample at 24 kHz costs one token.
let wav =
"data:audio/wav;base64,UklGRiYAAABXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAAZGF0YQIAAAAAAA==";
let mut items = images.clone();
items.push(Item::InputAudio {
audio_url: wav.to_owned(),
});
assert_eq!(render_output(items.clone().into(), Some(1)), items);
images.push(text("[omitted 1 audio items ...]"));
assert_eq!(render_output(items.into(), Some(0)), images);
}
#[test]
fn prior_image_or_audio_loss_forces_mixed_formatting_without_surviving_media() {
for (images, audio) in [(1, 0), (0, 1)] {
let collected = CollectedOutput {
items: vec![text("1234"), text("5678")],
gaps: vec![OutputGap {
boundary: OutputBoundary {
item_index: 1,
text_offset: 0,
},
omitted: OutputOmission {
text_bytes: 11,
text_items: 2,
image_items: images,
audio_items: audio,
},
}],
};
let notice = text(&format!(
"[Code Mode session output limit reached: omitted 11 text bytes; discarded 2 text segments, {images} images, {audio} audio items]"
));
assert_eq!(
render_output(collected, Some(1)),
[text("1234"), notice, text("[omitted 1 text items ...]")]
);
}
}
#[test]
fn alternating_lost_audio_and_empty_text_yield_one_notice_at_zero_budget() {
// Start at the renderer boundary so the regression doesn't allocate 16 GiB of rejected audio.
let count = 16_384;
let collected = CollectedOutput {
items: vec![text(""); count],
gaps: (0..count)
.map(|item_index| OutputGap {
boundary: OutputBoundary {
item_index,
text_offset: 0,
},
omitted: OutputOmission {
audio_items: 1,
..OutputOmission::default()
},
})
.collect(),
};
assert_eq!(
render_output(collected, Some(0)),
[text(
"[Code Mode session output limit reached: omitted 0 text bytes; discarded 0 text segments, 0 images, 16384 audio items]"
)]
);
}
#[test]
fn scattered_loss_is_summarized_once_without_joining_text_across_a_gap() {
let items: Vec<_> = (0..128)
.map(|n| Item::InputImage {
image_url: format!("img:{n}"),
detail: None,
})
.collect();
let collected = CollectedOutput {
gaps: (0..items.len())
.map(|item_index| OutputGap {
boundary: OutputBoundary {
item_index,
text_offset: 0,
},
omitted: OutputOmission {
text_bytes: 5,
text_items: 1,
image_items: 2,
audio_items: 3,
},
})
.collect(),
items: items.clone(),
};
let mut expected = items.clone();
expected.push(text(
"[Code Mode session output limit reached: across this observation, omitted 640 text bytes; discarded 128 text segments, 256 images, 384 audio items]",
));
assert_eq!(render_output(collected.clone(), Some(0)), expected);
let mut collected = collected;
collected.gaps.push(OutputGap {
boundary: OutputBoundary {
item_index: collected.items.len(),
text_offset: "left".len(),
},
omitted: OutputOmission {
text_bytes: 9,
..OutputOmission::default()
},
});
collected.items.push(text("leftright"));
let mut expected = items;
expected.extend([
text("left"),
text(
"[Code Mode session output limit reached: across this observation, omitted 649 text bytes; discarded 128 text segments, 256 images, 384 audio items]",
),
text("right"),
]);
assert_eq!(render_output(collected, Some(16)), expected);
}
#[test]
fn text_only_split_keeps_the_loss_notice_inside_the_rendered_text() {
let mut out = BoundedOutput::default();
let before = "🦀".repeat(MAX_OUTPUT_BYTES / 8);
let after = "🎻".repeat(MAX_OUTPUT_BYTES / 8);
out.push(text(&format!("{before}lost{after}")));
let rendered = render_output(out.into_collected_output(), Some(2));
let [Item::InputText { text: prefix }, notice, suffix] = rendered.as_slice() else {
panic!("expected a split")
};
assert!(
prefix.starts_with("Warning: truncated output")
&& prefix.contains('🦀')
&& !prefix.contains('🎻')
);
assert_eq!(
*notice,
text(
"[Code Mode session output limit reached: omitted 4 text bytes; discarded 0 text segments, 0 images, 0 audio items]"
)
);
assert_eq!(*suffix, text("🎻"));
}
#[test]
fn loss_notices_remain_in_source_order_across_budgets_and_unrelated_text() {
let before = "🦀".repeat(MAX_OUTPUT_BYTES / 8);
let after = "🎻".repeat(MAX_OUTPUT_BYTES / 8);
let original = format!("{before}{}{after}", "x".repeat(10_000));
let image = Item::InputImage {
image_url: "data:image/png;base64,AA==".to_owned(),
detail: Some(ImageDetail::Original),
};
let audio_notice = text(
"[Code Mode session output limit reached: omitted 0 text bytes; discarded 0 text segments, 0 images, 1 audio items]",
);
let image_notice = text(
"[Code Mode session output limit reached: omitted 0 text bytes; discarded 0 text segments, 1 images, 0 audio items]",
);
// Making room for the extra byte evicts one four-byte character from the suffix.
for (neighbor, lost) in [(None, 10000), (Some(""), 10000), (Some("x"), 10004)] {
let split_notice = text(&format!(
"[Code Mode session output limit reached: omitted {lost} text bytes; discarded 0 text segments, 0 images, 0 audio items]"
));
let mut out = BoundedOutput::default();
out.push(Item::InputAudio {
audio_url: "a".repeat(MAX_AUDIO_BYTES + 1),
});
out.push(text(&original));
out.push(Item::InputImage {
image_url: "i".repeat(BOUNDED_OUTPUT_MAX_IMAGE_BYTES + 1),
detail: None,
});
out.push(image.clone());
if let Some(neighbor) = neighbor {
out.push(text(neighbor));
}
let collected = out.into_collected_output();
let positions: Vec<_> = collected
.gaps
.iter()
.map(|gap| (gap.boundary.item_index, gap.boundary.text_offset))
.collect();
assert_eq!(positions, [(0, 0), (0, before.len()), (1, 0)]);
for budget in [0, 1, 2, MAX_OUTPUT_BYTES] {
let rendered = render_output(collected.clone(), Some(budget));
if budget == 0 {
assert_eq!(
&rendered[..2],
&[
text(&format!(
"[Code Mode session output limit reached: omitted {lost} text bytes; discarded 0 text segments, 1 images, 1 audio items]"
)),
image.clone()
]
);
continue;
}
if budget == 1 {
// Neither four-byte character fits its two-byte half. The split after
// Core's marker and the loss before the image are now the same position.
assert_eq!(&rendered[0], &audio_notice);
assert_eq!(
&rendered[2..4],
&[
text(&format!(
"[Code Mode session output limit reached: omitted {lost} text bytes; discarded 0 text segments, 1 images, 0 audio items]"
)),
image.clone()
]
);
continue;
}
let [
first,
Item::InputText { text: left },
between,
Item::InputText { text: right },
last,
preserved,
tail @ ..,
] = rendered.as_slice()
else {
panic!(
"expected three notices around split text, neighbor={neighbor:?}, budget={budget}"
)
};
assert_eq!(
(first, between, last, preserved),
(&audio_notice, &split_notice, &image_notice, &image)
);
assert!(left.starts_with('🦀') && !left.contains('🎻'));
assert!(right.ends_with('🎻') && !right.contains('🦀'));
assert_eq!(tail.len(), usize::from(neighbor == Some("x")));
}
}
}

View File

@@ -0,0 +1,63 @@
//! Measures tool-generated PCM WAV clips using the audio bytes actually present.
//! Unknown formats retain the existing audio output behavior.
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use akode_protocol::models::MAX_PROMPT_AUDIO_INPUT_BYTES;
pub(super) fn wav_duration_seconds(audio_url: &str) -> Option<f64> {
let (metadata, payload) = audio_url.split_once(',')?;
if !metadata
.split(';')
.skip(1)
.any(|part| part.eq_ignore_ascii_case("base64"))
|| payload.len() > MAX_PROMPT_AUDIO_INPUT_BYTES.div_ceil(3) * 4
{
return None;
}
let bytes = BASE64_STANDARD.decode(payload).ok()?;
if bytes.get(..4)? != b"RIFF" || bytes.get(8..12)? != b"WAVE" {
return None;
}
let mut chunks = bytes.get(12..)?;
let mut format = None;
while chunks.len() >= 8 {
let chunk_id = &chunks[..4];
let size = u32::from_le_bytes(chunks[4..8].try_into().ok()?) as usize;
let remaining = &chunks[8..];
// Streaming WAV headers can declare more data than the file contains.
let chunk = &remaining[..size.min(remaining.len())];
match chunk_id {
b"fmt " => {
let mut encoding = u16::from_le_bytes(chunk.get(..2)?.try_into().ok()?);
if encoding == 0xfffe {
// WAVE_FORMAT_EXTENSIBLE stores the encoding in a subtype GUID.
if chunk.get(26..40)?
!= [0, 0, 0, 0, 0x10, 0, 0x80, 0, 0, 0xaa, 0, 0x38, 0x9b, 0x71]
{
return None;
}
encoding = u16::from_le_bytes(chunk.get(24..26)?.try_into().ok()?);
}
if !matches!(encoding, 1 | 3) {
return None;
}
let sample_rate = u32::from_le_bytes(chunk.get(4..8)?.try_into().ok()?);
let block_align = u16::from_le_bytes(chunk.get(12..14)?.try_into().ok()?);
if sample_rate == 0 || block_align == 0 {
return None;
}
format = Some((sample_rate, block_align));
}
b"data" => {
let (sample_rate, block_align) = format?;
let frames = chunk.len() / usize::from(block_align);
return Some(frames as f64 / f64::from(sample_rate));
}
_ => {}
}
chunks = remaining.get(size.checked_add(size % 2)?..)?;
}
None
}

View File

@@ -0,0 +1,375 @@
use crate::session_runtime::OutputItem;
use std::sync::Arc;
use super::RuntimeEvent;
use super::RuntimeState;
use super::timers;
use super::value::json_to_v8;
use super::value::normalize_output_audio;
use super::value::normalize_output_image;
use super::value::serialize_output_text;
use super::value::throw_type_error;
use super::value::v8_value_to_json;
pub(super) fn tool_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let tool_index = match args.data().to_rust_string_lossy(scope).parse::<usize>() {
Ok(tool_index) => tool_index,
Err(_) => {
throw_type_error(scope, "invalid tool callback data");
return;
}
};
let input = if args.length() == 0 {
Ok(None)
} else {
v8_value_to_json(scope, args.get(0))
};
let input = match input {
Ok(input) => input,
Err(error_text) => {
throw_type_error(scope, &error_text);
return;
}
};
let (tool_name, tool_kind) = {
let Some(state) = scope.get_slot::<RuntimeState>() else {
throw_type_error(scope, "runtime state unavailable");
return;
};
// Input serialization can call exit() from a getter or toJSON.
if state.exit_requested {
return;
}
let Some(tool) = state.enabled_tools.get(tool_index) else {
throw_type_error(scope, "tool callback data is out of range");
return;
};
(tool.tool_name.clone(), tool.kind)
};
let Some(resolver) = v8::PromiseResolver::new(scope) else {
throw_type_error(scope, "failed to create tool promise");
return;
};
let promise = resolver.get_promise(scope);
let resolver = v8::Global::new(scope, resolver);
let Some(state) = scope.get_slot_mut::<RuntimeState>() else {
throw_type_error(scope, "runtime state unavailable");
return;
};
let id = format!("tool-{}", state.next_tool_call_id);
state.next_tool_call_id = state.next_tool_call_id.saturating_add(1);
let event_tx = state.event_tx.clone();
state.pending_tool_calls.insert(id.clone(), resolver);
let _ = event_tx.blocking_send(RuntimeEvent::ToolCall {
id,
name: tool_name,
kind: tool_kind,
input,
});
retval.set(promise.into());
}
pub(super) fn text_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let value = if args.length() == 0 {
v8::undefined(scope).into()
} else {
args.get(0)
};
let text = match serialize_output_text(scope, value) {
Ok(text) => text,
Err(error_text) => {
throw_type_error(scope, &error_text);
return;
}
};
if let Some(state) = scope.get_slot::<RuntimeState>()
&& !state.exit_requested
{
let _ = state
.event_tx
.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputText { text }));
}
retval.set(v8::undefined(scope).into());
}
pub(super) fn audio_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let value = if args.length() == 0 {
v8::undefined(scope).into()
} else {
args.get(0)
};
let audio_item = match normalize_output_audio(scope, value) {
Ok(audio_item) => audio_item,
Err(()) => return,
};
if let Some(state) = scope.get_slot::<RuntimeState>()
&& !state.exit_requested
{
let _ = state
.event_tx
.blocking_send(RuntimeEvent::ContentItem(audio_item));
}
retval.set(v8::undefined(scope).into());
}
pub(super) fn image_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let value = if args.length() == 0 {
v8::undefined(scope).into()
} else {
args.get(0)
};
let detail_override = if args.length() < 2 {
None
} else {
let detail = args.get(1);
if detail.is_string() {
Some(detail.to_rust_string_lossy(scope))
} else if detail.is_null() || detail.is_undefined() {
None
} else {
throw_type_error(scope, "image detail must be a string when provided");
return;
}
};
let image_item = match normalize_output_image(scope, value, detail_override) {
Ok(image_item) => image_item,
Err(()) => return,
};
if let Some(state) = scope.get_slot::<RuntimeState>()
&& !state.exit_requested
{
let _ = state
.event_tx
.blocking_send(RuntimeEvent::ContentItem(image_item));
}
retval.set(v8::undefined(scope).into());
}
pub(super) fn generated_image_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let value = if args.length() == 0 {
v8::undefined(scope).into()
} else {
args.get(0)
};
let output_hint = match generated_image_output_hint(scope, value) {
Ok(output_hint) => output_hint,
Err(error_text) => {
throw_type_error(scope, &error_text);
return;
}
};
let image_item = match normalize_output_image(scope, value, /*detail_override*/ None) {
Ok(image_item) => image_item,
Err(()) => return,
};
if let Some(state) = scope.get_slot::<RuntimeState>()
&& !state.exit_requested
{
let _ = state
.event_tx
.blocking_send(RuntimeEvent::ContentItem(image_item));
if let Some(text) = output_hint {
let _ = state
.event_tx
.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputText { text }));
}
}
retval.set(v8::undefined(scope).into());
}
fn generated_image_output_hint(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> Result<Option<String>, String> {
let object = v8::Local::<v8::Object>::try_from(value)
.map_err(|_| "generatedImage expects an image generation result object".to_string())?;
let key = v8::String::new(scope, "output_hint")
.ok_or_else(|| "failed to allocate generatedImage helper keys".to_string())?;
let output_hint = object
.get(scope, key.into())
.ok_or_else(|| "failed to read generatedImage output_hint".to_string())?;
if output_hint.is_undefined() {
return Ok(None);
}
if !output_hint.is_string() {
return Err("generatedImage output_hint must be a string when provided".to_string());
}
Ok(Some(output_hint.to_rust_string_lossy(scope)))
}
pub(super) fn store_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
_retval: v8::ReturnValue<v8::Value>,
) {
let key = match args.get(0).to_string(scope) {
Some(key) => key.to_rust_string_lossy(scope),
None => {
throw_type_error(scope, "store key must be a string");
return;
}
};
let value = args.get(1);
let serialized = match v8_value_to_json(scope, value) {
Ok(Some(value)) => value,
Ok(None) => {
throw_type_error(
scope,
&format!("Unable to store {key:?}. Only plain serializable objects can be stored."),
);
return;
}
Err(error_text) => {
throw_type_error(scope, &error_text);
return;
}
};
if let Some(state) = scope.get_slot_mut::<RuntimeState>()
&& !state.exit_requested
{
let serialized = Arc::new(serialized);
state
.stored_values
.insert(key.clone(), Arc::clone(&serialized));
state.stored_value_writes.insert(key, serialized);
}
}
pub(super) fn load_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let key = match args.get(0).to_string(scope) {
Some(key) => key.to_rust_string_lossy(scope),
None => {
throw_type_error(scope, "load key must be a string");
return;
}
};
let value = scope
.get_slot::<RuntimeState>()
.and_then(|state| state.stored_values.get(&key))
.cloned();
let Some(value) = value else {
retval.set(v8::undefined(scope).into());
return;
};
let Some(value) = json_to_v8(scope, &value) else {
throw_type_error(scope, "failed to load stored value");
return;
};
retval.set(value);
}
pub(super) fn notify_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let value = if args.length() == 0 {
v8::undefined(scope).into()
} else {
args.get(0)
};
let text = match serialize_output_text(scope, value) {
Ok(text) => text,
Err(error_text) => {
throw_type_error(scope, &error_text);
return;
}
};
if text.trim().is_empty() {
throw_type_error(scope, "notify expects non-empty text");
return;
}
if let Some(state) = scope.get_slot::<RuntimeState>()
&& !state.exit_requested
{
let _ = state.event_tx.blocking_send(RuntimeEvent::Notify {
call_id: state.tool_call_id.clone(),
text,
});
}
retval.set(v8::undefined(scope).into());
}
pub(super) fn set_timeout_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let timeout_id = match timers::schedule_timeout(scope, args) {
Ok(Some(timeout_id)) => timeout_id,
Ok(None) => return,
Err(error_text) => {
throw_type_error(scope, &error_text);
return;
}
};
retval.set(v8::Number::new(scope, timeout_id as f64).into());
}
pub(super) fn clear_timeout_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
if let Err(error_text) = timers::clear_timeout(scope, args) {
throw_type_error(scope, &error_text);
return;
}
retval.set(v8::undefined(scope).into());
}
pub(super) fn yield_control_callback(
scope: &mut v8::PinScope<'_, '_>,
_args: v8::FunctionCallbackArguments,
_retval: v8::ReturnValue<v8::Value>,
) {
if let Some(state) = scope.get_slot::<RuntimeState>()
&& !state.exit_requested
{
let _ = state.event_tx.blocking_send(RuntimeEvent::YieldRequested);
}
}
pub(super) fn exit_callback(
scope: &mut v8::PinScope<'_, '_>,
_args: v8::FunctionCallbackArguments,
_retval: v8::ReturnValue<v8::Value>,
) {
if let Some(state) = scope.get_slot_mut::<RuntimeState>() {
state.exit_requested = true;
}
scope.terminate_execution();
}
#[cfg(test)]
#[path = "callbacks_tests.rs"]
mod tests;

View File

@@ -0,0 +1,194 @@
//! Exercises the host guard separately from V8's interrupt mechanism. Simulate
//! V8 continuing to execute after exit was requested, including during getters.
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::mpsc as std_mpsc;
use akode_code_mode_protocol::CodeModeToolKind;
use akode_code_mode_protocol::EnabledToolMetadata;
use akode_protocol::ToolName;
use pretty_assertions::assert_eq;
use serde_json::json;
use tokio::sync::mpsc;
use super::super::RuntimeEvent;
use super::super::RuntimeState;
use super::super::ToolCallbackMetadata;
use super::super::globals;
use crate::session_runtime::OutputItem;
use crate::v8_init::ensure_v8_initialized;
// Deliberately leave JS running: the test must verify host-side admission even
// when V8 has not processed its interrupt. Returning a value exercises coercion.
fn mark_exit_requested(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
scope
.get_slot_mut::<RuntimeState>()
.expect("runtime state")
.exit_requested = true;
retval.set(args.get(0));
}
#[tokio::test]
async fn host_callbacks_admit_no_new_effects_after_exit_is_requested() {
for (label, source) in [
(
"ordinary calls",
r#"
markExit();
text("still working");
image("data:image/png;base64,AAA");
audio("data:audio/mpeg;base64,YXVkaW8=");
generatedImage({image_url: "data:image/png;base64,AAA", output_hint: "late"});
notify("late"); store("phase", "late");
tools.echo("late"); yield_control();
clearTimeout(earlyTimer); setTimeout(() => {}, 60000);
"#,
),
(
"text conversion",
r#"text({toJSON() { return markExit("late"); }});"#,
),
(
"notify conversion",
r#"notify({toJSON() { return markExit("late"); }});"#,
),
(
"store conversion",
r#"store("phase", {toJSON() { return markExit("late"); }});"#,
),
(
"store key",
r#"store({toString() { return markExit("phase"); }}, "late");"#,
),
(
"tool conversion",
r#"tools.echo({toJSON() { return markExit("late"); }});"#,
),
(
"image getter",
r#"image({get image_url() { return markExit("data:image/png;base64,AAA"); }});"#,
),
(
"audio getter",
r#"audio({get audio_url() { return markExit("data:audio/mpeg;base64,YXVkaW8="); }});"#,
),
(
"generated image hint",
r#"generatedImage({image_url: "data:image/png;base64,AAA", get output_hint() {return markExit("late"); }});"#,
),
(
"timer delay",
r#"setTimeout(() => {}, {valueOf() {return markExit(60000); }});"#,
),
(
"clear timer id",
r#"clearTimeout({valueOf() {return markExit(earlyTimer); }});"#,
),
] {
ensure_v8_initialized().expect("initialize V8");
let isolate = &mut v8::Isolate::new(v8::CreateParams::default());
v8::scope!(let scope, isolate);
let context = v8::Context::new(scope, Default::default());
let scope = &mut v8::ContextScope::new(scope, context);
let (event_tx, mut event_rx) = mpsc::unbounded_channel();
let (runtime_command_tx, _runtime_command_rx) = std_mpsc::channel();
let tool_name = ToolName::plain("echo");
globals::install_globals(
scope,
&[EnabledToolMetadata {
global_name: "echo".to_string(),
tool_name: tool_name.clone(),
description: String::new(),
kind: CodeModeToolKind::Function,
}],
)
.expect("install globals");
scope.set_slot(RuntimeState {
event_tx: event_tx.into(),
pending_tool_calls: HashMap::new(),
pending_timeouts: HashMap::new(),
stored_values: HashMap::new(),
stored_value_writes: HashMap::new(),
enabled_tools: vec![ToolCallbackMetadata {
tool_name,
kind: CodeModeToolKind::Function,
}],
next_tool_call_id: 1,
next_timeout_id: 1,
tool_call_id: "cell".to_string(),
runtime_command_tx,
exit_requested: false,
});
let marker = v8::Function::new(scope, mark_exit_requested).expect("exit marker");
let key = v8::String::new(scope, "markExit").expect("marker name");
context.global(scope).set(scope, key.into(), marker.into());
let program = v8::String::new(
scope,
&format!(
r#"
text("before"); store("phase", "before"); notify("before");
tools.echo("before");
const earlyTimer = setTimeout(() => text("early timer"), 60000);
{source}
"#
),
)
.expect("test program");
let tc = std::pin::pin!(v8::TryCatch::new(scope));
let tc = tc.init();
let result =
v8::Script::compile(&tc, program, /*origin*/ None).and_then(|script| script.run(&tc));
assert!(
result.is_some(),
"{label}: {:?}",
tc.exception().map(|e| e.to_rust_string_lossy(&tc))
);
assert!(
matches!(event_rx.try_recv(), Ok(RuntimeEvent::ContentItem(
OutputItem::InputText { text }
)) if text == "before"),
"{label}: pre-exit output"
);
assert!(
matches!(event_rx.try_recv(), Ok(RuntimeEvent::Notify { text, .. }) if text == "before"),
"{label}: pre-exit notification"
);
assert!(
matches!(event_rx.try_recv(), Ok(RuntimeEvent::ToolCall { id, input, .. })
if id == "tool-1" && input == Some(json!("before"))),
"{label}: pre-exit tool"
);
assert!(
matches!(event_rx.try_recv(), Err(mpsc::error::TryRecvError::Empty)),
"{label}: emitted an effect after exit"
);
let state = tc.get_slot::<RuntimeState>().expect("runtime state");
assert_eq!(
state.stored_value_writes,
HashMap::from([("phase".to_string(), Arc::new(json!("before")))]),
"{label}: stored writes"
);
assert_eq!(
state.stored_values, state.stored_value_writes,
"{label}: cell storage"
);
assert_eq!(state.next_tool_call_id, 2, "{label}: allocated tool ID");
assert_eq!(state.next_timeout_id, 2, "{label}: allocated timeout ID");
assert!(
state.pending_tool_calls.contains_key("tool-1"),
"{label}: lost prior tool"
);
assert!(
state.pending_timeouts.contains_key(&1),
"{label}: lost prior timer"
);
}
}

View File

@@ -0,0 +1,77 @@
//! Ordered runtime event transport with backpressure for bounded collectors.
use tokio::sync::mpsc;
use super::RuntimeEvent;
use akode_code_mode_protocol::CodeModeOutputTruncation;
// Amortize small-write handoffs while keeping the backlog of raw payloads
// ahead of the bounded collector small.
const EVENT_CAPACITY: usize = 4;
#[derive(Clone)]
pub(crate) enum RuntimeEventSender {
Legacy(mpsc::UnboundedSender<RuntimeEvent>),
Bounded(mpsc::Sender<RuntimeEvent>),
}
pub(crate) enum RuntimeEventReceiver {
Legacy(mpsc::UnboundedReceiver<RuntimeEvent>),
Bounded(mpsc::Receiver<RuntimeEvent>),
}
pub(crate) fn runtime_event_channel(
mode: CodeModeOutputTruncation,
) -> (RuntimeEventSender, RuntimeEventReceiver) {
match mode {
CodeModeOutputTruncation::Client => {
let (tx, rx) = mpsc::unbounded_channel();
(
RuntimeEventSender::Legacy(tx),
RuntimeEventReceiver::Legacy(rx),
)
}
CodeModeOutputTruncation::Server => {
let (tx, rx) = mpsc::channel(EVENT_CAPACITY);
(
RuntimeEventSender::Bounded(tx),
RuntimeEventReceiver::Bounded(rx),
)
}
}
}
impl From<mpsc::UnboundedSender<RuntimeEvent>> for RuntimeEventSender {
fn from(value: mpsc::UnboundedSender<RuntimeEvent>) -> Self {
Self::Legacy(value)
}
}
impl RuntimeEventReceiver {
pub(crate) async fn recv(&mut self) -> Option<RuntimeEvent> {
match self {
Self::Legacy(rx) => rx.recv().await,
Self::Bounded(rx) => rx.recv().await,
}
}
}
impl RuntimeEventSender {
/// Bounded sends run only on the dedicated V8 thread, preserving event order
/// without making synchronous JavaScript output helpers return promises.
/// Capacity limits the backlog between V8 and the cell actor.
///
/// # Panics
///
/// In server mode, panics if called from an async execution context.
pub(crate) fn blocking_send(&self, event: RuntimeEvent) -> Result<(), ()> {
match self {
Self::Legacy(tx) => tx.send(event).map_err(|_| ()),
Self::Bounded(tx) => tx.blocking_send(event).map_err(|_| ()),
}
}
}
#[cfg(test)]
#[path = "event_channel_tests.rs"]
mod tests;

View File

@@ -0,0 +1,133 @@
//! Raw emissions and control events share one bounded FIFO before collection.
use pretty_assertions::assert_eq;
use tokio::sync::oneshot;
use super::*;
use crate::session_runtime::OutputItem;
use akode_code_mode_protocol::host::BOUNDED_OUTPUT_MAX_BYTES as MAX_OUTPUT_BYTES;
#[tokio::test]
async fn a_blocked_send_uses_the_released_slot_before_the_receiver_takes_the_item() {
let (tx, mut rx) = runtime_event_channel(CodeModeOutputTruncation::Server);
let RuntimeEventSender::Bounded(raw) = tx.clone() else {
panic!("expected bounded sender");
};
let mut permits = raw.reserve_many(EVENT_CAPACITY).await.unwrap();
let (done_tx, mut done_rx) = oneshot::channel();
let text = "😀".repeat(MAX_OUTPUT_BYTES);
let producer_text = text.clone();
let producer = std::thread::spawn(move || {
let result = tx.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputText {
text: producer_text,
}));
let _ = done_tx.send(result);
});
// Queue a competing waiter before releasing the slot. A blocking producer can
// win the slot in FIFO order; a try_send can never find an unreserved slot.
let sent = tokio::time::timeout(std::time::Duration::from_secs(5), async {
let mut slot = permits.next().unwrap();
loop {
let mut next = std::pin::pin!(raw.reserve());
assert!(futures::poll!(next.as_mut()).is_pending());
drop(slot);
tokio::select! {
result = &mut done_rx => break result.unwrap(),
permit = &mut next => slot = permit.unwrap(),
}
tokio::task::yield_now().await;
}
})
.await
.expect("the producer must eventually acquire the released slot");
assert_eq!(sent, Ok(()));
// Close the test's sender so a missing event fails the receive immediately.
drop(permits);
drop(raw);
let event = rx.recv().await.unwrap();
let RuntimeEvent::ContentItem(item) = event else {
panic!("expected raw content");
};
assert_eq!(item, OutputItem::InputText { text });
producer.join().unwrap();
}
#[tokio::test]
async fn content_and_control_are_received_in_send_order() {
let (tx, mut rx) = runtime_event_channel(CodeModeOutputTruncation::Server);
let producer = std::thread::spawn(move || {
tx.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputImage {
image_url: "image".to_owned(),
detail: None,
}))
.unwrap();
tx.blocking_send(RuntimeEvent::YieldRequested).unwrap();
tx.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputText {
text: "after yield".to_owned(),
}))
.unwrap();
});
assert!(matches!(
rx.recv().await,
Some(RuntimeEvent::ContentItem(OutputItem::InputImage { .. }))
));
assert!(matches!(
rx.recv().await,
Some(RuntimeEvent::YieldRequested)
));
assert!(matches!(
rx.recv().await,
Some(RuntimeEvent::ContentItem(OutputItem::InputText { text }))
if text == "after yield"
));
producer.join().unwrap();
}
#[tokio::test]
async fn full_channel_blocks_the_producer_and_receiver_drop_releases_it() {
let (tx, rx) = runtime_event_channel(CodeModeOutputTruncation::Server);
let RuntimeEventSender::Bounded(tx) = tx else {
panic!("expected bounded sender");
};
for _ in 0..EVENT_CAPACITY {
tx.try_send(RuntimeEvent::Started).unwrap();
}
let (ready_tx, ready_rx) = oneshot::channel();
let producer = tokio::spawn(async move {
// Tokio's blocking_send runs this same send future. Polling it first
// proves the full channel has registered this producer as a waiter.
let mut send = std::pin::pin!(tx.send(RuntimeEvent::YieldRequested));
assert!(futures::poll!(send.as_mut()).is_pending());
ready_tx.send(()).unwrap();
send.await
});
// This current-thread runtime cannot resume us until the producer yields.
// Closing must wake that already-waiting task, not just reject a new send.
ready_rx.await.unwrap();
drop(rx);
let result = tokio::time::timeout(std::time::Duration::from_secs(1), producer)
.await
.expect("receiver drop must wake the blocked producer")
.expect("producer task");
assert!(matches!(
result,
Err(mpsc::error::SendError(RuntimeEvent::YieldRequested))
));
}
#[tokio::test]
async fn sending_after_receiver_drop_rejects_content() {
let (tx, rx) = runtime_event_channel(CodeModeOutputTruncation::Server);
drop(rx);
assert_eq!(
std::thread::spawn(move || tx.blocking_send(RuntimeEvent::ContentItem(
OutputItem::InputAudio {
audio_url: "large audio".repeat(MAX_OUTPUT_BYTES)
}
)))
.join()
.unwrap(),
Err(())
);
}

View File

@@ -0,0 +1,166 @@
use super::callbacks::audio_callback;
use super::callbacks::clear_timeout_callback;
use super::callbacks::exit_callback;
use super::callbacks::generated_image_callback;
use super::callbacks::image_callback;
use super::callbacks::load_callback;
use super::callbacks::notify_callback;
use super::callbacks::set_timeout_callback;
use super::callbacks::store_callback;
use super::callbacks::text_callback;
use super::callbacks::tool_callback;
use super::callbacks::yield_control_callback;
use akode_code_mode_protocol::EnabledToolMetadata;
pub(super) fn install_globals(
scope: &mut v8::PinScope<'_, '_>,
enabled_tools: &[EnabledToolMetadata],
) -> Result<(), String> {
let global = scope.get_current_context().global(scope);
delete_global(scope, global, "console")?;
delete_global(scope, global, "Atomics")?;
delete_global(scope, global, "SharedArrayBuffer")?;
delete_global(scope, global, "WebAssembly")?;
let tools = build_tools_object(scope, enabled_tools)?;
let all_tools = build_all_tools_value(scope, enabled_tools)?;
let clear_timeout = helper_function(scope, "clearTimeout", clear_timeout_callback)?;
let set_timeout = helper_function(scope, "setTimeout", set_timeout_callback)?;
let text = helper_function(scope, "text", text_callback)?;
let image = helper_function(scope, "image", image_callback)?;
let audio = helper_function(scope, "audio", audio_callback)?;
let generated_image = helper_function(scope, "generatedImage", generated_image_callback)?;
let store = helper_function(scope, "store", store_callback)?;
let load = helper_function(scope, "load", load_callback)?;
let notify = helper_function(scope, "notify", notify_callback)?;
let yield_control = helper_function(scope, "yield_control", yield_control_callback)?;
let exit = helper_function(scope, "exit", exit_callback)?;
set_global(scope, global, "tools", tools.into())?;
set_global(scope, global, "ALL_TOOLS", all_tools)?;
set_global(scope, global, "clearTimeout", clear_timeout.into())?;
set_global(scope, global, "setTimeout", set_timeout.into())?;
set_global(scope, global, "text", text.into())?;
set_global(scope, global, "image", image.into())?;
set_global(scope, global, "audio", audio.into())?;
set_global(scope, global, "generatedImage", generated_image.into())?;
set_global(scope, global, "store", store.into())?;
set_global(scope, global, "load", load.into())?;
set_global(scope, global, "notify", notify.into())?;
set_global(scope, global, "yield_control", yield_control.into())?;
set_global(scope, global, "exit", exit.into())?;
let source = v8::String::new(scope, include_str!("settled.js"))
.ok_or_else(|| "failed to allocate settlement helpers".to_string())?;
v8::Script::compile(scope, source, /*origin*/ None)
.and_then(|script| script.run(scope))
.ok_or_else(|| "failed to initialize settlement helpers".to_string())?;
Ok(())
}
fn build_tools_object<'s>(
scope: &mut v8::PinScope<'s, '_>,
enabled_tools: &[EnabledToolMetadata],
) -> Result<v8::Local<'s, v8::Object>, String> {
let tools = v8::Object::new(scope);
for (tool_index, tool) in enabled_tools.iter().enumerate() {
let name = v8::String::new(scope, &tool.global_name)
.ok_or_else(|| "failed to allocate tool name".to_string())?;
let function = tool_function(scope, tool_index)?;
tools.set(scope, name.into(), function.into());
}
Ok(tools)
}
fn build_all_tools_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
enabled_tools: &[EnabledToolMetadata],
) -> Result<v8::Local<'s, v8::Value>, String> {
let array = v8::Array::new(scope, enabled_tools.len() as i32);
let name_key = v8::String::new(scope, "name")
.ok_or_else(|| "failed to allocate ALL_TOOLS name key".to_string())?;
let description_key = v8::String::new(scope, "description")
.ok_or_else(|| "failed to allocate ALL_TOOLS description key".to_string())?;
for (index, tool) in enabled_tools.iter().enumerate() {
let item = v8::Object::new(scope);
let name = v8::String::new(scope, &tool.global_name)
.ok_or_else(|| "failed to allocate ALL_TOOLS name".to_string())?;
let description = v8::String::new(scope, &tool.description)
.ok_or_else(|| "failed to allocate ALL_TOOLS description".to_string())?;
if item.set(scope, name_key.into(), name.into()) != Some(true) {
return Err("failed to set ALL_TOOLS name".to_string());
}
if item.set(scope, description_key.into(), description.into()) != Some(true) {
return Err("failed to set ALL_TOOLS description".to_string());
}
if array.set_index(scope, index as u32, item.into()) != Some(true) {
return Err("failed to append ALL_TOOLS metadata".to_string());
}
}
Ok(array.into())
}
fn helper_function<'s, F>(
scope: &mut v8::PinScope<'s, '_>,
name: &str,
callback: F,
) -> Result<v8::Local<'s, v8::Function>, String>
where
F: v8::MapFnTo<v8::FunctionCallback>,
{
let name =
v8::String::new(scope, name).ok_or_else(|| "failed to allocate helper name".to_string())?;
let template = v8::FunctionTemplate::builder(callback)
.data(name.into())
.build(scope);
template
.get_function(scope)
.ok_or_else(|| "failed to create helper function".to_string())
}
fn tool_function<'s>(
scope: &mut v8::PinScope<'s, '_>,
tool_index: usize,
) -> Result<v8::Local<'s, v8::Function>, String> {
let data = v8::String::new(scope, &tool_index.to_string())
.ok_or_else(|| "failed to allocate tool callback data".to_string())?;
let template = v8::FunctionTemplate::builder(tool_callback)
.data(data.into())
.build(scope);
template
.get_function(scope)
.ok_or_else(|| "failed to create tool function".to_string())
}
fn set_global<'s>(
scope: &mut v8::PinScope<'s, '_>,
global: v8::Local<'s, v8::Object>,
name: &str,
value: v8::Local<'s, v8::Value>,
) -> Result<(), String> {
let key = v8::String::new(scope, name)
.ok_or_else(|| format!("failed to allocate global `{name}`"))?;
if global.set(scope, key.into(), value) == Some(true) {
Ok(())
} else {
Err(format!("failed to set global `{name}`"))
}
}
fn delete_global<'s>(
scope: &mut v8::PinScope<'s, '_>,
global: v8::Local<'s, v8::Object>,
name: &str,
) -> Result<(), String> {
let key = v8::String::new(scope, name)
.ok_or_else(|| format!("failed to allocate global `{name}`"))?;
if global.delete(scope, key.into()) == Some(true) {
Ok(())
} else {
Err(format!("failed to remove global `{name}`"))
}
}

View File

@@ -0,0 +1,619 @@
mod audio;
mod callbacks;
mod event_channel;
mod globals;
mod module_loader;
mod timers;
mod value;
use std::collections::HashMap;
use std::panic::AssertUnwindSafe;
use std::panic::catch_unwind;
use std::sync::Arc;
use std::sync::mpsc as std_mpsc;
use std::thread;
use crate::TaskFailureHandler;
use crate::session_runtime::OutputItem;
use crate::v8_init::ensure_v8_initialized;
use akode_code_mode_protocol::CodeModeToolKind;
use akode_code_mode_protocol::EnabledToolMetadata;
use akode_code_mode_protocol::ExecuteRequest;
use akode_code_mode_protocol::normalize_code_mode_identifier;
use akode_protocol::ToolName;
pub(crate) use event_channel::RuntimeEventReceiver;
pub(crate) use event_channel::RuntimeEventSender;
pub(crate) use event_channel::runtime_event_channel;
use serde_json::Value as JsonValue;
#[derive(Debug)]
pub(crate) enum RuntimeCommand {
ToolResponse { id: String, result: JsonValue },
ToolError { id: String, error_text: String },
TimeoutFired { id: u64 },
ObservePendingFrontier,
Terminate,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum PendingRuntimeMode {
#[cfg(test)]
Continue,
PauseUntilResumed,
}
#[derive(Debug)]
pub(crate) enum RuntimeControlCommand {
Continue,
Resume,
Terminate,
}
#[derive(Debug)]
pub(crate) enum RuntimeEvent {
Started,
Pending,
ContentItem(OutputItem),
YieldRequested,
ToolCall {
id: String,
name: ToolName,
kind: CodeModeToolKind,
input: Option<JsonValue>,
},
Notify {
call_id: String,
text: String,
},
Result {
stored_value_writes: HashMap<String, Arc<JsonValue>>,
error_text: Option<String>,
},
ThreadPanicked,
}
pub(crate) fn spawn_runtime(
stored_values: HashMap<String, Arc<JsonValue>>,
request: ExecuteRequest,
event_tx: impl Into<RuntimeEventSender>,
pending_mode: PendingRuntimeMode,
task_failure_handler: Option<TaskFailureHandler>,
) -> Result<
(
std_mpsc::Sender<RuntimeCommand>,
std_mpsc::Sender<RuntimeControlCommand>,
v8::IsolateHandle,
),
String,
> {
let event_tx = event_tx.into();
ensure_v8_initialized()?;
let (command_tx, command_rx) = std_mpsc::channel();
let (control_tx, control_rx) = std_mpsc::channel();
let runtime_command_tx = command_tx.clone();
let (isolate_handle_tx, isolate_handle_rx) = std_mpsc::sync_channel(1);
let enabled_tools = request
.enabled_tools
.into_iter()
.map(|definition| EnabledToolMetadata {
global_name: normalize_code_mode_identifier(&definition.name),
tool_name: definition.tool_name,
description: definition.description,
kind: definition.kind,
})
.collect::<Vec<_>>();
let config = RuntimeConfig {
tool_call_id: request.tool_call_id,
enabled_tools,
source: request.source,
stored_values,
};
let runtime_handle = tokio::runtime::Handle::current();
spawn_supervised_runtime_thread(event_tx.clone(), task_failure_handler, move || {
let _runtime_guard = runtime_handle.enter();
run_runtime(
config,
event_tx,
command_rx,
control_rx,
pending_mode,
isolate_handle_tx,
runtime_command_tx,
);
});
let isolate_handle = isolate_handle_rx
.recv()
.map_err(|_| "failed to initialize code mode runtime".to_string())?;
Ok((command_tx, control_tx, isolate_handle))
}
fn spawn_supervised_runtime_thread(
event_tx: impl Into<RuntimeEventSender>,
task_failure_handler: Option<TaskFailureHandler>,
runtime: impl FnOnce() + Send + 'static,
) {
let event_tx = event_tx.into();
thread::spawn(move || {
if catch_unwind(AssertUnwindSafe(runtime)).is_err() {
if let Some(task_failure_handler) = task_failure_handler {
task_failure_handler("code-mode V8 runtime thread panicked".to_string());
}
let _ = event_tx.blocking_send(RuntimeEvent::ThreadPanicked);
}
});
}
#[derive(Clone)]
struct RuntimeConfig {
tool_call_id: String,
enabled_tools: Vec<EnabledToolMetadata>,
source: String,
stored_values: HashMap<String, Arc<JsonValue>>,
}
// Callback indices refer to this cell's original catalog for its entire lifetime.
struct ToolCallbackMetadata {
tool_name: ToolName,
kind: CodeModeToolKind,
}
pub(super) struct RuntimeState {
event_tx: RuntimeEventSender,
pending_tool_calls: HashMap<String, v8::Global<v8::PromiseResolver>>,
pending_timeouts: HashMap<u64, timers::ScheduledTimeout>,
stored_values: HashMap<String, Arc<JsonValue>>,
stored_value_writes: HashMap<String, Arc<JsonValue>>,
enabled_tools: Vec<ToolCallbackMetadata>,
next_tool_call_id: u64,
next_timeout_id: u64,
tool_call_id: String,
runtime_command_tx: std_mpsc::Sender<RuntimeCommand>,
exit_requested: bool,
}
pub(super) enum CompletionState {
Pending,
Completed { error_text: Option<String> },
}
fn run_runtime(
config: RuntimeConfig,
event_tx: RuntimeEventSender,
command_rx: std_mpsc::Receiver<RuntimeCommand>,
control_rx: std_mpsc::Receiver<RuntimeControlCommand>,
pending_mode: PendingRuntimeMode,
isolate_handle_tx: std_mpsc::SyncSender<v8::IsolateHandle>,
runtime_command_tx: std_mpsc::Sender<RuntimeCommand>,
) {
let isolate = &mut v8::Isolate::new(v8::CreateParams::default());
let isolate_handle = isolate.thread_safe_handle();
if isolate_handle_tx.send(isolate_handle).is_err() {
return;
}
isolate.set_host_import_module_dynamically_callback(module_loader::dynamic_import_callback);
v8::scope!(let scope, isolate);
let context = v8::Context::new(scope, Default::default());
let scope = &mut v8::ContextScope::new(scope, context);
if let Err(error_text) = globals::install_globals(scope, &config.enabled_tools) {
send_result(&event_tx, HashMap::new(), Some(error_text));
return;
}
scope.set_slot(RuntimeState {
event_tx: event_tx.clone(),
pending_tool_calls: HashMap::new(),
pending_timeouts: HashMap::new(),
stored_values: config.stored_values,
stored_value_writes: HashMap::new(),
enabled_tools: config
.enabled_tools
.into_iter()
.map(|tool| ToolCallbackMetadata {
tool_name: tool.tool_name,
kind: tool.kind,
})
.collect(),
next_tool_call_id: 1,
next_timeout_id: 1,
tool_call_id: config.tool_call_id,
runtime_command_tx,
exit_requested: false,
});
let _ = event_tx.blocking_send(RuntimeEvent::Started);
let pending_promise = match module_loader::evaluate_main_module(scope, &config.source) {
Ok(pending_promise) => pending_promise,
Err(error_text) => {
send_scope_result(scope, &event_tx, Some(error_text));
return;
}
};
match module_loader::completion_state(scope, pending_promise.as_ref()) {
CompletionState::Completed { error_text } => {
send_scope_result(scope, &event_tx, error_text);
return;
}
CompletionState::Pending => {}
}
let mut pending_promise = pending_promise;
while let Some(command) =
next_runtime_command(&event_tx, &command_rx, &control_rx, pending_mode)
{
match command {
RuntimeCommand::Terminate => break,
RuntimeCommand::ToolResponse { id, result } => {
if let Err(error_text) =
module_loader::resolve_tool_response(scope, &id, Ok(result))
{
send_scope_result(scope, &event_tx, Some(error_text));
return;
}
}
RuntimeCommand::ToolError { id, error_text } => {
if let Err(runtime_error) =
module_loader::resolve_tool_response(scope, &id, Err(error_text))
{
send_scope_result(scope, &event_tx, Some(runtime_error));
return;
}
}
RuntimeCommand::TimeoutFired { id } => {
if let Err(runtime_error) = timers::invoke_timeout_callback(scope, id) {
send_scope_result(scope, &event_tx, Some(runtime_error));
return;
}
}
RuntimeCommand::ObservePendingFrontier => {}
}
scope.perform_microtask_checkpoint();
match module_loader::completion_state(scope, pending_promise.as_ref()) {
CompletionState::Completed { error_text } => {
send_scope_result(scope, &event_tx, error_text);
return;
}
CompletionState::Pending => {}
}
if let Some(promise) = pending_promise.as_ref() {
let promise = v8::Local::new(scope, promise);
if promise.state() != v8::PromiseState::Pending {
pending_promise = None;
}
}
}
}
fn next_runtime_command(
event_tx: &RuntimeEventSender,
command_rx: &std_mpsc::Receiver<RuntimeCommand>,
control_rx: &std_mpsc::Receiver<RuntimeControlCommand>,
pending_mode: PendingRuntimeMode,
) -> Option<RuntimeCommand> {
loop {
match command_rx.try_recv() {
Ok(command) => return Some(command),
Err(std_mpsc::TryRecvError::Disconnected) => return None,
Err(std_mpsc::TryRecvError::Empty) => {}
}
let _ = event_tx.blocking_send(RuntimeEvent::Pending);
match pending_mode {
#[cfg(test)]
PendingRuntimeMode::Continue => return command_rx.recv().ok(),
PendingRuntimeMode::PauseUntilResumed => match control_rx.recv().ok()? {
RuntimeControlCommand::Continue => return command_rx.recv().ok(),
RuntimeControlCommand::Resume => continue,
RuntimeControlCommand::Terminate => return Some(RuntimeCommand::Terminate),
},
}
}
}
fn send_scope_result(
scope: &mut v8::PinScope<'_, '_>,
event_tx: &RuntimeEventSender,
error_text: Option<String>,
) {
// Error rendering can itself run JS getters, including exit(). Capture
// the result only after every call into the exiting isolate has returned.
let state = scope.get_slot::<RuntimeState>();
let stored_value_writes = state
.map(|state| state.stored_value_writes.clone())
.unwrap_or_default();
let error_text = error_text.filter(|_| !state.is_some_and(|state| state.exit_requested));
send_result(event_tx, stored_value_writes, error_text);
}
fn send_result(
event_tx: &RuntimeEventSender,
stored_value_writes: HashMap<String, Arc<JsonValue>>,
error_text: Option<String>,
) {
let _ = event_tx.blocking_send(RuntimeEvent::Result {
stored_value_writes,
error_text,
});
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::time::Duration;
use pretty_assertions::assert_eq;
use tokio::sync::mpsc;
use super::ExecuteRequest;
use super::PendingRuntimeMode;
use super::RuntimeCommand;
use super::RuntimeControlCommand;
use super::RuntimeEvent;
use super::spawn_runtime;
use super::spawn_supervised_runtime_thread;
use crate::session_runtime::OutputItem;
fn execute_request(source: &str) -> ExecuteRequest {
ExecuteRequest {
tool_call_id: "call_1".to_string(),
enabled_tools: Vec::new(),
source: source.to_string(),
yield_time_ms: Some(1),
max_output_tokens: None,
}
}
#[test]
fn linked_v8_has_sandbox_enabled() {
unsafe extern "C" {
fn v8__V8__IsSandboxEnabled() -> bool;
}
// `rusty_v8` exposes this symbol for verifying linked sandbox support.
assert!(
unsafe { v8__V8__IsSandboxEnabled() },
"code mode must link against sandbox-enabled V8"
);
}
#[tokio::test]
async fn runtime_thread_panic_before_initialization_is_reported_directly() {
let (event_tx, event_rx) = mpsc::unbounded_channel();
drop(event_rx);
let (failure_tx, mut failure_rx) = mpsc::unbounded_channel();
spawn_supervised_runtime_thread(
event_tx,
Some(std::sync::Arc::new(move |reason| {
let _ = failure_tx.send(reason);
})),
|| panic!("runtime thread panic probe"),
);
assert_eq!(
tokio::time::timeout(Duration::from_secs(1), failure_rx.recv())
.await
.expect("runtime failure timeout")
.expect("runtime failure"),
"code-mode V8 runtime thread panicked"
);
}
#[tokio::test]
async fn runtime_thread_panic_is_forwarded_without_owner_supervision() {
let (event_tx, mut event_rx) = mpsc::unbounded_channel();
spawn_supervised_runtime_thread(
event_tx,
/*task_failure_handler*/ None,
|| panic!("runtime thread panic probe"),
);
assert!(matches!(
tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.expect("runtime panic event timeout"),
Some(RuntimeEvent::ThreadPanicked)
));
}
#[tokio::test]
async fn terminate_execution_stops_javascript() {
for source in [
r#"notify("started"); while (true) {}"#,
// The failed first read enters JSON fallback, whose TryCatch must preserve termination.
r#"
let reads = 0;
const value = {
get image_url() {
if (++reads === 1) throw new Error("enter fallback");
notify("started");
while (true) {}
}
};
try { image(value); } catch {}
text("continued after cancellation");
"#,
] {
let (event_tx, mut event_rx) = mpsc::unbounded_channel();
let (_runtime_tx, _runtime_control_tx, runtime_terminate_handle) = spawn_runtime(
HashMap::new(),
execute_request(source),
event_tx,
PendingRuntimeMode::Continue,
/*task_failure_handler*/ None,
)
.unwrap();
let started_event = tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.unwrap();
assert!(matches!(started_event, RuntimeEvent::Started));
// Started precedes evaluation; the notification proves the workload is running.
assert!(matches!(
tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap(),
Some(RuntimeEvent::Notify { .. })
));
assert!(runtime_terminate_handle.terminate_execution());
let result_event = tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.unwrap();
let RuntimeEvent::Result { error_text, .. } = result_event else {
panic!("expected runtime result after termination");
};
assert!(error_text.is_some());
assert!(
tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.is_none()
);
}
}
#[tokio::test]
async fn pending_mode_freezes_runtime_commands_until_resume() {
let (event_tx, mut event_rx) = mpsc::unbounded_channel();
let (runtime_tx, runtime_control_tx, _runtime_terminate_handle) = spawn_runtime(
HashMap::new(),
execute_request(
r#"
await new Promise((resolve) => setTimeout(resolve, 60_000));
text("after");
await new Promise(() => {});
"#,
),
event_tx,
PendingRuntimeMode::PauseUntilResumed,
/*task_failure_handler*/ None,
)
.unwrap();
assert!(matches!(
tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.unwrap(),
RuntimeEvent::Started
));
assert!(matches!(
tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.unwrap(),
RuntimeEvent::Pending
));
runtime_tx
.send(RuntimeCommand::TimeoutFired { id: 1 })
.unwrap();
assert!(
tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.is_err()
);
runtime_control_tx
.send(RuntimeControlCommand::Resume)
.unwrap();
let content_event = tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.unwrap();
let RuntimeEvent::ContentItem(OutputItem::InputText { text }) = content_event else {
panic!("expected resumed runtime output");
};
assert_eq!(text, "after");
assert!(matches!(
tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.unwrap(),
RuntimeEvent::Pending
));
runtime_control_tx
.send(RuntimeControlCommand::Terminate)
.unwrap();
}
#[tokio::test]
async fn timers_release_tasks_when_cleared_or_the_cell_finishes() {
let (event_tx, mut event_rx) = mpsc::unbounded_channel();
let (_runtime_tx, _runtime_control_tx, _runtime_terminate_handle) = spawn_runtime(
HashMap::new(),
execute_request(
r#"
clearTimeout(setTimeout(() => text("cancelled"), 3_600_000));
await new Promise((resolve) => setTimeout(resolve, 3_600_000));
text("done");
setTimeout(() => text("late"), 3_600_000);
"#,
),
event_tx,
PendingRuntimeMode::Continue,
/*task_failure_handler*/ None,
)
.unwrap();
loop {
match tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
{
Some(RuntimeEvent::Pending) => break,
Some(_) => {}
None => panic!("runtime closed before the timer was pending"),
}
}
tokio::task::yield_now().await;
assert_eq!(
tokio::runtime::Handle::current()
.metrics()
.num_alive_tasks(),
1
);
tokio::time::pause();
tokio::time::advance(Duration::from_secs(3_600)).await;
tokio::time::resume();
let mut output = Vec::new();
while let Some(event) = tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.expect("timer runtime should finish")
{
match event {
RuntimeEvent::ContentItem(item) => output.push(item),
RuntimeEvent::Result { error_text, .. } => assert_eq!(error_text, None),
_ => {}
}
}
assert_eq!(
output,
vec![OutputItem::InputText {
text: "done".to_string()
}]
);
tokio::task::yield_now().await;
assert_eq!(
tokio::runtime::Handle::current()
.metrics()
.num_alive_tasks(),
0
);
}
}

View File

@@ -0,0 +1,217 @@
use serde_json::Value as JsonValue;
use super::CompletionState;
use super::RuntimeState;
use super::value::json_to_v8;
use super::value::value_to_error_text;
pub(super) fn evaluate_main_module(
scope: &mut v8::PinScope<'_, '_>,
source_text: &str,
) -> Result<Option<v8::Global<v8::Promise>>, String> {
let tc = std::pin::pin!(v8::TryCatch::new(scope));
let mut tc = tc.init();
let source = v8::String::new(&tc, source_text)
.ok_or_else(|| "failed to allocate exec source".to_string())?;
let origin = script_origin(&mut tc, "exec_main.mjs")?;
let mut source = v8::script_compiler::Source::new(source, Some(&origin));
let module = v8::script_compiler::compile_module(&tc, &mut source).ok_or_else(|| {
tc.exception()
.map(|exception| value_to_error_text(&mut tc, exception))
.unwrap_or_else(|| "unknown code mode exception".to_string())
})?;
module
.instantiate_module(&tc, resolve_module_callback)
.ok_or_else(|| {
tc.exception()
.map(|exception| value_to_error_text(&mut tc, exception))
.unwrap_or_else(|| "unknown code mode exception".to_string())
})?;
let result = match module.evaluate(&tc) {
Some(result) => result,
None => {
if let Some(exception) = tc.exception() {
return Err(value_to_error_text(&mut tc, exception));
}
return Err("unknown code mode exception".to_string());
}
};
tc.perform_microtask_checkpoint();
if result.is_promise() {
let promise = v8::Local::<v8::Promise>::try_from(result)
.map_err(|_| "failed to read exec promise".to_string())?;
return Ok(Some(v8::Global::new(&tc, promise)));
}
Ok(None)
}
pub(super) fn resolve_tool_response(
scope: &mut v8::PinScope<'_, '_>,
id: &str,
response: Result<JsonValue, String>,
) -> Result<(), String> {
let resolver = {
let state = scope
.get_slot_mut::<RuntimeState>()
.ok_or_else(|| "runtime state unavailable".to_string())?;
state.pending_tool_calls.remove(id)
}
.ok_or_else(|| format!("unknown tool call `{id}`"))?;
// Release delivery handles before the cell ends; live promises retain their results.
v8::scope!(let scope, scope);
let tc = std::pin::pin!(v8::TryCatch::new(scope));
let mut tc = tc.init();
let resolver = v8::Local::new(&tc, &resolver);
match response {
Ok(result) => {
let value = json_to_v8(&mut tc, &result)
.ok_or_else(|| "failed to serialize tool response".to_string())?;
resolver.resolve(&tc, value);
}
Err(error_text) => {
let value = v8::String::new(&tc, &error_text)
.ok_or_else(|| "failed to allocate tool error".to_string())?;
resolver.reject(&tc, value.into());
}
}
if tc.has_caught() {
return Err(tc
.exception()
.map(|exception| value_to_error_text(&mut tc, exception))
.unwrap_or_else(|| "unknown code mode exception".to_string()));
}
Ok(())
}
pub(super) fn completion_state(
scope: &mut v8::PinScope<'_, '_>,
pending_promise: Option<&v8::Global<v8::Promise>>,
) -> CompletionState {
// Termination during a microtask can leave the module promise pending.
// This isolate belongs to the exiting cell; never pump or await it again.
if scope
.get_slot::<RuntimeState>()
.is_some_and(|state| state.exit_requested)
{
return CompletionState::Completed { error_text: None };
}
let Some(pending_promise) = pending_promise else {
return CompletionState::Completed { error_text: None };
};
let promise = v8::Local::new(scope, pending_promise);
match promise.state() {
v8::PromiseState::Pending => CompletionState::Pending,
v8::PromiseState::Fulfilled => CompletionState::Completed { error_text: None },
v8::PromiseState::Rejected => {
let result = promise.result(scope);
CompletionState::Completed {
error_text: Some(value_to_error_text(scope, result)),
}
}
}
}
fn script_origin<'s>(
scope: &mut v8::PinScope<'s, '_>,
resource_name_: &str,
) -> Result<v8::ScriptOrigin<'s>, String> {
let resource_name = v8::String::new(scope, resource_name_)
.ok_or_else(|| "failed to allocate script origin".to_string())?;
let source_map_url = v8::String::new(scope, resource_name_)
.ok_or_else(|| "failed to allocate source map url".to_string())?;
Ok(v8::ScriptOrigin::new(
scope,
resource_name.into(),
0,
0,
true,
0,
Some(source_map_url.into()),
true,
false,
true,
None,
))
}
fn resolve_module_callback<'s>(
context: v8::Local<'s, v8::Context>,
specifier: v8::Local<'s, v8::String>,
_import_attributes: v8::Local<'s, v8::FixedArray>,
_referrer: v8::Local<'s, v8::Module>,
) -> Option<v8::Local<'s, v8::Module>> {
v8::callback_scope!(unsafe scope, context);
let specifier = specifier.to_rust_string_lossy(scope);
resolve_module(scope, &specifier)
}
pub(super) fn dynamic_import_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
_host_defined_options: v8::Local<'s, v8::Data>,
_resource_name: v8::Local<'s, v8::Value>,
specifier: v8::Local<'s, v8::String>,
_import_attributes: v8::Local<'s, v8::FixedArray>,
) -> Option<v8::Local<'s, v8::Promise>> {
let specifier = specifier.to_rust_string_lossy(scope);
let resolver = v8::PromiseResolver::new(scope)?;
match resolve_module(scope, &specifier) {
Some(module) => {
if module.get_status() == v8::ModuleStatus::Uninstantiated
&& module
.instantiate_module(scope, resolve_module_callback)
.is_none()
{
let error = v8::String::new(scope, "failed to instantiate module")
.map(Into::into)
.unwrap_or_else(|| v8::undefined(scope).into());
resolver.reject(scope, error);
return Some(resolver.get_promise(scope));
}
if matches!(
module.get_status(),
v8::ModuleStatus::Instantiated | v8::ModuleStatus::Evaluated
) && module.evaluate(scope).is_none()
{
let error = v8::String::new(scope, "failed to evaluate module")
.map(Into::into)
.unwrap_or_else(|| v8::undefined(scope).into());
resolver.reject(scope, error);
return Some(resolver.get_promise(scope));
}
let namespace = module.get_module_namespace();
resolver.resolve(scope, namespace);
Some(resolver.get_promise(scope))
}
None => {
let error = v8::String::new(scope, "unsupported import in exec")
.map(Into::into)
.unwrap_or_else(|| v8::undefined(scope).into());
resolver.reject(scope, error);
Some(resolver.get_promise(scope))
}
}
}
fn resolve_module<'s>(
scope: &mut v8::PinScope<'s, '_>,
specifier: &str,
) -> Option<v8::Local<'s, v8::Module>> {
if let Some(message) =
v8::String::new(scope, &format!("Unsupported import in exec: {specifier}"))
{
scope.throw_exception(message.into());
} else {
scope.throw_exception(v8::undefined(scope).into());
}
None
}
#[cfg(test)]
#[path = "module_loader_tests.rs"]
mod tests;

View File

@@ -0,0 +1,67 @@
//! Checks that tool response delivery preserves live results without rooting discarded values.
use std::collections::HashMap;
use std::sync::mpsc as std_mpsc;
use pretty_assertions::assert_eq;
use serde_json::json;
use tokio::sync::mpsc;
use super::super::RuntimeState;
use super::super::value::v8_value_to_json;
use super::resolve_tool_response;
use crate::v8_init::ensure_v8_initialized;
#[test]
fn discarded_tool_response_is_collectible_before_cell_ends() {
ensure_v8_initialized().expect("initialize V8");
let isolate = &mut v8::Isolate::new(v8::CreateParams::default());
v8::scope!(let scope, isolate);
let context = v8::Context::new(scope, Default::default());
let scope = &mut v8::ContextScope::new(scope, context);
let (event_tx, _event_rx) = mpsc::unbounded_channel();
let (runtime_command_tx, _runtime_command_rx) = std_mpsc::channel();
scope.set_slot(RuntimeState {
event_tx: event_tx.into(),
pending_tool_calls: HashMap::new(),
pending_timeouts: HashMap::new(),
stored_values: HashMap::new(),
stored_value_writes: HashMap::new(),
enabled_tools: Vec::new(),
next_tool_call_id: 1,
next_timeout_id: 1,
tool_call_id: "cell".to_string(),
runtime_command_tx,
exit_requested: false,
});
let promise = {
v8::scope!(let scope, scope);
let resolver = v8::PromiseResolver::new(scope).expect("create tool promise");
let promise = resolver.get_promise(scope);
let resolver = v8::Global::new(scope, resolver);
scope
.get_slot_mut::<RuntimeState>()
.expect("runtime state")
.pending_tool_calls
.insert("tool".to_string(), resolver);
v8::Global::new(scope, promise)
};
let response = json!({"content": [{"type": "text", "text": "tool result"}]});
resolve_tool_response(scope, "tool", Ok(response.clone())).expect("resolve tool promise");
scope.perform_microtask_checkpoint();
scope.low_memory_notification();
let weak_result = {
v8::scope!(let scope, scope);
let promise = v8::Local::new(scope, &promise);
assert_eq!(promise.state(), v8::PromiseState::Fulfilled);
let result = promise.result(scope);
assert_eq!(v8_value_to_json(scope, result), Ok(Some(response)));
v8::Weak::new(scope, result)
};
drop(promise);
scope.low_memory_notification();
assert!(weak_result.is_empty(), "discarded response is still rooted");
}

View File

@@ -0,0 +1,67 @@
// Runtime-owned promise combinators; all state stays in the cell's V8 heap.
// Observe each input once and queue settlements while the consumer is busy.
// Repeated races can lose that order and attach extra reactions to pending inputs.
(() => {
function as_settled(promises) {
let ready = [];
let pending = 0;
let wake;
let closed = false;
function settle(result) {
pending--;
if (closed) return;
ready.push(result);
if (wake) {
const resolve = wake;
wake = undefined;
resolve();
}
}
const keyed = promises instanceof Map;
let position = 0;
try {
for (const entry of promises) {
const [index, promise] = keyed ? entry : [position++, entry];
pending++;
Promise.resolve(promise).then(
(value) => settle({ index, status: "fulfilled", value }),
(reason) => settle({ index, status: "rejected", reason }),
);
}
} catch (error) {
closed = true;
throw error;
}
return (async function* () {
try {
while (pending > 0 || ready.length > 0) {
if (ready.length === 0) {
await new Promise((resolve) => {
wake = resolve;
});
}
const batch = ready;
ready = [];
yield* batch;
}
} finally {
closed = true;
ready = [];
}
})();
}
async function stream_settled(promises, emit) {
if (typeof emit !== "function") {
throw new TypeError("stream_settled requires a callback");
}
for await (const result of as_settled(promises)) {
await emit(result);
}
}
Object.assign(globalThis, { as_settled, stream_settled });
})();

View File

@@ -0,0 +1,128 @@
use std::time::Duration;
use tokio_util::task::AbortOnDropHandle;
use super::RuntimeCommand;
use super::RuntimeState;
use super::value::value_to_error_text;
pub(super) struct ScheduledTimeout {
callback: v8::Global<v8::Function>,
// Clearing the timeout or dropping the isolate also cancels its sleep.
_task: AbortOnDropHandle<()>,
}
pub(super) fn schedule_timeout(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
) -> Result<Option<u64>, String> {
let callback = args.get(0);
if !callback.is_function() {
return Err("setTimeout expects a function callback".to_string());
}
let callback = v8::Local::<v8::Function>::try_from(callback)
.map_err(|_| "setTimeout expects a function callback".to_string())?;
let delay_ms = args
.get(1)
.number_value(scope)
.map(normalize_delay_ms)
.unwrap_or(0);
let callback = v8::Global::new(scope, callback);
let state = scope
.get_slot_mut::<RuntimeState>()
.ok_or_else(|| "runtime state unavailable".to_string())?;
// Converting the delay can execute JavaScript that calls exit().
if state.exit_requested {
return Ok(None);
}
let timeout_id = state.next_timeout_id;
state.next_timeout_id = state.next_timeout_id.saturating_add(1);
let runtime_command_tx = state.runtime_command_tx.clone();
let sleep = tokio::time::sleep(Duration::from_millis(delay_ms));
let task = tokio::spawn(async move {
sleep.await;
let _ = runtime_command_tx.send(RuntimeCommand::TimeoutFired { id: timeout_id });
});
state.pending_timeouts.insert(
timeout_id,
ScheduledTimeout {
callback,
_task: AbortOnDropHandle::new(task),
},
);
Ok(Some(timeout_id))
}
pub(super) fn clear_timeout(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
) -> Result<(), String> {
let Some(timeout_id) = timeout_id_from_args(scope, args)? else {
return Ok(());
};
let Some(state) = scope.get_slot_mut::<RuntimeState>() else {
return Err("runtime state unavailable".to_string());
};
if !state.exit_requested {
state.pending_timeouts.remove(&timeout_id);
}
Ok(())
}
pub(super) fn invoke_timeout_callback(
scope: &mut v8::PinScope<'_, '_>,
timeout_id: u64,
) -> Result<(), String> {
let callback = {
let state = scope
.get_slot_mut::<RuntimeState>()
.ok_or_else(|| "runtime state unavailable".to_string())?;
state.pending_timeouts.remove(&timeout_id)
};
let Some(callback) = callback else {
return Ok(());
};
let tc = std::pin::pin!(v8::TryCatch::new(scope));
let mut tc = tc.init();
let callback = v8::Local::new(&tc, &callback.callback);
let receiver = v8::undefined(&tc).into();
let _ = callback.call(&tc, receiver, &[]);
if tc.has_caught() {
return Err(tc
.exception()
.map(|exception| value_to_error_text(&mut tc, exception))
.unwrap_or_else(|| "unknown code mode exception".to_string()));
}
Ok(())
}
fn timeout_id_from_args(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
) -> Result<Option<u64>, String> {
if args.length() == 0 || args.get(0).is_null_or_undefined() {
return Ok(None);
}
let Some(timeout_id) = args.get(0).number_value(scope) else {
return Err("clearTimeout expects a numeric timeout id".to_string());
};
if !timeout_id.is_finite() || timeout_id <= 0.0 {
return Ok(None);
}
Ok(Some(timeout_id.trunc().min(u64::MAX as f64) as u64))
}
fn normalize_delay_ms(delay_ms: f64) -> u64 {
if !delay_ms.is_finite() || delay_ms <= 0.0 {
0
} else {
delay_ms.trunc().min(u64::MAX as f64) as u64
}
}

View File

@@ -0,0 +1,386 @@
use serde_json::Value as JsonValue;
use crate::session_runtime::OutputItem;
use akode_code_mode_protocol::DEFAULT_IMAGE_DETAIL;
use akode_code_mode_protocol::ImageDetail;
use super::RuntimeState;
use super::audio::wav_duration_seconds;
const IMAGE_HELPER_EXPECTS_MESSAGE: &str = "image expects a non-empty image URL string, an object with image_url and optional detail, or a raw MCP image block";
const AUDIO_HELPER_EXPECTS_MESSAGE: &str = "audio expects a non-empty audio URL string, an object with audio_url, or a raw MCP audio block";
const REMOTE_IMAGE_URL_ERROR: &str = "Tool call failed: remote image URLs are not supported in tool outputs. Pass a base64 data URI instead";
const INVALID_IMAGE_URL_ERROR: &str =
"Tool call failed: invalid image output. Pass a base64 data URI instead";
const INVALID_AUDIO_URL_ERROR: &str =
"Tool call failed: invalid audio output. Pass a base64 data URI instead";
const AKODE_IMAGE_DETAIL_META_KEY: &str = "codex/imageDetail";
pub(super) fn serialize_output_text(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> Result<String, String> {
if value.is_undefined()
|| value.is_null()
|| value.is_boolean()
|| value.is_number()
|| value.is_big_int()
|| value.is_string()
{
return Ok(value.to_rust_string_lossy(scope));
}
let tc = std::pin::pin!(v8::TryCatch::new(scope));
let mut tc = tc.init();
if let Some(stringified) = v8::json::stringify(&tc, value) {
return Ok(stringified.to_rust_string_lossy(&tc));
}
if tc.has_caught() {
return Err(tc
.exception()
.map(|exception| value_to_error_text(&mut tc, exception))
.unwrap_or_else(|| "unknown code mode exception".to_string()));
}
Ok(value.to_rust_string_lossy(&tc))
}
pub(super) fn normalize_output_image(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
detail_override: Option<String>,
) -> Result<OutputItem, ()> {
let result = (|| -> Result<OutputItem, String> {
let (image_url, detail) = if value.is_string() {
(value.to_rust_string_lossy(scope), None)
} else if value.is_object() && !value.is_array() {
let object = v8::Local::<v8::Object>::try_from(value)
.map_err(|_| IMAGE_HELPER_EXPECTS_MESSAGE.to_string())?;
if let Some(image) = parse_non_mcp_output_image(scope, object)? {
image
} else {
parse_mcp_output_image(scope, value)?
}
} else {
return Err(IMAGE_HELPER_EXPECTS_MESSAGE.to_string());
};
if image_url.is_empty() {
return Err(IMAGE_HELPER_EXPECTS_MESSAGE.to_string());
}
let Some((scheme, _)) = image_url.split_once(':') else {
return Err(INVALID_IMAGE_URL_ERROR.to_string());
};
if scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") {
return Err(REMOTE_IMAGE_URL_ERROR.to_string());
}
if !scheme.eq_ignore_ascii_case("data") {
return Err(INVALID_IMAGE_URL_ERROR.to_string());
}
let detail = detail_override.or(detail);
let detail = match detail {
Some(detail) => {
let normalized = detail.to_ascii_lowercase();
Some(match normalized.as_str() {
"auto" => ImageDetail::Auto,
"low" => ImageDetail::Low,
"high" => ImageDetail::High,
"original" => ImageDetail::Original,
_ => {
return Err(
"image detail must be one of: auto, low, high, original".to_string()
);
}
})
}
None => Some(DEFAULT_IMAGE_DETAIL),
};
Ok(OutputItem::InputImage { image_url, detail })
})();
match result {
Ok(item) => Ok(item),
Err(error_text) => {
throw_type_error(scope, &error_text);
Err(())
}
}
}
fn parse_non_mcp_output_image(
scope: &mut v8::PinScope<'_, '_>,
object: v8::Local<'_, v8::Object>,
) -> Result<Option<(String, Option<String>)>, String> {
let image_url_key = v8::String::new(scope, "image_url")
.ok_or_else(|| "failed to allocate image helper keys".to_string())?;
let Some(image_url) = object.get(scope, image_url_key.into()) else {
return Ok(None);
};
if image_url.is_undefined() {
return Ok(None);
}
if !image_url.is_string() {
return Err(IMAGE_HELPER_EXPECTS_MESSAGE.to_string());
}
let detail_key = v8::String::new(scope, "detail")
.ok_or_else(|| "failed to allocate image helper keys".to_string())?;
let detail = parse_image_detail_value(scope, object.get(scope, detail_key.into()))?;
Ok(Some((image_url.to_rust_string_lossy(scope), detail)))
}
fn parse_mcp_output_image(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> Result<(String, Option<String>), String> {
let Some(result) = v8_value_to_json(scope, value)? else {
return Err(IMAGE_HELPER_EXPECTS_MESSAGE.to_string());
};
let JsonValue::Object(result) = result else {
return Err(IMAGE_HELPER_EXPECTS_MESSAGE.to_string());
};
let Some(item_type) = result.get("type").and_then(JsonValue::as_str) else {
return Err(IMAGE_HELPER_EXPECTS_MESSAGE.to_string());
};
if item_type != "image" {
return Err(format!(
"image only accepts MCP image blocks, got \"{item_type}\""
));
}
let data = result
.get("data")
.and_then(JsonValue::as_str)
.ok_or_else(|| "image expected MCP image data".to_string())?;
if data.is_empty() {
return Err("image expected MCP image data".to_string());
}
let image_url = if data.to_ascii_lowercase().starts_with("data:") {
data.to_string()
} else {
let mime_type = result
.get("mimeType")
.or_else(|| result.get("mime_type"))
.and_then(JsonValue::as_str)
.filter(|mime_type| !mime_type.is_empty())
.unwrap_or("application/octet-stream");
format!("data:{mime_type};base64,{data}")
};
let detail = result
.get("_meta")
.and_then(JsonValue::as_object)
.and_then(|meta| meta.get(AKODE_IMAGE_DETAIL_META_KEY))
.and_then(JsonValue::as_str)
.filter(|detail| matches!(*detail, "auto" | "low" | "high" | "original"))
.map(str::to_string);
Ok((image_url, detail))
}
fn parse_image_detail_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
value: Option<v8::Local<'s, v8::Value>>,
) -> Result<Option<String>, String> {
match value {
Some(value) if value.is_string() => Ok(Some(value.to_rust_string_lossy(scope))),
Some(value) if value.is_null() || value.is_undefined() => Ok(None),
Some(_) => Err("image detail must be a string when provided".to_string()),
None => Ok(None),
}
}
pub(super) fn normalize_output_audio(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> Result<OutputItem, ()> {
let result = (|| -> Result<OutputItem, String> {
let audio_url = if value.is_string() {
value.to_rust_string_lossy(scope)
} else if value.is_object() && !value.is_array() {
let object = v8::Local::<v8::Object>::try_from(value)
.map_err(|_| AUDIO_HELPER_EXPECTS_MESSAGE.to_string())?;
if let Some(audio_url) = parse_non_mcp_output_audio(scope, object)? {
audio_url
} else {
parse_mcp_output_audio(scope, value)?
}
} else {
return Err(AUDIO_HELPER_EXPECTS_MESSAGE.to_string());
};
if audio_url.is_empty() {
return Err(AUDIO_HELPER_EXPECTS_MESSAGE.to_string());
}
let Some((scheme, _)) = audio_url.split_once(':') else {
return Err(INVALID_AUDIO_URL_ERROR.to_string());
};
if !scheme.eq_ignore_ascii_case("data") {
return Err(INVALID_AUDIO_URL_ERROR.to_string());
}
// Tiny tool-generated clips cannot be encoded reliably by audio models.
if wav_duration_seconds(&audio_url).is_some_and(|duration| duration < 0.025) {
return Ok(OutputItem::InputText {
text: "Audio output omitted because the clip is shorter than 25 ms; use a longer clip."
.to_string(),
});
}
Ok(OutputItem::InputAudio { audio_url })
})();
match result {
Ok(item) => Ok(item),
Err(error_text) => {
throw_type_error(scope, &error_text);
Err(())
}
}
}
fn parse_non_mcp_output_audio(
scope: &mut v8::PinScope<'_, '_>,
object: v8::Local<'_, v8::Object>,
) -> Result<Option<String>, String> {
let audio_url_key = v8::String::new(scope, "audio_url")
.ok_or_else(|| "failed to allocate audio helper keys".to_string())?;
let Some(audio_url) = object.get(scope, audio_url_key.into()) else {
return Ok(None);
};
if audio_url.is_undefined() {
return Ok(None);
}
if !audio_url.is_string() {
return Err(AUDIO_HELPER_EXPECTS_MESSAGE.to_string());
}
Ok(Some(audio_url.to_rust_string_lossy(scope)))
}
fn parse_mcp_output_audio(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> Result<String, String> {
let Some(result) = v8_value_to_json(scope, value)? else {
return Err(AUDIO_HELPER_EXPECTS_MESSAGE.to_string());
};
let JsonValue::Object(result) = result else {
return Err(AUDIO_HELPER_EXPECTS_MESSAGE.to_string());
};
let Some(item_type) = result.get("type").and_then(JsonValue::as_str) else {
return Err(AUDIO_HELPER_EXPECTS_MESSAGE.to_string());
};
if item_type != "audio" {
return Err(format!(
"audio only accepts MCP audio blocks, got \"{item_type}\""
));
}
let data = result
.get("data")
.and_then(JsonValue::as_str)
.ok_or_else(|| "audio expected MCP audio data".to_string())?;
if data.is_empty() {
return Err("audio expected MCP audio data".to_string());
}
if data.to_ascii_lowercase().starts_with("data:") {
Ok(data.to_string())
} else {
let mime_type = result
.get("mimeType")
.or_else(|| result.get("mime_type"))
.and_then(JsonValue::as_str)
.filter(|mime_type| !mime_type.is_empty())
.unwrap_or("application/octet-stream");
Ok(format!("data:{mime_type};base64,{data}"))
}
}
pub(super) fn v8_value_to_json(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> Result<Option<JsonValue>, String> {
// Reentering V8 during termination can replace it with a catchable exception.
if scope.is_execution_terminating() {
return Err("JavaScript execution terminated".to_string());
}
// V8 stringifies undefined as the non-JSON text "undefined".
if value.is_undefined() {
return Ok(None);
}
let tc = std::pin::pin!(v8::TryCatch::new(scope));
let mut tc = tc.init();
let Some(stringified) = v8::json::stringify(&tc, value) else {
if tc.has_caught() {
return Err(tc
.exception()
.map(|exception| value_to_error_text(&mut tc, exception))
.unwrap_or_else(|| "unknown code mode exception".to_string()));
}
return Ok(None);
};
let json = stringified.to_rust_string_lossy(&tc);
// V8 emits compact JSON with these ASCII key names unescaped. The object/comma
// prefix and colon distinguish keys from string contents. Reject these before
// Serde can reinterpret them as values and bypass its normal recursion limit.
// TODO(cconger): Remove this guard once our resolved serde_json dependency
// includes the upstream private-key provenance fix. Retain regression coverage
// for literal keys, depth limits, and session recovery.
// https://github.com/cconger/json/commit/63f6f14053ef3a173013d7e5ee5ac74140736929
if [
r#"{"$serde_json::private::RawValue":"#,
r#","$serde_json::private::RawValue":"#,
r#"{"$serde_json::private::Number":"#,
r#","$serde_json::private::Number":"#,
]
.into_iter()
.any(|key| json.contains(key))
{
return Err("failed to serialize JavaScript value: reserved JSON object key".to_string());
}
serde_json::from_str(&json)
.map(Some)
.map_err(|err| format!("failed to serialize JavaScript value: {err}"))
}
pub(super) fn json_to_v8<'s>(
scope: &mut v8::PinScope<'s, '_>,
value: &JsonValue,
) -> Option<v8::Local<'s, v8::Value>> {
let json = serde_json::to_string(value).ok()?;
let json = v8::String::new(scope, &json)?;
v8::json::parse(scope, json)
}
pub(super) fn value_to_error_text(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> String {
if value.is_object()
&& let Ok(object) = v8::Local::<v8::Object>::try_from(value)
&& let Some(key) = v8::String::new(scope, "stack")
&& let Some(stack) = object.get(scope, key.into())
&& stack.is_string()
{
return stack.to_rust_string_lossy(scope);
}
// The stack getter can call exit() and V8 can clear its termination before
// returning here. Never enter a user-defined toString() after that.
if scope
.get_slot::<RuntimeState>()
.is_some_and(|state| state.exit_requested)
{
// send_scope_result reports this as successful exit and preserves prior stores.
return String::new();
}
value.to_rust_string_lossy(scope)
}
pub(super) fn throw_type_error(scope: &mut v8::PinScope<'_, '_>, message: &str) {
// Preserve V8's uncatchable termination instead of replacing it with a JS error.
if scope.is_execution_terminating() {
return;
}
if let Some(message) = v8::String::new(scope, message) {
scope.throw_exception(message.into());
}
}

View File

@@ -0,0 +1,518 @@
use std::sync::Arc;
use std::time::Duration;
use akode_code_mode_protocol::CellId;
use akode_code_mode_protocol::CodeModeNestedToolCall;
use akode_code_mode_protocol::CodeModeOutputTruncation;
use akode_code_mode_protocol::CodeModeSession;
use akode_code_mode_protocol::CodeModeSessionCellExecutionLimits;
use akode_code_mode_protocol::CodeModeSessionDelegate;
use akode_code_mode_protocol::CodeModeSessionOptions;
use akode_code_mode_protocol::CodeModeSessionResultFuture;
use akode_code_mode_protocol::CodeModeToolKind;
use akode_code_mode_protocol::DEFAULT_EXEC_YIELD_TIME_MS;
use akode_code_mode_protocol::ExecuteRequest;
use akode_code_mode_protocol::ExecuteToPendingOutcome;
use akode_code_mode_protocol::FunctionCallOutputContentItem;
use akode_code_mode_protocol::RuntimeResponse;
use akode_code_mode_protocol::StartedCell;
use akode_code_mode_protocol::TerminateRequest;
use akode_code_mode_protocol::WaitOutcome;
use akode_code_mode_protocol::WaitRequest;
use akode_code_mode_protocol::WaitToPendingOutcome;
use akode_code_mode_protocol::WaitToPendingRequest;
use serde_json::Value as JsonValue;
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use crate::TaskFailureHandler;
use crate::cell_actor::take_completed_event;
use crate::output::OutputCollector;
use crate::session_runtime as runtime;
use crate::session_runtime::SessionRuntime;
const YIELD_GRACE_PERIOD: Duration = Duration::from_secs(1);
const MIN_YIELD_TIME_FOR_GRACE: Duration = Duration::from_secs(10);
pub struct InProcessCodeModeSession {
runtime: SessionRuntime,
options: CodeModeSessionOptions,
}
impl InProcessCodeModeSession {
pub fn new() -> Self {
Self::with_limits(CodeModeSessionCellExecutionLimits::default())
}
pub fn with_limits(cell_execution_limits: CodeModeSessionCellExecutionLimits) -> Self {
Self::with_options(
CodeModeSessionOptions {
cell_execution_limits,
..CodeModeSessionOptions::default()
},
/*task_failure_handler*/ None,
)
}
/// Select output handling at creation. A session's mode must remain fixed
/// for all of its cells and observations.
pub fn with_options(
options: CodeModeSessionOptions,
task_failure_handler: Option<TaskFailureHandler>,
) -> Self {
Self {
runtime: SessionRuntime::new_with_task_failure_handler(task_failure_handler),
options: CodeModeSessionOptions {
cell_execution_limits: CodeModeSessionCellExecutionLimits {
max_heap_size_bytes: None,
..options.cell_execution_limits
},
..options
},
}
}
pub async fn execute(
&self,
request: ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
preempt: Option<CancellationToken>,
) -> Result<StartedCell, String> {
let yield_time_ms = request.yield_time_ms.unwrap_or(DEFAULT_EXEC_YIELD_TIME_MS);
let max_output_tokens = request.max_output_tokens;
let output_truncation = self.options.output_truncation;
let started = self
.runtime
.execute(
runtime_request(request, self.options.output_truncation),
runtime::ObserveMode::YieldAfter(self.resolve_yield_timeout(yield_time_ms))
.with_yield_signal(preempt.unwrap_or_default()),
Arc::new(ProtocolDelegate { delegate }),
)
.await
.map_err(|error| error.to_string())?;
let cell_id = protocol_cell_id(&started.cell_id);
let response_cell_id = cell_id.clone();
let (response_tx, response_rx) = oneshot::channel();
tokio::spawn(async move {
let response = started
.initial_event()
.await
.map_err(|error| error.to_string())
.and_then(|event| {
runtime_response(
&response_cell_id,
event,
output_truncation,
max_output_tokens,
)
});
let _ = response_tx.send(response);
});
Ok(StartedCell::from_result_receiver(cell_id, response_rx))
}
pub async fn execute_to_pending(
&self,
request: ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
) -> Result<ExecuteToPendingOutcome, String> {
let max_output_tokens = request.max_output_tokens;
let started = self
.runtime
.execute(
runtime_request(request, self.options.output_truncation),
runtime::ObserveMode::PendingFrontier,
Arc::new(ProtocolDelegate { delegate }),
)
.await
.map_err(|error| error.to_string())?;
let cell_id = protocol_cell_id(&started.cell_id);
let event = started
.initial_event()
.await
.map_err(|error| error.to_string())?;
pending_outcome(
&cell_id,
event,
self.options.output_truncation,
max_output_tokens,
)
}
pub async fn wait(
&self,
request: WaitRequest,
preempt: Option<CancellationToken>,
) -> Result<WaitOutcome, String> {
self.begin_wait(request, preempt).await.await
}
async fn begin_wait(
&self,
request: WaitRequest,
preempt: Option<CancellationToken>,
) -> CodeModeSessionResultFuture<'static, WaitOutcome> {
let WaitRequest {
cell_id,
yield_time_ms,
max_output_tokens,
} = request;
let output_truncation = self.options.output_truncation;
let runtime_cell_id = runtime_cell_id(&cell_id);
match self
.runtime
.begin_observe(
&runtime_cell_id,
runtime::ObserveMode::YieldAfter(self.resolve_yield_timeout(yield_time_ms))
.with_yield_signal(preempt.unwrap_or_default()),
)
.await
{
Ok(pending_event) => Box::pin(async move {
match pending_event.event().await {
Ok(event) => Ok(WaitOutcome::LiveCell(runtime_response(
&cell_id,
event,
output_truncation,
max_output_tokens,
)?)),
Err(runtime::Error::MissingCell(_) | runtime::Error::ClosedCell(_)) => {
Ok(WaitOutcome::MissingCell(missing_cell_response(
cell_id,
output_truncation,
max_output_tokens,
)?))
}
Err(error) => Err(error.to_string()),
}
}),
Err(runtime::Error::MissingCell(_) | runtime::Error::ClosedCell(_)) => {
missing_wait(cell_id, output_truncation, max_output_tokens)
}
Err(error) => Box::pin(async move { Err(error.to_string()) }),
}
}
pub async fn terminate(&self, request: TerminateRequest) -> Result<WaitOutcome, String> {
let TerminateRequest {
cell_id,
max_output_tokens,
} = request;
match self.runtime.terminate(&runtime_cell_id(&cell_id)).await {
Ok(event) => Ok(WaitOutcome::LiveCell(runtime_response(
&cell_id,
event,
self.options.output_truncation,
max_output_tokens,
)?)),
Err(runtime::Error::MissingCell(_) | runtime::Error::ClosedCell(_)) => {
Ok(WaitOutcome::MissingCell(missing_cell_response(
cell_id,
self.options.output_truncation,
max_output_tokens,
)?))
}
Err(error) => Err(error.to_string()),
}
}
pub async fn wait_to_pending(
&self,
request: WaitToPendingRequest,
) -> Result<WaitToPendingOutcome, String> {
let cell_id = request.cell_id;
match self
.runtime
.observe(
&runtime_cell_id(&cell_id),
runtime::ObserveMode::PendingFrontier,
)
.await
{
Ok(event) => Ok(WaitToPendingOutcome::LiveCell(pending_outcome(
&cell_id,
event,
self.options.output_truncation,
/*max_output_tokens*/ None,
)?)),
Err(runtime::Error::MissingCell(_) | runtime::Error::ClosedCell(_)) => {
Ok(WaitToPendingOutcome::MissingCell(missing_cell_response(
cell_id,
self.options.output_truncation,
/*max_output_tokens*/ None,
)?))
}
Err(error) => Err(error.to_string()),
}
}
pub async fn shutdown(&self) -> Result<(), String> {
self.runtime
.shutdown()
.await
.map_err(|error| error.to_string())
}
fn resolve_yield_timeout(&self, yield_time_ms: u64) -> Duration {
let yield_time = Duration::from_millis(yield_time_ms);
let timeout = if yield_time >= MIN_YIELD_TIME_FOR_GRACE {
yield_time.saturating_add(YIELD_GRACE_PERIOD)
} else {
yield_time
};
self.options
.cell_execution_limits
.max_yield_time_ms
.map(Duration::from_millis)
.map_or(timeout, |limit| timeout.min(limit))
}
}
impl Default for InProcessCodeModeSession {
fn default() -> Self {
Self::new()
}
}
impl CodeModeSession for InProcessCodeModeSession {
fn output_truncation(&self) -> CodeModeOutputTruncation {
self.options.output_truncation
}
fn execute<'a>(
&'a self,
request: ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
preempt: Option<CancellationToken>,
) -> CodeModeSessionResultFuture<'a, StartedCell> {
Box::pin(InProcessCodeModeSession::execute(
self, request, delegate, preempt,
))
}
fn wait<'a>(
&'a self,
request: WaitRequest,
preempt: Option<CancellationToken>,
) -> CodeModeSessionResultFuture<'a, WaitOutcome> {
Box::pin(InProcessCodeModeSession::wait(self, request, preempt))
}
fn terminate<'a>(
&'a self,
request: TerminateRequest,
) -> CodeModeSessionResultFuture<'a, WaitOutcome> {
Box::pin(InProcessCodeModeSession::terminate(self, request))
}
fn shutdown<'a>(&'a self) -> CodeModeSessionResultFuture<'a, ()> {
Box::pin(InProcessCodeModeSession::shutdown(self))
}
}
struct ProtocolDelegate {
delegate: Arc<dyn CodeModeSessionDelegate>,
}
impl runtime::SessionRuntimeDelegate for ProtocolDelegate {
#[tracing::instrument(
name = "code_mode.runtime.invoke_tool",
level = "info",
skip_all,
fields(
cell.id = %invocation.cell_id,
runtime_tool_call_id = invocation.runtime_tool_call_id.as_str(),
tool_name = invocation.tool_name.name.as_str(),
tool_namespace = invocation.tool_name.namespace.as_deref(),
)
)]
async fn invoke_tool(
&self,
invocation: runtime::NestedToolCall,
cancellation_token: CancellationToken,
) -> Result<JsonValue, String> {
self.delegate
.invoke_tool(
CodeModeNestedToolCall {
cell_id: protocol_cell_id(&invocation.cell_id),
runtime_tool_call_id: invocation.runtime_tool_call_id,
tool_name: akode_protocol::ToolName {
name: invocation.tool_name.name,
namespace: invocation.tool_name.namespace,
},
tool_kind: match invocation.tool_kind {
runtime::ToolKind::Function => CodeModeToolKind::Function,
runtime::ToolKind::Freeform => CodeModeToolKind::Freeform,
},
input: invocation.input,
},
cancellation_token,
)
.await
}
async fn notify(
&self,
call_id: String,
cell_id: runtime::CellId,
text: String,
cancellation_token: CancellationToken,
) -> Result<(), String> {
self.delegate
.notify(
call_id,
protocol_cell_id(&cell_id),
text,
cancellation_token,
)
.await
}
fn cell_closed(&self, cell_id: &runtime::CellId) {
self.delegate.cell_closed(&protocol_cell_id(cell_id));
}
}
fn runtime_request(
request: ExecuteRequest,
output_truncation: CodeModeOutputTruncation,
) -> runtime::CreateCellRequest {
runtime::CreateCellRequest {
output_truncation,
tool_call_id: request.tool_call_id,
enabled_tools: request
.enabled_tools
.into_iter()
.map(|definition| runtime::ToolDefinition {
name: definition.name,
tool_name: runtime::ToolName {
name: definition.tool_name.name,
namespace: definition.tool_name.namespace,
},
description: definition.description,
kind: match definition.kind {
CodeModeToolKind::Function => runtime::ToolKind::Function,
CodeModeToolKind::Freeform => runtime::ToolKind::Freeform,
},
})
.collect(),
source: request.source,
}
}
fn runtime_cell_id(cell_id: &CellId) -> runtime::CellId {
runtime::CellId::new(cell_id.as_str())
}
fn protocol_cell_id(cell_id: &runtime::CellId) -> CellId {
CellId::new(cell_id.as_str().to_string())
}
fn pending_outcome(
cell_id: &CellId,
event: runtime::CellEvent,
output_truncation: CodeModeOutputTruncation,
max_output_tokens: Option<usize>,
) -> Result<ExecuteToPendingOutcome, String> {
match event {
runtime::CellEvent::Pending {
content_items,
pending_tool_call_ids,
} => Ok(ExecuteToPendingOutcome::Pending {
cell_id: cell_id.clone(),
content_items: rendered_items(content_items, output_truncation, max_output_tokens),
pending_tool_call_ids,
}),
event => Ok(ExecuteToPendingOutcome::Completed(runtime_response(
cell_id,
event,
output_truncation,
max_output_tokens,
)?)),
}
}
fn runtime_response(
cell_id: &CellId,
event: runtime::CellEvent,
output_truncation: CodeModeOutputTruncation,
max_output_tokens: Option<usize>,
) -> Result<RuntimeResponse, String> {
match event {
runtime::CellEvent::Yielded { content_items } => Ok(RuntimeResponse::Yielded {
cell_id: cell_id.clone(),
content_items: rendered_items(content_items, output_truncation, max_output_tokens),
code_mode_host_duration: None,
}),
runtime::CellEvent::Completed {
content_items,
error_text,
result_buffered_for,
} => Ok(RuntimeResponse::Result {
cell_id: cell_id.clone(),
content_items: rendered_items(content_items, output_truncation, max_output_tokens),
error_text,
result_buffered_for,
code_mode_host_duration: None,
}),
runtime::CellEvent::Terminated { content_items } => Ok(RuntimeResponse::Terminated {
cell_id: cell_id.clone(),
content_items: rendered_items(content_items, output_truncation, max_output_tokens),
code_mode_host_duration: None,
}),
runtime::CellEvent::Pending { .. } => {
Err("cell returned a pending frontier unexpectedly".to_string())
}
}
}
fn rendered_items(
items: OutputCollector,
mode: CodeModeOutputTruncation,
max_output_tokens: Option<usize>,
) -> Vec<FunctionCallOutputContentItem> {
let items = items.into_collected_output();
match mode {
CodeModeOutputTruncation::Client => items.into_untruncated_items(),
CodeModeOutputTruncation::Server => crate::output::render_output(items, max_output_tokens),
}
}
fn missing_cell_response(
cell_id: CellId,
mode: CodeModeOutputTruncation,
max_output_tokens: Option<usize>,
) -> Result<RuntimeResponse, String> {
let error_text = format!("exec cell {cell_id} not found");
let mut output = OutputCollector::new(mode);
let event = take_completed_event(&mut output, Some(error_text));
runtime_response(&cell_id, event, mode, max_output_tokens)
}
fn missing_wait(
cell_id: CellId,
mode: CodeModeOutputTruncation,
max_output_tokens: Option<usize>,
) -> CodeModeSessionResultFuture<'static, WaitOutcome> {
Box::pin(async move {
Ok(WaitOutcome::MissingCell(missing_cell_response(
cell_id,
mode,
max_output_tokens,
)?))
})
}
#[cfg(test)]
#[path = "service_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "service_contract_tests.rs"]
mod contract_tests;
#[cfg(test)]
#[path = "service_output_collection_tests.rs"]
mod output_collection_tests;

View File

@@ -0,0 +1,215 @@
//! Covers short-WAV handling and Server audio output alongside other Code Mode outputs.
use super::cell_id;
use super::execute;
use super::execute_request;
use crate::ExecuteRequest;
use crate::FunctionCallOutputContentItem;
use crate::InProcessCodeModeSession;
use crate::RuntimeResponse;
use crate::WaitOutcome;
use crate::WaitRequest;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use akode_code_mode_protocol::CodeModeOutputTruncation;
use akode_code_mode_protocol::CodeModeSessionOptions;
use akode_code_mode_protocol::host::BOUNDED_OUTPUT_MAX_BYTES;
use pretty_assertions::assert_eq;
const SHORT_AUDIO_OMISSION_TEXT: &str =
"Audio output omitted because the clip is shorter than 25 ms; use a longer clip.";
fn pcm16_wav(sample_rate: u32, frames: usize) -> Vec<u8> {
let data_size = u32::try_from(frames * 2).unwrap();
let mut wav = b"RIFF".to_vec();
wav.extend_from_slice(&(36 + data_size).to_le_bytes());
wav.extend_from_slice(b"WAVEfmt ");
wav.extend_from_slice(&16_u32.to_le_bytes());
wav.extend_from_slice(&1_u16.to_le_bytes());
wav.extend_from_slice(&1_u16.to_le_bytes());
wav.extend_from_slice(&sample_rate.to_le_bytes());
wav.extend_from_slice(&(sample_rate * 2).to_le_bytes());
wav.extend_from_slice(&2_u16.to_le_bytes());
wav.extend_from_slice(&16_u16.to_le_bytes());
wav.extend_from_slice(b"data");
wav.extend_from_slice(&data_size.to_le_bytes());
wav.resize(44 + frames * 2, /*value*/ 0);
wav
}
#[tokio::test]
async fn audio_helper_omits_short_wav_in_all_input_forms() {
for (sample_rate, frames, omitted) in [
(24_000, 0, true),
(24_000, 1, true),
(24_000, 599, true),
(24_000, 600, false),
(24_000, 601, false),
(44_100, 223, true),
(44_100, 1_102, true),
(44_100, 1_103, false),
(30_870, 223, true),
(30_870, 771, true),
(30_870, 772, false),
(34_398, 221, true),
(34_398, 859, true),
(34_398, 860, false),
] {
let payload = BASE64_STANDARD.encode(pcm16_wav(sample_rate, frames));
let audio_url = format!("data:audio/wav;base64,{payload}");
let service = InProcessCodeModeSession::new();
let response = execute(
&service,
ExecuteRequest {
source: format!(
r#"audio({audio_url:?}); audio({{audio_url:{audio_url:?}}});
audio({{type:"audio",mimeType:"audio/wav",data:{payload:?}}});"#
),
yield_time_ms: None,
..execute_request("")
},
)
.await;
let expected = if omitted {
FunctionCallOutputContentItem::InputText {
text: SHORT_AUDIO_OMISSION_TEXT.to_string(),
}
} else {
FunctionCallOutputContentItem::InputAudio { audio_url }
};
assert_eq!(
response,
RuntimeResponse::Result {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: vec![expected; 3],
result_buffered_for: std::time::Duration::ZERO,
error_text: None,
},
"sample rate {sample_rate}, frames {frames}"
);
}
}
#[tokio::test]
async fn audio_helper_bounds_wav_data_and_preserves_outputs_after_yield() {
let mut metadata_short = pcm16_wav(/*sample_rate*/ 24_000, /*frames*/ 1);
let mut valid = pcm16_wav(/*sample_rate*/ 24_000, /*frames*/ 600);
let mut list = b"LIST".to_vec();
list.extend_from_slice(&(4_u32 + 8 + 2048).to_le_bytes());
list.extend_from_slice(b"INFOINAM");
list.extend_from_slice(&2048_u32.to_le_bytes());
list.resize(8 + 4 + 8 + 2048, /*value*/ 0);
list.extend_from_slice(b"JUNK\x01\0\0\0x\0");
for wav in [&mut metadata_short, &mut valid] {
drop(wav.splice(36..36, list.iter().copied()));
let riff_size = u32::try_from(wav.len() - 8).unwrap();
wav[4..8].copy_from_slice(&riff_size.to_le_bytes());
}
let mut truncated = pcm16_wav(/*sample_rate*/ 24_000, /*frames*/ 0);
truncated[4..8].copy_from_slice(&48_036_u32.to_le_bytes());
truncated[40..44].copy_from_slice(&48_000_u32.to_le_bytes());
let mut bounded = pcm16_wav(/*sample_rate*/ 24_000, /*frames*/ 600);
bounded[40..44].copy_from_slice(&2_u32.to_le_bytes());
let urls = [metadata_short, truncated, bounded, valid]
.map(|wav| format!("data:audio/wav;base64,{}", BASE64_STANDARD.encode(wav)));
let audio_urls = serde_json::to_string(&urls).unwrap();
let service = InProcessCodeModeSession::new();
let response = execute(
&service,
ExecuteRequest {
source: format!(
"text('before'); await yield_control(); \
for (const audio_url of {audio_urls}) audio({{audio_url}}); text('after');"
),
yield_time_ms: None,
..execute_request("")
},
)
.await;
assert_eq!(
response,
RuntimeResponse::Yielded {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: vec![FunctionCallOutputContentItem::InputText {
text: "before".to_string(),
}],
}
);
let mut expected = vec![
FunctionCallOutputContentItem::InputText {
text: SHORT_AUDIO_OMISSION_TEXT.to_string(),
};
3
];
expected.push(FunctionCallOutputContentItem::InputAudio {
audio_url: urls[3].clone(),
});
expected.push(FunctionCallOutputContentItem::InputText {
text: "after".to_string(),
});
let actual = service
.wait(
WaitRequest {
max_output_tokens: None,
cell_id: cell_id("1"),
yield_time_ms: 60_000,
},
/*preempt*/ None,
)
.await
.unwrap();
assert_eq!(
actual,
WaitOutcome::LiveCell(RuntimeResponse::Result {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: expected,
result_buffered_for: actual.result_buffered_for().unwrap(),
error_text: None,
})
);
}
#[tokio::test]
async fn server_omits_audio_above_the_text_allowance_at_zero_tokens() {
let session = InProcessCodeModeSession::with_options(
CodeModeSessionOptions {
output_truncation: CodeModeOutputTruncation::Server,
..CodeModeSessionOptions::default()
},
/*task_failure_handler*/ None,
);
// Each clip exceeds the text allowance, but the clips fit the separate
// audio allowance and reach the zero-token formatter.
let wav = pcm16_wav(/*sample_rate*/ 24_000, BOUNDED_OUTPUT_MAX_BYTES / 2);
let payload = BASE64_STANDARD.encode(wav);
let source = format!(
"const clip = 'data:audio/wav;base64,{payload}'; for (let i = 0; i < 6; i++) {{ audio(clip); text(''); }}"
);
let response = execute(
&session,
ExecuteRequest {
yield_time_ms: Some(60_000),
max_output_tokens: Some(0),
..execute_request(&source)
},
)
.await;
let RuntimeResponse::Result {
content_items,
error_text,
..
} = response
else {
panic!("expected completed cell");
};
assert_eq!(error_text, None);
assert_eq!(
content_items,
[FunctionCallOutputContentItem::InputText {
text: "[omitted 6 audio items ...]".to_owned(),
}]
);
}

View File

@@ -0,0 +1,674 @@
use akode_code_mode_protocol::NoopCodeModeSessionDelegate;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use akode_code_mode_protocol::NotificationFuture;
use akode_code_mode_protocol::ToolInvocationFuture;
use akode_protocol::ToolName;
use pretty_assertions::assert_eq;
use tokio::sync::Notify;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use super::*;
use crate::CodeModeToolKind;
use crate::ToolDefinition;
#[derive(Debug, PartialEq)]
enum DelegateEvent {
NotificationStarted,
NotificationCancelled,
ToolStarted,
ToolCancelled,
CellClosed(CellId),
}
struct BlockingDelegate {
events_tx: mpsc::UnboundedSender<DelegateEvent>,
notification_finished: AtomicBool,
tool_finished: AtomicBool,
tool_release: Notify,
}
struct HeldNotificationDelegate {
events_tx: mpsc::UnboundedSender<DelegateEvent>,
notification_release: Notify,
}
impl HeldNotificationDelegate {
fn new() -> (Arc<Self>, mpsc::UnboundedReceiver<DelegateEvent>) {
let (events_tx, events_rx) = mpsc::unbounded_channel();
(
Arc::new(Self {
events_tx,
notification_release: Notify::new(),
}),
events_rx,
)
}
fn release_notification(&self) {
self.notification_release.notify_one();
}
}
impl CodeModeSessionDelegate for HeldNotificationDelegate {
fn invoke_tool<'a>(
&'a self,
_invocation: CodeModeNestedToolCall,
cancellation_token: CancellationToken,
) -> ToolInvocationFuture<'a> {
Box::pin(async move {
cancellation_token.cancelled().await;
Err("cancelled".to_string())
})
}
fn notify<'a>(
&'a self,
_call_id: String,
_cell_id: CellId,
_text: String,
cancellation_token: CancellationToken,
) -> NotificationFuture<'a> {
Box::pin(async move {
let _ = self.events_tx.send(DelegateEvent::NotificationStarted);
cancellation_token.cancelled().await;
let _ = self.events_tx.send(DelegateEvent::NotificationCancelled);
self.notification_release.notified().await;
Ok(())
})
}
fn cell_closed(&self, cell_id: &CellId) {
let _ = self
.events_tx
.send(DelegateEvent::CellClosed(cell_id.clone()));
}
}
impl BlockingDelegate {
fn new() -> (Arc<Self>, mpsc::UnboundedReceiver<DelegateEvent>) {
let (events_tx, events_rx) = mpsc::unbounded_channel();
(
Arc::new(Self {
events_tx,
notification_finished: AtomicBool::new(false),
tool_finished: AtomicBool::new(false),
tool_release: Notify::new(),
}),
events_rx,
)
}
fn release_tool(&self) {
self.tool_release.notify_one();
}
}
impl CodeModeSessionDelegate for BlockingDelegate {
fn invoke_tool<'a>(
&'a self,
_invocation: CodeModeNestedToolCall,
cancellation_token: CancellationToken,
) -> ToolInvocationFuture<'a> {
Box::pin(async move {
let _ = self.events_tx.send(DelegateEvent::ToolStarted);
tokio::select! {
_ = self.tool_release.notified() => {
self.tool_finished.store(true, Ordering::Release);
Ok(serde_json::Value::Null)
}
_ = cancellation_token.cancelled() => {
self.tool_finished.store(true, Ordering::Release);
let _ = self.events_tx.send(DelegateEvent::ToolCancelled);
Err("cancelled".to_string())
}
}
})
}
fn notify<'a>(
&'a self,
_call_id: String,
_cell_id: CellId,
_text: String,
cancellation_token: CancellationToken,
) -> NotificationFuture<'a> {
Box::pin(async move {
let _ = self.events_tx.send(DelegateEvent::NotificationStarted);
cancellation_token.cancelled().await;
self.notification_finished.store(true, Ordering::Release);
let _ = self.events_tx.send(DelegateEvent::NotificationCancelled);
Err("cancelled".to_string())
})
}
fn cell_closed(&self, cell_id: &CellId) {
let _ = self
.events_tx
.send(DelegateEvent::CellClosed(cell_id.clone()));
}
}
fn cell_id(value: &str) -> CellId {
CellId::new(value.to_string())
}
fn execute_request(source: &str) -> ExecuteRequest {
ExecuteRequest {
tool_call_id: "call-1".to_string(),
enabled_tools: Vec::new(),
source: source.to_string(),
yield_time_ms: Some(1),
max_output_tokens: None,
}
}
fn blocking_tool() -> ToolDefinition {
ToolDefinition {
name: "block".to_string(),
tool_name: ToolName::plain("block"),
description: String::new(),
kind: CodeModeToolKind::Function,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
}
}
async fn next_event(events_rx: &mut mpsc::UnboundedReceiver<DelegateEvent>) -> DelegateEvent {
tokio::time::timeout(Duration::from_secs(2), events_rx.recv())
.await
.expect("delegate event timeout")
.expect("delegate event channel closed")
}
#[tokio::test]
async fn yielded_cells_retain_their_own_delegate_until_closed() {
let service = InProcessCodeModeSession::new();
let (delegate_a, mut events_a) = BlockingDelegate::new();
let (delegate_b, mut events_b) = BlockingDelegate::new();
let weak_a = Arc::downgrade(&delegate_a);
let request = ExecuteRequest {
enabled_tools: vec![blocking_tool()],
..execute_request("await tools.block({}); await tools.block({});")
};
let a = service
.execute(request.clone(), delegate_a.clone(), /*preempt*/ None)
.await
.unwrap();
assert_eq!(next_event(&mut events_a).await, DelegateEvent::ToolStarted);
assert!(matches!(
a.initial_response().await.unwrap(),
RuntimeResponse::Yielded { .. }
));
let b = service
.execute(request, delegate_b.clone(), /*preempt*/ None)
.await
.unwrap();
assert_eq!(next_event(&mut events_b).await, DelegateEvent::ToolStarted);
assert!(matches!(
b.initial_response().await.unwrap(),
RuntimeResponse::Yielded { .. }
));
// A's next callback must still reach A after B has started in the same session.
delegate_a.release_tool();
assert_eq!(next_event(&mut events_a).await, DelegateEvent::ToolStarted);
delegate_a.release_tool();
let actual = service
.wait(
WaitRequest {
max_output_tokens: None,
cell_id: cell_id("1"),
yield_time_ms: 60_000,
},
/*preempt*/ None,
)
.await
.unwrap();
assert_eq!(
actual,
WaitOutcome::LiveCell(RuntimeResponse::Result {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: Vec::new(),
result_buffered_for: actual.result_buffered_for().unwrap(),
error_text: None
})
);
assert_eq!(
next_event(&mut events_a).await,
DelegateEvent::CellClosed(cell_id("1"))
);
drop(delegate_a);
assert_eq!(
tokio::time::timeout(Duration::from_secs(2), events_a.recv())
.await
.unwrap(),
None
);
assert!(weak_a.upgrade().is_none());
service.terminate(cell_id("2").into()).await.unwrap();
assert_eq!(
next_event(&mut events_b).await,
DelegateEvent::ToolCancelled
);
assert_eq!(
next_event(&mut events_b).await,
DelegateEvent::CellClosed(cell_id("2"))
);
}
#[tokio::test]
async fn yields_and_resumes() {
let service = InProcessCodeModeSession::new();
let cell = service
.execute(
ExecuteRequest {
source: r#"text("before"); yield_control(); text("after");"#.to_string(),
yield_time_ms: Some(60_000),
..execute_request("")
},
Arc::new(NoopCodeModeSessionDelegate),
/*preempt*/ None,
)
.await
.unwrap();
assert_eq!(
cell.initial_response().await.unwrap(),
RuntimeResponse::Yielded {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: vec![FunctionCallOutputContentItem::InputText {
text: "before".to_string(),
}],
}
);
let actual = service
.wait(
WaitRequest {
max_output_tokens: None,
cell_id: cell_id("1"),
yield_time_ms: 60_000,
},
/*preempt*/ None,
)
.await
.unwrap();
assert_eq!(
actual,
WaitOutcome::LiveCell(RuntimeResponse::Result {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: vec![FunctionCallOutputContentItem::InputText {
text: "after".to_string(),
}],
result_buffered_for: actual.result_buffered_for().unwrap(),
error_text: None,
})
);
}
#[tokio::test]
async fn returns_and_resumes_from_the_pending_frontier() {
let (delegate, mut events_rx) = BlockingDelegate::new();
let service = InProcessCodeModeSession::new();
assert_eq!(
service
.execute_to_pending(
ExecuteRequest {
enabled_tools: vec![blocking_tool()],
source: r#"
await tools.block({});
text("after");
"#
.to_string(),
yield_time_ms: Some(60_000),
..execute_request("")
},
delegate.clone()
)
.await
.unwrap(),
ExecuteToPendingOutcome::Pending {
cell_id: cell_id("1"),
content_items: Vec::new(),
pending_tool_call_ids: vec!["tool-1".to_string()],
}
);
assert_eq!(next_event(&mut events_rx).await, DelegateEvent::ToolStarted);
delegate.release_tool();
assert_eq!(
service
.wait_to_pending(WaitToPendingRequest {
cell_id: cell_id("1"),
})
.await
.unwrap(),
WaitToPendingOutcome::LiveCell(ExecuteToPendingOutcome::Completed(
RuntimeResponse::Result {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: vec![FunctionCallOutputContentItem::InputText {
text: "after".to_string(),
}],
result_buffered_for: Duration::ZERO,
error_text: None,
}
))
);
}
#[tokio::test]
async fn observed_natural_completion_wins_over_termination() {
let service = InProcessCodeModeSession::new();
let cell = service
.execute(
execute_request(r#"yield_control(); store("finished", true); text("done");"#),
Arc::new(NoopCodeModeSessionDelegate),
/*preempt*/ None,
)
.await
.unwrap();
assert_eq!(
cell.initial_response().await.unwrap(),
RuntimeResponse::Yielded {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: Vec::new(),
}
);
tokio::time::timeout(Duration::from_secs(1), async {
loop {
let response = service
.execute(
ExecuteRequest {
yield_time_ms: Some(60_000),
..execute_request(r#"text(String(load("finished")));"#)
},
Arc::new(NoopCodeModeSessionDelegate),
/*preempt*/ None,
)
.await
.unwrap()
.initial_response()
.await
.unwrap();
let RuntimeResponse::Result { content_items, .. } = response else {
panic!("expected stored-value probe to complete");
};
if content_items
== vec![FunctionCallOutputContentItem::InputText {
text: "true".to_string(),
}]
{
break;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
let actual = service.terminate(cell_id("1").into()).await.unwrap();
let result_buffered_for = actual.result_buffered_for().unwrap();
assert!(!result_buffered_for.is_zero());
assert_eq!(
actual,
WaitOutcome::LiveCell(RuntimeResponse::Result {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: vec![FunctionCallOutputContentItem::InputText {
text: "done".to_string(),
}],
result_buffered_for,
error_text: None,
})
);
}
#[tokio::test]
async fn termination_cancels_pending_callbacks_before_responding() {
let (delegate, mut events_rx) = BlockingDelegate::new();
let service = InProcessCodeModeSession::new();
let cell = service
.execute(
execute_request(r#"notify("pending"); await new Promise(() => {});"#),
delegate.clone(),
/*preempt*/ None,
)
.await
.unwrap();
assert_eq!(
next_event(&mut events_rx).await,
DelegateEvent::NotificationStarted
);
assert_eq!(
cell.initial_response().await.unwrap(),
RuntimeResponse::Yielded {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: Vec::new(),
}
);
assert_eq!(
service.terminate(cell_id("1").into()).await.unwrap(),
WaitOutcome::LiveCell(RuntimeResponse::Terminated {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: Vec::new(),
})
);
assert!(delegate.notification_finished.load(Ordering::Acquire));
assert_eq!(
next_event(&mut events_rx).await,
DelegateEvent::NotificationCancelled
);
assert_eq!(
next_event(&mut events_rx).await,
DelegateEvent::CellClosed(cell_id("1"))
);
}
#[tokio::test]
async fn shutdown_cancels_notifications_while_natural_completion_is_draining() {
let (delegate, mut events_rx) = HeldNotificationDelegate::new();
let service = Arc::new(InProcessCodeModeSession::new());
service
.execute(
execute_request(r#"notify("pending");"#),
delegate.clone(),
/*preempt*/ None,
)
.await
.unwrap();
assert_eq!(
next_event(&mut events_rx).await,
DelegateEvent::NotificationStarted
);
let shutdown_service = Arc::clone(&service);
let shutdown = tokio::spawn(async move { shutdown_service.shutdown().await });
assert_eq!(
next_event(&mut events_rx).await,
DelegateEvent::NotificationCancelled
);
delegate.release_notification();
assert_eq!(shutdown.await.unwrap(), Ok(()));
assert_eq!(
next_event(&mut events_rx).await,
DelegateEvent::CellClosed(cell_id("1"))
);
}
#[tokio::test]
async fn repeated_termination_is_rejected_while_callback_cleanup_is_pending() {
let (delegate, mut events_rx) = HeldNotificationDelegate::new();
let service = Arc::new(InProcessCodeModeSession::new());
let cell = service
.execute(
execute_request(r#"notify("pending"); await new Promise(() => {});"#),
delegate.clone(),
/*preempt*/ None,
)
.await
.unwrap();
assert_eq!(
next_event(&mut events_rx).await,
DelegateEvent::NotificationStarted
);
assert_eq!(
cell.initial_response().await.unwrap(),
RuntimeResponse::Yielded {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: Vec::new(),
}
);
let terminating_service = Arc::clone(&service);
let first_termination =
tokio::spawn(async move { terminating_service.terminate(cell_id("1").into()).await });
assert_eq!(
next_event(&mut events_rx).await,
DelegateEvent::NotificationCancelled
);
let repeated_termination = service.terminate(cell_id("1").into()).await;
delegate.release_notification();
assert_eq!(
repeated_termination.unwrap_err(),
"exec cell 1 is already terminating"
);
assert_eq!(
first_termination.await.unwrap().unwrap(),
WaitOutcome::LiveCell(RuntimeResponse::Terminated {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: Vec::new(),
})
);
assert_eq!(
next_event(&mut events_rx).await,
DelegateEvent::CellClosed(cell_id("1"))
);
}
#[tokio::test]
async fn second_observer_is_rejected_without_displacing_the_first() {
let service = InProcessCodeModeSession::new();
let cell = service
.execute(
execute_request("await new Promise(() => {});"),
Arc::new(NoopCodeModeSessionDelegate),
/*preempt*/ None,
)
.await
.unwrap();
assert_eq!(
cell.initial_response().await.unwrap(),
RuntimeResponse::Yielded {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: Vec::new(),
}
);
let first_observer = service
.begin_wait(
WaitRequest {
cell_id: cell_id("1"),
yield_time_ms: 60_000,
max_output_tokens: None,
},
/*preempt*/ None,
)
.await;
assert_eq!(
service
.wait(
WaitRequest {
cell_id: cell_id("1"),
yield_time_ms: 60_000,
max_output_tokens: None,
},
/*preempt*/ None,
)
.await
.unwrap_err(),
"exec cell 1 already has an active observer"
);
let terminated = RuntimeResponse::Terminated {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: Vec::new(),
};
assert_eq!(
service.terminate(cell_id("1").into()).await.unwrap(),
WaitOutcome::LiveCell(terminated.clone())
);
assert_eq!(
first_observer.await.unwrap(),
WaitOutcome::LiveCell(terminated)
);
}
#[tokio::test]
async fn natural_completion_cleans_up_callbacks_before_responding() {
let (delegate, mut events_rx) = BlockingDelegate::new();
let service = InProcessCodeModeSession::new();
let cell = service
.execute(
ExecuteRequest {
enabled_tools: vec![blocking_tool()],
source: r#"tools.block({}); text("done");"#.to_string(),
yield_time_ms: Some(60_000),
..execute_request("")
},
delegate.clone(),
/*preempt*/ None,
)
.await
.unwrap();
assert_eq!(next_event(&mut events_rx).await, DelegateEvent::ToolStarted);
assert_eq!(
cell.initial_response().await.unwrap(),
RuntimeResponse::Result {
code_mode_host_duration: None,
cell_id: cell_id("1"),
content_items: vec![FunctionCallOutputContentItem::InputText {
text: "done".to_string(),
}],
result_buffered_for: Duration::ZERO,
error_text: None,
}
);
assert!(delegate.tool_finished.load(Ordering::Acquire));
assert_eq!(
next_event(&mut events_rx).await,
DelegateEvent::ToolCancelled
);
assert_eq!(
next_event(&mut events_rx).await,
DelegateEvent::CellClosed(cell_id("1"))
);
}

View File

@@ -0,0 +1,340 @@
//! Real-runtime regressions for bounded output, observation and termination.
use std::sync::Arc;
use std::time::Duration;
use akode_code_mode_protocol::ExecuteRequest;
use akode_code_mode_protocol::FunctionCallOutputContentItem;
use akode_code_mode_protocol::NoopCodeModeSessionDelegate;
use akode_code_mode_protocol::RuntimeResponse;
use akode_code_mode_protocol::WaitOutcome;
use akode_code_mode_protocol::WaitRequest;
use pretty_assertions::assert_eq;
use super::InProcessCodeModeSession;
use crate::output::MAX_OUTPUT_ITEMS;
use crate::output::MAX_SERVER_DIAGNOSTIC_BYTES;
use akode_code_mode_protocol::CodeModeOutputTruncation;
use akode_code_mode_protocol::CodeModeSessionOptions;
use akode_code_mode_protocol::host::BOUNDED_OUTPUT_MAX_BYTES as MAX_OUTPUT_BYTES;
use akode_code_mode_protocol::host::BOUNDED_OUTPUT_MAX_IMAGE_BYTES as MAX_IMAGE_BYTES;
fn server_session() -> InProcessCodeModeSession {
InProcessCodeModeSession::with_options(
CodeModeSessionOptions {
output_truncation: CodeModeOutputTruncation::Server,
..CodeModeSessionOptions::default()
},
/*task_failure_handler*/ None,
)
}
async fn start(session: &InProcessCodeModeSession, source: &str) -> RuntimeResponse {
session
.execute(
ExecuteRequest {
tool_call_id: "bounded-output".to_owned(),
enabled_tools: Vec::new(),
source: source.to_owned(),
yield_time_ms: Some(60_000),
// These tests isolate collector overflow from the per-observation
// formatter: request enough room to display every retained item.
max_output_tokens: Some(MAX_OUTPUT_BYTES),
},
Arc::new(NoopCodeModeSessionDelegate),
/*preempt*/ None,
)
.await
.unwrap()
.initial_response()
.await
.unwrap()
}
#[tokio::test]
async fn bounded_output_keeps_head_tail_without_stopping_the_cell() {
let session = server_session();
let emitted = MAX_OUTPUT_ITEMS + 100;
let response = start(
&session,
&format!("text('begin'); for (let i = 0; i < {emitted}; i++) text(i); text('end');"),
)
.await;
let RuntimeResponse::Result {
content_items,
error_text,
..
} = response
else {
panic!("expected completed cell");
};
assert_eq!(error_text, None);
assert_eq!(content_items.len(), MAX_OUTPUT_ITEMS);
assert_eq!(
content_items.first(),
Some(&FunctionCallOutputContentItem::InputText {
text: "begin".to_owned()
})
);
assert_eq!(
content_items.last(),
Some(&FunctionCallOutputContentItem::InputText {
text: "end".to_owned()
})
);
assert!(matches!(
&content_items[MAX_OUTPUT_ITEMS / 2],
FunctionCallOutputContentItem::InputText { text }
if text.starts_with("[Code Mode session output limit reached: omitted ")
));
}
#[tokio::test]
async fn huge_output_is_bounded_and_yield_drain_starts_a_new_budget() {
let session = server_session();
// Continue immediately after yielding to exercise the FIFO boundary as
// well as discarding the already-delivered bounded snapshot.
let response = start(
&session,
r#"text('😀'.repeat(1000000)); yield_control(); text('after yield');"#,
)
.await;
let RuntimeResponse::Yielded {
cell_id,
content_items,
..
} = response
else {
panic!("expected yielded cell");
};
assert_eq!(
content_items,
vec![
FunctionCallOutputContentItem::InputText {
text: "😀".repeat(MAX_OUTPUT_BYTES / 8)
},
FunctionCallOutputContentItem::InputText {
text: format!(
"[Code Mode session output limit reached: omitted {} text bytes; discarded 0 text segments, 0 images, 0 audio items]",
4_000_000 - MAX_OUTPUT_BYTES
)
},
FunctionCallOutputContentItem::InputText {
text: "😀".repeat(MAX_OUTPUT_BYTES / 8)
},
]
);
let response = session
.wait(
WaitRequest {
cell_id,
yield_time_ms: 60_000,
max_output_tokens: None,
},
/*preempt*/ None,
)
.await
.unwrap();
let WaitOutcome::LiveCell(RuntimeResponse::Result {
content_items,
error_text,
..
}) = response
else {
panic!("expected completed cell");
};
assert_eq!(
(content_items, error_text),
(
vec![FunctionCallOutputContentItem::InputText {
text: "after yield".to_owned()
}],
None
)
);
}
#[tokio::test]
async fn a_single_oversized_image_is_omitted_without_losing_surrounding_text() {
let session = server_session();
let response = start(
&session,
&format!("text('before'); image('data:image/png;base64,' + 'A'.repeat({MAX_IMAGE_BYTES})); text('after');"),
)
.await;
let RuntimeResponse::Result {
content_items,
error_text,
..
} = response
else {
panic!("expected completed cell");
};
assert_eq!(
(content_items, error_text),
(
vec![
FunctionCallOutputContentItem::InputText {
text: "before".to_owned()
},
FunctionCallOutputContentItem::InputText {
text: "[Code Mode session output limit reached: omitted 0 text bytes; discarded 0 text segments, 1 images, 0 audio items]".to_owned()
},
FunctionCallOutputContentItem::InputText {
text: "after".to_owned()
}
],
None
)
);
}
#[tokio::test]
async fn termination_releases_a_flooding_bounded_runtime() {
let session = server_session();
let emitted = MAX_OUTPUT_ITEMS + 100;
let response = start(
&session,
&format!(
"for (let i = 0; ; i++) {{
text('output');
if (i === {emitted}) yield_control();
}}"
),
)
.await;
let RuntimeResponse::Yielded {
cell_id,
content_items,
..
} = response
else {
panic!("expected yielded cell");
};
assert_eq!(content_items.len(), MAX_OUTPUT_ITEMS);
assert!(matches!(
&content_items[MAX_OUTPUT_ITEMS / 2],
FunctionCallOutputContentItem::InputText { text }
if text.starts_with("[Code Mode session output limit reached: omitted ")
));
let response = tokio::time::timeout(Duration::from_secs(5), session.terminate(cell_id.into()))
.await
.expect("termination must unblock output")
.unwrap();
assert!(matches!(
response,
WaitOutcome::LiveCell(RuntimeResponse::Terminated { .. })
));
session.shutdown().await.unwrap();
}
#[tokio::test]
async fn terminal_error_shares_the_collector_limit_and_remains_a_failure() {
let session = server_session();
let response = start(
&session,
"text('before'); throw 'error-start:' + 'x'.repeat(2 * 1024 * 1024) + ':error-end';",
)
.await;
let RuntimeResponse::Result {
content_items,
error_text,
..
} = response
else {
panic!("expected failed cell");
};
let diagnostic = error_text.expect("overflowed diagnostics still report failure");
// The model-output budget is generous, but the diagnostic has its own limit.
assert!(diagnostic.len() <= MAX_SERVER_DIAGNOSTIC_BYTES);
assert!(diagnostic.starts_with("error-start:"));
assert!(diagnostic.ends_with(":error-end"));
let notice = content_items
.iter()
.find_map(|item| match item {
FunctionCallOutputContentItem::InputText { text }
if text.starts_with("[Code Mode session output limit reached: omitted ") =>
{
Some(text)
}
_ => None,
})
.expect("terminal overflow notice");
let total_text_bytes: usize = content_items
.iter()
.map(|item| match item {
FunctionCallOutputContentItem::InputText { text } => text.len(),
_ => 0,
})
.sum();
assert!(total_text_bytes - notice.len() <= MAX_OUTPUT_BYTES);
assert!(matches!(content_items.last(),
Some(FunctionCallOutputContentItem::InputText { text }) if text.ends_with(":error-end")
));
session.shutdown().await.unwrap();
}
#[tokio::test]
async fn wait_preserves_diagnostics_across_output_budgets() {
let source = "yield_control(); text('before'); throw 'start:' + '🎷'.repeat(4096) + ':end';";
let raw_error = format!("start:{}:end", "🎷".repeat(4096));
for mode in [
CodeModeOutputTruncation::Client,
CodeModeOutputTruncation::Server,
] {
let session = InProcessCodeModeSession::with_options(
CodeModeSessionOptions {
output_truncation: mode,
..CodeModeSessionOptions::default()
},
/*task_failure_handler*/ None,
);
// The error fits the diagnostic limit but exceeds both output budgets.
for max_output_tokens in [0, 16] {
let response = start(&session, source).await;
let RuntimeResponse::Yielded { cell_id, .. } = response else {
panic!("expected yield before error");
};
let WaitOutcome::LiveCell(RuntimeResponse::Result {
content_items,
error_text,
..
}) = session
.wait(
WaitRequest {
cell_id,
yield_time_ms: 60_000,
max_output_tokens: Some(max_output_tokens),
},
/*preempt*/ None,
)
.await
.unwrap()
else {
panic!("expected completed cell");
};
let diagnostic = error_text.expect("errors remain failures at all budgets");
assert_eq!(diagnostic, raw_error);
match mode {
CodeModeOutputTruncation::Client => {
assert_eq!(
content_items,
vec![FunctionCallOutputContentItem::InputText {
text: "before".to_owned()
}]
);
}
CodeModeOutputTruncation::Server => {
if max_output_tokens != 0 {
assert!(matches!(
content_items.first(),
Some(FunctionCallOutputContentItem::InputText { text })
if text.starts_with("Warning: truncated output")
));
}
}
}
}
session.shutdown().await.unwrap();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,326 @@
mod types;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
pub(crate) use akode_code_mode_protocol::FunctionCallOutputContentItem as OutputItem;
use opentelemetry::context::FutureExt;
use serde_json::Value as JsonValue;
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
pub(crate) use self::types::CellEvent;
pub(crate) use self::types::CellId;
pub(crate) use self::types::CreateCellRequest;
pub(crate) use self::types::Error;
pub(crate) use self::types::NestedToolCall;
pub(crate) use self::types::Observation;
pub(crate) use self::types::ObserveMode;
pub(crate) use self::types::SessionRuntimeDelegate;
pub(crate) use self::types::ToolDefinition;
pub(crate) use self::types::ToolKind;
pub(crate) use self::types::ToolName;
use crate::TaskFailureHandler;
use crate::cell_actor::CellActor;
use crate::cell_actor::CellError;
use crate::cell_actor::CellEventFuture;
use crate::cell_actor::CellHandle;
use crate::cell_actor::CellHost;
use crate::cell_actor::CellState;
use crate::cell_actor::CellToolCall;
use crate::cell_actor::CompletionCommit;
type RuntimeEventFuture = Pin<Box<dyn Future<Output = Result<CellEvent, Error>> + Send + 'static>>;
/// Owns all cells and shared state for one transport-neutral code-mode session.
pub(crate) struct SessionRuntime {
inner: Arc<Inner>,
}
struct Inner {
// Cells snapshot the keys while sharing immutable payloads, so later commits cannot
// change an existing cell's view and unused values do not need to be copied.
stored_values: Mutex<HashMap<String, Arc<JsonValue>>>,
cells: Mutex<HashMap<CellId, CellHandle>>,
cell_tasks: TaskTracker,
shutdown_token: CancellationToken,
task_failure_handler: Option<TaskFailureHandler>,
next_cell_id: AtomicU64,
}
impl SessionRuntime {
#[cfg(test)]
pub(crate) fn new() -> Self {
Self::new_with_task_failure_handler(/*task_failure_handler*/ None)
}
pub(crate) fn new_with_task_failure_handler(
task_failure_handler: Option<TaskFailureHandler>,
) -> Self {
Self {
inner: Arc::new(Inner {
stored_values: Mutex::new(HashMap::new()),
cells: Mutex::new(HashMap::new()),
cell_tasks: TaskTracker::new(),
shutdown_token: CancellationToken::new(),
task_failure_handler,
next_cell_id: AtomicU64::new(1),
}),
}
}
pub(crate) async fn execute<D: SessionRuntimeDelegate>(
&self,
request: CreateCellRequest,
initial_observation: impl Into<Observation> + Send,
delegate: Arc<D>,
) -> Result<StartedCell, Error> {
if self.inner.shutdown_token.is_cancelled() {
return Err(Error::ShuttingDown);
}
let cell_id = self.allocate_cell_id()?;
let initial_event = self
.start_cell(
cell_id.clone(),
request,
initial_observation.into(),
delegate,
)
.await?;
Ok(StartedCell {
cell_id,
initial_event,
})
}
pub(crate) async fn observe(
&self,
cell_id: &CellId,
mode: ObserveMode,
) -> Result<CellEvent, Error> {
self.begin_observe(cell_id, mode).await?.event().await
}
pub(crate) async fn begin_observe(
&self,
cell_id: &CellId,
observation: impl Into<Observation> + Send,
) -> Result<PendingEvent, Error> {
let handle = self
.inner
.cells
.lock()
.await
.get(cell_id)
.cloned()
.ok_or_else(|| Error::MissingCell(cell_id.clone()))?;
Ok(PendingEvent {
event: map_actor_event(cell_id.clone(), handle.observe(observation)),
})
}
pub(crate) async fn terminate(&self, cell_id: &CellId) -> Result<CellEvent, Error> {
let handle = self
.inner
.cells
.lock()
.await
.get(cell_id)
.cloned()
.ok_or_else(|| Error::MissingCell(cell_id.clone()))?;
handle
.terminate()
.await
.map_err(|error| actor_error(cell_id, error))
}
pub(crate) async fn shutdown(&self) -> Result<(), Error> {
self.begin_shutdown();
// Taking the registry lock ensures every cell that passed the shutdown
// check has registered its actor with the tracker before we wait.
let cells = self.inner.cells.lock().await;
self.inner.cell_tasks.close();
drop(cells);
self.inner.cell_tasks.wait().await;
Ok(())
}
fn allocate_cell_id(&self) -> Result<CellId, Error> {
self.inner
.next_cell_id
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |next_cell_id| {
next_cell_id.checked_add(1)
})
.map(|cell_id| CellId::new(cell_id.to_string()))
.map_err(|_| Error::CellIdSpaceExhausted)
}
async fn start_cell<D: SessionRuntimeDelegate>(
&self,
cell_id: CellId,
request: CreateCellRequest,
initial_observation: Observation,
delegate: Arc<D>,
) -> Result<RuntimeEventFuture, Error> {
let stored_values = self.inner.stored_values.lock().await.clone();
let host = Arc::new(RuntimeCellHost {
delegate,
cell_id: cell_id.clone(),
inner: Arc::clone(&self.inner),
execution_context: opentelemetry::Context::current(),
});
let mut cells = self.inner.cells.lock().await;
if self.inner.shutdown_token.is_cancelled() {
return Err(Error::ShuttingDown);
}
if cells.contains_key(&cell_id) {
return Err(Error::DuplicateCell(cell_id));
}
let cell_state = Arc::new(CellState::new(self.inner.shutdown_token.child_token()));
let (handle, initial_event, task) = CellActor::prepare(
request,
stored_values,
host,
initial_observation,
cell_state,
self.inner.task_failure_handler.clone(),
)
.map_err(Error::Runtime)?;
cells.insert(cell_id.clone(), handle);
let task = self.inner.cell_tasks.spawn(task);
if let Some(task_failure_handler) = self.inner.task_failure_handler.clone() {
let failed_cell_id = cell_id.clone();
let _failure_watcher = self.inner.cell_tasks.spawn(async move {
if let Err(err) = task.await {
task_failure_handler(format!(
"code-mode cell {failed_cell_id} task failed: {err}"
));
}
});
}
drop(cells);
Ok(map_actor_event(cell_id, initial_event))
}
fn begin_shutdown(&self) {
self.inner.shutdown_token.cancel();
self.inner.cell_tasks.close();
}
}
impl Drop for SessionRuntime {
fn drop(&mut self) {
self.begin_shutdown();
}
}
/// A cell admitted by [`SessionRuntime::execute`].
pub(crate) struct StartedCell {
pub(crate) cell_id: CellId,
initial_event: RuntimeEventFuture,
}
impl StartedCell {
pub(crate) async fn initial_event(self) -> Result<CellEvent, Error> {
self.initial_event.await
}
}
/// An admitted observation that has not reached its requested frontier yet.
pub(crate) struct PendingEvent {
event: RuntimeEventFuture,
}
impl PendingEvent {
pub(crate) async fn event(self) -> Result<CellEvent, Error> {
self.event.await
}
}
struct RuntimeCellHost<D: SessionRuntimeDelegate> {
delegate: Arc<D>,
cell_id: CellId,
inner: Arc<Inner>,
// Callbacks outlive the initial request and run in separate tasks. Preserve
// their trace parent without retaining the request's tracing span.
execution_context: opentelemetry::Context,
}
impl<D: SessionRuntimeDelegate> CellHost for RuntimeCellHost<D> {
async fn invoke_tool(
&self,
invocation: CellToolCall,
cancellation_token: CancellationToken,
) -> Result<JsonValue, String> {
self.delegate
.invoke_tool(
NestedToolCall {
cell_id: self.cell_id.clone(),
runtime_tool_call_id: invocation.id,
tool_name: invocation.name,
tool_kind: invocation.kind,
input: invocation.input,
},
cancellation_token,
)
.with_context(self.execution_context.clone())
.await
}
async fn notify(
&self,
call_id: String,
text: String,
cancellation_token: CancellationToken,
) -> Result<(), String> {
self.delegate
.notify(call_id, self.cell_id.clone(), text, cancellation_token)
.await
}
async fn commit_completion(
&self,
stored_value_writes: HashMap<String, Arc<JsonValue>>,
event: impl FnOnce() -> CellEvent + Send,
cell_state: Arc<CellState>,
) -> CompletionCommit {
let cancellation_token = cell_state.cancellation_token();
let mut stored_values = tokio::select! {
biased;
_ = cancellation_token.cancelled() => {
return CompletionCommit::Rejected;
}
stored_values = self.inner.stored_values.lock() => stored_values,
};
cell_state.commit_completion(event, || {
stored_values.extend(stored_value_writes);
drop(stored_values);
})
}
async fn closed(&self) {
self.inner.cells.lock().await.remove(&self.cell_id);
self.delegate.cell_closed(&self.cell_id);
}
}
fn map_actor_event(cell_id: CellId, event: CellEventFuture) -> RuntimeEventFuture {
Box::pin(async move { event.await.map_err(|error| actor_error(&cell_id, error)) })
}
fn actor_error(cell_id: &CellId, error: CellError) -> Error {
match error {
CellError::Busy => Error::BusyObserver(cell_id.clone()),
CellError::AlreadyTerminating => Error::AlreadyTerminating(cell_id.clone()),
CellError::Closed => Error::ClosedCell(cell_id.clone()),
}
}
#[cfg(test)]
#[path = "tests.rs"]
mod tests;

View File

@@ -0,0 +1,267 @@
use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;
use std::task::Waker;
use std::time::Duration;
use akode_code_mode_protocol::CodeModeOutputTruncation;
use pretty_assertions::assert_eq;
use serde_json::Value as JsonValue;
use tokio_util::sync::CancellationToken;
use super::*;
use crate::cell_actor::CompletionCommit;
use crate::output::OutputCollector;
struct RecordingDelegate;
struct PanickingClosedDelegate;
impl SessionRuntimeDelegate for RecordingDelegate {
async fn invoke_tool(
&self,
_invocation: NestedToolCall,
_cancellation_token: CancellationToken,
) -> Result<JsonValue, String> {
Ok(JsonValue::Null)
}
async fn notify(
&self,
_call_id: String,
_cell_id: CellId,
_text: String,
_cancellation_token: CancellationToken,
) -> Result<(), String> {
Ok(())
}
fn cell_closed(&self, _cell_id: &CellId) {}
}
impl SessionRuntimeDelegate for PanickingClosedDelegate {
async fn invoke_tool(
&self,
_invocation: NestedToolCall,
_cancellation_token: CancellationToken,
) -> Result<JsonValue, String> {
Ok(JsonValue::Null)
}
async fn notify(
&self,
_call_id: String,
_cell_id: CellId,
_text: String,
_cancellation_token: CancellationToken,
) -> Result<(), String> {
Ok(())
}
fn cell_closed(&self, _cell_id: &CellId) {
panic!("cell close panic probe");
}
}
#[tokio::test]
async fn reports_cell_actor_panics_to_the_owner() {
let (failure_tx, mut failure_rx) = tokio::sync::mpsc::unbounded_channel();
let runtime = SessionRuntime::new_with_task_failure_handler(Some(Arc::new(move |reason| {
let _ = failure_tx.send(reason);
})));
let started = runtime
.execute(
execute_request(r#"text("done");"#),
ObserveMode::YieldAfter(Duration::from_secs(1)),
Arc::new(PanickingClosedDelegate),
)
.await
.expect("start cell");
assert_eq!(
started.initial_event().await,
Ok(CellEvent::Completed {
content_items: OutputCollector::Client(vec![OutputItem::InputText {
text: "done".to_string(),
}]),
result_buffered_for: Duration::ZERO,
error_text: None,
})
);
runtime.shutdown().await.expect("shutdown runtime");
let failure = failure_rx
.try_recv()
.expect("shutdown should wait for the cell failure watcher");
assert!(failure.contains("code-mode cell 1 task failed"));
}
#[tokio::test]
async fn termination_rejects_a_waiting_store_commit_before_the_next_cell_can_load_it() {
let runtime = SessionRuntime::new();
let cell_state = Arc::new(CellState::new(CancellationToken::new()));
let host = RuntimeCellHost {
delegate: Arc::new(RecordingDelegate),
cell_id: CellId::new("terminating-writer"),
inner: Arc::clone(&runtime.inner),
execution_context: opentelemetry::Context::new(),
};
let stored_values = runtime.inner.stored_values.lock().await;
let commit = host.commit_completion(
HashMap::from([(
"candidate".to_string(),
Arc::new(JsonValue::String("lost".to_string())),
)]),
|| panic!("terminated cell must not construct completion output"),
Arc::clone(&cell_state),
);
tokio::pin!(commit);
let waker = Waker::noop();
let mut context = Context::from_waker(waker);
assert!(matches!(commit.as_mut().poll(&mut context), Poll::Pending));
let termination = cell_state.request_termination();
drop(stored_values);
assert_eq!(commit.await, CompletionCommit::Rejected);
let terminated = CellEvent::Terminated {
content_items: OutputCollector::Client(Vec::new()),
};
assert_eq!(
cell_state.finish_termination(terminated.clone()),
Some(terminated.clone())
);
assert_eq!(termination.await, Ok(terminated));
assert!(
!runtime
.inner
.stored_values
.lock()
.await
.contains_key("candidate")
);
let reader = runtime
.execute(
CreateCellRequest {
output_truncation: CodeModeOutputTruncation::Client,
tool_call_id: "reader".to_string(),
enabled_tools: Vec::new(),
source: r#"text(String(load("candidate")));"#.to_string(),
},
ObserveMode::YieldAfter(Duration::from_secs(1)),
Arc::new(RecordingDelegate),
)
.await
.unwrap();
assert_eq!(
reader.initial_event().await,
Ok(CellEvent::Completed {
content_items: OutputCollector::Client(vec![OutputItem::InputText {
text: "undefined".to_string(),
}]),
result_buffered_for: Duration::ZERO,
error_text: None,
})
);
runtime.shutdown().await.unwrap();
}
fn execute_request(source: &str) -> CreateCellRequest {
CreateCellRequest {
output_truncation: CodeModeOutputTruncation::Client,
tool_call_id: "call-1".to_string(),
enabled_tools: Vec::new(),
source: source.to_string(),
}
}
#[tokio::test]
async fn cell_id_allocation_fails_before_wrapping() {
let runtime = SessionRuntime::new();
runtime
.inner
.next_cell_id
.store(u64::MAX, Ordering::Relaxed);
assert_eq!(
runtime
.execute(
execute_request(r#"text("unreachable");"#),
ObserveMode::YieldAfter(Duration::from_secs(1)),
Arc::new(RecordingDelegate)
)
.await
.err(),
Some(Error::CellIdSpaceExhausted)
);
}
#[tokio::test]
#[expect(
clippy::await_holding_invalid_type,
reason = "test holds the registry lock to force admission ahead of shutdown"
)]
async fn shutdown_rejects_cell_admission_queued_before_the_registry_lock() {
let runtime = Arc::new(SessionRuntime::new());
let cells = runtime.inner.cells.lock().await;
let execution = runtime.execute(
execute_request("while (true) {}"),
ObserveMode::YieldAfter(Duration::from_millis(/*millis*/ 1)),
Arc::new(RecordingDelegate),
);
tokio::pin!(execution);
std::future::poll_fn(|context| match execution.as_mut().poll(context) {
Poll::Pending => Poll::Ready(()),
Poll::Ready(Ok(_)) => panic!("execution completed before the registry lock was released"),
Poll::Ready(Err(error)) => {
panic!("execution failed before the registry lock was released: {error}")
}
})
.await;
let shutdown = runtime.shutdown();
tokio::pin!(shutdown);
std::future::poll_fn(|context| match shutdown.as_mut().poll(context) {
Poll::Pending => Poll::Ready(()),
Poll::Ready(Ok(())) => panic!("shutdown completed before acquiring the registry lock"),
Poll::Ready(Err(error)) => {
panic!("shutdown failed before acquiring the registry lock: {error}")
}
})
.await;
drop(cells);
assert!(matches!(execution.await, Err(Error::ShuttingDown)));
assert_eq!(shutdown.await, Ok(()));
}
#[tokio::test]
async fn drop_terminates_cells_when_the_registry_is_locked() {
let runtime = SessionRuntime::new();
let started = runtime
.execute(
execute_request("while (true) {}"),
ObserveMode::YieldAfter(Duration::from_millis(/*millis*/ 1)),
Arc::new(RecordingDelegate),
)
.await
.unwrap();
assert_eq!(started.cell_id, CellId::new("1"));
assert_eq!(
started.initial_event().await,
Ok(CellEvent::Yielded {
content_items: OutputCollector::Client(Vec::new()),
})
);
let inner = Arc::clone(&runtime.inner);
let cells = inner.cells.lock().await;
drop(runtime);
drop(cells);
tokio::time::timeout(Duration::from_secs(/*secs*/ 1), inner.cell_tasks.wait())
.await
.unwrap();
assert!(inner.cell_tasks.is_empty());
}

View File

@@ -0,0 +1,184 @@
use std::fmt;
use std::future::Future;
use std::time::Duration;
use serde_json::Value as JsonValue;
use tokio_util::sync::CancellationToken;
use crate::output::OutputCollector;
/// Identifies one execution cell within a session runtime.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub(crate) struct CellId(String);
impl CellId {
pub(crate) fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
pub(crate) fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for CellId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
/// Selects the next observable frontier for a running cell.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ObserveMode {
YieldAfter(Duration),
PendingFrontier,
}
/// A signal may end an observation early without cancelling the cell.
pub(crate) struct Observation {
pub(crate) mode: ObserveMode,
pub(crate) yield_signal: CancellationToken,
}
impl ObserveMode {
pub(crate) fn with_yield_signal(self, yield_signal: CancellationToken) -> Observation {
Observation {
mode: self,
yield_signal,
}
}
}
impl From<ObserveMode> for Observation {
fn from(mode: ObserveMode) -> Self {
mode.with_yield_signal(CancellationToken::new())
}
}
/// An observable cell lifecycle event.
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub(crate) enum CellEvent {
Yielded {
content_items: OutputCollector,
},
Pending {
content_items: OutputCollector,
pending_tool_call_ids: Vec<String>,
},
Completed {
content_items: OutputCollector,
/// None is success. Server diagnostics have already been bounded
/// independently of the observing request's output budget.
error_text: Option<String>,
/// Time the completed result spent waiting for an observer.
result_buffered_for: Duration,
},
Terminated {
content_items: OutputCollector,
},
}
/// Transport-neutral input for creating a cell.
///
/// The owning session assigns the cell ID when it admits the request.
pub(crate) struct CreateCellRequest {
pub(crate) output_truncation: akode_code_mode_protocol::CodeModeOutputTruncation,
pub(crate) tool_call_id: String,
pub(crate) enabled_tools: Vec<ToolDefinition>,
pub(crate) source: String,
}
/// Tool metadata exposed to code running inside a cell.
pub(crate) struct ToolDefinition {
pub(crate) name: String,
pub(crate) tool_name: ToolName,
pub(crate) description: String,
pub(crate) kind: ToolKind,
}
/// A tool name with an optional namespace.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct ToolName {
pub(crate) name: String,
pub(crate) namespace: Option<String>,
}
/// The JavaScript calling convention for a tool.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ToolKind {
Function,
Freeform,
}
/// A nested tool request emitted by a running cell.
pub(crate) struct NestedToolCall {
pub(crate) cell_id: CellId,
pub(crate) runtime_tool_call_id: String,
pub(crate) tool_name: ToolName,
pub(crate) tool_kind: ToolKind,
pub(crate) input: Option<JsonValue>,
}
/// Host callbacks used by cells owned by a [`super::SessionRuntime`].
///
/// Implementations must honor cancellation tokens. `cell_closed` is called
/// after the runtime has stopped routing requests to the cell.
pub(crate) trait SessionRuntimeDelegate: Send + Sync + 'static {
fn invoke_tool(
&self,
invocation: NestedToolCall,
cancellation_token: CancellationToken,
) -> impl Future<Output = Result<JsonValue, String>> + Send;
fn notify(
&self,
call_id: String,
cell_id: CellId,
text: String,
cancellation_token: CancellationToken,
) -> impl Future<Output = Result<(), String>> + Send;
fn cell_closed(&self, cell_id: &CellId);
}
/// A failure reported by a session runtime operation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum Error {
ShuttingDown,
CellIdSpaceExhausted,
DuplicateCell(CellId),
MissingCell(CellId),
BusyObserver(CellId),
AlreadyTerminating(CellId),
ClosedCell(CellId),
Runtime(String),
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ShuttingDown => formatter.write_str("code mode session is shutting down"),
Self::CellIdSpaceExhausted => {
formatter.write_str("code mode session exhausted its cell ID space")
}
Self::DuplicateCell(cell_id) => write!(formatter, "exec cell {cell_id} already exists"),
Self::MissingCell(cell_id) => write!(formatter, "exec cell {cell_id} not found"),
Self::BusyObserver(cell_id) => {
write!(
formatter,
"exec cell {cell_id} already has an active observer"
)
}
Self::AlreadyTerminating(cell_id) => {
write!(formatter, "exec cell {cell_id} is already terminating")
}
Self::ClosedCell(cell_id) => {
write!(formatter, "exec cell {cell_id} closed unexpectedly")
}
Self::Runtime(error_text) => formatter.write_str(error_text),
}
}
}
impl std::error::Error for Error {}

View File

@@ -0,0 +1,278 @@
//! Persistent module state with explicit microtask pumping and no dynamic executable loading.
use std::collections::HashMap;
use std::io;
use akode_plugin_host::protocol::*;
use super::failures;
use super::transport::Transport;
pub(super) struct Engine {
context: v8::Global<v8::Context>,
namespace: Option<v8::Global<v8::Object>>,
pending_promises: HashMap<u64, v8::Global<v8::Promise>>,
pub(super) transport: Transport,
entered: bool,
isolate: v8::OwnedIsolate,
}
impl Engine {
/// Construct an isolate; user code runs only in watchdog-protected turns.
pub(super) fn new(transport: Transport) -> io::Result<Self> {
// V8 heap exhaustion is fatal to the shared helper; the parent survives and can restart it.
let mut isolate =
v8::Isolate::new(v8::CreateParams::default().heap_limits(0, 64 * 1024 * 1024));
isolate.set_microtasks_policy(v8::MicrotasksPolicy::Explicit);
failures::install(&mut isolate);
// V8 rejects dynamic imports when no host loader is installed.
isolate.set_allow_wasm_code_generation_callback(reject_wasm);
let context = {
v8::scope!(let scope, &mut isolate);
let context = v8::Context::new(scope, Default::default());
context.set_allow_generation_from_strings(false);
let scope = &mut v8::ContextScope::new(scope, context);
let global = context.global(scope);
// Binary buffers are omitted until the sandbox-enabled allocator supports quotas.
for name in [
"console",
"ArrayBuffer",
"SharedArrayBuffer",
"Atomics",
"WebAssembly",
"DataView",
"Int8Array",
"Uint8Array",
"Uint8ClampedArray",
"Int16Array",
"Uint16Array",
"Int32Array",
"Uint32Array",
"Float16Array",
"Float32Array",
"Float64Array",
"BigInt64Array",
"BigUint64Array",
] {
let key = v8::String::new(scope, name)
.ok_or_else(|| io::Error::other("V8 allocation failed"))?;
if global.delete(scope, key.into()) != Some(true) {
return Err(io::Error::other("failed to restrict UI globals"));
}
}
v8::Global::new(scope, context)
};
let mut runtime = Self {
entered: true,
transport,
isolate,
context,
namespace: None,
pending_promises: HashMap::new(),
};
// SAFETY: no handle scopes remain; the executor enters only the isolate being polled.
unsafe {
runtime.isolate.exit();
}
runtime.entered = false;
Ok(runtime)
}
pub(super) fn handle(&self) -> v8::IsolateHandle {
self.isolate.thread_safe_handle()
}
pub(super) fn turn(
&mut self,
message: HostMessage,
) -> Result<Vec<RuntimeMessage>, RuntimeMessage> {
// SAFETY: all isolates stay on this executor; no scopes survive a turn.
unsafe {
self.isolate.enter();
}
self.entered = true;
let result = match message {
HostMessage::Initialize { source } => self
.load(&source)
.map(|()| vec![RuntimeMessage::Initialized]),
HostMessage::Dispatch {
id,
export,
return_mode,
} => self.dispatch(id, &export, return_mode),
HostMessage::Close => Err(ErrorCode::InvalidProgram),
};
let script_error = failures::take(&mut self.isolate);
// SAFETY: load/dispatch have released all scopes before yielding the executor.
unsafe {
self.isolate.exit();
}
self.entered = false;
result.map_err(|code| RuntimeMessage::Error { code, script_error })
}
pub(super) fn load(&mut self, source: &str) -> Result<(), ErrorCode> {
if self.namespace.is_some() || source.len() > MAX_SOURCE {
return Err(ErrorCode::InvalidProgram);
}
v8::scope!(let scope, &mut self.isolate);
let context = v8::Local::new(scope, &self.context);
let scope = &mut v8::ContextScope::new(scope, context);
let tc = std::pin::pin!(v8::TryCatch::new(scope));
let mut tc = tc.init();
let result = (|| {
let source = v8::String::new(&tc, source).ok_or(ErrorCode::QuotaExceeded)?;
let name = v8::String::new(&tc, "plugin.mjs").ok_or(ErrorCode::QuotaExceeded)?;
let origin = v8::ScriptOrigin::new(
&tc,
name.into(),
/*resource_line_offset*/ 0,
/*resource_column_offset*/ 0,
/*resource_is_shared_cross_origin*/ false,
/*script_id*/ 0,
/*source_map_url*/ None,
/*resource_is_opaque*/ false,
/*is_wasm*/ false,
/*is_module*/ true,
/*host_defined_options*/ None,
);
let mut source = v8::script_compiler::Source::new(source, Some(&origin));
let module = v8::script_compiler::compile_module(&tc, &mut source)
.ok_or(ErrorCode::InvalidProgram)?;
// Reject imports before V8 invokes its platform-specific resolver callback.
if module.get_module_requests().length() != 0 {
let text = v8::String::new(&tc, "module imports are unavailable")
.ok_or(ErrorCode::QuotaExceeded)?;
let error = v8::Exception::type_error(&tc, text);
let message = v8::Exception::create_message(&tc, error);
failures::record(&mut tc, Some(message));
return Err(ErrorCode::InvalidProgram);
}
module
.instantiate_module(&tc, |_, _, _, _| None)
.ok_or(ErrorCode::InvalidProgram)?;
let evaluation = module.evaluate(&tc).ok_or(ErrorCode::ExecutionFailed)?;
let evaluation = v8::Local::<v8::Promise>::try_from(evaluation)
.map_err(|_| ErrorCode::InvalidProgram)?;
failures::checkpoint(&mut tc)?;
if evaluation.state() != v8::PromiseState::Fulfilled {
return Err(ErrorCode::ExecutionFailed);
}
let namespace = v8::Local::<v8::Object>::try_from(module.get_module_namespace())
.map_err(|_| ErrorCode::InvalidProgram)?;
self.namespace = Some(v8::Global::new(&tc, namespace));
Ok(())
})();
if result.is_err() {
let message = tc.message();
failures::record(&mut tc, message);
}
result
}
/// One JS turn; unresolved invocations yield back to the IPC dispatcher.
pub(super) fn dispatch(
&mut self,
id: u64,
export: &str,
return_mode: ReturnMode,
) -> Result<Vec<RuntimeMessage>, ErrorCode> {
let namespace = self.namespace.as_ref().ok_or(ErrorCode::InvalidProgram)?;
v8::scope!(let scope, &mut self.isolate);
let context = v8::Local::new(scope, &self.context);
let scope = &mut v8::ContextScope::new(scope, context);
let tc = std::pin::pin!(v8::TryCatch::new(scope));
let mut tc = tc.init();
let result = (|| {
let mut replies = Vec::new();
if export.is_empty()
|| export.len() > MAX_METHOD
|| self.pending_promises.contains_key(&id)
{
return Err(ErrorCode::QuotaExceeded);
}
let namespace = v8::Local::new(&tc, namespace);
let key = v8::String::new(&tc, export).ok_or(ErrorCode::QuotaExceeded)?;
let function = namespace
.get(&tc, key.into())
.ok_or(ErrorCode::InvalidProgram)?;
let function = v8::Local::<v8::Function>::try_from(function)
.map_err(|_| ErrorCode::InvalidProgram)?;
let receiver = v8::undefined(&tc).into();
let result = function
.call(&tc, receiver, &[])
.ok_or(ErrorCode::ExecutionFailed)?;
if return_mode == ReturnMode::MaybeAsync && result.is_promise() {
if self.pending_promises.len() >= MAX_PENDING_PROMISES {
return Err(ErrorCode::QuotaExceeded);
}
let promise = v8::Local::<v8::Promise>::try_from(result)
.map_err(|_| ErrorCode::InvalidResult)?;
self.pending_promises
.insert(id, v8::Global::new(&tc, promise));
} else {
replies.push(RuntimeMessage::Reply {
id,
value: result_string(&mut tc, result)?,
});
}
failures::checkpoint(&mut tc)?;
let completed: Vec<_> = self
.pending_promises
.extract_if(|_, promise| {
v8::Local::new(&tc, &*promise).state() != v8::PromiseState::Pending
})
.collect();
for (id, promise) in completed {
let promise = v8::Local::new(&tc, promise);
if promise.state() != v8::PromiseState::Fulfilled {
failures::record_rejection(&mut tc, promise);
return Err(ErrorCode::ExecutionFailed);
}
let value = promise.result(&tc);
replies.push(RuntimeMessage::Reply {
id,
value: result_string(&mut tc, value)?,
});
}
if self.pending_promises.contains_key(&id) {
replies.push(RuntimeMessage::Pending { id });
}
Ok(replies)
})();
if result.is_err() {
let message = tc.message();
failures::record(&mut tc, message);
}
result
}
}
impl Drop for Engine {
fn drop(&mut self) {
// SAFETY: the executor drops only exited engines. OwnedIsolate's destructor exits it.
if !self.entered {
unsafe {
self.isolate.enter();
}
}
}
}
fn result_string(
scope: &mut v8::PinScope<'_, '_>,
result: v8::Local<v8::Value>,
) -> Result<String, ErrorCode> {
let value = v8::Local::<v8::String>::try_from(result).map_err(|_| ErrorCode::InvalidResult)?;
if value.length() > MAX_RESULT || value.utf8_length(scope) > MAX_RESULT {
return Err(ErrorCode::QuotaExceeded);
}
Ok(value.to_rust_string_lossy(scope))
}
unsafe extern "C" fn reject_wasm(
_context: v8::Local<v8::Context>,
_source: v8::Local<v8::String>,
) -> bool {
false
}

View File

@@ -0,0 +1,99 @@
//! Bounded per-isolate rejection tracking and script error capture.
use akode_plugin_host::protocol::ErrorCode;
use akode_plugin_host::protocol::MAX_SCRIPT_ERROR_BYTES;
use akode_plugin_host::protocol::PluginScriptError;
const MAX_REJECTIONS: usize = 32;
#[derive(Default)]
struct Failures {
rejected: Vec<v8::Global<v8::Promise>>,
overflowed: bool,
script_error: Option<PluginScriptError>,
}
pub(super) fn install(isolate: &mut v8::OwnedIsolate) {
isolate.set_slot(Failures::default());
isolate.set_promise_reject_callback(rejected);
}
extern "C" fn rejected(message: v8::PromiseRejectMessage) {
// SAFETY: V8 supplies the callback's active isolate and scope.
v8::callback_scope!(unsafe scope, &message);
match message.get_event() {
v8::PromiseRejectEvent::PromiseRejectWithNoHandler => {
let promise = v8::Global::new(scope, message.get_promise());
let Some(state) = scope.get_slot_mut::<Failures>() else {
return;
};
if state.rejected.len() == MAX_REJECTIONS {
state.overflowed = true;
} else {
state.rejected.push(promise);
}
}
v8::PromiseRejectEvent::PromiseHandlerAddedAfterReject => {
let promise = message.get_promise();
if let Some(state) = scope.get_slot_mut::<Failures>() {
state.rejected.retain(|candidate| candidate != &promise);
}
}
v8::PromiseRejectEvent::PromiseRejectAfterResolved
| v8::PromiseRejectEvent::PromiseResolveAfterResolved => {}
}
}
pub(super) fn checkpoint(scope: &mut v8::PinScope<'_, '_>) -> Result<(), ErrorCode> {
scope.perform_microtask_checkpoint();
if scope.is_execution_terminating() {
return Err(ErrorCode::ExecutionFailed);
}
let (rejected, overflowed) = {
let state = scope
.get_slot_mut::<Failures>()
.ok_or(ErrorCode::ExecutionFailed)?;
(
std::mem::take(&mut state.rejected),
std::mem::take(&mut state.overflowed),
)
};
if let Some(promise) = rejected.first() {
let promise = v8::Local::new(scope, promise);
record_rejection(scope, promise);
return Err(ErrorCode::ExecutionFailed);
}
if overflowed {
return Err(ErrorCode::QuotaExceeded);
}
Ok(())
}
pub(super) fn record_rejection(scope: &mut v8::PinScope<'_, '_>, promise: v8::Local<v8::Promise>) {
let reason = promise.result(scope);
let message = v8::Exception::create_message(scope, reason);
record(scope, Some(message));
}
pub(super) fn record(scope: &mut v8::PinScope<'_, '_>, message: Option<v8::Local<v8::Message>>) {
let Some(message) = message else { return };
let text = message.get(scope);
let full_len = text.utf8_length(scope);
let mut bytes = vec![0; full_len.min(MAX_SCRIPT_ERROR_BYTES)];
let len = text.write_utf8_v2(scope, &mut bytes, v8::WriteFlags::kReplaceInvalidUtf8, None);
let script_error = PluginScriptError {
message: String::from_utf8_lossy(&bytes[..len]).into_owned(),
line: message.get_line_number(scope),
column: message.get_start_column().checked_add(1),
truncated: len < full_len,
};
if let Some(state) = scope.get_slot_mut::<Failures>() {
state.script_error = Some(script_error);
}
}
pub(super) fn take(isolate: &mut v8::Isolate) -> Option<PluginScriptError> {
isolate
.get_slot_mut::<Failures>()
.and_then(|state| state.script_error.take())
}

View File

@@ -0,0 +1,23 @@
//! Lightweight UI isolates share one bounded executor in the plugin process.
//! No ordinary CodeMode tools or globals.
//! Script failures discard their isolate without affecting its peers.
mod engine;
mod failures;
mod transport;
mod watchdog;
mod workers;
use std::io;
pub fn run() -> io::Result<()> {
crate::initialize_v8(crate::V8JitMode::Disabled).map_err(io::Error::other)?;
unsafe extern "C" {
fn v8__V8__IsSandboxEnabled() -> bool;
}
// SAFETY: linked V8 exposes this query and has already been initialized.
if !unsafe { v8__V8__IsSandboxEnabled() } {
return Err(io::Error::other("sandbox-enabled V8 required"));
}
workers::run()
}

View File

@@ -0,0 +1,133 @@
//! Framed I/O and per-instance queue admission for the plugin child.
use akode_plugin_host::framing;
use akode_plugin_host::protocol::MAX_IN_FLIGHT_TURNS;
use akode_plugin_host::protocol::Packet;
use akode_plugin_host::protocol::RuntimeMessage;
use futures::io::AllowStdIo;
use std::io;
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::mpsc;
use tokio::sync::OwnedSemaphorePermit;
use tokio::sync::Semaphore;
use tokio_util::codec::FramedRead;
use tokio_util::codec::FramedWrite;
use tokio_util::codec::LengthDelimitedCodec;
use tokio_util::compat::Compat;
use tokio_util::compat::FuturesAsyncReadCompatExt;
use tokio_util::compat::FuturesAsyncWriteCompatExt;
// A reply may reach the parent just before its writer releases the output slot.
pub(super) const OUTPUT_SLOTS_PER_INSTANCE: usize = MAX_IN_FLIGHT_TURNS + 1;
/// Only poll on a dedicated blocking thread: AllowStdIo blocks inside poll_read.
pub(super) fn blocking_reader<R: io::Read>(
input: R,
) -> FramedRead<Compat<AllowStdIo<R>>, LengthDelimitedCodec> {
FramedRead::new(AllowStdIo::new(input).compat(), framing::codec())
}
/// Only poll on a dedicated blocking thread: AllowStdIo blocks inside poll_write.
pub(super) fn blocking_writer<W: io::Write>(
output: W,
) -> FramedWrite<Compat<AllowStdIo<W>>, LengthDelimitedCodec> {
FramedWrite::new(AllowStdIo::new(output).compat_write(), framing::codec())
}
pub(super) struct Instance {
pub(super) id: u64,
pub(super) retired: Arc<AtomicBool>,
pub(super) close_output: OnceLock<(mpsc::SyncSender<QueuedOutput>, QueuedOutput)>,
pub(super) closed: AtomicBool,
pub(super) input_slots: Arc<Semaphore>,
output_slots: Arc<Semaphore>,
}
impl Instance {
pub(super) fn new(id: u64) -> Self {
Self {
id,
retired: Arc::new(AtomicBool::new(false)),
close_output: OnceLock::new(),
closed: AtomicBool::new(false),
input_slots: Arc::new(Semaphore::new(MAX_IN_FLIGHT_TURNS)),
output_slots: Arc::new(Semaphore::new(OUTPUT_SLOTS_PER_INSTANCE)),
}
}
}
impl Drop for Instance {
fn drop(&mut self) {
// The engine, queued turns and earlier output have all released this instance.
if let Some((outgoing_tx, output)) = self.close_output.take()
&& let Err(error) = outgoing_tx.try_send(output)
{
super::workers::fatal(io::Error::other(error));
}
}
}
pub(super) enum OutputReservation {
Turn {
_instance: Arc<Instance>,
_permit: OwnedSemaphorePermit,
},
Close {
retired: Arc<AtomicBool>,
},
Rejected {
_permit: OwnedSemaphorePermit,
},
}
pub(super) struct QueuedOutput {
pub(super) packets: Vec<Packet<RuntimeMessage>>,
pub(super) _reservation: OutputReservation,
}
pub(super) struct Transport {
pub(super) instance: Arc<Instance>,
pub(super) outgoing_tx: mpsc::SyncSender<QueuedOutput>,
}
impl Transport {
pub(super) fn ensure_open(&self) -> io::Result<()> {
if self.instance.closed.load(Ordering::Acquire) {
return Err(io::Error::other("plugin instance closed"));
}
Ok(())
}
pub(super) fn write(&self, messages: Vec<RuntimeMessage>) -> io::Result<()> {
self.ensure_open()?;
if messages.is_empty() {
return Ok(());
}
let permit = Arc::clone(&self.instance.output_slots)
.try_acquire_owned()
.map_err(|_| io::Error::other("plugin instance output full"))?;
let packets = messages
.into_iter()
.map(|message| Packet {
instance: self.instance.id,
message,
})
.collect();
self.outgoing_tx
.try_send(QueuedOutput {
packets,
_reservation: OutputReservation::Turn {
_instance: Arc::clone(&self.instance),
_permit: permit,
},
})
.map_err(io::Error::other)
}
}
#[cfg(test)]
#[path = "transport_tests.rs"]
mod tests;

View File

@@ -0,0 +1,71 @@
#![cfg(test)]
//! Native sends fail immediately on saturation or cancellation.
use super::*;
use futures::SinkExt;
use futures::StreamExt;
use futures::executor::block_on;
use pretty_assertions::assert_eq;
#[test]
fn a_full_instance_output_does_not_block_peers_or_the_executor() {
let (outgoing_tx, outgoing_rx) = mpsc::sync_channel(OUTPUT_SLOTS_PER_INSTANCE + 1);
let first = Transport {
instance: Arc::new(Instance::new(/*id*/ 1)),
outgoing_tx: outgoing_tx.clone(),
};
let peer = Transport {
instance: Arc::new(Instance::new(/*id*/ 2)),
outgoing_tx,
};
for _ in 0..OUTPUT_SLOTS_PER_INSTANCE {
first.write(vec![RuntimeMessage::Initialized]).unwrap();
}
assert!(first.write(vec![RuntimeMessage::Initialized]).is_err());
peer.write(vec![RuntimeMessage::Initialized]).unwrap();
assert_eq!(outgoing_rx.recv().unwrap().packets[0].instance, 1);
first.write(vec![RuntimeMessage::Initialized]).unwrap();
first.instance.closed.store(true, Ordering::Release);
assert!(first.write(vec![RuntimeMessage::Initialized]).is_err());
}
#[test]
fn rejects_length_before_reading_payload() {
let bytes = u32::MAX.to_le_bytes();
assert_eq!(
block_on(blocking_reader(bytes.as_slice()).next())
.unwrap()
.unwrap_err()
.kind(),
io::ErrorKind::InvalidData
);
}
#[test]
fn rejects_truncated_payload() {
assert_eq!(
block_on(blocking_reader([1, 0, 0, 0].as_slice()).next())
.unwrap_or_else(|| Err(io::ErrorKind::UnexpectedEof.into()))
.unwrap_err()
.kind(),
io::ErrorKind::UnexpectedEof
);
}
#[test]
fn blocking_transport_preserves_wire_format_and_buffered_frames() -> io::Result<()> {
let payloads = [b"abc".as_slice(), b"", b"hi\0"];
let mut bytes = Vec::new();
{
let mut output = blocking_writer(&mut bytes);
for payload in payloads {
block_on(output.send(payload.to_vec().into()))?;
}
}
assert_eq!(bytes, b"\x03\0\0\0abc\0\0\0\0\x03\0\0\0hi\0");
let mut input = blocking_reader(bytes.as_slice());
for payload in payloads {
assert_eq!(block_on(input.next()).unwrap()?.as_ref(), payload);
}
Ok(())
}

View File

@@ -0,0 +1,143 @@
//! One observer interrupts the active JS turn; disarming and interruption share a lock.
use std::io;
use std::sync::Arc;
use std::sync::Condvar;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::thread::JoinHandle;
use std::time::Duration;
use std::time::Instant;
struct Active {
instance: u64,
handle: v8::IsolateHandle,
deadline: Instant,
terminated: bool,
}
#[derive(Default)]
struct Execution {
active: Option<Active>,
stopped: bool,
}
type Shared = Arc<(Mutex<Execution>, Condvar)>;
#[derive(Clone)]
pub(super) struct Observer(Shared);
pub(super) struct IsolateExecutionWatchdog {
pub(super) observer: Observer,
thread: Option<JoinHandle<()>>,
}
impl IsolateExecutionWatchdog {
pub(super) fn new() -> io::Result<Self> {
let shared = Arc::new((Mutex::new(Execution::default()), Condvar::new()));
let observer = Observer(Arc::clone(&shared));
let thread = std::thread::Builder::new()
.name("ui-plugin-watchdog".into())
.spawn(move || {
let (lock, changed) = &*shared;
let mut state = lock
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
while !state.stopped {
if let Some(active) = &mut state.active
&& !active.terminated
{
let remaining = active.deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
active.handle.terminate_execution();
active.terminated = true;
} else {
(state, _) = changed
.wait_timeout(state, remaining)
.unwrap_or_else(std::sync::PoisonError::into_inner);
continue;
}
}
state = changed
.wait(state)
.unwrap_or_else(std::sync::PoisonError::into_inner);
}
})?;
Ok(Self {
observer,
thread: Some(thread),
})
}
pub(super) fn arm(&self, instance: u64, handle: v8::IsolateHandle) {
let (lock, changed) = &*self.observer.0;
let mut state = lock
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
assert!(state.active.is_none());
state.active = Some(Active {
instance,
handle,
deadline: Instant::now() + Duration::from_millis(100),
terminated: false,
});
changed.notify_one();
}
pub(super) fn disarm(&self) -> io::Result<()> {
self.disarm_with(|lock| {
lock.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
})
}
fn disarm_with<'a>(
&'a self,
acquire: impl FnOnce(&'a Mutex<Execution>) -> MutexGuard<'a, Execution>,
) -> io::Result<()> {
let (lock, changed) = &*self.observer.0;
let active = acquire(lock).active.take();
changed.notify_one();
if active.is_some_and(|active| active.terminated) {
Err(io::Error::new(
io::ErrorKind::TimedOut,
"plugin execution deadline exceeded",
))
} else {
Ok(())
}
}
}
#[cfg(test)]
#[path = "watchdog_tests.rs"]
mod tests;
impl Observer {
pub(super) fn cancel(&self, instance: u64) {
let (lock, changed) = &*self.0;
let mut state = lock
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(active) = &mut state.active
&& active.instance == instance
{
active.handle.terminate_execution();
active.terminated = true;
}
changed.notify_one();
}
}
impl Drop for IsolateExecutionWatchdog {
fn drop(&mut self) {
let (lock, changed) = &*self.observer.0;
lock.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.stopped = true;
changed.notify_one();
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}

View File

@@ -0,0 +1,38 @@
#![cfg(test)]
use super::*;
use pretty_assertions::assert_eq;
use std::sync::mpsc;
#[test]
fn disarm_waits_for_an_interrupt_in_progress() {
crate::v8_init::ensure_v8_initialized().unwrap();
let isolate = v8::Isolate::new(Default::default());
let watchdog = IsolateExecutionWatchdog {
observer: Observer(Arc::new((Mutex::new(Execution::default()), Condvar::new()))),
thread: None,
};
watchdog.arm(/*instance*/ 1, isolate.thread_safe_handle());
let (lock, _) = &*watchdog.observer.0;
let mut interrupt = lock.lock().unwrap();
std::thread::scope(|scope| {
let (attempt_tx, attempt_rx) = mpsc::sync_channel(0);
let watchdog = &watchdog;
let disarming = scope.spawn(move || {
watchdog.disarm_with(|lock| {
assert!(matches!(
lock.try_lock(),
Err(std::sync::TryLockError::WouldBlock)
));
attempt_tx.send(()).unwrap();
lock.lock().unwrap()
})
});
attempt_rx.recv().unwrap();
interrupt.active.as_mut().unwrap().terminated = true;
drop(interrupt);
assert_eq!(
disarming.join().unwrap().unwrap_err().kind(),
io::ErrorKind::TimedOut
);
});
}

View File

@@ -0,0 +1,286 @@
//! Dedicated stdin, stdout, JS execution and watchdog threads. Queue admission is
//! per instance, and cancellation bypasses queued JS turns; V8 manages its own workers.
use std::collections::HashMap;
use std::io;
use std::sync::Arc;
use std::sync::Weak;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::mpsc;
use std::thread;
use super::engine::Engine;
use super::transport::Instance;
use super::transport::OUTPUT_SLOTS_PER_INSTANCE;
use super::transport::OutputReservation;
use super::transport::QueuedOutput;
use super::transport::Transport;
use super::transport::blocking_reader;
use super::transport::blocking_writer;
use super::watchdog::IsolateExecutionWatchdog;
use akode_plugin_host::MAX_INSTANCES;
use akode_plugin_host::protocol::ErrorCode;
use akode_plugin_host::protocol::HostMessage;
use akode_plugin_host::protocol::MAX_IN_FLIGHT_TURNS;
use akode_plugin_host::protocol::Packet;
use akode_plugin_host::protocol::RuntimeMessage;
use futures::SinkExt;
use futures::StreamExt;
use futures::executor::block_on;
use tokio::sync::OwnedSemaphorePermit;
use tokio::sync::Semaphore;
// Every instance reserves space for its turns and one close; output also reserves
// one slot for a rejected open.
const COMMAND_QUEUE_CAPACITY: usize = MAX_INSTANCES * (MAX_IN_FLIGHT_TURNS + 1);
const OUTPUT_QUEUE_CAPACITY: usize = MAX_INSTANCES * (OUTPUT_SLOTS_PER_INSTANCE + 1) + 1;
enum Command {
Turn {
packet: Packet<HostMessage>,
instance: Arc<Instance>,
_permit: OwnedSemaphorePermit,
},
Close(Arc<Instance>),
}
pub(super) fn run() -> io::Result<()> {
let (outgoing_tx, outgoing_rx) = mpsc::sync_channel::<QueuedOutput>(OUTPUT_QUEUE_CAPACITY);
thread::Builder::new()
.name("ui-plugin-output".into())
.spawn(move || {
let mut writer = blocking_writer(io::stdout().lock());
if let Err(error) = block_on(writer.send(akode_plugin_host::READY.to_vec().into())) {
fatal(error);
}
for output in outgoing_rx {
// The parent can send a replacement as soon as it reads Closed.
if let OutputReservation::Close { retired } = &output._reservation {
retired.store(true, Ordering::Release);
}
for packet in &output.packets {
let bytes =
serde_json::to_vec(packet).unwrap_or_else(|error| fatal(error.into()));
if let Err(error) = block_on(writer.send(bytes.into())) {
fatal(error);
}
}
}
})?;
let watchdog = IsolateExecutionWatchdog::new()?;
let observer = watchdog.observer.clone();
let (command_tx, command_rx) = mpsc::sync_channel(COMMAND_QUEUE_CAPACITY);
let executor_outgoing_tx = outgoing_tx.clone();
thread::Builder::new()
.name("ui-plugin-executor".into())
.spawn(move || {
if let Err(error) = execute(command_rx, executor_outgoing_tx, watchdog) {
fatal(error);
}
})?;
let mut live = HashMap::<u64, (Arc<AtomicBool>, Weak<Instance>)>::new();
let rejected_slot = Arc::new(Semaphore::new(1));
let mut last_id = None;
let mut input = blocking_reader(io::stdin().lock());
loop {
let packet: Packet<HostMessage> =
serde_json::from_slice(&block_on(input.next()).ok_or(io::ErrorKind::UnexpectedEof)??)?;
// An instance keeps its registration until its engine, queued turns and output drain.
live.retain(|_, (retired, _)| !retired.load(Ordering::Acquire));
let instance = match &packet.message {
HostMessage::Initialize { .. } => {
if last_id.is_some_and(|last| packet.instance <= last) {
return Err(io::Error::other("invalid plugin instance ID"));
}
last_id = Some(packet.instance);
if live.len() >= MAX_INSTANCES {
// Backpressure excess opens instead of accumulating unbounded close frames.
let permit = block_on(Arc::clone(&rejected_slot).acquire_owned())
.map_err(io::Error::other)?;
outgoing_tx
.try_send(QueuedOutput {
packets: vec![close_packet(packet.instance)],
_reservation: OutputReservation::Rejected { _permit: permit },
})
.map_err(io::Error::other)?;
continue;
}
let instance = Arc::new(Instance::new(packet.instance));
live.insert(
instance.id,
(Arc::clone(&instance.retired), Arc::downgrade(&instance)),
);
instance
}
HostMessage::Dispatch { .. } | HostMessage::Close => {
let Some(instance) = live
.get(&packet.instance)
.and_then(|(_, instance)| instance.upgrade())
else {
continue;
};
instance
}
};
admit_turn(packet, instance, &observer, &command_tx)?;
}
}
fn admit_turn(
packet: Packet<HostMessage>,
instance: Arc<Instance>,
observer: &super::watchdog::Observer,
command_tx: &mpsc::SyncSender<Command>,
) -> io::Result<()> {
if instance.closed.load(Ordering::Acquire) {
return Ok(());
}
let permit = if matches!(packet.message, HostMessage::Close) {
None
} else {
Arc::clone(&instance.input_slots).try_acquire_owned().ok()
};
let command = if let Some(permit) = permit {
Command::Turn {
packet,
instance,
_permit: permit,
}
} else {
if instance.closed.swap(true, Ordering::AcqRel) {
return Ok(());
}
observer.cancel(instance.id);
Command::Close(instance)
};
command_tx.try_send(command).map_err(io::Error::other)
}
fn execute(
command_rx: mpsc::Receiver<Command>,
outgoing_tx: mpsc::SyncSender<QueuedOutput>,
watchdog: IsolateExecutionWatchdog,
) -> io::Result<()> {
let mut instances = HashMap::<u64, Engine>::new();
for command in command_rx {
let (packet, instance, _permit) = match command {
Command::Close(instance) => {
if instances.remove(&instance.id).is_some() {
send_close(&outgoing_tx, instance, /*error*/ None)?;
}
continue;
}
Command::Turn {
packet,
instance,
_permit,
} => (packet, instance, _permit),
};
if instance.closed.load(Ordering::Acquire) {
if matches!(packet.message, HostMessage::Initialize { .. })
|| instances.remove(&instance.id).is_some()
{
send_close(&outgoing_tx, instance, /*error*/ None)?;
}
continue;
}
if matches!(packet.message, HostMessage::Initialize { .. }) {
let transport = Transport {
instance: Arc::clone(&instance),
outgoing_tx: outgoing_tx.clone(),
};
match Engine::new(transport) {
Ok(engine) => {
instances.insert(instance.id, engine);
}
Err(error) => {
eprintln!("plugin isolate initialization failed: {error}");
instance.closed.store(true, Ordering::Release);
send_close(&outgoing_tx, instance, /*error*/ None)?;
continue;
}
}
}
let Some(engine) = instances.get_mut(&instance.id) else {
let was_closed = instance.closed.swap(true, Ordering::AcqRel);
let error = (!was_closed).then_some(RuntimeMessage::Error {
code: ErrorCode::ExecutionFailed,
script_error: None,
});
send_close(&outgoing_tx, instance, error)?;
continue;
};
watchdog.arm(instance.id, engine.handle());
let result = engine
.transport
.ensure_open()
.map(|()| engine.turn(packet.message));
drop(_permit);
let error = match (watchdog.disarm(), result) {
(Ok(()), Ok(Ok(messages))) => {
if engine.transport.write(messages).is_ok() {
continue;
}
None
}
(Ok(()), Ok(Err(error))) => Some(error),
(Ok(()), Err(_)) => None,
(Err(_), _) => Some(RuntimeMessage::Error {
code: ErrorCode::ExecutionTimedOut,
script_error: None,
}),
};
let error = if instance.closed.swap(true, Ordering::AcqRel) {
None
} else {
error
};
instances.remove(&instance.id);
send_close(&outgoing_tx, instance, error)?;
}
Err(io::Error::other("plugin input stopped"))
}
fn close_packet(instance: u64) -> Packet<RuntimeMessage> {
Packet {
instance,
message: RuntimeMessage::Closed,
}
}
fn send_close(
outgoing_tx: &mpsc::SyncSender<QueuedOutput>,
instance: Arc<Instance>,
error: Option<RuntimeMessage>,
) -> io::Result<()> {
let mut packets = Vec::new();
if let Some(error) = error {
packets.push(Packet {
instance: instance.id,
message: error,
});
}
packets.push(close_packet(instance.id));
instance
.close_output
.set((
outgoing_tx.clone(),
QueuedOutput {
packets,
_reservation: OutputReservation::Close {
retired: Arc::clone(&instance.retired),
},
},
))
.map_err(|_| io::Error::other("plugin close already scheduled"))
}
pub(super) fn fatal(error: io::Error) -> ! {
eprintln!("plugin helper failed: {error}");
std::process::exit(1);
}
#[cfg(test)]
#[path = "workers_tests.rs"]
mod tests;

View File

@@ -0,0 +1,126 @@
#![cfg(test)]
//! Exercise executor invariants that the stdin reader normally enforces.
use super::*;
use akode_plugin_host::protocol::ReturnMode;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn missing_engine_fails_only_its_instance() {
crate::v8_init::ensure_v8_initialized().unwrap();
let peer = Arc::new(Instance::new(/*id*/ 1));
let missing = Arc::new(Instance::new(/*id*/ 2));
let dispatch = || HostMessage::Dispatch {
id: 0,
export: "default".into(),
return_mode: ReturnMode::Sync,
};
let (command_tx, command_rx) = mpsc::channel();
for (instance, message) in [
(
&peer,
HostMessage::Initialize {
source: "export default () => 'alive'".into(),
},
),
(&missing, dispatch()),
(&peer, dispatch()),
] {
command_tx
.send(Command::Turn {
packet: Packet {
instance: instance.id,
message,
},
instance: Arc::clone(instance),
_permit: Arc::clone(&instance.input_slots)
.try_acquire_owned()
.unwrap(),
})
.unwrap();
}
drop(command_tx);
let (outgoing_tx, outgoing_rx) = mpsc::sync_channel(OUTPUT_QUEUE_CAPACITY);
let error = execute(
command_rx,
outgoing_tx,
IsolateExecutionWatchdog::new().unwrap(),
)
.unwrap_err();
assert_eq!(error.to_string(), "plugin input stopped");
assert!(missing.closed.load(Ordering::Acquire));
drop(missing);
let packets: Vec<_> = outgoing_rx
.into_iter()
.flat_map(|output| output.packets)
.collect();
assert_eq!(
serde_json::to_value(packets).unwrap(),
json!([
{"instance":1,"message":{"type":"initialized"}},
{"instance":1,"message":{"type":"reply","id":0,"value":"alive"}},
{"instance":2,"message":{"type":"error","code":"execution_failed","scriptError":null}},
{"instance":2,"message":{"type":"closed"}}
])
);
}
#[test]
fn close_waits_for_the_last_queued_turn() {
let (outgoing_tx, outgoing_rx) = mpsc::sync_channel(OUTPUT_QUEUE_CAPACITY);
let instance = Arc::new(Instance::new(/*id*/ 1));
let queued_turn = Arc::clone(&instance);
send_close(&outgoing_tx, instance, /*error*/ None).unwrap();
assert!(matches!(
outgoing_rx.try_recv(),
Err(mpsc::TryRecvError::Empty)
));
drop(queued_turn);
let output = outgoing_rx.try_recv().unwrap();
assert_eq!(
serde_json::to_value(output.packets).unwrap(),
json!([{"instance":1,"message":{"type":"closed"}}])
);
}
#[test]
fn input_overload_closes_only_the_busy_instance() {
let busy = Arc::new(Instance::new(/*id*/ 1));
let peer = Arc::new(Instance::new(/*id*/ 2));
let watchdog = IsolateExecutionWatchdog::new().unwrap();
let (command_tx, command_rx) = mpsc::sync_channel(COMMAND_QUEUE_CAPACITY);
let dispatch = |instance: &Arc<Instance>, id| {
let packet = Packet {
instance: instance.id,
message: HostMessage::Dispatch {
id,
export: "run".into(),
return_mode: ReturnMode::Sync,
},
};
admit_turn(
packet,
Arc::clone(instance),
&watchdog.observer,
&command_tx,
)
.unwrap();
};
// Leave every turn queued so its permit stays in flight.
for id in 0..=MAX_IN_FLIGHT_TURNS as u64 {
dispatch(&busy, id);
}
dispatch(&peer, 0);
for _ in 0..MAX_IN_FLIGHT_TURNS {
assert!(
matches!(command_rx.try_recv(), Ok(Command::Turn { instance, .. }) if instance.id == busy.id)
);
}
assert!(
matches!(command_rx.try_recv(), Ok(Command::Close(instance)) if instance.id == busy.id)
);
assert!(
matches!(command_rx.try_recv(), Ok(Command::Turn { instance, .. }) if instance.id == peer.id)
);
}

View File

@@ -0,0 +1,70 @@
use std::sync::OnceLock;
/// Controls whether V8 may generate executable code at runtime.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum V8JitMode {
#[default]
Enabled,
Disabled,
}
struct V8Initialization {
_platform: v8::SharedRef<v8::Platform>,
jit_mode: V8JitMode,
}
static V8_INITIALIZATION: OnceLock<Result<V8Initialization, String>> = OnceLock::new();
/// Initializes the process-wide V8 platform with the requested JIT mode.
///
/// Call this before executing any code-mode cells when JIT must be disabled.
/// V8 cannot change JIT mode after initialization, so a later call requesting
/// a different mode returns an error. Code mode initializes V8 with JIT enabled
/// by default when this function has not been called explicitly.
pub fn initialize_v8(jit_mode: V8JitMode) -> Result<(), String> {
match V8_INITIALIZATION.get_or_init(|| initialize_v8_with_mode(jit_mode)) {
Ok(initialization) if initialization.jit_mode == jit_mode => Ok(()),
Ok(initialization) => Err(format!(
"V8 was already initialized with JIT {}",
initialization.jit_mode.description()
)),
Err(error_text) => Err(error_text.clone()),
}
}
pub(crate) fn ensure_v8_initialized() -> Result<(), String> {
match V8_INITIALIZATION.get_or_init(|| initialize_v8_with_mode(V8JitMode::Enabled)) {
Ok(_) => Ok(()),
Err(error_text) => Err(error_text.clone()),
}
}
fn initialize_v8_with_mode(jit_mode: V8JitMode) -> Result<V8Initialization, String> {
v8::icu::set_common_data_78(deno_core_icudata::ICU_DATA)
.map_err(|error_code| format!("failed to initialize ICU data: {error_code}"))?;
// The pinned V8 can inline Array.prototype.sort with incompatible element kinds.
// Disable the affected paths in TurboFan and the Maglev/Turbolev frontend until
// our V8 artifacts include the upstream fix for mixed-element sorting:
// https://github.com/v8/v8/commit/e0562d87ad9c17042b581582c99237d798572e67
v8::V8::set_flags_from_string("--no-maglev --no-turbolev --no-turbo-inline-array-builtins");
match jit_mode {
V8JitMode::Enabled => {}
V8JitMode::Disabled => v8::V8::set_flags_from_string("--jitless"),
}
let platform = v8::new_default_platform(0, false).make_shared();
v8::V8::initialize_platform(platform.clone());
v8::V8::initialize();
Ok(V8Initialization {
_platform: platform,
jit_mode,
})
}
impl V8JitMode {
fn description(self) -> &'static str {
match self {
Self::Enabled => "enabled",
Self::Disabled => "disabled",
}
}
}