aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 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) })
}