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,273 @@
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use std::sync::PoisonError;
use std::time::Duration;
use akode_code_mode_protocol::CellId;
use akode_code_mode_protocol::grpc;
use akode_protocol::protocol::W3cTraceContext;
use futures::FutureExt;
use tokio_util::sync::CancellationToken;
use tracing::Instrument;
use tracing::warn;
use super::SessionInner;
use super::completion;
use super::conversion;
use super::deadline;
use super::state::CallbackAdmission;
impl SessionInner {
pub(super) fn spawn_session_events(
self: &Arc<Self>,
events: tonic::Streaming<grpc::SessionEvent>,
) {
self.spawn_stream(events, "session lease", Self::handle_session_event);
}
pub(super) fn spawn_tool_subscription(
self: &Arc<Self>,
calls: tonic::Streaming<grpc::ToolCall>,
) {
self.spawn_stream(calls, "tool subscription", Self::handle_tool_call);
}
fn spawn_stream<T: Send + 'static>(
self: &Arc<Self>,
mut stream: tonic::Streaming<T>,
stream_name: &'static str,
handle: fn(&Arc<Self>, T) -> Result<(), String>,
) {
let inner = Arc::clone(self);
self.stream_tasks.spawn(async move {
loop {
let message = tokio::select! {
biased;
_ = inner.stopped.cancelled() => return,
message = stream.message() => message,
};
match message {
Ok(Some(message)) => {
if let Err(error) = handle(&inner, message) {
inner.fail(error);
return;
}
}
Ok(None) => {
inner.fail(format!("gRPC code-mode {stream_name} closed unexpectedly"));
return;
}
Err(error) => {
inner.fail(deadline::failure(stream_name, error));
return;
}
}
}
});
}
fn handle_session_event(self: &Arc<Self>, event: grpc::SessionEvent) -> Result<(), String> {
match event
.event
.ok_or_else(|| "gRPC code-mode host sent an empty session event".to_string())?
{
grpc::session_event::Event::Opened(_) => {
Err("gRPC code-mode host repeated the session opening event".to_string())
}
grpc::session_event::Event::ToolCallCancelled(cancelled) => {
self.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.cancel_invocation(&cancelled.invocation_id)?;
Ok(())
}
grpc::session_event::Event::Notification(notification) => {
self.handle_notification(notification)
}
grpc::session_event::Event::NotificationCancelled(_) => Ok(()),
grpc::session_event::Event::CellClosed(closed) => {
let cell = self
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.close_cell(closed)?;
self.report_closed_cell(cell);
Ok(())
}
}
}
fn handle_tool_call(self: &Arc<Self>, call: grpc::ToolCall) -> Result<(), String> {
if call.session_id != self.id {
return Err(format!(
"gRPC code-mode tool invocation belongs to session {} instead of {}",
call.session_id, self.id
));
}
let admission = self
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.admit_invocation(&call)?;
let callback_span = tracing::info_span!(
"code_mode.grpc.callback",
otel.name = "code_mode.grpc.callback",
session.id = %call.session_id,
execution.id = %call.execution_id,
cell.id = %call.cell_id,
invocation.id = %call.invocation_id,
);
if let Some(traceparent) = call.traceparent.as_ref() {
akode_otel::set_parent_from_w3c_trace_context(
&callback_span,
&W3cTraceContext {
traceparent: Some(traceparent.clone()),
tracestate: None,
},
);
}
let invocation_id = call.invocation_id.clone();
let cancellation = match admission {
CallbackAdmission::Active(cancellation, delegate) => Ok((cancellation, delegate)),
CallbackAdmission::Cancelled => return Ok(()),
CallbackAdmission::Closed => Err(format!("code-mode cell {} is closed", call.cell_id)),
CallbackAdmission::Rejected(error) => Err(error),
};
let (cancellation, delegate) = match cancellation {
Ok(cancellation) => cancellation,
Err(error) => {
let inner = Arc::clone(self);
tokio::spawn(async move {
inner
.complete_tool_call(invocation_id, CancellationToken::new(), Err(error))
.await;
});
return Ok(());
}
};
let invocation = conversion::tool_call(call);
let inner = Arc::clone(self);
tokio::spawn(
async move {
let result = match invocation {
Ok(invocation) => {
let callback = AssertUnwindSafe(async {
delegate
.invoke_tool(invocation, cancellation.child_token())
.await
})
.catch_unwind();
tokio::select! {
biased;
_ = cancellation.cancelled() => return,
result = callback => match result {
Ok(result) => result,
Err(_) => Err("code-mode tool delegate panicked".to_string()),
},
}
}
Err(error) => Err(error),
};
inner
.complete_tool_call(invocation_id, cancellation, result)
.await;
}
.instrument(callback_span),
);
Ok(())
}
async fn complete_tool_call(
&self,
invocation_id: String,
cancellation: CancellationToken,
result: Result<serde_json::Value, String>,
) {
let request = completion::request(&self.id, &invocation_id, result);
tokio::select! {
biased;
_ = cancellation.cancelled() => {}
// NotFound can mean an invocation in a live session was canceled.
// Check cancellation before treating a completion error as fatal.
result = async {
let _permit = self.completion_permits.acquire().await
.map_err(|_| "code-mode completion queue is closed".to_string())?;
let mut client = self.client()?;
deadline::request(
self,
"tool invocation completion",
Duration::ZERO,
client.complete_tool_call(self.request(request)),
).await
} => {
if let Err(error) = result
&& !cancellation.is_cancelled()
&& !self.stopped.is_cancelled()
{
self.fail(error);
}
}
}
self.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.finish_invocation(&invocation_id);
}
fn handle_notification(
self: &Arc<Self>,
notification: grpc::Notification,
) -> Result<(), String> {
let admission = self
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.admit_notification(&notification)?;
let (cancellation, delegate) = match admission {
CallbackAdmission::Active(cancellation, delegate) => (cancellation, delegate),
CallbackAdmission::Cancelled | CallbackAdmission::Closed => return Ok(()),
CallbackAdmission::Rejected(error) => {
warn!("code-mode notification was dropped: {error}");
return Ok(());
}
};
let execution_id = notification.execution_id;
let inner = Arc::clone(self);
// Delegate callbacks stay outside the tracked session tasks so shutdown can cancel
// them without waiting for arbitrary delegate work to complete.
tokio::spawn(async move {
let callback = AssertUnwindSafe(async {
delegate
.notify(
notification.call_id,
CellId::new(notification.cell_id),
notification.text,
cancellation,
)
.await
})
.catch_unwind();
let result = tokio::select! {
biased;
_ = inner.stopped.cancelled() => return,
result = callback => result,
};
match result {
Ok(Ok(())) => {}
Ok(Err(error)) => warn!("code-mode notification delegate failed: {error}"),
Err(_) => warn!("code-mode notification delegate panicked"),
}
let cell = inner
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.finish_notification(&execution_id);
inner.report_closed_cell(cell);
});
Ok(())
}
}
#[cfg(test)]
#[path = "callbacks_tests.rs"]
mod tests;

View File

@@ -0,0 +1,132 @@
//! Keeps late callback failures from disrupting cancellation and shutdown.
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::time::Duration;
use akode_code_mode_protocol::CodeModeOutputTruncation;
use http_body_util::Full;
use pretty_assertions::assert_eq;
use tokio::sync::Notify;
use tokio::sync::Semaphore;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use tonic::body::Body;
use tonic::codegen::Bytes;
use tonic::codegen::http::Response;
use tower::service_fn;
use tower::util::BoxCloneSyncService;
use super::super::GrpcClient;
use super::super::MAX_IN_FLIGHT_COMPLETIONS;
use super::super::state::SessionState;
use super::super::transport::SharedTransport;
use super::SessionInner;
use crate::remote_session::wait_for_watch;
#[tokio::test]
async fn missing_invocation_completion_racing_cancellation_preserves_session() {
let cancellation = CancellationToken::new();
let completion_cancellation = cancellation.clone();
let client = GrpcClient::new(BoxCloneSyncService::new(service_fn(move |_request| {
// Cancel after the biased select has polled cancellation, before the RPC fails.
completion_cancellation.cancel();
async { Ok(tonic::Status::not_found("unknown code-mode tool invocation").into_http()) }
})));
let session = session(client);
session
.complete_tool_call(
"invocation".to_string(),
cancellation,
Ok(serde_json::Value::Null),
)
.await;
assert_eq!(session.require_open(), Ok(()));
}
fn session(client: GrpcClient) -> Arc<SessionInner> {
let client = Arc::new(client);
Arc::new(SessionInner {
id: "session".to_string(),
output_truncation: CodeModeOutputTruncation::Client,
route: None,
runtime: tokio::runtime::Handle::current(),
state: Mutex::new(SessionState::with_client(Arc::clone(&client))),
wait_slots: Mutex::new(HashMap::new()),
shutdown_requested: AtomicBool::new(/*v*/ false),
shutdown_result: Mutex::new(/*t*/ None),
stopped: CancellationToken::new(),
stream_tasks: TaskTracker::new(),
completion_permits: Arc::new(Semaphore::new(MAX_IN_FLIGHT_COMPLETIONS)),
_transport: Arc::new(SharedTransport::Connected(client)),
})
}
#[tokio::test]
async fn cancelled_completion_does_not_wait_for_delivery_capacity() {
let client = GrpcClient::new(BoxCloneSyncService::new(service_fn(|_request| async {
Ok(tonic::Status::internal("a queued completion must not send an RPC").into_http())
})));
let session = session(client);
let _capacity = session
.completion_permits
.acquire_many(MAX_IN_FLIGHT_COMPLETIONS as u32)
.await
.expect("fill delivery window");
let cancellation = CancellationToken::new();
let completion = session.complete_tool_call(
"queued".to_string(),
cancellation.clone(),
Ok(serde_json::Value::Null),
);
tokio::pin!(completion);
assert!(futures::poll!(completion.as_mut()).is_pending());
cancellation.cancel();
completion.await;
assert_eq!(session.require_open(), Ok(()));
}
#[tokio::test(start_paused = true)]
async fn shutdown_is_ordered_with_session_failure() {
let close_started = Arc::new(Notify::new());
let finish_close = Arc::new(Notify::new());
let started = Arc::clone(&close_started);
let finish = Arc::clone(&finish_close);
let client = GrpcClient::new(BoxCloneSyncService::new(service_fn(move |_request| {
let started = Arc::clone(&started);
let finish = Arc::clone(&finish);
async move {
started.notify_one();
finish.notified().await;
Ok(Response::builder()
.header("content-type", "application/grpc")
.header("grpc-status", "0")
// An empty protobuf CloseSessionResponse in a gRPC frame.
.body(Body::new(Full::new(Bytes::from_static(b"\0\0\0\0\0"))))
.expect("close response"))
}
})));
let closing = session(client.clone());
let result = closing.request_shutdown();
tokio::time::timeout(Duration::from_secs(5), close_started.notified())
.await
.expect("CloseSession started");
// A callback can decide to fail just before shutdown starts, then reach
// fail() after CloseSession is in flight. Recheck at the state transition.
closing.fail("late callback failure".to_string());
assert!(!closing.stopped.is_cancelled());
finish_close.notify_one();
assert_eq!(wait_for_watch(result).await, Ok(()));
// If failure wins first, shutdown observes a closed session and skips the RPC.
let failed = session(client);
failed.fail("earlier callback failure".to_string());
assert!(failed.stopped.is_cancelled());
assert_eq!(wait_for_watch(failed.request_shutdown()).await, Ok(()));
}

View File

@@ -0,0 +1,54 @@
use akode_code_mode_protocol::grpc;
use akode_code_mode_protocol::host::MAX_FRAME_BYTES;
use prost::Message;
pub(super) fn request(
session_id: &str,
invocation_id: &str,
result: Result<serde_json::Value, String>,
) -> grpc::CompleteToolCallRequest {
request_with_maximum(session_id, invocation_id, result, MAX_FRAME_BYTES)
}
fn request_with_maximum(
session_id: &str,
invocation_id: &str,
result: Result<serde_json::Value, String>,
maximum_message_bytes: usize,
) -> grpc::CompleteToolCallRequest {
let outcome = match result {
Ok(value) => match serde_json::to_vec(&value) {
Ok(output_json) => {
grpc::complete_tool_call_request::Outcome::Succeeded(grpc::ToolCallSucceeded {
output_json,
})
}
Err(error) => grpc::complete_tool_call_request::Outcome::Failed(grpc::ToolCallFailed {
message: format!("failed to encode code-mode tool result: {error}"),
}),
},
Err(message) => {
grpc::complete_tool_call_request::Outcome::Failed(grpc::ToolCallFailed { message })
}
};
let mut request = grpc::CompleteToolCallRequest {
session_id: session_id.to_string(),
invocation_id: invocation_id.to_string(),
outcome: Some(outcome),
};
let encoded_bytes = request.encoded_len();
if encoded_bytes > maximum_message_bytes {
request.outcome = Some(grpc::complete_tool_call_request::Outcome::Failed(
grpc::ToolCallFailed {
message: format!(
"code-mode tool result of {encoded_bytes} encoded bytes exceeds the gRPC message limit of {maximum_message_bytes} bytes"
),
},
));
}
request
}
#[cfg(test)]
#[path = "completion_tests.rs"]
mod tests;

View File

@@ -0,0 +1,41 @@
use akode_code_mode_protocol::grpc;
use pretty_assertions::assert_eq;
use prost::Message;
use super::request;
use super::request_with_maximum;
#[test]
fn completion_size_includes_the_protobuf_envelope() {
let output = serde_json::Value::String("a".repeat(100));
let raw_json_bytes = serde_json::to_vec(&output).expect("valid JSON").len();
let completion = request_with_maximum("session", "invocation", Ok(output), raw_json_bytes);
assert!(matches!(
completion.outcome,
Some(grpc::complete_tool_call_request::Outcome::Failed(grpc::ToolCallFailed {
message,
})) if message.contains("encoded bytes exceeds the gRPC message limit")
));
}
#[test]
fn delegate_errors_larger_than_64_kib_are_preserved() {
let error = "🦀".repeat(64 * 1024);
let completion = request("session", "invocation", Err(error.clone()));
let Some(grpc::complete_tool_call_request::Outcome::Failed(failure)) = completion.outcome
else {
panic!("expected a failed tool completion");
};
assert_eq!(failure.message, error);
}
#[test]
fn completion_at_exact_message_limit_is_accepted() {
let value = serde_json::json!({ "ok": true });
let expected = request("session", "invocation", Ok(value.clone()));
let actual = request_with_maximum("session", "invocation", Ok(value), expected.encoded_len());
assert_eq!(actual, expected);
}

View File

@@ -0,0 +1,204 @@
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::CodeModeToolKind;
use akode_code_mode_protocol::ExecuteRequest;
use akode_code_mode_protocol::FunctionCallOutputContentItem;
use akode_code_mode_protocol::ImageDetail;
use akode_code_mode_protocol::RuntimeResponse;
use akode_code_mode_protocol::ToolDefinition;
use akode_code_mode_protocol::WaitOutcome;
use akode_code_mode_protocol::grpc;
use akode_protocol::ToolName;
pub(super) fn output_budget(
mode: CodeModeOutputTruncation,
max_output_tokens: Option<usize>,
) -> Result<Option<u64>, String> {
match mode {
CodeModeOutputTruncation::Client => Ok(None),
CodeModeOutputTruncation::Server => max_output_tokens
.map(u64::try_from)
.transpose()
.map_err(|error| format!("invalid code-mode output token limit: {error}")),
}
}
pub(super) fn execute_request(
session_id: &str,
execution_id: String,
request: ExecuteRequest,
) -> Result<grpc::ExecuteRequest, String> {
Ok(grpc::ExecuteRequest {
session_id: session_id.to_string(),
execution_id,
tool_call_id: request.tool_call_id,
source: request.source,
enabled_tools: request
.enabled_tools
.into_iter()
.map(tool_definition)
.collect::<Result<Vec<_>, _>>()?,
yield_time_ms: request.yield_time_ms,
max_output_tokens: request
.max_output_tokens
.map(u64::try_from)
.transpose()
.map_err(|error| format!("invalid code-mode output token limit: {error}"))?,
})
}
fn tool_definition(definition: ToolDefinition) -> Result<grpc::ToolDefinition, String> {
Ok(grpc::ToolDefinition {
name: definition.name,
tool_name: Some(grpc::ToolName {
name: definition.tool_name.name,
namespace: definition.tool_name.namespace,
}),
description: definition.description,
kind: match definition.kind {
CodeModeToolKind::Function => grpc::ToolKind::Function as i32,
CodeModeToolKind::Freeform => grpc::ToolKind::Freeform as i32,
},
input_schema_json: definition
.input_schema
.map(|schema| serde_json::to_vec(&schema))
.transpose()
.map_err(|error| format!("failed to encode code-mode tool input schema: {error}"))?,
output_schema_json: definition
.output_schema
.map(|schema| serde_json::to_vec(&schema))
.transpose()
.map_err(|error| format!("failed to encode code-mode tool output schema: {error}"))?,
})
}
pub(super) fn tool_call(call: grpc::ToolCall) -> Result<CodeModeNestedToolCall, String> {
let name = call
.tool_name
.ok_or_else(|| "code-mode tool invocation omitted its tool name".to_string())?;
let kind = match grpc::ToolKind::try_from(call.tool_kind) {
Ok(grpc::ToolKind::Function) => CodeModeToolKind::Function,
Ok(grpc::ToolKind::Freeform) => CodeModeToolKind::Freeform,
Ok(grpc::ToolKind::Unspecified) | Err(_) => {
return Err(format!(
"code-mode tool invocation has invalid kind {}",
call.tool_kind
));
}
};
let input = call
.input_json
.map(|input| serde_json::from_slice(&input))
.transpose()
.map_err(|error| format!("code-mode tool invocation contains invalid JSON: {error}"))?;
Ok(CodeModeNestedToolCall {
cell_id: CellId::new(call.cell_id),
runtime_tool_call_id: call.runtime_tool_call_id,
tool_name: ToolName::new(name.namespace, name.name),
tool_kind: kind,
input,
})
}
pub(super) fn runtime_response(outcome: grpc::ExecutionOutcome) -> Result<RuntimeResponse, String> {
let code_mode_host_duration = Some(Duration::from_nanos(outcome.code_mode_host_duration_ns));
super::validate_identifier(&outcome.cell_id, "cell ID")?;
let cell_id = CellId::new(outcome.cell_id);
let content_items = outcome
.content_items
.into_iter()
.map(content_item)
.collect::<Result<Vec<_>, _>>()?;
let response = match outcome
.outcome
.ok_or_else(|| "code-mode execution omitted its outcome".to_string())?
{
grpc::execution_outcome::Outcome::Yielded(_) => RuntimeResponse::Yielded {
cell_id,
content_items,
code_mode_host_duration,
},
grpc::execution_outcome::Outcome::Terminated(_) => RuntimeResponse::Terminated {
cell_id,
content_items,
code_mode_host_duration,
},
grpc::execution_outcome::Outcome::Completed(completed) => RuntimeResponse::Result {
cell_id,
content_items,
error_text: completed.error_text,
result_buffered_for: Duration::ZERO,
code_mode_host_duration,
},
};
Ok(response)
}
pub(super) fn wait_outcome(
response: tonic::Response<grpc::WaitResponse>,
) -> Result<WaitOutcome, String> {
let (metadata, response, _) = response.into_parts();
let outcome = match response
.state
.ok_or_else(|| "code-mode wait omitted its outcome".to_string())?
{
grpc::wait_response::State::LiveCell(response) => {
let mut response = runtime_response(response)?;
if let RuntimeResponse::Result {
result_buffered_for,
..
} = &mut response
{
// Older hosts may omit this metadata, including for completed results.
*result_buffered_for = metadata
.get(grpc::RESULT_BUFFERED_FOR_NS_METADATA)
.and_then(|value| value.to_str().ok()?.parse().ok())
.map(Duration::from_nanos)
.unwrap_or_default();
}
WaitOutcome::LiveCell(response)
}
grpc::wait_response::State::MissingCell(response) => {
WaitOutcome::MissingCell(runtime_response(response)?)
}
};
Ok(outcome)
}
fn content_item(item: grpc::ContentItem) -> Result<FunctionCallOutputContentItem, String> {
match item
.item
.ok_or_else(|| "code-mode execution returned an empty content item".to_string())?
{
grpc::content_item::Item::Text(text) => {
Ok(FunctionCallOutputContentItem::InputText { text: text.text })
}
grpc::content_item::Item::Image(image) => Ok(FunctionCallOutputContentItem::InputImage {
image_url: image.image_url,
detail: image.detail.map(image_detail).transpose()?,
}),
grpc::content_item::Item::Audio(audio) => Ok(FunctionCallOutputContentItem::InputAudio {
audio_url: audio.audio_url,
}),
}
}
fn image_detail(value: i32) -> Result<ImageDetail, String> {
match grpc::ImageDetail::try_from(value) {
Ok(grpc::ImageDetail::Auto) => Ok(ImageDetail::Auto),
Ok(grpc::ImageDetail::Low) => Ok(ImageDetail::Low),
Ok(grpc::ImageDetail::High) => Ok(ImageDetail::High),
Ok(grpc::ImageDetail::Original) => Ok(ImageDetail::Original),
Ok(grpc::ImageDetail::Unspecified) | Err(_) => {
Err(format!("code-mode image has invalid detail value {value}"))
}
}
}
#[cfg(test)]
#[path = "conversion_tests.rs"]
mod tests;

View File

@@ -0,0 +1,265 @@
use akode_code_mode_protocol::CellId;
use akode_code_mode_protocol::CodeModeNestedToolCall;
use akode_code_mode_protocol::CodeModeToolKind;
use akode_code_mode_protocol::ExecuteRequest;
use akode_code_mode_protocol::FunctionCallOutputContentItem;
use akode_code_mode_protocol::ImageDetail;
use akode_code_mode_protocol::RuntimeResponse;
use akode_code_mode_protocol::ToolDefinition;
use akode_code_mode_protocol::WaitOutcome;
use akode_code_mode_protocol::grpc;
use akode_protocol::ToolName;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::time::Duration;
use super::execute_request;
use super::runtime_response;
use super::tool_call;
use super::wait_outcome;
#[test]
fn execute_request_preserves_tool_schemas_namespaces_and_limits() {
let request = ExecuteRequest {
tool_call_id: "outer".to_string(),
enabled_tools: vec![ToolDefinition {
name: "search".to_string(),
tool_name: ToolName::namespaced("work", "search"),
description: "search the workspace".to_string(),
kind: CodeModeToolKind::Freeform,
input_schema: Some(json!({"type": "object"})),
input_schema_max_bytes: None,
output_schema: Some(json!({"type": "string"})),
}],
source: "text('hello')".to_string(),
yield_time_ms: Some(25),
max_output_tokens: Some(128),
};
assert_eq!(
execute_request("session", "execution".to_string(), request),
Ok(grpc::ExecuteRequest {
session_id: "session".to_string(),
execution_id: "execution".to_string(),
tool_call_id: "outer".to_string(),
source: "text('hello')".to_string(),
enabled_tools: vec![grpc::ToolDefinition {
name: "search".to_string(),
tool_name: Some(grpc::ToolName {
name: "search".to_string(),
namespace: Some("work".to_string()),
}),
description: "search the workspace".to_string(),
kind: grpc::ToolKind::Freeform as i32,
input_schema_json: Some(br#"{"type":"object"}"#.to_vec()),
output_schema_json: Some(br#"{"type":"string"}"#.to_vec()),
}],
yield_time_ms: Some(25),
max_output_tokens: Some(128),
})
);
}
#[test]
fn tool_call_decodes_structured_input_and_namespace() {
let call = grpc::ToolCall {
session_id: "session".to_string(),
execution_id: "execution".to_string(),
cell_id: "cell".to_string(),
invocation_id: "invocation".to_string(),
runtime_tool_call_id: "runtime-call".to_string(),
tool_name: Some(grpc::ToolName {
name: "search".to_string(),
namespace: Some("work".to_string()),
}),
tool_kind: grpc::ToolKind::Function as i32,
input_json: Some(br#"{"query":"hello"}"#.to_vec()),
sequence: 1,
traceparent: None,
};
assert_eq!(
tool_call(call),
Ok(CodeModeNestedToolCall {
cell_id: CellId::new("cell".to_string()),
runtime_tool_call_id: "runtime-call".to_string(),
tool_name: ToolName::namespaced("work", "search"),
tool_kind: CodeModeToolKind::Function,
input: Some(json!({"query": "hello"})),
})
);
}
#[test]
fn runtime_response_decodes_mixed_content_items() {
let outcome = grpc::ExecutionOutcome {
code_mode_host_duration_ns: 0,
cell_id: "cell".to_string(),
content_items: vec![
grpc::ContentItem {
item: Some(grpc::content_item::Item::Text(grpc::TextContent {
text: "hello".to_string(),
})),
},
grpc::ContentItem {
item: Some(grpc::content_item::Item::Image(grpc::ImageContent {
image_url: "data:image/png;base64,AA==".to_string(),
detail: Some(grpc::ImageDetail::Original as i32),
})),
},
grpc::ContentItem {
item: Some(grpc::content_item::Item::Audio(grpc::AudioContent {
audio_url: "data:audio/wav;base64,AA==".to_string(),
})),
},
],
outcome: Some(grpc::execution_outcome::Outcome::Completed(
grpc::ExecutionCompleted {
error_text: Some("warning".to_string()),
},
)),
};
assert_eq!(
runtime_response(outcome),
Ok(RuntimeResponse::Result {
code_mode_host_duration: Some(Duration::ZERO),
cell_id: CellId::new("cell".to_string()),
content_items: vec![
FunctionCallOutputContentItem::InputText {
text: "hello".to_string(),
},
FunctionCallOutputContentItem::InputImage {
image_url: "data:image/png;base64,AA==".to_string(),
detail: Some(ImageDetail::Original),
},
FunctionCallOutputContentItem::InputAudio {
audio_url: "data:audio/wav;base64,AA==".to_string(),
},
],
result_buffered_for: Duration::ZERO,
error_text: Some("warning".to_string()),
})
);
}
#[test]
fn wait_outcome_preserves_missing_cell_state() {
let response = grpc::WaitResponse {
state: Some(grpc::wait_response::State::MissingCell(
grpc::ExecutionOutcome {
code_mode_host_duration_ns: 0,
cell_id: "missing".to_string(),
content_items: Vec::new(),
outcome: Some(grpc::execution_outcome::Outcome::Terminated(
grpc::ExecutionTerminated {},
)),
},
)),
};
assert_eq!(
wait_outcome(tonic::Response::new(response)),
Ok(WaitOutcome::MissingCell(RuntimeResponse::Terminated {
code_mode_host_duration: Some(Duration::ZERO),
cell_id: CellId::new("missing".to_string()),
content_items: Vec::new(),
}))
);
}
#[test]
fn oversized_response_cell_ids_are_rejected() {
let response = grpc::ExecutionOutcome {
code_mode_host_duration_ns: 0,
cell_id: "x".repeat(grpc::MAX_IDENTIFIER_BYTES + 1),
content_items: Vec::new(),
outcome: Some(grpc::execution_outcome::Outcome::Yielded(
grpc::ExecutionYielded {},
)),
};
assert_eq!(
runtime_response(response),
Err(format!(
"gRPC code-mode host returned cell ID exceeding {} bytes",
grpc::MAX_IDENTIFIER_BYTES
))
);
}
#[test]
fn invalid_output_enums_and_missing_oneofs_are_rejected() {
let invalid_image = grpc::ExecutionOutcome {
code_mode_host_duration_ns: 0,
cell_id: "cell".to_string(),
content_items: vec![grpc::ContentItem {
item: Some(grpc::content_item::Item::Image(grpc::ImageContent {
image_url: "image".to_string(),
detail: Some(grpc::ImageDetail::Unspecified as i32),
})),
}],
outcome: Some(grpc::execution_outcome::Outcome::Yielded(
grpc::ExecutionYielded {},
)),
};
assert!(runtime_response(invalid_image).is_err());
assert!(wait_outcome(tonic::Response::new(grpc::WaitResponse { state: None })).is_err());
}
/// Zero is a valid measurement, and decoding must not round nanoseconds to
/// milliseconds even at the limits of the wire representation.
#[test]
fn host_timing_preserves_zero_and_nanosecond_precision() {
for code_mode_host_duration_ns in [0, 1_234_567, u64::MAX] {
let outcome = grpc::ExecutionOutcome {
cell_id: "cell".to_string(),
content_items: Vec::new(),
code_mode_host_duration_ns,
outcome: Some(grpc::execution_outcome::Outcome::Yielded(
grpc::ExecutionYielded {},
)),
};
let expected = RuntimeResponse::Yielded {
cell_id: CellId::new("cell".to_string()),
content_items: Vec::new(),
code_mode_host_duration: Some(Duration::from_nanos(code_mode_host_duration_ns)),
};
assert_eq!(runtime_response(outcome.clone()).as_ref(), Ok(&expected));
assert_eq!(
wait_outcome(tonic::Response::new(grpc::WaitResponse {
state: Some(grpc::wait_response::State::LiveCell(outcome)),
})),
Ok(WaitOutcome::LiveCell(expected))
);
}
}
#[test]
fn completed_wait_reads_optional_buffered_duration_from_response_metadata() {
for (metadata, expected_ns) in [(None, 0), (Some("0"), 0), (Some("42"), 42)] {
let mut response = tonic::Response::new(grpc::WaitResponse {
state: Some(grpc::wait_response::State::LiveCell(
grpc::ExecutionOutcome {
cell_id: "cell".to_string(),
outcome: Some(grpc::execution_outcome::Outcome::Completed(
grpc::ExecutionCompleted::default(),
)),
..Default::default()
},
)),
});
if let Some(value) = metadata {
response.metadata_mut().insert(
grpc::RESULT_BUFFERED_FOR_NS_METADATA,
value.parse().unwrap(),
);
}
let wait = wait_outcome(response).unwrap();
assert_eq!(
wait.result_buffered_for(),
Some(Duration::from_nanos(expected_ns))
);
}
}

View File

@@ -0,0 +1,110 @@
use std::fmt::Display;
use std::future::Future;
use std::time::Duration;
use super::SessionInner;
const TRANSPORT_TIMEOUT: Duration = Duration::from_secs(60);
const MAX_ERROR_BYTES: usize = 512;
pub(super) async fn startup<T, E: Display>(
operation: &str,
request: impl Future<Output = Result<T, E>>,
) -> Result<T, String> {
match enforce(operation, Duration::ZERO, request).await {
Ok(result) => Ok(result),
Err(RequestError::Failed(error)) => Err(failure(operation, error)),
Err(RequestError::TimedOut(reason)) => Err(reason),
}
}
pub(super) async fn request<T>(
session: &SessionInner,
operation: &str,
runtime_timeout: Duration,
request: impl Future<Output = Result<T, tonic::Status>>,
) -> Result<T, String> {
let result = tokio::select! {
biased;
_ = session.stopped.cancelled() => {
return Err("gRPC code-mode session closed".to_string());
}
result = enforce(operation, runtime_timeout, request) => result,
};
match result {
Ok(value) => Ok(value),
Err(RequestError::Failed(error)) => {
let reason = failure(operation, &error);
// Only the proxy can declare a pinned route lost. Ordinary RPC and
// connection failures must not discard a potentially live session.
if session.route.is_some()
&& error.code() == tonic::Code::Unavailable
&& error
.metadata()
.get("x-code-mode-route-lost")
.is_some_and(|value| value == "true")
{
session.fail(reason.clone());
}
Err(reason)
}
Err(RequestError::TimedOut(reason)) => {
session.fail(reason.clone());
Err(reason)
}
}
}
/// Invalidates the session on RPCs where `NotFound` means the session is missing.
pub(super) async fn session_request<T>(
session: &SessionInner,
operation: &str,
runtime_timeout: Duration,
rpc: impl Future<Output = Result<T, tonic::Status>>,
) -> Result<T, String> {
request(session, operation, runtime_timeout, async {
let result = rpc.await;
if let Err(error) = &result
&& error.code() == tonic::Code::NotFound
{
session.fail(failure(operation, error));
}
result
})
.await
}
pub(super) fn failure(operation: &str, error: impl Display) -> String {
let mut message = format!("gRPC code-mode {operation} failed: {error}");
if message.len() > MAX_ERROR_BYTES {
let boundary = message.floor_char_boundary(MAX_ERROR_BYTES - "...".len());
message.truncate(boundary);
message.push_str("...");
}
message
}
async fn enforce<T, E>(
operation: &str,
runtime_timeout: Duration,
request: impl Future<Output = Result<T, E>>,
) -> Result<T, RequestError<E>> {
let timeout = runtime_timeout.saturating_add(TRANSPORT_TIMEOUT);
match tokio::time::timeout(timeout, request).await {
Ok(Ok(value)) => Ok(value),
Ok(Err(error)) => Err(RequestError::Failed(error)),
Err(_) => Err(RequestError::TimedOut(format!(
"gRPC code-mode host timed out waiting for {operation} response"
))),
}
}
enum RequestError<E> {
Failed(E),
TimedOut(String),
}
#[cfg(test)]
#[path = "deadline_tests.rs"]
mod tests;

View File

@@ -0,0 +1,131 @@
use std::future::pending;
use std::sync::Arc;
use std::time::Duration;
use akode_code_mode_protocol::DEFAULT_EXEC_YIELD_TIME_MS;
use pretty_assertions::assert_eq;
use super::MAX_ERROR_BYTES;
use super::RequestError;
use super::enforce;
use super::startup;
#[tokio::test(start_paused = true)]
async fn stalled_transport_fails_after_its_deadline() {
let task = tokio::spawn(enforce(
"termination",
Duration::ZERO,
pending::<Result<(), tonic::Status>>(),
));
tokio::task::yield_now().await;
tokio::time::advance(Duration::from_secs(61)).await;
assert!(matches!(
task.await.expect("deadline task"),
Err(RequestError::TimedOut(message))
if message == "gRPC code-mode host timed out waiting for termination response"
));
}
#[tokio::test(start_paused = true)]
async fn requested_runtime_duration_is_added_to_the_transport_deadline() {
let task = tokio::spawn(enforce(
"wait",
Duration::from_secs(120),
pending::<Result<(), tonic::Status>>(),
));
tokio::task::yield_now().await;
tokio::time::advance(Duration::from_secs(61)).await;
tokio::task::yield_now().await;
assert!(!task.is_finished());
tokio::time::advance(Duration::from_secs(120)).await;
assert!(matches!(
task.await.expect("deadline task"),
Err(RequestError::TimedOut(_))
));
}
#[tokio::test(start_paused = true)]
async fn default_execution_yield_and_grace_extend_the_outcome_deadline() {
let runtime_timeout =
Duration::from_millis(DEFAULT_EXEC_YIELD_TIME_MS).saturating_add(Duration::from_secs(1));
let task = tokio::spawn(enforce(
"execution outcome",
runtime_timeout,
pending::<Result<(), tonic::Status>>(),
));
tokio::task::yield_now().await;
tokio::time::advance(Duration::from_secs(70)).await;
tokio::task::yield_now().await;
assert!(!task.is_finished());
tokio::time::advance(Duration::from_secs(2)).await;
assert!(matches!(
task.await.expect("execution outcome deadline task"),
Err(RequestError::TimedOut(message))
if message == "gRPC code-mode host timed out waiting for execution outcome response"
));
}
#[tokio::test]
async fn transport_status_is_preserved() {
let result = enforce("wait", Duration::ZERO, async {
Err::<(), _>(tonic::Status::not_found("missing"))
})
.await;
match result {
Err(RequestError::Failed(error)) => {
assert_eq!(error.code(), tonic::Code::NotFound);
assert_eq!(error.message(), "missing");
}
_ => panic!("expected the original gRPC status"),
}
}
#[tokio::test]
async fn transport_status_messages_are_bounded_at_utf8_boundaries() {
let error = startup("session opening", async {
Err::<(), _>(tonic::Status::internal("🦀".repeat(MAX_ERROR_BYTES)))
})
.await
.expect_err("oversized gRPC status must fail");
assert!(error.len() <= MAX_ERROR_BYTES);
assert!(error.starts_with("gRPC code-mode session opening failed:"));
assert!(error.ends_with("..."));
}
#[tokio::test(start_paused = true)]
async fn stalled_channel_acquisition_times_out_and_remains_retryable() {
let channel = Arc::new(tokio::sync::OnceCell::new());
let stalled_channel = Arc::clone(&channel);
let stalled = tokio::spawn(async move {
startup("transport connection", async {
stalled_channel
.get_or_try_init(pending::<Result<usize, String>>)
.await
.copied()
})
.await
});
tokio::task::yield_now().await;
tokio::time::advance(Duration::from_secs(61)).await;
assert_eq!(
stalled.await.expect("channel connection task"),
Err("gRPC code-mode host timed out waiting for transport connection response".to_string())
);
assert_eq!(
startup("transport connection", async {
channel
.get_or_try_init(|| async { Ok::<_, String>(42usize) })
.await
.copied()
})
.await,
Ok(42)
);
}

View File

@@ -0,0 +1,132 @@
use std::sync::Arc;
use akode_code_mode_protocol::CellId;
use akode_code_mode_protocol::CodeModeNestedToolCall;
use akode_code_mode_protocol::CodeModeSessionDelegate;
use akode_code_mode_protocol::NotificationFuture;
use akode_code_mode_protocol::RuntimeResponse;
use akode_code_mode_protocol::StartedCell;
use akode_code_mode_protocol::ToolInvocationFuture;
use akode_code_mode_protocol::WaitOutcome;
use tokio_util::sync::CancellationToken;
pub(super) struct GenerationDelegate {
pub(super) delegate: Arc<dyn CodeModeSessionDelegate>,
pub(super) generation: u64,
}
impl CodeModeSessionDelegate for GenerationDelegate {
fn invoke_tool<'a>(
&'a self,
mut invocation: CodeModeNestedToolCall,
cancellation_token: CancellationToken,
) -> ToolInvocationFuture<'a> {
invocation.cell_id = public_cell_id(self.generation, &invocation.cell_id);
self.delegate.invoke_tool(invocation, cancellation_token)
}
fn notify<'a>(
&'a self,
call_id: String,
cell_id: CellId,
text: String,
cancellation_token: CancellationToken,
) -> NotificationFuture<'a> {
self.delegate.notify(
call_id,
public_cell_id(self.generation, &cell_id),
text,
cancellation_token,
)
}
fn cell_closed(&self, cell_id: &CellId) {
self.delegate
.cell_closed(&public_cell_id(self.generation, cell_id));
}
}
fn public_cell_id(generation: u64, cell_id: &CellId) -> CellId {
if generation == 1 {
cell_id.clone()
} else {
CellId::new(format!("g{generation}:{cell_id}"))
}
}
pub(super) fn remote_cell_id(generation: u64, cell_id: &CellId) -> Result<CellId, String> {
if generation == 1 {
return Ok(cell_id.clone());
}
let prefix = format!("g{generation}:");
cell_id
.as_str()
.strip_prefix(&prefix)
.map(|cell_id| CellId::new(cell_id.to_string()))
.ok_or_else(|| "cell belongs to a stale code-mode host generation".to_string())
}
pub(super) fn public_started_cell(generation: u64, started: StartedCell) -> StartedCell {
if generation == 1 {
return started;
}
let cell_id = public_cell_id(generation, &started.cell_id);
StartedCell::from_future(cell_id, async move {
started
.initial_response()
.await
.map(|response| public_runtime_response(generation, response))
})
}
fn public_runtime_response(generation: u64, response: RuntimeResponse) -> RuntimeResponse {
match response {
RuntimeResponse::Yielded {
cell_id,
content_items,
code_mode_host_duration,
} => RuntimeResponse::Yielded {
cell_id: public_cell_id(generation, &cell_id),
content_items,
code_mode_host_duration,
},
RuntimeResponse::Terminated {
cell_id,
content_items,
code_mode_host_duration,
} => RuntimeResponse::Terminated {
cell_id: public_cell_id(generation, &cell_id),
content_items,
code_mode_host_duration,
},
RuntimeResponse::Result {
cell_id,
content_items,
result_buffered_for,
error_text,
code_mode_host_duration,
} => RuntimeResponse::Result {
cell_id: public_cell_id(generation, &cell_id),
content_items,
result_buffered_for,
error_text,
code_mode_host_duration,
},
}
}
pub(super) fn public_wait_outcome(generation: u64, outcome: WaitOutcome) -> WaitOutcome {
match outcome {
WaitOutcome::LiveCell(response) => {
WaitOutcome::LiveCell(public_runtime_response(generation, response))
}
WaitOutcome::MissingCell(response) => {
WaitOutcome::MissingCell(public_runtime_response(generation, response))
}
}
}
#[cfg(test)]
#[path = "generation_tests.rs"]
mod tests;

View File

@@ -0,0 +1,270 @@
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use akode_code_mode_protocol::CellId;
use akode_code_mode_protocol::CodeModeNestedToolCall;
use akode_code_mode_protocol::CodeModeSessionDelegate;
use akode_code_mode_protocol::CodeModeToolKind;
use akode_code_mode_protocol::FunctionCallOutputContentItem;
use akode_code_mode_protocol::NotificationFuture;
use akode_code_mode_protocol::RuntimeResponse;
use akode_code_mode_protocol::StartedCell;
use akode_code_mode_protocol::ToolInvocationFuture;
use akode_code_mode_protocol::WaitOutcome;
use akode_protocol::ToolName;
use pretty_assertions::assert_eq;
use serde_json::json;
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use super::GenerationDelegate;
use super::public_cell_id;
use super::public_started_cell;
use super::public_wait_outcome;
use super::remote_cell_id;
#[derive(Default)]
struct RecordingDelegate {
calls: Mutex<Vec<CodeModeNestedToolCall>>,
notifications: Mutex<Vec<(String, CellId, String)>>,
closed: Mutex<Vec<CellId>>,
}
impl CodeModeSessionDelegate for RecordingDelegate {
fn invoke_tool<'a>(
&'a self,
invocation: CodeModeNestedToolCall,
_cancellation_token: CancellationToken,
) -> ToolInvocationFuture<'a> {
self.calls.lock().expect("calls lock").push(invocation);
Box::pin(async { Ok(json!({ "ok": true })) })
}
fn notify<'a>(
&'a self,
call_id: String,
cell_id: CellId,
text: String,
_cancellation_token: CancellationToken,
) -> NotificationFuture<'a> {
self.notifications
.lock()
.expect("notifications lock")
.push((call_id, cell_id, text));
Box::pin(async { Ok(()) })
}
fn cell_closed(&self, cell_id: &CellId) {
self.closed
.lock()
.expect("closed cells lock")
.push(cell_id.clone());
}
}
#[test]
fn first_generation_preserves_existing_cell_ids() {
let cell_id = CellId::new("42".to_string());
assert_eq!(public_cell_id(/*generation*/ 1, &cell_id), cell_id);
assert_eq!(remote_cell_id(/*generation*/ 1, &cell_id), Ok(cell_id));
}
#[test]
fn first_generation_preserves_opaque_cell_ids_that_resemble_generation_prefixes() {
for value in ["graphics:1", "g2:42"] {
let cell_id = CellId::new(value.to_string());
assert_eq!(public_cell_id(/*generation*/ 1, &cell_id), cell_id);
assert_eq!(remote_cell_id(/*generation*/ 1, &cell_id), Ok(cell_id));
}
}
#[test]
fn later_generations_prefix_public_ids_and_strip_wire_ids() {
let wire_id = CellId::new("42".to_string());
let public_id = CellId::new("g2:42".to_string());
assert_eq!(public_cell_id(/*generation*/ 2, &wire_id), public_id);
assert_eq!(remote_cell_id(/*generation*/ 2, &public_id), Ok(wire_id));
}
#[test]
fn stale_generation_ids_are_rejected_after_reconnection() {
for cell_id in [
"42".to_string(),
"g1:42".to_string(),
"g3:42".to_string(),
"x".repeat(10_000),
] {
assert_eq!(
remote_cell_id(/*generation*/ 2, &CellId::new(cell_id)),
Err("cell belongs to a stale code-mode host generation".to_string())
);
}
}
#[tokio::test]
async fn reconnect_maps_every_delegate_callback_to_its_generation() {
let recording = Arc::new(RecordingDelegate::default());
let delegate = GenerationDelegate {
delegate: recording.clone(),
generation: 2,
};
let wire_id = CellId::new("42".to_string());
let public_id = CellId::new("g2:42".to_string());
let invocation = CodeModeNestedToolCall {
cell_id: wire_id.clone(),
runtime_tool_call_id: "runtime-call".to_string(),
tool_name: ToolName::plain("echo"),
tool_kind: CodeModeToolKind::Function,
input: Some(json!({ "value": true })),
};
assert_eq!(
delegate
.invoke_tool(invocation.clone(), CancellationToken::new())
.await,
Ok(json!({ "ok": true }))
);
assert_eq!(
delegate
.notify(
"outer-call".to_string(),
wire_id.clone(),
"notice".to_string(),
CancellationToken::new(),
)
.await,
Ok(())
);
delegate.cell_closed(&wire_id);
assert_eq!(
*recording.calls.lock().expect("calls lock"),
vec![CodeModeNestedToolCall {
cell_id: public_id.clone(),
..invocation
}]
);
assert_eq!(
*recording.notifications.lock().expect("notifications lock"),
vec![(
"outer-call".to_string(),
public_id.clone(),
"notice".to_string()
)]
);
assert_eq!(
*recording.closed.lock().expect("closed cells lock"),
vec![public_id]
);
}
#[tokio::test]
async fn reconnected_execution_maps_started_and_initial_response_ids() {
let (response_tx, response_rx) = oneshot::channel();
let wire_id = CellId::new("42".to_string());
let public_id = CellId::new("g2:42".to_string());
let claimed = Arc::new(AtomicBool::new(false));
let initial_response_claimed = Arc::clone(&claimed);
let response = RuntimeResponse::Result {
code_mode_host_duration: None,
cell_id: wire_id.clone(),
content_items: vec![FunctionCallOutputContentItem::InputText {
text: "result".to_string(),
}],
result_buffered_for: Duration::ZERO,
error_text: None,
};
let started = StartedCell::from_future(wire_id, async move {
initial_response_claimed.store(true, Ordering::Release);
response_rx.await.expect("receive initial response")
});
let started = public_started_cell(/*generation*/ 2, started);
assert_eq!(started.cell_id, public_id);
tokio::task::yield_now().await;
assert!(!claimed.load(Ordering::Acquire));
response_tx
.send(Ok(response))
.expect("send initial response");
assert_eq!(
started.initial_response().await,
Ok(RuntimeResponse::Result {
code_mode_host_duration: None,
cell_id: public_id,
content_items: vec![FunctionCallOutputContentItem::InputText {
text: "result".to_string(),
}],
result_buffered_for: Duration::ZERO,
error_text: None,
})
);
}
#[test]
fn reconnected_wait_maps_live_and_missing_outcomes() {
let public_id = CellId::new("g2:42".to_string());
let yielded = RuntimeResponse::Yielded {
code_mode_host_duration: None,
cell_id: CellId::new("42".to_string()),
content_items: Vec::new(),
};
let terminated = RuntimeResponse::Terminated {
code_mode_host_duration: None,
cell_id: CellId::new("42".to_string()),
content_items: Vec::new(),
};
assert_eq!(
public_wait_outcome(/*generation*/ 2, WaitOutcome::LiveCell(yielded)),
WaitOutcome::LiveCell(RuntimeResponse::Yielded {
code_mode_host_duration: None,
cell_id: public_id.clone(),
content_items: Vec::new(),
})
);
assert_eq!(
public_wait_outcome(/*generation*/ 2, WaitOutcome::MissingCell(terminated)),
WaitOutcome::MissingCell(RuntimeResponse::Terminated {
code_mode_host_duration: None,
cell_id: public_id,
content_items: Vec::new(),
})
);
}
/// Replacing a host generation changes public cell IDs without losing the
/// operation's original duration on either the exec or wait path.
#[tokio::test]
async fn cell_id_remapping_preserves_code_mode_host_duration() {
let cell_id = CellId::new("42".to_string());
let code_mode_host_duration = Some(Duration::from_nanos(/*nanos*/ 1_234_567));
let response = RuntimeResponse::Yielded {
cell_id: cell_id.clone(),
content_items: Vec::new(),
code_mode_host_duration,
};
let initial = response.clone();
let started = StartedCell::from_future(cell_id, async move { Ok(initial) });
let expected = RuntimeResponse::Yielded {
cell_id: CellId::new("g2:42".to_string()),
content_items: Vec::new(),
code_mode_host_duration,
};
assert_eq!(
public_started_cell(/*generation*/ 2, started)
.initial_response()
.await
.as_ref(),
Ok(&expected),
);
assert_eq!(
public_wait_outcome(/*generation*/ 2, WaitOutcome::LiveCell(response)),
WaitOutcome::LiveCell(expected),
);
}

View File

@@ -0,0 +1,516 @@
use std::collections::HashMap;
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
use std::sync::Weak;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use akode_code_mode_protocol::CellId;
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::CodeModeSessionProvider;
use akode_code_mode_protocol::CodeModeSessionProviderFuture;
use akode_code_mode_protocol::CodeModeSessionResultFuture;
use akode_code_mode_protocol::ExecuteRequest;
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::grpc;
use akode_code_mode_protocol::grpc::code_mode_host_client::CodeModeHostClient;
use akode_http_client::HttpClientFactory;
use akode_http_client::OutboundProxyPolicy;
use rand::Rng;
use tokio::sync::Semaphore;
use tokio::sync::watch;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use tonic::transport::Channel;
use tracing::Instrument;
use self::operations::WaitSlot;
use self::state::ClosedCell;
use self::state::SessionState;
use self::transport::GrpcTransport;
use self::transport::SharedTransport;
use crate::remote_session::ShutdownResultReceiver;
use crate::remote_session::wait_for_watch;
mod callbacks;
mod completion;
mod conversion;
mod deadline;
mod generation;
mod operations;
mod process_metrics;
mod reconnect;
mod state;
mod transport;
type GrpcClient = CodeModeHostClient<GrpcTransport>;
const SHUTDOWN_ERROR: &str = "code mode session is shutting down";
const ROUTE_HEADER: &str = "x-code-mode-route";
// Bound result-delivery RPCs, not running tools. A full completion burst can
// exhaust HTTP/2's small-DATA-frame budget and disconnect every shared session.
const MAX_IN_FLIGHT_COMPLETIONS: usize = 64;
fn inject_span_traceparent<T>(request: &mut tonic::Request<T>, span: &tracing::Span) {
if let Some(traceparent) =
akode_otel::span_w3c_trace_context(span).and_then(|trace| trace.traceparent)
&& let Ok(traceparent) = traceparent.parse()
{
request.metadata_mut().insert("traceparent", traceparent);
}
}
/// Creates code-mode sessions over an HTTP/2 gRPC connection.
///
/// Metrics requests do not open sessions, retry RPCs, or explicitly reset the
/// connection. URL providers may initialize their client or establish a network
/// connection; caller-supplied channels and transports retain their reconnect
/// policy. Preventing child creation requires a process-owned transport.
#[derive(Clone)]
pub struct GrpcCodeModeSessionProvider {
transport: Arc<SharedTransport>,
completion_permits: Arc<Semaphore>,
// Reloaded threads share this counter rather than reusing a cell namespace.
next_generation: Arc<AtomicU64>,
}
impl GrpcCodeModeSessionProvider {
/// Connects lazily to an `http://`, `https://`, or `unix://` gRPC endpoint.
pub fn new(endpoint: impl Into<String>) -> Self {
Self::with_http_client_factory(
endpoint,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
}
/// Connects using the application's resolved outbound proxy and custom CA policy.
pub fn with_http_client_factory(
endpoint: impl Into<String>,
http_client_factory: HttpClientFactory,
) -> Self {
Self::from_transport(SharedTransport::new(endpoint.into(), http_client_factory))
}
/// Uses an existing channel, including channels backed by custom transports.
pub fn with_channel(channel: Channel) -> Self {
Self::from_transport(SharedTransport::with_channel(channel))
}
/// Uses a caller-owned transport, which can prevent observation RPCs from
/// starting or replacing process-owned connections.
pub fn with_transport<T>(transport: T) -> Self
where
T: tower::Service<
tonic::codegen::http::Request<tonic::body::Body>,
Response = tonic::codegen::http::Response<tonic::body::Body>,
Error = tonic::Status,
> + Clone
+ Send
+ Sync
+ 'static,
T::Future: Send + 'static,
{
Self::from_transport(SharedTransport::with_transport(
tower::util::BoxCloneSyncService::new(transport),
))
}
fn from_transport(transport: SharedTransport) -> Self {
Self {
transport: Arc::new(transport),
completion_permits: Arc::new(Semaphore::new(MAX_IN_FLIGHT_COMPLETIONS)),
next_generation: Arc::new(AtomicU64::new(1)),
}
}
#[tracing::instrument(name = "code_mode.grpc.open_binding", level = "info", skip_all)]
async fn open_binding(
&self,
options: &CodeModeSessionOptions,
pinned_mode: Option<CodeModeOutputTruncation>,
) -> Result<Arc<GrpcCodeModeSession>, String> {
let client = deadline::startup("transport connection", self.transport.client()).await?;
let requested_mode = pinned_mode.unwrap_or(options.output_truncation);
let limits = &options.cell_execution_limits;
let limits = grpc::SessionCellExecutionLimits {
max_yield_time_ms: limits.max_yield_time_ms,
max_heap_size_bytes: limits
.max_heap_size_bytes
.map(u64::try_from)
.transpose()
.map_err(|error| format!("invalid code-mode heap size limit: {error}"))?,
};
let cell_execution_limits = (limits.max_yield_time_ms.is_some()
|| limits.max_heap_size_bytes.is_some())
.then_some(limits);
let open_session_span = tracing::info_span!("code_mode.grpc.open_session");
let (lease, first, route) = deadline::startup("session opening", async {
let mut retries = 0;
loop {
let mut request = tonic::Request::new(grpc::OpenSessionRequest {
max_pending_delegate_calls: Some(
akode_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS as u32,
),
cell_execution_limits,
output_truncation: match requested_mode {
CodeModeOutputTruncation::Client => None,
CodeModeOutputTruncation::Server => {
Some(grpc::OutputTruncation::Server.into())
}
},
});
inject_span_traceparent(&mut request, &open_session_span);
let result = async {
let response = client.as_ref().clone().open_session(request).await?;
let route = response.metadata().get(ROUTE_HEADER).cloned();
if route
.as_ref()
.is_some_and(|value| value.as_bytes().len() > 256)
{
return Err(tonic::Status::invalid_argument(
"session routing token is too long",
));
}
let mut lease = response.into_inner();
let first = lease.message().await?.ok_or_else(|| {
tonic::Status::unavailable("session lease ended before opening")
})?;
Ok::<_, tonic::Status>((lease, first, route))
}
.await;
let Err(error) = &result else { return result };
if retries == 4
|| !matches!(
error.code(),
tonic::Code::Unavailable | tonic::Code::ResourceExhausted
)
{
return result;
}
// No execution has started, and dropping a failed lease releases
// any partial admission. Never apply these retries to Execute.
tracing::warn!(%error, retry = retries + 1, "retrying code-mode session admission");
if retries > 0 {
let delay_ms = 50_u64 << (retries - 1);
let jitter = rand::rng().random_range(0.9..1.1);
let delay = Duration::from_millis((delay_ms as f64 * jitter) as u64);
tokio::time::sleep(delay).await;
}
retries += 1;
}
})
.instrument(open_session_span.clone())
.await?;
let Some(grpc::session_event::Event::Opened(opened)) = first.event else {
return Err("gRPC code-mode session lease omitted its opening event".to_string());
};
validate_identifier(&opened.session_id, "session ID")?;
let host_mode =
grpc::OutputTruncation::try_from(opened.output_truncation.unwrap_or_default())
.map_err(|_| "gRPC code-mode host returned an unknown output truncation mode")?;
let output_truncation = match host_mode {
grpc::OutputTruncation::Unspecified | grpc::OutputTruncation::Client => {
CodeModeOutputTruncation::Client
}
grpc::OutputTruncation::Server => CodeModeOutputTruncation::Server,
};
if output_truncation == CodeModeOutputTruncation::Server
&& requested_mode == CodeModeOutputTruncation::Client
{
return Err(format!(
"gRPC code-mode host selected {output_truncation:?} output truncation, requested {requested_mode:?}"
));
}
if pinned_mode.is_some_and(|previous| previous != output_truncation) {
// Dropping the opening lease releases this incompatible session before subscribing.
return Err(
"gRPC code-mode host changed the session output truncation mode on reconnect"
.to_string(),
);
}
let inner = Arc::new(SessionInner {
id: opened.session_id,
output_truncation,
route,
runtime: tokio::runtime::Handle::current(),
state: Mutex::new(SessionState::with_client(client)),
wait_slots: Mutex::new(HashMap::new()),
shutdown_requested: AtomicBool::new(false),
shutdown_result: Mutex::new(None),
stopped: CancellationToken::new(),
stream_tasks: TaskTracker::new(),
completion_permits: Arc::clone(&self.completion_permits),
_transport: Arc::clone(&self.transport),
});
let mut opening = OpeningSession {
inner: Some(Arc::clone(&inner)),
};
inner.spawn_session_events(lease);
let subscribe_span = tracing::info_span!(
"code_mode.grpc.subscribe_to_tool_calls",
session.id = %inner.id,
);
let mut request = inner.request(grpc::SubscribeToToolCallsRequest {
session_id: inner.id.clone(),
tool_names: Vec::new(),
});
inject_span_traceparent(&mut request, &subscribe_span);
let mut client = inner.client()?;
let response =
match deadline::startup("tool subscription", client.subscribe_to_tool_calls(request))
.instrument(subscribe_span)
.await
{
Ok(response) => response,
Err(error) => {
let _ = wait_for_watch(inner.request_shutdown()).await;
return Err(error);
}
};
inner.spawn_tool_subscription(response.into_inner());
inner.require_open()?;
opening.inner = None;
Ok(Arc::new(GrpcCodeModeSession { inner }))
}
}
impl CodeModeSessionProvider for GrpcCodeModeSessionProvider {
fn sample_process_metrics(
&self,
) -> CodeModeSessionResultFuture<'_, akode_code_mode_protocol::CodeModeProcessMetricsSample>
{
Box::pin(process_metrics::sample(self))
}
fn create_session(&self) -> CodeModeSessionProviderFuture<'_> {
self.create_session_with_limits(CodeModeSessionCellExecutionLimits::default())
}
fn create_session_with_limits<'a>(
&'a self,
limits: CodeModeSessionCellExecutionLimits,
) -> CodeModeSessionProviderFuture<'a> {
self.create_session_with_options(CodeModeSessionOptions {
cell_execution_limits: limits,
..CodeModeSessionOptions::default()
})
}
fn create_session_with_options<'a>(
&'a self,
options: CodeModeSessionOptions,
) -> CodeModeSessionProviderFuture<'a> {
Box::pin(async move {
let session = Arc::new(reconnect::ReconnectableSession::new(self.clone(), options));
session.initialize().await?;
Ok(session as _)
})
}
}
struct GrpcCodeModeSession {
inner: Arc<SessionInner>,
}
struct OpeningSession {
inner: Option<Arc<SessionInner>>,
}
impl Drop for OpeningSession {
fn drop(&mut self) {
let Some(inner) = self.inner.take() else {
return;
};
if tokio::runtime::Handle::try_current().is_ok() {
inner.request_shutdown();
} else {
inner.close_state(/*failure*/ None);
}
}
}
impl CodeModeSession for GrpcCodeModeSession {
fn output_truncation(&self) -> CodeModeOutputTruncation {
self.inner.output_truncation
}
fn execute<'a>(
&'a self,
request: ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
preempt: Option<CancellationToken>,
) -> CodeModeSessionResultFuture<'a, StartedCell> {
Box::pin(self.inner.execute(request, delegate, preempt))
}
fn wait<'a>(
&'a self,
request: WaitRequest,
preempt: Option<CancellationToken>,
) -> CodeModeSessionResultFuture<'a, WaitOutcome> {
Box::pin(self.inner.wait(request, preempt))
}
fn terminate<'a>(
&'a self,
request: TerminateRequest,
) -> CodeModeSessionResultFuture<'a, WaitOutcome> {
Box::pin(self.inner.terminate(request))
}
fn shutdown<'a>(&'a self) -> CodeModeSessionResultFuture<'a, ()> {
Box::pin(wait_for_watch(self.inner.request_shutdown()))
}
}
impl Drop for GrpcCodeModeSession {
fn drop(&mut self) {
self.inner.request_shutdown();
}
}
pub(super) struct SessionInner {
pub(super) id: String,
output_truncation: CodeModeOutputTruncation,
// Affinity belongs to the session: parents and children may share a transport
// while being admitted to different hosts. The token is opaque to Codex.
route: Option<tonic::metadata::MetadataValue<tonic::metadata::Ascii>>,
runtime: tokio::runtime::Handle,
state: Mutex<SessionState>,
wait_slots: Mutex<HashMap<CellId, Weak<WaitSlot>>>,
shutdown_requested: AtomicBool,
shutdown_result: Mutex<Option<ShutdownResultReceiver>>,
pub(super) stopped: CancellationToken,
stream_tasks: TaskTracker,
completion_permits: Arc<Semaphore>,
_transport: Arc<SharedTransport>,
}
impl SessionInner {
pub(super) fn client(&self) -> Result<GrpcClient, String> {
self.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.client()
}
pub(super) fn request<T>(&self, message: T) -> tonic::Request<T> {
let mut request = tonic::Request::new(message);
if let Some(route) = &self.route {
request.metadata_mut().insert(ROUTE_HEADER, route.clone());
}
request
}
pub(super) fn require_open(&self) -> Result<(), String> {
self.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.require_open()?;
if self.shutdown_requested.load(Ordering::Acquire) {
return Err(SHUTDOWN_ERROR.to_string());
}
Ok(())
}
pub(super) fn report_closed_cell(&self, cell: Option<ClosedCell>) {
if let Some((cell_id, delegate)) = cell {
self.wait_slots
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(&cell_id);
let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
delegate.cell_closed(&cell_id);
}));
}
}
pub(super) fn fail(&self, reason: String) {
self.close_state(Some(reason));
}
fn close_state(&self, failure: Option<String>) {
let cells = {
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
// Order failure with request_shutdown. Once shutdown starts,
// CloseSession owns cleanup; a late error must not cancel its RPC.
if failure.is_some() && self.shutdown_requested.load(Ordering::Acquire) {
return;
}
state.close(failure)
};
self.stopped.cancel();
self.stream_tasks.close();
for cell_id in cells {
self.report_closed_cell(Some(cell_id));
}
}
fn request_shutdown(self: &Arc<Self>) -> ShutdownResultReceiver {
{
let _state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
self.shutdown_requested.store(true, Ordering::Release);
}
let mut result = self
.shutdown_result
.lock()
.unwrap_or_else(PoisonError::into_inner);
if let Some(receiver) = result.as_ref() {
return receiver.clone();
}
let (sender, receiver) = watch::channel(None);
*result = Some(receiver.clone());
let inner = Arc::clone(self);
self.runtime.spawn(async move {
let result = inner.drive_shutdown().await;
sender.send_replace(Some(result));
});
receiver
}
async fn drive_shutdown(&self) -> Result<(), String> {
let result = if let Ok(mut client) = self.client() {
deadline::request(
self,
"session shutdown",
Duration::ZERO,
client.close_session(self.request(grpc::CloseSessionRequest {
session_id: self.id.clone(),
})),
)
.await
.map(|_| ())
} else {
Ok(())
};
self.close_state(/*failure*/ None);
self.stream_tasks.wait().await;
result
}
}
fn validate_identifier(value: &str, field: &str) -> Result<(), String> {
if value.is_empty() {
return Err(format!("gRPC code-mode host returned an empty {field}"));
}
if value.len() > grpc::MAX_IDENTIFIER_BYTES {
return Err(format!(
"gRPC code-mode host returned {field} exceeding {} bytes",
grpc::MAX_IDENTIFIER_BYTES
));
}
Ok(())
}

View File

@@ -0,0 +1,506 @@
use std::sync::Arc;
use std::sync::PoisonError;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use akode_code_mode_protocol::CellId;
use akode_code_mode_protocol::CodeModeSessionDelegate;
use akode_code_mode_protocol::DEFAULT_EXEC_YIELD_TIME_MS;
use akode_code_mode_protocol::ExecuteRequest;
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::grpc;
use akode_protocol::protocol::W3cTraceContext;
use tokio::sync::OwnedMutexGuard;
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use tokio_util::task::AbortOnDropHandle;
use tracing::Instrument;
use tracing::debug;
use uuid::Uuid;
use super::SessionInner;
use super::conversion;
use super::deadline;
pub(super) struct WaitSlot {
lock: Arc<tokio::sync::Mutex<()>>,
active: AtomicBool,
}
struct ExecutionOwnership {
session: Arc<SessionInner>,
execution_id: String,
armed: bool,
}
impl Drop for ExecutionOwnership {
fn drop(&mut self) {
if !self.armed {
return;
}
let cell = self
.session
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove_execution(&self.execution_id);
let Some((cell_id, delegate)) = cell else {
return;
};
self.session
.report_closed_cell(Some((cell_id.clone(), delegate)));
if self.session.stopped.is_cancelled() {
return;
}
let session = Arc::clone(&self.session);
self.session.runtime.spawn(async move {
if let Err(error) = session.terminate(cell_id.into()).await
&& !session.stopped.is_cancelled()
{
debug!("abandoned code-mode execution termination raced closure: {error}");
}
});
}
}
impl SessionInner {
pub(super) async fn execute(
self: &Arc<Self>,
request: ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
preempt: Option<CancellationToken>,
) -> Result<StartedCell, String> {
self.require_open()?;
let execution_id = Uuid::new_v4().to_string();
let execute_span = tracing::info_span!(
"code_mode.grpc.execute",
otel.name = "code_mode.grpc.execute",
execution.id = %execution_id,
call_id = %request.tool_call_id,
);
let trace = akode_otel::span_w3c_trace_context(&execute_span);
let request = conversion::execute_request(&self.id, execution_id.clone(), request)?;
self.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.begin_execution(&request, delegate)?;
let ownership = ExecutionOwnership {
session: Arc::clone(self),
execution_id: execution_id.clone(),
armed: true,
};
let (started_tx, started_rx) = oneshot::channel();
let inner = Arc::clone(self);
self.stream_tasks.spawn(async move {
let _watcher = preempt.map(|signal| {
inner.watch_yield(
signal,
grpc::yield_observation_request::Observation::ExecutionId(execution_id),
)
});
inner
.drive_execution(request, ownership, started_tx, trace)
.instrument(execute_span)
.await;
});
started_rx
.await
.map_err(|_| "gRPC code-mode execution driver ended unexpectedly".to_string())?
}
async fn drive_execution(
self: Arc<Self>,
request: grpc::ExecuteRequest,
ownership: ExecutionOwnership,
started_tx: oneshot::Sender<Result<StartedCell, String>>,
trace: Option<W3cTraceContext>,
) {
let runtime_timeout =
Duration::from_millis(request.yield_time_ms.unwrap_or(DEFAULT_EXEC_YIELD_TIME_MS))
.saturating_add(Duration::from_secs(1));
let opening = async {
let mut client = self.client()?;
let mut request = self.request(request);
if let Some(traceparent) = trace.and_then(|trace| trace.traceparent)
&& let Ok(traceparent) = traceparent.parse()
{
request.metadata_mut().insert("traceparent", traceparent);
}
let mut stream = deadline::session_request(
&self,
"execution",
Duration::ZERO,
client.execute(request),
)
.await?
.into_inner();
let first = deadline::session_request(
&self,
"execution starting event",
Duration::ZERO,
stream.message(),
)
.await?
.ok_or_else(|| {
"gRPC code-mode execution ended before its starting event".to_string()
})?;
let Some(grpc::execute_event::Event::Started(started)) = first.event else {
return Err("gRPC code-mode execution omitted its starting event".to_string());
};
super::validate_identifier(&started.execution_id, "execution ID")?;
if started.execution_id != ownership.execution_id {
let error = format!(
"gRPC code-mode execution returned ID {} instead of {}",
started.execution_id, ownership.execution_id
);
self.fail(error.clone());
return Err(error);
}
let admission = self
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.admit_execution(&ownership.execution_id, &started.cell_id);
if let Err(error) = admission {
self.fail(error.clone());
return Err(error);
}
Ok((CellId::new(started.cell_id), stream))
}
.await;
let (cell_id, stream) = match opening {
Ok(opening) => opening,
Err(error) => {
let _ = started_tx.send(Err(error));
return;
}
};
let (response_tx, response_rx) = oneshot::channel();
let mut claim = ownership;
let started = StartedCell::from_future(cell_id.clone(), async move {
let closure = claim
.session
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.mark_execution_ready(&claim.execution_id);
match closure {
Ok(cell) => claim.session.report_closed_cell(cell),
Err(error) => {
claim.session.fail(error.clone());
return Err(error);
}
}
let response = response_rx
.await
.map_err(|_| "exec runtime ended unexpectedly".to_string())??;
claim.armed = false;
drop(claim);
Ok(response)
});
if started_tx.send(Ok(started)).is_err() {
return;
}
self.drive_execution_outcome(cell_id, stream, response_tx, runtime_timeout)
.await;
}
async fn drive_execution_outcome(
self: Arc<Self>,
cell_id: CellId,
mut stream: tonic::Streaming<grpc::ExecuteEvent>,
mut response_tx: oneshot::Sender<Result<RuntimeResponse, String>>,
runtime_timeout: Duration,
) {
let outcome = tokio::select! {
biased;
_ = response_tx.closed() => return,
outcome = deadline::session_request(
&self,
"execution outcome",
runtime_timeout,
stream.message(),
) => match outcome {
Ok(Some(grpc::ExecuteEvent {
event: Some(grpc::execute_event::Event::Outcome(outcome)),
})) => conversion::runtime_response(outcome),
Ok(Some(_)) => {
Err("gRPC code-mode execution returned an unexpected event".to_string())
}
Ok(None) => Err("gRPC code-mode execution omitted its initial outcome".to_string()),
Err(error) => Err(error),
},
};
let outcome = match outcome {
Ok(response) if runtime_response_cell_id(&response) != &cell_id => {
let error = format!(
"gRPC code-mode execution returned cell {} instead of {cell_id}",
runtime_response_cell_id(&response)
);
self.fail(error.clone());
Err(error)
}
Ok(response) => {
tokio::select! {
biased;
_ = response_tx.closed() => return,
_ = self.settle_notifications(&response) => {}
}
Ok(response)
}
Err(error) => Err(error),
};
let _ = response_tx.send(outcome);
}
pub(super) async fn wait(
self: &Arc<Self>,
request: WaitRequest,
preempt: Option<CancellationToken>,
) -> Result<WaitOutcome, String> {
self.require_open()?;
let slot = {
let mut slots = self
.wait_slots
.lock()
.unwrap_or_else(PoisonError::into_inner);
slots.retain(|_, slot| slot.strong_count() != 0);
let slot = match slots
.get(&request.cell_id)
.and_then(std::sync::Weak::upgrade)
{
Some(slot) => slot,
None => {
let slot = Arc::new(WaitSlot {
lock: Arc::new(tokio::sync::Mutex::new(())),
active: AtomicBool::new(false),
});
slots.insert(request.cell_id.clone(), Arc::downgrade(&slot));
slot
}
};
if slot.active.swap(true, Ordering::AcqRel) {
return Err(format!(
"exec cell {} already has an active observer",
request.cell_id
));
}
slot
};
let lock = Arc::clone(&slot.lock);
let mut cancellation = WaitCancellation {
session: Arc::clone(self),
slot: Some(slot),
wait_id: None,
permit: None,
};
let permit = lock.lock_owned().await;
self.require_open()?;
let wait_id = Uuid::new_v4().to_string();
cancellation.wait_id = Some(wait_id.clone());
cancellation.permit = Some(permit);
let expected_cell_id = request.cell_id;
let runtime_timeout =
Duration::from_millis(request.yield_time_ms).saturating_add(Duration::from_secs(1));
let request = grpc::WaitRequest {
session_id: self.id.clone(),
cell_id: expected_cell_id.as_str().to_string(),
wait_id: wait_id.clone(),
yield_time_ms: request.yield_time_ms,
max_output_tokens: conversion::output_budget(
self.output_truncation,
request.max_output_tokens,
)?,
};
let mut client = self.client()?;
let watcher = preempt.map(|signal| {
self.watch_yield(
signal,
grpc::yield_observation_request::Observation::WaitId(wait_id),
)
});
let response = deadline::session_request(
self,
"wait",
runtime_timeout,
client.wait(self.request(request)),
)
.await;
drop(watcher);
cancellation.disarm();
self.prune_wait_slots();
let outcome = conversion::wait_outcome(response?)?;
self.validate_wait_cell(&expected_cell_id, outcome).await
}
fn watch_yield(
self: &Arc<Self>,
yield_signal: CancellationToken,
observation: grpc::yield_observation_request::Observation,
) -> AbortOnDropHandle<()> {
let session = Arc::clone(self);
let request = self.request(grpc::YieldObservationRequest {
session_id: self.id.clone(),
observation: Some(observation),
});
AbortOnDropHandle::new(tokio::spawn(async move {
yield_signal.cancelled().await;
let Ok(mut client) = session.client() else {
return;
};
if let Err(error) = deadline::startup("yield observation", async move {
client.yield_observation(request).await.map(|_| ())
})
.await
{
// An older host may not implement this RPC; the normal timeout still applies.
debug!("could not yield code-mode observation early: {error}");
}
}))
}
pub(super) async fn terminate(&self, request: TerminateRequest) -> Result<WaitOutcome, String> {
self.require_open()?;
let mut client = self.client()?;
let response = deadline::session_request(
self,
"termination",
Duration::ZERO,
client.terminate(self.request(grpc::TerminateRequest {
session_id: self.id.clone(),
cell_id: request.cell_id.as_str().to_string(),
max_output_tokens: conversion::output_budget(
self.output_truncation,
request.max_output_tokens,
)?,
})),
)
.await?;
let outcome = conversion::wait_outcome(response)?;
self.validate_wait_cell(&request.cell_id, outcome).await
}
async fn validate_wait_cell(
&self,
expected_cell_id: &CellId,
outcome: WaitOutcome,
) -> Result<WaitOutcome, String> {
let response = match &outcome {
WaitOutcome::LiveCell(response) | WaitOutcome::MissingCell(response) => response,
};
let actual_cell_id = runtime_response_cell_id(response);
if actual_cell_id != expected_cell_id {
let error = format!(
"gRPC code-mode host returned cell {actual_cell_id} instead of {expected_cell_id}"
);
self.fail(error.clone());
return Err(error);
}
self.settle_notifications(response).await;
Ok(outcome)
}
async fn settle_notifications(&self, response: &RuntimeResponse) {
match response {
RuntimeResponse::Yielded { .. } => {}
RuntimeResponse::Terminated { cell_id, .. } => self
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.cancel_notifications(cell_id),
RuntimeResponse::Result { cell_id, .. } => {
let cancellation = self
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.notification_cancellation(cell_id);
if let Some(cancellation) = cancellation {
// CellClosed follows notifications on the lease stream and cancels this
// token only after every admitted notification has finished.
cancellation.cancelled().await;
}
}
}
}
fn prune_wait_slots(&self) {
self.wait_slots
.lock()
.unwrap_or_else(PoisonError::into_inner)
.retain(|_, slot| slot.strong_count() != 0);
}
}
fn runtime_response_cell_id(response: &RuntimeResponse) -> &CellId {
match response {
RuntimeResponse::Yielded { cell_id, .. }
| RuntimeResponse::Terminated { cell_id, .. }
| RuntimeResponse::Result { cell_id, .. } => cell_id,
}
}
struct WaitCancellation {
session: Arc<SessionInner>,
slot: Option<Arc<WaitSlot>>,
wait_id: Option<String>,
permit: Option<OwnedMutexGuard<()>>,
}
impl WaitCancellation {
fn disarm(&mut self) {
self.wait_id = None;
if let Some(slot) = self.slot.take() {
slot.active.store(false, Ordering::Release);
}
self.permit = None;
}
}
impl Drop for WaitCancellation {
fn drop(&mut self) {
let slot = self.slot.take();
if let Some(slot) = slot.as_ref() {
slot.active.store(false, Ordering::Release);
}
let Some(wait_id) = self.wait_id.take() else {
return;
};
let permit = self.permit.take();
if self.session.stopped.is_cancelled() {
return;
}
let session = Arc::clone(&self.session);
self.session.runtime.spawn(async move {
let Ok(mut client) = session.client() else {
return;
};
let result = deadline::request(
&session,
"wait cancellation",
Duration::ZERO,
client.cancel_wait(session.request(grpc::CancelWaitRequest {
session_id: session.id.clone(),
wait_id,
})),
)
.await;
if let Err(error) = result
&& !session.stopped.is_cancelled()
{
session.fail(format!(
"failed to retire canceled gRPC code-mode wait: {error}"
));
}
drop(permit);
drop(slot);
session.prune_wait_slots();
});
}
}

View File

@@ -0,0 +1,50 @@
//! A bounded, non-retrying host observation. No session binding or recovery is
//! involved: a failed RPC never explicitly retires the execution connection.
//! Connection establishment and reconnection remain the transport's policy.
use std::time::Duration;
use akode_code_mode_protocol::CodeModeProcessMetrics;
use akode_code_mode_protocol::CodeModeProcessMetricsSample;
use akode_code_mode_protocol::grpc;
use tonic::Code;
use super::GrpcCodeModeSessionProvider;
pub(super) async fn sample(
provider: &GrpcCodeModeSessionProvider,
) -> Result<CodeModeProcessMetricsSample, String> {
let deadline = Duration::from_secs(/*secs*/ 1);
tokio::time::timeout(deadline, async {
let client = provider.transport.client().await?;
let mut request = tonic::Request::new(grpc::GetProcessMetricsRequest {});
request.set_timeout(deadline);
match client.as_ref().clone().get_process_metrics(request).await {
Ok(response) => {
let snapshot = response.into_inner();
if snapshot.process_id == 0
|| !snapshot.process_start_time_seconds.is_finite()
|| snapshot.process_start_time_seconds <= 0.0
|| !snapshot.cpu_seconds_total.is_finite()
|| snapshot.cpu_seconds_total < 0.0
{
return Err("invalid code-mode process metrics snapshot".to_string());
}
Ok(CodeModeProcessMetricsSample::Snapshot(
CodeModeProcessMetrics {
process_id: snapshot.process_id,
process_start_time_seconds: snapshot.process_start_time_seconds,
cpu_seconds_total: snapshot.cpu_seconds_total,
resident_memory_bytes: snapshot.resident_memory_bytes,
},
))
}
Err(status) if status.code() == Code::Unimplemented => {
Ok(CodeModeProcessMetricsSample::Unsupported)
}
Err(status) => Err(format!("code-mode process metrics failed: {status}")),
}
})
.await
.map_err(|_| "code-mode process metrics timed out".to_string())?
}

View File

@@ -0,0 +1,280 @@
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::PoisonError;
use std::sync::atomic::Ordering;
use akode_code_mode_protocol::CodeModeOutputTruncation;
use akode_code_mode_protocol::CodeModeSession;
use akode_code_mode_protocol::CodeModeSessionDelegate;
use akode_code_mode_protocol::CodeModeSessionOptions;
use akode_code_mode_protocol::CodeModeSessionResultFuture;
use akode_code_mode_protocol::ExecuteRequest;
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 tokio::sync::Semaphore;
use tokio::sync::watch;
use tokio_util::sync::CancellationToken;
use super::GrpcCodeModeSession;
use super::GrpcCodeModeSessionProvider;
use super::SHUTDOWN_ERROR;
use super::generation;
use super::generation::GenerationDelegate;
use crate::remote_session::ShutdownResultReceiver;
use crate::remote_session::wait_for_watch;
pub(super) struct ReconnectableSession {
inner: Arc<ReconnectInner>,
}
struct ReconnectInner {
provider: GrpcCodeModeSessionProvider,
options: CodeModeSessionOptions,
binding: Mutex<Option<SessionBinding>>,
// The negotiated mode belongs to the logical session, including after
// shutdown releases the binding. Never pin a mode from an unpublished open.
output_truncation: OnceLock<CodeModeOutputTruncation>,
opening_permit: Semaphore,
shutdown_requested: CancellationToken,
shutdown_result: Mutex<Option<ShutdownResultReceiver>>,
}
#[derive(Clone)]
struct SessionBinding {
session: Arc<GrpcCodeModeSession>,
generation: u64,
}
impl ReconnectableSession {
pub(super) fn new(
provider: GrpcCodeModeSessionProvider,
options: CodeModeSessionOptions,
) -> Self {
Self {
inner: Arc::new(ReconnectInner {
provider,
options,
binding: Mutex::new(None),
output_truncation: OnceLock::new(),
opening_permit: Semaphore::new(/*permits*/ 1),
shutdown_requested: CancellationToken::new(),
shutdown_result: Mutex::new(None),
}),
}
}
pub(super) async fn initialize(&self) -> Result<(), String> {
self.inner.get_or_open_binding().await.map(|_| ())
}
}
impl CodeModeSession for ReconnectableSession {
fn output_truncation(&self) -> CodeModeOutputTruncation {
self.inner
.output_truncation
.get()
.copied()
.unwrap_or_default()
}
fn execute<'a>(
&'a self,
request: ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
preempt: Option<CancellationToken>,
) -> CodeModeSessionResultFuture<'a, StartedCell> {
// Capture before polling so queued calls cannot silently cross a runtime reset.
let generation = self.inner.binding().map(|binding| binding.generation);
Box::pin(async move {
let binding = self.inner.binding_for_request(generation).await?;
let delegate = Arc::new(GenerationDelegate {
delegate,
generation: binding.generation,
});
let started = binding.session.execute(request, delegate, preempt).await?;
Ok(generation::public_started_cell(binding.generation, started))
})
}
fn wait<'a>(
&'a self,
request: WaitRequest,
preempt: Option<CancellationToken>,
) -> CodeModeSessionResultFuture<'a, WaitOutcome> {
let generation = self.inner.binding().map(|binding| binding.generation);
Box::pin(async move {
let binding = self.inner.binding_for_request(generation).await?;
let request = WaitRequest {
max_output_tokens: request.max_output_tokens,
cell_id: generation::remote_cell_id(binding.generation, &request.cell_id)?,
yield_time_ms: request.yield_time_ms,
};
let outcome = binding.session.wait(request, preempt).await?;
Ok(generation::public_wait_outcome(binding.generation, outcome))
})
}
fn terminate<'a>(
&'a self,
request: TerminateRequest,
) -> CodeModeSessionResultFuture<'a, WaitOutcome> {
Box::pin(async move {
// Cleanup must not replace the runtime and hide its loss from the next request.
let binding = self
.inner
.binding()
.ok_or_else(|| SHUTDOWN_ERROR.to_string())?;
let cell_id = generation::remote_cell_id(binding.generation, &request.cell_id)?;
let outcome = binding
.session
.terminate(TerminateRequest { cell_id, ..request })
.await?;
Ok(generation::public_wait_outcome(binding.generation, outcome))
})
}
fn shutdown<'a>(&'a self) -> CodeModeSessionResultFuture<'a, ()> {
Box::pin(wait_for_watch(self.inner.request_shutdown()))
}
}
impl Drop for ReconnectableSession {
fn drop(&mut self) {
if tokio::runtime::Handle::try_current().is_ok() {
self.inner.request_shutdown();
}
}
}
impl ReconnectInner {
async fn binding_for_request(&self, generation: Option<u64>) -> Result<SessionBinding, String> {
let binding = self.get_or_open_binding().await?;
if generation != Some(binding.generation) {
return Err(concat!(
"The exec runtime was replaced. Stored values and running cells were lost. ",
"Prior external tool operations may have completed; inspect their results before retrying. ",
"You may continue with a fresh exec call.",
).into());
}
Ok(binding)
}
async fn get_or_open_binding(&self) -> Result<SessionBinding, String> {
if self.shutdown_requested.is_cancelled() {
return Err(SHUTDOWN_ERROR.to_string());
}
if let Some(binding) = self.live_binding() {
return Ok(binding);
}
let _opening_permit = tokio::select! {
biased;
_ = self.shutdown_requested.cancelled() => {
return Err(SHUTDOWN_ERROR.to_string());
}
permit = self.opening_permit.acquire() => permit
.map_err(|_| "gRPC code-mode session opening coordinator closed".to_string())?,
};
if self.shutdown_requested.is_cancelled() {
return Err(SHUTDOWN_ERROR.to_string());
}
if let Some(binding) = self.live_binding() {
return Ok(binding);
}
if let Some(binding) = self.binding() {
wait_for_watch(binding.session.inner.request_shutdown()).await?;
}
let generation = self
.provider
.next_generation
.fetch_add(1, Ordering::Relaxed);
let session = tokio::select! {
biased;
_ = self.shutdown_requested.cancelled() => {
return Err(SHUTDOWN_ERROR.to_string());
}
session = self.provider.open_binding(&self.options, self.output_truncation.get().copied()) => session?,
};
let binding = SessionBinding {
session,
generation,
};
let published = {
let mut current = self.binding.lock().unwrap_or_else(PoisonError::into_inner);
if self.shutdown_requested.is_cancelled() {
false
} else {
*current = Some(binding.clone());
self.output_truncation
.get_or_init(|| binding.session.output_truncation());
true
}
};
if !published {
let _ = wait_for_watch(binding.session.inner.request_shutdown()).await;
return Err(SHUTDOWN_ERROR.to_string());
}
Ok(binding)
}
fn live_binding(&self) -> Option<SessionBinding> {
self.binding()
.filter(|binding| !binding.session.inner.stopped.is_cancelled())
}
fn binding(&self) -> Option<SessionBinding> {
self.binding
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
fn request_shutdown(self: &Arc<Self>) -> ShutdownResultReceiver {
{
let binding = self.binding.lock().unwrap_or_else(PoisonError::into_inner);
self.shutdown_requested.cancel();
if let Some(binding) = binding.as_ref() {
binding.session.inner.request_shutdown();
}
}
let mut result = self
.shutdown_result
.lock()
.unwrap_or_else(PoisonError::into_inner);
if let Some(receiver) = result.as_ref() {
return receiver.clone();
}
let (sender, receiver) = watch::channel(None);
*result = Some(receiver.clone());
let inner = Arc::clone(self);
tokio::spawn(async move {
let opening_permit = match inner.opening_permit.acquire().await {
Ok(permit) => permit,
Err(_) => {
sender.send_replace(Some(Err(
"gRPC code-mode session opening coordinator closed".to_string(),
)));
return;
}
};
let binding = inner
.binding
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take();
drop(opening_permit);
let result = match binding {
Some(binding) => wait_for_watch(binding.session.inner.request_shutdown()).await,
None => Ok(()),
};
sender.send_replace(Some(result));
});
receiver
}
}

View File

@@ -0,0 +1,431 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::sync::Arc;
use akode_code_mode_protocol::CodeModeSessionDelegate;
use akode_code_mode_protocol::CellId;
use akode_code_mode_protocol::grpc;
use akode_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
use akode_protocol::ToolName;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
const MAX_RECENT_CALLBACK_IDS: usize = 4_096;
struct ActiveCallback {
execution_id: String,
cancellation: CancellationToken,
}
pub(super) type ClosedCell = (CellId, Arc<dyn CodeModeSessionDelegate>);
pub(super) enum CallbackAdmission {
Active(CancellationToken, Arc<dyn CodeModeSessionDelegate>),
Cancelled,
Closed,
Rejected(String),
}
struct ExecutionRecord {
delegate: Arc<dyn CodeModeSessionDelegate>,
cell_id: Option<CellId>,
tool_call_id: String,
enabled_tools: HashMap<ToolName, i32>,
started: bool,
ready: bool,
closed: bool,
notifications: usize,
cancellation: CancellationToken,
}
impl ExecutionRecord {
fn accept_cell(&mut self, cell_id: &str) -> Result<(), String> {
super::validate_identifier(cell_id, "cell ID")?;
if let Some(current) = self.cell_id.as_ref() {
if current.as_str() != cell_id {
return Err(format!(
"code-mode execution changed cell ID from {current} to {cell_id}"
));
}
} else {
self.cell_id = Some(CellId::new(cell_id.to_string()));
}
Ok(())
}
}
#[derive(Default)]
struct RecentIds {
values: HashSet<Uuid>,
order: VecDeque<Uuid>,
}
impl RecentIds {
fn remember(&mut self, value: Uuid) {
if !self.values.insert(value) {
return;
}
self.order.push_back(value);
while self.order.len() > MAX_RECENT_CALLBACK_IDS {
if let Some(expired) = self.order.pop_front() {
self.values.remove(&expired);
}
}
}
fn remove(&mut self, value: &Uuid) -> bool {
self.values.remove(value)
}
fn contains(&self, value: &Uuid) -> bool {
self.values.contains(value)
}
}
#[derive(Default)]
pub(super) struct SessionState {
// Only a live session owns a share of the worker connection.
client: Option<Arc<super::GrpcClient>>,
executions: HashMap<String, ExecutionRecord>,
invocations: HashMap<String, ActiveCallback>,
notifications: usize,
seen_invocations: RecentIds,
cancelled_invocations: RecentIds,
failure: Option<String>,
closed: bool,
}
impl SessionState {
pub(super) fn with_client(client: Arc<super::GrpcClient>) -> Self {
Self {
client: Some(client),
..Self::default()
}
}
pub(super) fn client(&self) -> Result<super::GrpcClient, String> {
self.client
.as_deref()
.cloned()
.ok_or_else(|| self.closed_error())
}
fn closed_error(&self) -> String {
self.failure
.clone()
.unwrap_or_else(|| "code-mode gRPC session is closed".to_string())
}
pub(super) fn require_open(&self) -> Result<(), String> {
if self.closed {
return Err(self.closed_error());
}
Ok(())
}
pub(super) fn begin_execution(
&mut self,
request: &grpc::ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
) -> Result<(), String> {
self.require_open()?;
if request.execution_id.is_empty() || self.executions.contains_key(&request.execution_id) {
return Err("code-mode execution ID was empty or reused".to_string());
}
super::validate_identifier(&request.tool_call_id, "tool call ID")?;
let enabled_tools = request
.enabled_tools
.iter()
.map(|definition| {
let name = definition
.tool_name
.as_ref()
.ok_or_else(|| "code-mode enabled tool omitted its tool name".to_string())?;
Ok((
ToolName::new(name.namespace.clone(), name.name.clone())
.with_default_namespace(),
definition.kind,
))
})
.collect::<Result<HashMap<_, _>, String>>()?;
self.executions.insert(
request.execution_id.clone(),
ExecutionRecord {
tool_call_id: request.tool_call_id.clone(),
enabled_tools,
delegate,
cell_id: None,
started: false,
ready: false,
closed: false,
notifications: 0,
cancellation: CancellationToken::new(),
},
);
Ok(())
}
pub(super) fn admit_execution(
&mut self,
execution_id: &str,
cell_id: &str,
) -> Result<(), String> {
self.require_open()?;
self.check_cell_ownership(execution_id, cell_id)?;
let execution = self
.executions
.get_mut(execution_id)
.ok_or_else(|| format!("unknown code-mode execution {execution_id}"))?;
if execution.started {
return Err(format!("code-mode execution {execution_id} started twice"));
}
execution.accept_cell(cell_id)?;
execution.started = true;
Ok(())
}
pub(super) fn mark_execution_ready(
&mut self,
execution_id: &str,
) -> Result<Option<ClosedCell>, String> {
self.require_open()?;
let execution = self
.executions
.get_mut(execution_id)
.ok_or_else(|| format!("unknown code-mode execution {execution_id}"))?;
if !execution.started || execution.ready {
return Err(format!(
"code-mode execution {execution_id} was not ready to be claimed"
));
}
execution.ready = true;
Ok(self.close_execution_if_ready(execution_id))
}
pub(super) fn admit_invocation(
&mut self,
call: &grpc::ToolCall,
) -> Result<CallbackAdmission, String> {
self.require_open()?;
let invocation_id = Uuid::parse_str(&call.invocation_id)
.map_err(|_| "code-mode tool invocation ID must be a UUID".to_string())?;
if self.invocations.contains_key(&call.invocation_id)
|| self.seen_invocations.contains(&invocation_id)
{
return Err("code-mode tool invocation ID was reused".to_string());
}
self.check_cell_ownership(&call.execution_id, &call.cell_id)?;
let Some(execution) = self.executions.get_mut(&call.execution_id) else {
self.seen_invocations.remember(invocation_id);
self.cancelled_invocations.remove(&invocation_id);
return Ok(CallbackAdmission::Closed);
};
execution.accept_cell(&call.cell_id)?;
let execution_closed = execution.closed;
self.seen_invocations.remember(invocation_id);
let invocation_cancelled = self.cancelled_invocations.remove(&invocation_id);
if execution_closed {
return Ok(CallbackAdmission::Closed);
}
if invocation_cancelled {
return Ok(CallbackAdmission::Cancelled);
}
let Some(name) = call.tool_name.as_ref() else {
return Ok(CallbackAdmission::Rejected(
"code-mode tool invocation omitted its tool name".to_string(),
));
};
let tool_name =
ToolName::new(name.namespace.clone(), name.name.clone()).with_default_namespace();
if execution.enabled_tools.get(&tool_name) != Some(&call.tool_kind) {
return Ok(CallbackAdmission::Rejected(format!(
"code-mode tool {tool_name} is not enabled for this execution"
)));
}
if self.invocations.len() + self.notifications >= MAX_PENDING_DELEGATE_CALLS {
return Ok(CallbackAdmission::Rejected(
"code-mode host exceeded its pending delegate callback limit".to_string(),
));
}
let cancellation = CancellationToken::new();
self.invocations.insert(
call.invocation_id.clone(),
ActiveCallback {
execution_id: call.execution_id.clone(),
cancellation: cancellation.clone(),
},
);
Ok(CallbackAdmission::Active(
cancellation,
Arc::clone(&execution.delegate),
))
}
pub(super) fn admit_notification(
&mut self,
notification: &grpc::Notification,
) -> Result<CallbackAdmission, String> {
self.require_open()?;
Uuid::parse_str(&notification.notification_id)
.map_err(|_| "code-mode notification ID must be a UUID".to_string())?;
super::validate_identifier(&notification.call_id, "notification call ID")?;
self.check_cell_ownership(&notification.execution_id, &notification.cell_id)?;
let Some(execution) = self.executions.get_mut(&notification.execution_id) else {
return Ok(CallbackAdmission::Closed);
};
execution.accept_cell(&notification.cell_id)?;
if notification.call_id != execution.tool_call_id {
return Err("code-mode notification call ID does not match its execution".to_string());
}
if execution.closed {
return Ok(CallbackAdmission::Closed);
}
if self.invocations.len() + self.notifications >= MAX_PENDING_DELEGATE_CALLS {
return Ok(CallbackAdmission::Rejected(
"code-mode host exceeded its pending delegate callback limit".to_string(),
));
}
execution.notifications += 1;
self.notifications += 1;
Ok(CallbackAdmission::Active(
execution.cancellation.child_token(),
Arc::clone(&execution.delegate),
))
}
pub(super) fn finish_notification(&mut self, execution_id: &str) -> Option<ClosedCell> {
let execution = self.executions.get_mut(execution_id)?;
execution.notifications = execution.notifications.checked_sub(1)?;
self.notifications -= 1;
self.close_execution_if_ready(execution_id)
}
pub(super) fn cancel_notifications(&self, cell_id: &CellId) {
if let Some(cancellation) = self.notification_cancellation(cell_id) {
cancellation.cancel();
}
}
pub(super) fn notification_cancellation(&self, cell_id: &CellId) -> Option<CancellationToken> {
self.executions
.values()
.find(|execution| execution.cell_id.as_ref() == Some(cell_id))
.map(|execution| execution.cancellation.clone())
}
pub(super) fn cancel_invocation(&mut self, invocation_id: &str) -> Result<(), String> {
let parsed = Uuid::parse_str(invocation_id)
.map_err(|_| "code-mode tool invocation ID must be a UUID".to_string())?;
if let Some(callback) = self.invocations.remove(invocation_id) {
callback.cancellation.cancel();
} else if !self.seen_invocations.contains(&parsed) {
self.cancelled_invocations.remember(parsed);
}
Ok(())
}
pub(super) fn finish_invocation(&mut self, invocation_id: &str) {
self.invocations.remove(invocation_id);
}
pub(super) fn close_cell(
&mut self,
closed: grpc::CellClosed,
) -> Result<Option<ClosedCell>, String> {
self.require_open()?;
self.check_cell_ownership(&closed.execution_id, &closed.cell_id)?;
let Some(execution) = self.executions.get_mut(&closed.execution_id) else {
return Ok(None);
};
execution.accept_cell(&closed.cell_id)?;
if execution.closed {
return Err(format!(
"code-mode host returned an invalid closure for cell {}",
closed.cell_id
));
}
execution.closed = true;
if execution.notifications == 0 {
execution.cancellation.cancel();
}
self.revoke_execution_callbacks(&closed.execution_id);
Ok(self.close_execution_if_ready(&closed.execution_id))
}
pub(super) fn close(&mut self, failure: Option<String>) -> Vec<ClosedCell> {
if self.closed {
return Vec::new();
}
self.closed = true;
self.client = None;
self.failure = failure;
self.notifications = 0;
for (_, callback) in self.invocations.drain() {
callback.cancellation.cancel();
}
self.executions
.drain()
.filter_map(|(_, execution)| {
execution.cancellation.cancel();
execution
.cell_id
.map(|cell_id| (cell_id, execution.delegate))
})
.collect()
}
fn close_execution_if_ready(&mut self, execution_id: &str) -> Option<ClosedCell> {
self.executions
.get(execution_id)
.is_some_and(|execution| {
execution.started
&& execution.ready
&& execution.closed
&& execution.notifications == 0
})
.then(|| self.remove_execution(execution_id))
.flatten()
}
pub(super) fn remove_execution(&mut self, execution_id: &str) -> Option<ClosedCell> {
let execution = self.executions.remove(execution_id)?;
self.notifications -= execution.notifications;
execution.cancellation.cancel();
self.revoke_execution_callbacks(execution_id);
execution
.cell_id
.map(|cell_id| (cell_id, execution.delegate))
}
fn check_cell_ownership(&self, execution_id: &str, cell_id: &str) -> Result<(), String> {
if self.executions.contains_key(execution_id)
&& self.executions.iter().any(|(id, execution)| {
id != execution_id
&& execution
.cell_id
.as_ref()
.is_some_and(|current| current.as_str() == cell_id)
})
{
return Err(format!("code-mode host reused active cell ID {cell_id}"));
}
Ok(())
}
fn revoke_execution_callbacks(&mut self, execution_id: &str) {
self.invocations.retain(|_, callback| {
if callback.execution_id != execution_id {
return true;
}
callback.cancellation.cancel();
false
});
}
}
#[cfg(test)]
#[path = "state_tests.rs"]
mod tests;

View File

@@ -0,0 +1,567 @@
use akode_code_mode_protocol::CellId;
use akode_code_mode_protocol::NoopCodeModeSessionDelegate;
use akode_code_mode_protocol::grpc;
use akode_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use uuid::Uuid;
use super::CallbackAdmission;
use super::SessionState;
fn request(execution_id: &str) -> grpc::ExecuteRequest {
grpc::ExecuteRequest {
session_id: "session".to_string(),
execution_id: execution_id.to_string(),
tool_call_id: "call".to_string(),
source: String::new(),
enabled_tools: vec![grpc::ToolDefinition {
name: "tool".to_string(),
tool_name: Some(grpc::ToolName {
name: "tool".to_string(),
namespace: None,
}),
description: String::new(),
kind: grpc::ToolKind::Function as i32,
input_schema_json: None,
output_schema_json: None,
}],
yield_time_ms: None,
max_output_tokens: None,
}
}
fn tool_call(execution_id: &str, invocation_id: u128) -> grpc::ToolCall {
let invocation_id = Uuid::from_u128(invocation_id).to_string();
grpc::ToolCall {
session_id: "session".to_string(),
execution_id: execution_id.to_string(),
cell_id: "cell".to_string(),
invocation_id: invocation_id.clone(),
runtime_tool_call_id: format!("runtime-{invocation_id}"),
tool_name: Some(grpc::ToolName {
name: "tool".to_string(),
namespace: None,
}),
tool_kind: grpc::ToolKind::Function as i32,
input_json: None,
sequence: 1,
traceparent: None,
}
}
fn notification(execution_id: &str, notification_id: u128) -> grpc::Notification {
grpc::Notification {
notification_id: Uuid::from_u128(notification_id).to_string(),
execution_id: execution_id.to_string(),
cell_id: "cell".to_string(),
call_id: "call".to_string(),
text: "hello".to_string(),
}
}
#[test]
fn callbacks_use_their_execution_delegate_before_cell_admission() {
let mut state = SessionState::default();
let delegates: Vec<Arc<dyn akode_code_mode_protocol::CodeModeSessionDelegate>> = vec![
Arc::new(NoopCodeModeSessionDelegate),
Arc::new(NoopCodeModeSessionDelegate),
];
for (index, delegate) in delegates.iter().enumerate() {
state
.begin_execution(&request(&index.to_string()), delegate.clone())
.unwrap();
}
for (index, delegate) in delegates.iter().enumerate() {
let mut call = tool_call(&index.to_string(), index as u128 + 1);
call.cell_id = format!("cell-{index}");
let CallbackAdmission::Active(_, actual) = state.admit_invocation(&call).unwrap() else {
panic!("callback should be admitted before the execute response");
};
assert!(Arc::ptr_eq(&actual, delegate));
let mut notice = notification(&index.to_string(), index as u128 + 1);
notice.cell_id = call.cell_id;
let CallbackAdmission::Active(_, actual) = state.admit_notification(&notice).unwrap()
else {
panic!("notification should be admitted before the execute response");
};
assert!(Arc::ptr_eq(&actual, delegate));
}
drop(state.close(/*failure*/ None));
for delegate in delegates {
assert_eq!(Arc::strong_count(&delegate), 1);
}
}
#[test]
fn cell_closure_drains_notifications_and_cancels_tool_callbacks() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
let first = state
.admit_invocation(&tool_call("execution", /*invocation_id*/ 1))
.expect("accept early invocation");
let CallbackAdmission::Active(first_cancellation, _) = first else {
panic!("first callback was not admitted");
};
let CallbackAdmission::Active(notification_cancellation, _) = state
.admit_notification(&notification("execution", /*notification_id*/ 1))
.expect("admit notification")
else {
panic!("notification was not admitted");
};
assert!(
state
.close_cell(grpc::CellClosed {
execution_id: "execution".to_string(),
cell_id: "cell".to_string(),
final_tool_call_sequence: 3,
})
.expect("record cell closure")
.is_none()
);
assert!(first_cancellation.is_cancelled());
assert!(!notification_cancellation.is_cancelled());
state
.admit_execution("execution", "cell")
.expect("admit started cell");
assert!(matches!(
state
.admit_invocation(&tool_call("execution", /*invocation_id*/ 2))
.expect("reject invocation for a closed cell"),
CallbackAdmission::Closed
));
assert!(
state
.mark_execution_ready("execution")
.expect("claim started cell")
.is_none()
);
assert_eq!(
state
.finish_notification("execution")
.map(|(cell_id, _)| cell_id),
Some(CellId::new("cell".to_string()))
);
assert!(notification_cancellation.is_cancelled());
}
#[test]
fn cell_closure_waits_until_the_started_cell_is_claimed() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
assert!(
state
.close_cell(grpc::CellClosed {
execution_id: "execution".to_string(),
cell_id: "cell".to_string(),
final_tool_call_sequence: 0,
})
.expect("record early cell closure")
.is_none()
);
state
.admit_execution("execution", "cell")
.expect("admit started cell");
assert_eq!(
state
.mark_execution_ready("execution")
.map(|cell| cell.map(|(cell_id, _)| cell_id))
.expect("claim started cell"),
Some(CellId::new("cell".to_string()))
);
}
#[test]
fn oversized_cell_ids_are_rejected_before_admission() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
assert_eq!(
state.admit_execution("execution", &"x".repeat(grpc::MAX_IDENTIFIER_BYTES + 1)),
Err(format!(
"gRPC code-mode host returned cell ID exceeding {} bytes",
grpc::MAX_IDENTIFIER_BYTES
))
);
assert!(state.remove_execution("execution").is_none());
}
#[test]
fn callbacks_cannot_claim_another_executions_cell() {
let mut state = SessionState::default();
state
.begin_execution(&request("first"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register first execution");
state
.begin_execution(&request("second"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register second execution");
state
.admit_invocation(&tool_call("first", /*invocation_id*/ 1))
.expect("allow the first execution to claim its cell");
let expected = "code-mode host reused active cell ID cell".to_string();
assert_eq!(
state
.admit_invocation(&tool_call("second", /*invocation_id*/ 2))
.err(),
Some(expected.clone())
);
assert_eq!(
state
.admit_notification(&notification("second", /*notification_id*/ 1))
.err(),
Some(expected.clone())
);
assert_eq!(
state
.close_cell(grpc::CellClosed {
execution_id: "second".to_string(),
cell_id: "cell".to_string(),
final_tool_call_sequence: 0,
})
.err(),
Some(expected.clone())
);
assert_eq!(state.admit_execution("second", "cell"), Err(expected));
}
#[test]
fn abandonment_before_start_ignores_later_cell_closure() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
assert!(state.remove_execution("execution").is_none());
assert!(
state
.close_cell(grpc::CellClosed {
execution_id: "execution".to_string(),
cell_id: "cell".to_string(),
final_tool_call_sequence: 0,
})
.expect("ignore closure for abandoned execution")
.is_none()
);
assert!(state.close(/*failure*/ None).is_empty());
}
#[test]
fn abandonment_revokes_callbacks_and_ignores_late_events() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
let CallbackAdmission::Active(invocation, _) = state
.admit_invocation(&tool_call("execution", /*invocation_id*/ 1))
.expect("admit callback before execution starts")
else {
panic!("invocation was not admitted");
};
assert_eq!(
state
.remove_execution("execution")
.map(|(cell_id, _)| cell_id),
Some(CellId::new("cell".to_string()))
);
assert!(invocation.is_cancelled());
assert!(matches!(
state
.admit_invocation(&tool_call("execution", /*invocation_id*/ 2))
.expect("reject delayed tool invocation"),
CallbackAdmission::Closed
));
assert!(
state
.close_cell(grpc::CellClosed {
execution_id: "execution".to_string(),
cell_id: "cell".to_string(),
final_tool_call_sequence: 1,
})
.expect("ignore delayed cell closure")
.is_none()
);
assert!(state.close(/*failure*/ None).is_empty());
}
#[test]
fn invocation_cancellation_revokes_delegate_and_late_completion() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
state
.admit_execution("execution", "cell")
.expect("admit execution");
state
.mark_execution_ready("execution")
.expect("claim execution");
let invocation = tool_call("execution", /*invocation_id*/ 1);
let CallbackAdmission::Active(cancellation, _) = state
.admit_invocation(&invocation)
.expect("accept invocation")
else {
panic!("invocation was not admitted");
};
state
.cancel_invocation(&invocation.invocation_id)
.expect("cancel invocation");
assert!(cancellation.is_cancelled());
state.finish_invocation(&invocation.invocation_id);
assert_eq!(
state
.close_cell(grpc::CellClosed {
execution_id: "execution".to_string(),
cell_id: "cell".to_string(),
final_tool_call_sequence: 1,
})
.map(|cell| cell.map(|(cell_id, _)| cell_id))
.expect("close cell"),
Some(CellId::new("cell".to_string()))
);
}
#[test]
fn duplicate_invocation_ids_are_rejected() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
state
.admit_execution("execution", "cell")
.expect("admit execution");
let invocation = tool_call("execution", /*invocation_id*/ 1);
state
.admit_invocation(&invocation)
.expect("accept invocation");
state.finish_invocation(&invocation.invocation_id);
assert!(state.admit_invocation(&invocation).is_err());
}
#[test]
fn tool_callbacks_must_match_the_executions_enabled_tools() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
let mut disabled = tool_call("execution", /*invocation_id*/ 1);
disabled.tool_name = Some(grpc::ToolName {
name: "hidden".to_string(),
namespace: None,
});
assert!(matches!(
state.admit_invocation(&disabled),
Ok(CallbackAdmission::Rejected(error))
if error == "code-mode tool hidden is not enabled for this execution"
));
let mut wrong_namespace = tool_call("execution", /*invocation_id*/ 2);
wrong_namespace.tool_name = Some(grpc::ToolName {
name: "tool".to_string(),
namespace: Some("private".to_string()),
});
assert!(matches!(
state.admit_invocation(&wrong_namespace),
Ok(CallbackAdmission::Rejected(_))
));
let mut wrong_kind = tool_call("execution", /*invocation_id*/ 3);
wrong_kind.tool_kind = grpc::ToolKind::Freeform as i32;
assert!(matches!(
state.admit_invocation(&wrong_kind),
Ok(CallbackAdmission::Rejected(_))
));
let mut explicit_default_namespace = tool_call("execution", /*invocation_id*/ 4);
explicit_default_namespace.tool_name = Some(grpc::ToolName {
name: "tool".to_string(),
namespace: Some("functions".to_string()),
});
assert!(matches!(
state.admit_invocation(&explicit_default_namespace),
Ok(CallbackAdmission::Active(_, _))
));
assert_eq!(state.require_open(), Ok(()));
}
#[test]
fn execution_call_ids_must_be_bounded() {
let mut state = SessionState::default();
let mut oversized = request("execution");
oversized.tool_call_id = "x".repeat(grpc::MAX_IDENTIFIER_BYTES + 1);
assert_eq!(
state.begin_execution(&oversized, Arc::new(NoopCodeModeSessionDelegate)),
Err(format!(
"gRPC code-mode host returned tool call ID exceeding {} bytes",
grpc::MAX_IDENTIFIER_BYTES
))
);
assert!(state.remove_execution("execution").is_none());
}
#[test]
fn notification_call_ids_must_match_their_execution() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
let mut oversized = notification("execution", /*notification_id*/ 1);
oversized.call_id = "x".repeat(grpc::MAX_IDENTIFIER_BYTES + 1);
assert_eq!(
state.admit_notification(&oversized).err(),
Some(format!(
"gRPC code-mode host returned notification call ID exceeding {} bytes",
grpc::MAX_IDENTIFIER_BYTES
))
);
let mut mismatched = notification("execution", /*notification_id*/ 2);
mismatched.call_id = "other-call".to_string();
assert_eq!(
state.admit_notification(&mismatched).err(),
Some("code-mode notification call ID does not match its execution".to_string())
);
assert!(matches!(
state.admit_notification(&notification("execution", /*notification_id*/ 3)),
Ok(CallbackAdmission::Active(_, _))
));
}
#[test]
fn malformed_callback_ids_are_rejected_before_retention() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
let mut invalid_invocation = tool_call("execution", /*invocation_id*/ 1);
invalid_invocation.invocation_id = "not-a-uuid".to_string();
assert_eq!(
state.admit_invocation(&invalid_invocation).err(),
Some("code-mode tool invocation ID must be a UUID".to_string())
);
assert_eq!(
state.cancel_invocation("not-a-uuid"),
Err("code-mode tool invocation ID must be a UUID".to_string())
);
assert_eq!(
state.cancel_invocation(&"x".repeat(grpc::MAX_IDENTIFIER_BYTES + 1)),
Err("code-mode tool invocation ID must be a UUID".to_string())
);
let mut invalid_notification = notification("execution", /*notification_id*/ 1);
invalid_notification.notification_id = "not-a-uuid".to_string();
assert_eq!(
state.admit_notification(&invalid_notification).err(),
Some("code-mode notification ID must be a UUID".to_string())
);
let invocation = tool_call("execution", /*invocation_id*/ 2);
state
.cancel_invocation(&invocation.invocation_id)
.expect("remember valid cancellation");
assert!(matches!(
state.admit_invocation(&invocation),
Ok(CallbackAdmission::Cancelled)
));
}
#[test]
fn notifications_and_tools_share_the_pending_delegate_limit() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
for index in 0..MAX_PENDING_DELEGATE_CALLS {
assert!(matches!(
state.admit_notification(&notification("execution", index as u128 + 1)),
Ok(CallbackAdmission::Active(_, _))
));
}
assert!(matches!(
state.admit_notification(&notification("execution", /*notification_id*/ 2_000)),
Ok(CallbackAdmission::Rejected(error))
if error == "code-mode host exceeded its pending delegate callback limit"
));
assert!(matches!(
state.admit_invocation(&tool_call("execution", /*invocation_id*/ 1)),
Ok(CallbackAdmission::Rejected(error))
if error == "code-mode host exceeded its pending delegate callback limit"
));
assert_eq!(state.require_open(), Ok(()));
assert!(state.finish_notification("execution").is_none());
assert!(matches!(
state.admit_invocation(&tool_call("execution", /*invocation_id*/ 2)),
Ok(CallbackAdmission::Active(_, _))
));
}
#[test]
fn terminated_cells_cancel_pending_notifications() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
let CallbackAdmission::Active(cancellation, _) = state
.admit_notification(&notification("execution", /*notification_id*/ 1))
.expect("admit notification")
else {
panic!("notification was not admitted");
};
state.cancel_notifications(&CellId::new("cell".to_string()));
assert!(cancellation.is_cancelled());
assert!(state.finish_notification("execution").is_none());
}
#[test]
fn disconnect_revokes_callbacks_and_returns_each_live_cell_once() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
state
.admit_execution("execution", "cell")
.expect("admit execution");
let CallbackAdmission::Active(cancellation, _) = state
.admit_invocation(&tool_call("execution", /*invocation_id*/ 1))
.expect("accept invocation")
else {
panic!("invocation was not admitted");
};
let CallbackAdmission::Active(notification_cancellation, _) = state
.admit_notification(&notification("execution", /*notification_id*/ 1))
.expect("admit notification")
else {
panic!("notification was not admitted");
};
assert_eq!(
state
.close(Some("lease closed".to_string()))
.into_iter()
.map(|(cell_id, _)| cell_id)
.collect::<Vec<_>>(),
vec![CellId::new("cell".to_string())]
);
assert!(cancellation.is_cancelled());
assert!(notification_cancellation.is_cancelled());
assert!(state.close(/*failure*/ None).is_empty());
assert_eq!(state.require_open(), Err("lease closed".to_string()));
}

View File

@@ -0,0 +1,158 @@
use std::sync::Arc;
use std::sync::Weak;
use akode_code_mode_protocol::grpc::code_mode_host_client::CodeModeHostClient;
use akode_code_mode_protocol::host::MAX_FRAME_BYTES;
use akode_http_client::ClientRouteClass;
use akode_http_client::HttpClientFactory;
use http_body_util::BodyExt;
use tonic::Status;
use tonic::body::Body;
use tonic::codegen::http::Request;
use tonic::codegen::http::Response;
use tonic::codegen::http::Uri;
use tonic::transport::Channel;
use tonic::transport::Endpoint;
use tower::ServiceExt;
use tower::service_fn;
use tower::util::BoxCloneSyncService;
use super::GrpcClient;
pub(super) type GrpcTransport = BoxCloneSyncService<Request<Body>, Response<Body>, Status>;
pub(super) enum SharedTransport {
Url {
endpoint: String,
http_client_factory: HttpClientFactory,
client: tokio::sync::Mutex<Option<(HttpClientFactory, Weak<GrpcClient>)>>,
},
Connected(Arc<GrpcClient>),
}
impl SharedTransport {
pub(super) fn new(endpoint: String, http_client_factory: HttpClientFactory) -> Self {
Self::Url {
endpoint,
http_client_factory,
client: tokio::sync::Mutex::new(None),
}
}
pub(super) fn with_channel(channel: Channel) -> Self {
let transport = channel.map_err(|error| Status::from_error(Box::new(error)));
Self::Connected(Arc::new(
CodeModeHostClient::new(BoxCloneSyncService::new(transport))
.accept_compressed(tonic::codec::CompressionEncoding::Zstd)
.max_decoding_message_size(MAX_FRAME_BYTES)
.max_encoding_message_size(MAX_FRAME_BYTES),
))
}
pub(super) fn with_transport(transport: GrpcTransport) -> Self {
Self::Connected(Arc::new(
CodeModeHostClient::new(transport)
.accept_compressed(tonic::codec::CompressionEncoding::Zstd)
.max_decoding_message_size(MAX_FRAME_BYTES)
.max_encoding_message_size(MAX_FRAME_BYTES),
))
}
pub(super) async fn client(&self) -> Result<Arc<GrpcClient>, String> {
let (endpoint, http_client_factory, client) = match self {
Self::Url {
endpoint,
http_client_factory,
client,
} => (endpoint, http_client_factory, client),
Self::Connected(client) => return Ok(client.clone()),
};
let bound_factory = http_client_factory.clone().with_network_policy(
http_client_factory
.network_policy()
.clone()
.for_current_account(),
);
let mut cached = client.lock().await;
if let Some((factory, client)) = cached.as_ref()
&& factory == &bound_factory
&& let Some(client) = client.upgrade()
{
return Ok(client);
}
let client = if endpoint.starts_with("unix:") {
let channel = Endpoint::from_shared(endpoint.clone())
.map_err(|error| format!("invalid gRPC code-mode Unix socket endpoint: {error}"))?
.connect_lazy();
let transport = channel.map_err(|error| Status::from_error(Box::new(error)));
CodeModeHostClient::new(BoxCloneSyncService::new(transport))
} else {
let target = reqwest::Url::parse(endpoint)
.map_err(|error| format!("invalid gRPC code-mode host URL: {error}"))?;
if !matches!(target.scheme(), "http" | "https") {
return Err("gRPC code-mode host URL must use http or https".to_string());
}
if !target.username().is_empty() || target.password().is_some() {
return Err("gRPC code-mode host URL must not include credentials".to_string());
}
if target.path() != "/" || target.query().is_some() || target.fragment().is_some() {
return Err(
"gRPC code-mode host URL must not include a path, query, or fragment"
.to_string(),
);
}
let origin: Uri = endpoint
.parse()
.map_err(|error| format!("invalid gRPC code-mode host origin: {error}"))?;
let client = akode_http_client::RouteAwareClientPool::with_builder(
bound_factory.clone(),
ClientRouteClass::Other,
akode_http_client::HttpClientBuilder::new()
.without_request_logging()
// Some hosts assign a worker per connection. A quiet session
// must still reach the worker holding its open lease.
.without_pool_idle_timeout()
.http2_prior_knowledge()
.without_redirects(),
);
let transport = service_fn(move |request: Request<Body>| {
let client = client.clone();
async move {
let request =
request.map(|body| reqwest::Body::wrap_stream(body.into_data_stream()));
let request = reqwest::Request::try_from(request)
.map_err(|error| Status::invalid_argument(error.to_string()))?;
let response = client
.execute(request)
.await
.map_err(|error| {
// Sending can fail on DNS or a reset connection before
// headers arrive. Keep these distinct from RPC errors.
let mut status = if matches!(
&error,
akode_http_client::HttpError::Request(error)
if error.is_connect() || error.is_request()
) {
Status::unavailable(error.to_string())
} else {
Status::unknown(error.to_string())
};
status.set_source(Arc::new(error));
status
})?
.into_http_response();
Ok::<_, Status>(response.map(Body::new))
}
});
CodeModeHostClient::with_origin(BoxCloneSyncService::new(transport), origin)
};
let client = client
.accept_compressed(tonic::codec::CompressionEncoding::Zstd)
.max_decoding_message_size(MAX_FRAME_BYTES)
.max_encoding_message_size(MAX_FRAME_BYTES);
// Let the last session release its worker even if the provider stays alive.
let client = Arc::new(client);
*cached = Some((bound_factory, Arc::downgrade(&client)));
Ok(client)
}
}

View File

@@ -0,0 +1,8 @@
mod grpc_session;
mod remote_session;
pub use akode_code_mode_protocol::*;
pub use grpc_session::GrpcCodeModeSessionProvider;
pub use remote_session::DisabledCodeModeSessionProvider;
pub use remote_session::ProcessOwnedCodeModeSession;
pub use remote_session::ProcessOwnedCodeModeSessionProvider;

View File

@@ -0,0 +1,600 @@
use std::io;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::OnceLock;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
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::CodeModeSessionProvider;
use akode_code_mode_protocol::CodeModeSessionProviderFuture;
use akode_code_mode_protocol::CodeModeSessionResultFuture;
use akode_code_mode_protocol::ExecuteRequest;
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::host::SessionId;
use akode_install_context::InstallContext;
use tokio::sync::Semaphore;
use tokio::sync::watch;
use tokio_util::sync::CancellationToken;
use self::connection::Connection;
use self::connection::ConnectionError;
use self::connection::RemoteSession;
use self::connection::SessionCleanup;
use self::delegate::TracedCellDelegate;
mod connection;
mod delegate;
pub(crate) type ShutdownResultReceiver = watch::Receiver<Option<Result<(), String>>>;
/// Creates code-mode sessions backed by one lazily spawned process host.
pub struct ProcessOwnedCodeModeSessionProvider {
host: Arc<OwnedCodeModeHost>,
}
/// Rejects code-mode sessions when the standalone host is disabled.
#[derive(Default)]
pub struct DisabledCodeModeSessionProvider;
impl ProcessOwnedCodeModeSessionProvider {
pub fn with_host_program(host_program: PathBuf) -> Self {
Self {
host: Arc::new(OwnedCodeModeHost::new(host_program)),
}
}
fn process_host(&self) -> Arc<OwnedCodeModeHost> {
Arc::clone(&self.host)
}
}
impl Default for ProcessOwnedCodeModeSessionProvider {
fn default() -> Self {
Self::with_host_program(InstallContext::current().code_mode_host_program())
}
}
impl CodeModeSessionProvider for ProcessOwnedCodeModeSessionProvider {
fn availability(&self) -> Result<(), String> {
let host_program = &self.host.host_program;
if host_program.is_file() {
Ok(())
} else {
Err(ConnectionError::Spawn {
host_program: host_program.clone(),
error: io::Error::new(io::ErrorKind::NotFound, "host executable was not found"),
}
.to_string())
}
}
fn create_session(&self) -> CodeModeSessionProviderFuture<'_> {
self.create_session_with_limits(CodeModeSessionCellExecutionLimits::default())
}
fn create_session_with_limits<'a>(
&'a self,
limits: CodeModeSessionCellExecutionLimits,
) -> CodeModeSessionProviderFuture<'a> {
self.create_session_with_options(CodeModeSessionOptions {
cell_execution_limits: limits,
..CodeModeSessionOptions::default()
})
}
fn create_session_with_options<'a>(
&'a self,
options: CodeModeSessionOptions,
) -> CodeModeSessionProviderFuture<'a> {
Box::pin(create_host_session(self.process_host(), options))
}
}
impl CodeModeSessionProvider for DisabledCodeModeSessionProvider {
fn availability(&self) -> Result<(), String> {
Err("code-mode host is disabled".to_string())
}
fn create_session(&self) -> CodeModeSessionProviderFuture<'_> {
Box::pin(async { Err("code-mode host is disabled".to_string()) })
}
fn create_session_with_limits<'a>(
&'a self,
_limits: CodeModeSessionCellExecutionLimits,
) -> CodeModeSessionProviderFuture<'a> {
self.create_session()
}
}
async fn create_host_session(
host: Arc<OwnedCodeModeHost>,
options: CodeModeSessionOptions,
) -> Result<Arc<dyn CodeModeSession>, String> {
let session = ProcessOwnedCodeModeSession::with_host(host, options);
session.connection().await?;
Ok(Arc::new(session))
}
struct OwnedCodeModeHost {
host_program: PathBuf,
connection: StdMutex<Option<Arc<Connection>>>,
connect_permit: Semaphore,
connection_generation: AtomicU64,
last_connection_error: StdMutex<Option<(u64, String)>>,
next_session_id: AtomicU64,
}
impl OwnedCodeModeHost {
fn new(host_program: PathBuf) -> Self {
Self {
host_program,
connection: StdMutex::new(None),
connect_permit: Semaphore::new(/*permits*/ 1),
connection_generation: AtomicU64::new(0),
last_connection_error: StdMutex::new(None),
next_session_id: AtomicU64::new(1),
}
}
async fn connection(&self) -> Result<Arc<Connection>, ConnectionError> {
if let Some(connection) = self.live_connection() {
return Ok(connection);
}
let observed_generation = self.connection_generation.load(Ordering::Acquire);
let _connect_permit = self.connect_permit.acquire().await.map_err(|_| {
ConnectionError::Other("code-mode host connection coordinator closed".into())
})?;
if let Some(connection) = self.live_connection() {
return Ok(connection);
}
let completed_generation = self.connection_generation.load(Ordering::Acquire);
if completed_generation != observed_generation
&& let Some((generation, error)) = self
.last_connection_error
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_ref()
&& *generation == completed_generation
{
return Err(ConnectionError::Other(error.clone()));
}
let connection = Connection::spawn(&self.host_program).await;
let new_connection = match connection {
Ok(connection) => connection,
Err(error) => {
let generation = self.connection_generation.fetch_add(1, Ordering::AcqRel) + 1;
*self
.last_connection_error
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) =
Some((generation, error.to_string()));
return Err(error);
}
};
let new_connection = Arc::new(new_connection);
*self
.connection
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::clone(&new_connection));
Ok(new_connection)
}
fn live_connection(&self) -> Option<Arc<Connection>> {
self.connection
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_ref()
.filter(|connection| connection.is_alive())
.cloned()
}
fn allocate_session(&self) -> RemoteSession {
// The shared ordinal also keeps cell IDs distinct after a thread reload.
let generation = self.next_session_id.fetch_add(1, Ordering::Relaxed);
let id = match SessionId::new(format!("session-{generation}")) {
Ok(session_id) => session_id,
Err(_) => unreachable!("a generated code-mode session ID is nonempty"),
};
RemoteSession { id, generation }
}
}
enum SessionState {
New,
Opening {
remote: RemoteSession,
result_rx: watch::Receiver<Option<Result<SessionBinding, String>>>,
},
Open(SessionBinding),
Closing,
Closed,
}
#[derive(Clone)]
struct SessionBinding {
connection: Arc<Connection>,
remote: RemoteSession,
cleanup: SessionCleanup,
}
struct SessionInner {
host: Arc<OwnedCodeModeHost>,
options: CodeModeSessionOptions,
// The first successful open fixes the output policy for all generations of this session.
output_truncation: OnceLock<CodeModeOutputTruncation>,
state: StdMutex<SessionState>,
shutdown_requested: AtomicBool,
shutdown_result: StdMutex<Option<ShutdownResultReceiver>>,
retired_cleanups: StdMutex<Vec<SessionCleanup>>,
}
/// A logical code-mode session assigned to a process host.
pub struct ProcessOwnedCodeModeSession {
inner: Arc<SessionInner>,
}
impl ProcessOwnedCodeModeSession {
pub fn new() -> Self {
Self::with_host(
Arc::new(OwnedCodeModeHost::new(
InstallContext::current().code_mode_host_program(),
)),
CodeModeSessionOptions::default(),
)
}
fn with_host(host: Arc<OwnedCodeModeHost>, options: CodeModeSessionOptions) -> Self {
Self {
inner: Arc::new(SessionInner {
host,
options,
output_truncation: OnceLock::new(),
state: StdMutex::new(SessionState::New),
shutdown_requested: AtomicBool::new(false),
shutdown_result: StdMutex::new(None),
retired_cleanups: StdMutex::new(Vec::new()),
}),
}
}
async fn connection(&self) -> Result<SessionBinding, String> {
self.inner.connection().await
}
fn server_output_budget(&self, budget: Option<usize>) -> Option<usize> {
budget.filter(|_| self.output_truncation() == CodeModeOutputTruncation::Server)
}
pub async fn execute(
&self,
mut request: ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
preempt: Option<CancellationToken>,
) -> Result<StartedCell, String> {
let binding = self.connection().await?;
let delegate = Arc::new(TracedCellDelegate {
delegate,
trace: akode_otel::current_span_w3c_trace_context(),
});
// V1 encodes the exec budget as i32. Its maximum already exceeds the host collector limit.
request.max_output_tokens = self
.server_output_budget(request.max_output_tokens)
.map(|tokens| tokens.min(i32::MAX as usize));
binding
.connection
.execute(binding.remote, request, delegate, preempt)
.await
}
pub async fn wait(
&self,
mut request: WaitRequest,
preempt: Option<CancellationToken>,
) -> Result<WaitOutcome, String> {
let binding = self.connection().await?;
request.max_output_tokens = self.server_output_budget(request.max_output_tokens);
binding
.connection
.wait(binding.remote, request, preempt)
.await
}
pub async fn terminate(&self, mut request: TerminateRequest) -> Result<WaitOutcome, String> {
let binding = self.connection().await?;
request.max_output_tokens = self.server_output_budget(request.max_output_tokens);
binding.connection.terminate(binding.remote, request).await
}
pub async fn shutdown(&self) -> Result<(), String> {
wait_for_watch(self.inner.request_shutdown()).await
}
}
impl SessionInner {
async fn connection(self: &Arc<Self>) -> Result<SessionBinding, String> {
loop {
if self.shutdown_requested.load(Ordering::Acquire) {
return Err("code mode session is shutting down".to_string());
}
let (result_rx, start) = {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match &*state {
SessionState::New => {
let remote = self.host.allocate_session();
let (result_tx, result_rx) = watch::channel(None);
*state = SessionState::Opening {
remote: remote.clone(),
result_rx: result_rx.clone(),
};
(result_rx, Some((remote, result_tx)))
}
SessionState::Opening { result_rx, .. } => (result_rx.clone(), None),
SessionState::Open(binding) if binding.connection.is_alive() => {
return Ok(binding.clone());
}
SessionState::Open(binding) => {
self.retain_cleanup(binding.cleanup.clone());
*state = SessionState::New;
continue;
}
SessionState::Closing | SessionState::Closed => {
return Err("code mode session is shutting down".to_string());
}
}
};
if let Some((remote, result_tx)) = start {
let inner = Arc::clone(self);
tokio::spawn(async move {
inner.open(remote, result_tx).await;
});
}
return wait_for_watch(result_rx).await;
}
}
async fn open(
self: Arc<Self>,
remote: RemoteSession,
result_tx: watch::Sender<Option<Result<SessionBinding, String>>>,
) {
let result = match self.host.connection().await {
Ok(connection) => {
let cleanup = connection
.open_session(
remote.clone(),
self.options.clone(),
&self.output_truncation,
)
.await;
cleanup.map(|cleanup| SessionBinding {
connection,
remote: remote.clone(),
cleanup,
})
}
Err(err) => Err(err.to_string()),
};
{
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if matches!(
&*state,
SessionState::Opening {
remote: opening_remote,
..
} if opening_remote == &remote
) {
*state = match &result {
Ok(binding) => SessionState::Open(binding.clone()),
Err(_) => SessionState::New,
};
}
}
result_tx.send_replace(Some(result));
}
fn request_shutdown(self: &Arc<Self>) -> ShutdownResultReceiver {
self.shutdown_requested.store(true, Ordering::Release);
let mut shutdown_result = self
.shutdown_result
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(result_rx) = shutdown_result.as_ref() {
return result_rx.clone();
}
let (result_tx, result_rx) = watch::channel(None);
*shutdown_result = Some(result_rx.clone());
let inner = Arc::clone(self);
tokio::spawn(async move {
let result = inner.drive_shutdown().await;
result_tx.send_replace(Some(result));
});
result_rx
}
async fn drive_shutdown(self: &Arc<Self>) -> Result<(), String> {
loop {
let action = {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match &*state {
SessionState::New => {
*state = SessionState::Closed;
ShutdownAction::Finish
}
SessionState::Opening { result_rx, .. } => {
ShutdownAction::WaitForOpen(result_rx.clone())
}
SessionState::Open(binding) if !binding.connection.is_alive() => {
let cleanup = binding.cleanup.clone();
*state = SessionState::Closing;
ShutdownAction::WaitForSessionCleanup(cleanup)
}
SessionState::Open(binding) => {
let binding = binding.clone();
*state = SessionState::Closing;
ShutdownAction::Close(binding)
}
SessionState::Closing => {
return Err("code-mode session shutdown driver entered twice".to_string());
}
SessionState::Closed => return Ok(()),
}
};
match action {
ShutdownAction::WaitForOpen(result_rx) => {
let _ = wait_for_watch(result_rx).await;
}
ShutdownAction::Finish => {
self.wait_for_retired_cleanups().await;
return Ok(());
}
ShutdownAction::WaitForSessionCleanup(cleanup) => {
cleanup.wait().await;
self.wait_for_retired_cleanups().await;
*self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = SessionState::Closed;
return Ok(());
}
ShutdownAction::Close(binding) => {
let result = binding.connection.shutdown_session(binding.remote).await;
if result.is_err() && !binding.connection.is_alive() {
binding.cleanup.wait().await;
}
self.wait_for_retired_cleanups().await;
*self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = SessionState::Closed;
return result;
}
}
}
}
fn retain_cleanup(&self, cleanup: SessionCleanup) {
let mut retired = self
.retired_cleanups
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
retired.retain(|cleanup| !cleanup.is_complete());
if !cleanup.is_complete() {
retired.push(cleanup);
}
}
async fn wait_for_retired_cleanups(&self) {
let retired = std::mem::take(
&mut *self
.retired_cleanups
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
);
for cleanup in retired {
cleanup.wait().await;
}
}
}
enum ShutdownAction {
WaitForOpen(watch::Receiver<Option<Result<SessionBinding, String>>>),
Finish,
WaitForSessionCleanup(SessionCleanup),
Close(SessionBinding),
}
pub(crate) async fn wait_for_watch<T>(
mut result_rx: watch::Receiver<Option<Result<T, String>>>,
) -> Result<T, String>
where
T: Clone,
{
loop {
if let Some(result) = result_rx.borrow().clone() {
return result;
}
result_rx
.changed()
.await
.map_err(|_| "code-mode session transition stopped".to_string())?;
}
}
impl Drop for ProcessOwnedCodeModeSession {
fn drop(&mut self) {
if tokio::runtime::Handle::try_current().is_ok() {
self.inner.request_shutdown();
}
}
}
impl Default for ProcessOwnedCodeModeSession {
fn default() -> Self {
Self::new()
}
}
impl CodeModeSession for ProcessOwnedCodeModeSession {
fn output_truncation(&self) -> CodeModeOutputTruncation {
self.inner
.output_truncation
.get()
.copied()
.unwrap_or_default()
}
fn execute<'a>(
&'a self,
request: ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
preempt: Option<CancellationToken>,
) -> CodeModeSessionResultFuture<'a, StartedCell> {
Box::pin(ProcessOwnedCodeModeSession::execute(
self, request, delegate, preempt,
))
}
fn wait<'a>(
&'a self,
request: WaitRequest,
preempt: Option<CancellationToken>,
) -> CodeModeSessionResultFuture<'a, WaitOutcome> {
Box::pin(ProcessOwnedCodeModeSession::wait(self, request, preempt))
}
fn terminate<'a>(
&'a self,
request: TerminateRequest,
) -> CodeModeSessionResultFuture<'a, WaitOutcome> {
Box::pin(ProcessOwnedCodeModeSession::terminate(self, request))
}
fn shutdown<'a>(&'a self) -> CodeModeSessionResultFuture<'a, ()> {
Box::pin(ProcessOwnedCodeModeSession::shutdown(self))
}
}
#[cfg(test)]
#[path = "remote_session_tests.rs"]
mod tests;

View File

@@ -0,0 +1,638 @@
use std::fmt;
use std::future::Future;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use akode_code_mode_protocol::CodeModeOutputTruncation;
use akode_code_mode_protocol::CodeModeSessionCellExecutionLimits;
use akode_code_mode_protocol::CodeModeSessionDelegate;
use akode_code_mode_protocol::CodeModeSessionOptions;
use akode_code_mode_protocol::ExecuteRequest;
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::host::BOUNDED_OUTPUT_CAPABILITY;
use akode_code_mode_protocol::host::Capability;
use akode_code_mode_protocol::host::CapabilitySet;
use akode_code_mode_protocol::host::ClientHello;
use akode_code_mode_protocol::host::ClientToHost;
use akode_code_mode_protocol::host::EncodedFrame;
use akode_code_mode_protocol::host::FramedReader;
use akode_code_mode_protocol::host::FramedWriter;
use akode_code_mode_protocol::host::HostToClient;
use akode_code_mode_protocol::host::LARGE_DELEGATE_CAPACITY_CAPABILITY;
use akode_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
use akode_code_mode_protocol::host::ProtocolVersion;
use akode_code_mode_protocol::host::RequestId;
use akode_code_mode_protocol::host::SESSION_RESOURCE_LIMITS_CAPABILITY;
use akode_code_mode_protocol::host::SupportedProtocolVersions;
use akode_code_mode_protocol::host::YIELD_OBSERVATION_CAPABILITY;
use akode_protocol::shell_environment::scrub_non_inheritable_env_vars;
use tokio::io::AsyncBufReadExt;
use tokio::io::BufReader;
use tokio::process::Child;
use tokio::process::ChildStdin;
use tokio::process::ChildStdout;
use tokio::process::Command;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::debug;
use tracing::warn;
use self::driver::ConnectionDriver;
use self::driver::DriverCommand;
use self::driver::DriverEvent;
use self::driver::DriverLifecycle;
pub(super) use self::driver::RemoteSession;
pub(super) use self::driver::SessionCleanup;
use self::reader::drive_reader;
mod driver;
mod reader;
// Accommodate a completion burst and concurrent control messages from a full host.
const IPC_CHANNEL_CAPACITY: usize = MAX_PENDING_DELEGATE_CALLS * 2;
const LOCAL_HOST_STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
// TODO(anp) make this timeout configurable if 60 seconds is insufficient.
const DEFAULT_HOST_WAIT_TRANSPORT_TIMEOUT: Duration = Duration::from_secs(60);
// Host spawn errors become model-visible tool output. Bound configured paths
// while preserving the executable-bearing suffix needed to diagnose failures.
const MAX_DISPLAYED_HOST_PROGRAM_BYTES: usize = 512;
const TRUNCATED_HOST_PROGRAM_PREFIX: &str = "...";
pub(super) enum ConnectionError {
Spawn {
host_program: PathBuf,
error: io::Error,
},
Other(String),
}
impl fmt::Display for ConnectionError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Spawn {
host_program,
error,
} => {
let host_program = host_program.to_string_lossy();
if host_program.len() <= MAX_DISPLAYED_HOST_PROGRAM_BYTES {
return write!(
formatter,
"failed to spawn code-mode host {host_program}: {error}"
);
}
let mut suffix_start = host_program.len()
- (MAX_DISPLAYED_HOST_PROGRAM_BYTES - TRUNCATED_HOST_PROGRAM_PREFIX.len());
while !host_program.is_char_boundary(suffix_start) {
suffix_start += 1;
}
write!(
formatter,
"failed to spawn code-mode host {TRUNCATED_HOST_PROGRAM_PREFIX}{}: {error}",
&host_program[suffix_start..]
)
}
Self::Other(message) => formatter.write_str(message),
}
}
}
pub(super) struct Connection {
command_tx: mpsc::Sender<DriverCommand>,
execute_claim_tx: mpsc::UnboundedSender<RequestId>,
alive: Arc<AtomicBool>,
failure: Arc<std::sync::Mutex<Option<String>>>,
cancellation: CancellationToken,
capabilities: CapabilitySet,
}
struct CallerCancellation {
token: CancellationToken,
armed: bool,
}
struct ConnectionSupervisor {
child: Child,
event_tx: mpsc::Sender<DriverEvent>,
cancellation: CancellationToken,
alive: Arc<AtomicBool>,
failure: Arc<std::sync::Mutex<Option<String>>>,
driver_task: JoinHandle<()>,
reader_task: JoinHandle<Result<(), String>>,
writer_task: JoinHandle<Result<(), String>>,
}
impl CallerCancellation {
fn new() -> Self {
Self {
token: CancellationToken::new(),
armed: true,
}
}
fn token(&self) -> CancellationToken {
self.token.clone()
}
fn disarm(mut self) {
self.armed = false;
}
}
impl Drop for CallerCancellation {
fn drop(&mut self) {
if self.armed {
self.token.cancel();
}
}
}
impl Connection {
pub(super) async fn spawn(host_program: &Path) -> Result<Self, ConnectionError> {
let mut command = Command::new(host_program);
#[cfg(unix)]
command.process_group(0);
#[cfg(windows)]
command.creation_flags(/*flags*/ 0x0800_0000); // CREATE_NO_WINDOW
command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
scrub_non_inheritable_env_vars(command.as_std_mut());
let mut child = command.spawn().map_err(|error| ConnectionError::Spawn {
host_program: host_program.to_path_buf(),
error,
})?;
if let Some(stderr) = child.stderr.take() {
tokio::spawn(async move {
let mut lines = BufReader::new(stderr).lines();
loop {
match lines.next_line().await {
Ok(Some(line)) => debug!("code-mode host stderr: {line}"),
Ok(None) => break,
Err(err) => {
warn!("failed to read code-mode host stderr: {err}");
break;
}
}
}
});
}
let stdin = child
.stdin
.take()
.ok_or_else(|| ConnectionError::Other("spawned code-mode host has no stdin".into()))?;
let stdout = child
.stdout
.take()
.ok_or_else(|| ConnectionError::Other("spawned code-mode host has no stdout".into()))?;
Self::establish(FramedReader::new(stdout), FramedWriter::new(stdin), child).await
}
async fn establish(
mut reader: FramedReader<ChildStdout>,
mut writer: FramedWriter<ChildStdin>,
mut child: Child,
) -> Result<Self, ConnectionError> {
let handshake = async {
let session_limits_capability = Capability::new(SESSION_RESOURCE_LIMITS_CAPABILITY)
.map_err(|error| error.to_string())?;
let yield_capability =
Capability::new(YIELD_OBSERVATION_CAPABILITY).map_err(|error| error.to_string())?;
let output_capability =
Capability::new(BOUNDED_OUTPUT_CAPABILITY).map_err(|error| error.to_string())?;
let delegate_capacity = Capability::new(LARGE_DELEGATE_CAPACITY_CAPABILITY)
.map_err(|error| error.to_string())?;
let optional_capabilities = CapabilitySet::try_new([
session_limits_capability,
yield_capability,
output_capability,
delegate_capacity,
])
.map_err(|error| error.to_string())?;
let hello = ClientHello::new(
SupportedProtocolVersions::try_new([ProtocolVersion::V1])
.map_err(|err| err.to_string())?,
CapabilitySet::empty(),
optional_capabilities,
)
.map_err(|err| err.to_string())?;
writer
.write(&ClientToHost::ClientHello(hello))
.await
.map_err(|err| format!("failed to write code-mode host hello: {err}"))?;
match reader
.read()
.await
.map_err(|err| format!("failed to read code-mode host hello: {err}"))?
{
Some(HostToClient::HostHello(hello))
if hello.selected_version() == ProtocolVersion::V1 =>
{
Ok(hello.capabilities().clone())
}
Some(HostToClient::HandshakeRejected { reason }) => {
Err(format!("code-mode host rejected the handshake: {reason:?}"))
}
Some(message) => Err(format!(
"code-mode host returned an invalid handshake response: {message:?}"
)),
None => Err("code-mode host exited during handshake".to_string()),
}
};
let handshake_result =
match tokio::time::timeout(LOCAL_HOST_STARTUP_TIMEOUT, handshake).await {
Ok(result) => result,
Err(_) => {
kill_and_reap(&mut child).await;
return Err(ConnectionError::Other(
"timed out negotiating with the code-mode host".into(),
));
}
};
let capabilities = match handshake_result {
Ok(negotiated) => negotiated,
Err(err) => {
kill_and_reap(&mut child).await;
return Err(ConnectionError::Other(err));
}
};
let (command_tx, command_rx) = mpsc::channel(IPC_CHANNEL_CAPACITY);
let (event_tx, event_rx) = mpsc::channel(IPC_CHANNEL_CAPACITY);
let (outgoing_tx, outgoing_rx) = mpsc::channel::<EncodedFrame>(IPC_CHANNEL_CAPACITY);
let cancellation = CancellationToken::new();
let alive = Arc::new(AtomicBool::new(true));
let failure = Arc::new(std::sync::Mutex::new(None));
let writer_cancellation = cancellation.clone();
let writer_task =
tokio::spawn(
async move { drive_writer(writer, outgoing_rx, writer_cancellation).await },
);
let reader_events = event_tx.clone();
let reader_cancellation = cancellation.clone();
let reader_task =
tokio::spawn(
async move { drive_reader(reader, reader_events, reader_cancellation).await },
);
let (driver, execute_claim_tx) = ConnectionDriver::new(
command_rx,
event_rx,
event_tx.clone(),
outgoing_tx,
DriverLifecycle {
alive: Arc::clone(&alive),
failure: Arc::clone(&failure),
cancellation: cancellation.clone(),
},
);
let driver_task = tokio::spawn(driver.run());
tokio::spawn(
ConnectionSupervisor {
child,
event_tx,
cancellation: cancellation.clone(),
alive: Arc::clone(&alive),
failure: Arc::clone(&failure),
driver_task,
reader_task,
writer_task,
}
.run(),
);
Ok(Self {
command_tx,
execute_claim_tx,
alive,
failure,
cancellation,
capabilities,
})
}
pub(super) fn is_alive(&self) -> bool {
if self.command_tx.is_closed() {
mark_connection_dead(
&self.alive,
&self.failure,
"code-mode connection driver closed".to_string(),
);
}
self.alive.load(Ordering::Acquire)
}
fn supports(&self, capability: &str) -> bool {
self.capabilities
.iter()
.any(|value| value.as_str() == capability)
}
pub(super) async fn open_session(
&self,
session: RemoteSession,
mut options: CodeModeSessionOptions,
pinned: &OnceLock<CodeModeOutputTruncation>,
) -> Result<SessionCleanup, String> {
if options.cell_execution_limits != CodeModeSessionCellExecutionLimits::default()
&& !self.supports(SESSION_RESOURCE_LIMITS_CAPABILITY)
{
return Err(format!(
"code-mode host does not support session resource limits: missing `{SESSION_RESOURCE_LIMITS_CAPABILITY}` capability"
));
}
let pinned_mode = pinned.get().copied();
let output_truncation = if self.supports(BOUNDED_OUTPUT_CAPABILITY) {
pinned_mode.unwrap_or(options.output_truncation)
} else if pinned_mode == Some(CodeModeOutputTruncation::Server) {
return Err(
"code-mode host cannot preserve server output truncation after reconnect".into(),
);
} else {
CodeModeOutputTruncation::Client
};
options.output_truncation = output_truncation;
let cleanup = SessionCleanup::new();
let cancellation = CallerCancellation::new();
let (response_tx, response_rx) = oneshot::channel();
self.send(DriverCommand::OpenSession {
session,
options,
cleanup: cleanup.clone(),
caller_cancellation: cancellation.token(),
response_tx,
})
.await?;
let result = self.receive(response_rx).await;
cancellation.disarm();
result?;
pinned.get_or_init(|| output_truncation);
Ok(cleanup)
}
pub(super) async fn execute(
&self,
session: RemoteSession,
request: ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
yield_signal: Option<CancellationToken>,
) -> Result<StartedCell, String> {
let yield_signal = self.supported_yield_signal(yield_signal);
let cancellation = CallerCancellation::new();
let (response_tx, response_rx) = oneshot::channel();
self.send(DriverCommand::Execute {
session,
request,
delegate,
caller_cancellation: cancellation.token(),
yield_signal,
response_tx,
})
.await?;
let delivered = match self.receive(response_rx).await {
Ok(delivered) => delivered,
Err(err) => {
cancellation.disarm();
return Err(err);
}
};
self.execute_claim_tx
.send(delivered.request_id)
.map_err(|_| self.failure_message())?;
cancellation.disarm();
Ok(delivered.started)
}
pub(super) async fn wait(
&self,
session: RemoteSession,
request: WaitRequest,
yield_signal: Option<CancellationToken>,
) -> Result<WaitOutcome, String> {
let yield_signal = self.supported_yield_signal(yield_signal);
// Account for the runtime's one-second yield grace separately from transport.
let runtime_timeout =
Duration::from_millis(request.yield_time_ms).saturating_add(Duration::from_secs(1));
let cancellation = CallerCancellation::new();
let (response_tx, response_rx) = oneshot::channel();
let result = self
.with_transport_deadline(runtime_timeout, "wait", async {
self.send(DriverCommand::Wait {
session,
request,
caller_cancellation: cancellation.token(),
yield_signal,
response_tx,
})
.await?;
self.receive(response_rx).await
})
.await;
cancellation.disarm();
result
}
fn supported_yield_signal(
&self,
signal: Option<CancellationToken>,
) -> Option<CancellationToken> {
self.supports(YIELD_OBSERVATION_CAPABILITY)
.then_some(signal)
.flatten()
}
pub(super) async fn terminate(
&self,
session: RemoteSession,
request: TerminateRequest,
) -> Result<WaitOutcome, String> {
let (response_tx, response_rx) = oneshot::channel();
self.with_transport_deadline(Duration::ZERO, "terminate", async {
self.send(DriverCommand::Terminate {
session,
request,
response_tx,
})
.await?;
self.receive(response_rx).await
})
.await
}
pub(super) async fn shutdown_session(&self, session: RemoteSession) -> Result<(), String> {
let (response_tx, response_rx) = oneshot::channel();
self.send(DriverCommand::ShutdownSession {
session,
response_tx,
})
.await?;
self.receive(response_rx).await
}
async fn with_transport_deadline<T>(
&self,
runtime_timeout: Duration,
request_type: &str,
request: impl Future<Output = Result<T, String>>,
) -> Result<T, String> {
let deadline = runtime_timeout.saturating_add(DEFAULT_HOST_WAIT_TRANSPORT_TIMEOUT);
match tokio::time::timeout(deadline, request).await {
Ok(result) => result,
Err(_) => {
warn!(request_type, "code-mode host request exceeded its deadline");
let reason =
format!("code-mode host timed out waiting for {request_type} response");
mark_connection_dead(&self.alive, &self.failure, reason.clone());
self.cancellation.cancel();
Err(reason)
}
}
}
async fn send(&self, command: DriverCommand) -> Result<(), String> {
if !self.is_alive() {
return Err(self.failure_message());
}
self.command_tx
.send(command)
.await
.map_err(|_| self.failure_message())
}
async fn receive<T>(
&self,
response_rx: oneshot::Receiver<Result<T, String>>,
) -> Result<T, String> {
response_rx.await.map_err(|_| self.failure_message())?
}
fn failure_message(&self) -> String {
self.failure
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
.unwrap_or_else(|| "code-mode host connection closed".to_string())
}
}
async fn drive_writer(
mut writer: FramedWriter<ChildStdin>,
mut outgoing: mpsc::Receiver<EncodedFrame>,
cancellation: CancellationToken,
) -> Result<(), String> {
loop {
tokio::select! {
_ = cancellation.cancelled() => return Ok(()),
frame = outgoing.recv() => {
let Some(frame) = frame else {
return Err("code-mode host outgoing stream closed".to_string());
};
tokio::select! {
_ = cancellation.cancelled() => return Ok(()),
result = writer.write_frame(&frame) => {
result.map_err(|error| {
format!("failed to write code-mode host message: {error}")
})?;
}
}
}
}
}
}
impl Drop for Connection {
fn drop(&mut self) {
mark_connection_dead(
&self.alive,
&self.failure,
"code-mode host connection closed".to_string(),
);
self.cancellation.cancel();
}
}
impl ConnectionSupervisor {
async fn run(mut self) {
let mut child_exited = false;
let reason = tokio::select! {
biased;
_ = self.cancellation.cancelled() => failure_message(&self.failure),
result = &mut self.driver_task => match result {
Ok(()) => "code-mode connection driver exited unexpectedly".to_string(),
Err(err) => format!("code-mode connection driver task failed: {err}"),
},
result = &mut self.reader_task => task_failure("reader", result),
result = &mut self.writer_task => task_failure("writer", result),
result = self.child.wait() => {
child_exited = true;
match result {
Ok(status) => format!("code-mode host exited with status {status}"),
Err(error) => format!("failed waiting for code-mode host: {error}"),
}
}
};
mark_connection_dead(&self.alive, &self.failure, reason.clone());
let _ = self.event_tx.try_send(DriverEvent::Failed(reason));
self.cancellation.cancel();
if !child_exited {
kill_and_reap(&mut self.child).await;
}
}
}
fn task_failure(
task_name: &str,
result: Result<Result<(), String>, tokio::task::JoinError>,
) -> String {
match result {
Ok(Ok(())) => format!("code-mode connection {task_name} exited unexpectedly"),
Ok(Err(err)) => err,
Err(err) => format!("code-mode connection {task_name} task failed: {err}"),
}
}
fn mark_connection_dead(
alive: &AtomicBool,
failure: &std::sync::Mutex<Option<String>>,
reason: String,
) {
alive.store(false, Ordering::Release);
let mut failure = failure
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if failure.is_none() {
*failure = Some(reason);
}
}
fn failure_message(failure: &std::sync::Mutex<Option<String>>) -> String {
failure
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
.unwrap_or_else(|| "code-mode host connection closed".to_string())
}
async fn kill_and_reap(child: &mut Child) {
let _ = child.start_kill();
let _ = child.wait().await;
}

View File

@@ -0,0 +1,184 @@
use std::collections::VecDeque;
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use akode_code_mode_protocol::CellId;
use akode_code_mode_protocol::CodeModeSessionDelegate;
use akode_code_mode_protocol::host::EncodedFrame;
use akode_code_mode_protocol::host::HostToClient;
use akode_code_mode_protocol::host::RequestId;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
pub(in crate::remote_session) use self::cleanup::SessionCleanup;
use self::delegate_runtime::DelegateRuntime;
use self::request_tracker::RequestTracker;
use self::session_registry::SessionRegistry;
pub(super) use self::types::DriverCommand;
pub(super) use self::types::DriverEvent;
pub(in crate::remote_session) use self::types::RemoteSession;
mod cell_ids;
mod cleanup;
mod commands;
mod delegate_runtime;
mod request_tracker;
mod responses;
mod session_registry;
mod types;
pub(super) struct DriverLifecycle {
pub(super) alive: Arc<AtomicBool>,
pub(super) failure: Arc<std::sync::Mutex<Option<String>>>,
pub(super) cancellation: CancellationToken,
}
pub(super) struct ConnectionDriver {
command_rx: mpsc::Receiver<DriverCommand>,
event_rx: mpsc::Receiver<DriverEvent>,
event_tx: mpsc::Sender<DriverEvent>,
execute_claim_rx: mpsc::UnboundedReceiver<RequestId>,
outgoing_tx: mpsc::Sender<EncodedFrame>,
requests: RequestTracker,
deferred_host_messages: VecDeque<HostToClient>,
sessions: SessionRegistry,
delegates: DelegateRuntime,
alive: Arc<AtomicBool>,
failure: Arc<std::sync::Mutex<Option<String>>>,
cancellation: CancellationToken,
failed: bool,
}
impl ConnectionDriver {
pub(super) fn new(
command_rx: mpsc::Receiver<DriverCommand>,
event_rx: mpsc::Receiver<DriverEvent>,
event_tx: mpsc::Sender<DriverEvent>,
outgoing_tx: mpsc::Sender<EncodedFrame>,
lifecycle: DriverLifecycle,
) -> (Self, mpsc::UnboundedSender<RequestId>) {
let (execute_claim_tx, execute_claim_rx) = mpsc::unbounded_channel();
(
Self {
command_rx,
event_rx,
event_tx: event_tx.clone(),
execute_claim_rx,
outgoing_tx,
requests: RequestTracker::new(),
deferred_host_messages: VecDeque::new(),
sessions: SessionRegistry::new(),
delegates: DelegateRuntime::new(event_tx),
alive: lifecycle.alive,
failure: lifecycle.failure,
cancellation: lifecycle.cancellation,
failed: false,
},
execute_claim_tx,
)
}
pub(super) async fn run(mut self) {
loop {
tokio::select! {
biased;
_ = self.cancellation.cancelled() => {
self.fail("code-mode host connection closed".to_string());
return;
}
event = self.event_rx.recv() => {
let Some(event) = event else {
self.fail("code-mode host event stream closed".to_string());
return;
};
if !self.cancel_dropped_callers() || !self.handle_event(event) {
return;
}
}
claim = self.execute_claim_rx.recv() => {
let Some(request_id) = claim else {
self.fail("code-mode execute claim stream closed".to_string());
return;
};
self.requests.claim_execute(request_id);
}
command = self.command_rx.recv() => {
let Some(command) = command else {
self.fail("code-mode host command stream closed".to_string());
return;
};
if !self.cancel_dropped_callers() || !self.handle_command(command) {
return;
}
}
}
}
}
fn handle_event(&mut self, event: DriverEvent) -> bool {
let keep_running = match event {
DriverEvent::HostMessage(message) => self.handle_host_message(message),
DriverEvent::DelegateCompleted { id, result } => self.complete_delegate(id, result),
DriverEvent::RequestCancelled(id) => self.cancel_request(id),
DriverEvent::YieldRequest(id) => self.yield_request(id),
DriverEvent::Failed(reason) => {
self.fail(reason);
false
}
};
if keep_running {
self.flush_deferred_waits()
} else {
false
}
}
fn queue_frame(&mut self, frame: EncodedFrame) -> bool {
match self.outgoing_tx.try_send(frame) {
Ok(()) => true,
Err(mpsc::error::TrySendError::Full(_)) => {
self.fail("code-mode host outgoing queue is full".to_string());
false
}
Err(mpsc::error::TrySendError::Closed(_)) => {
self.fail("code-mode host writer closed".to_string());
false
}
}
}
fn fail(&mut self, reason: String) {
if self.failed {
return;
}
self.failed = true;
self.alive.store(false, Ordering::Release);
let reason = {
let mut failure = self
.failure
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
failure.get_or_insert(reason).clone()
};
self.requests.fail_all(&reason);
let failed_sessions = self.sessions.drain();
self.delegates.fail_all(failed_sessions);
self.cancellation.cancel();
}
}
impl Drop for ConnectionDriver {
fn drop(&mut self) {
self.fail("code-mode connection driver stopped unexpectedly".to_string());
}
}
fn notify_cell_closed(delegate: &Arc<dyn CodeModeSessionDelegate>, cell_id: &CellId) {
let _ = std::panic::catch_unwind(AssertUnwindSafe(|| delegate.cell_closed(cell_id)));
}
#[cfg(test)]
#[path = "driver_tests.rs"]
mod tests;

View File

@@ -0,0 +1,119 @@
use akode_code_mode_protocol::CellId;
use akode_code_mode_protocol::RuntimeResponse;
use akode_code_mode_protocol::WaitOutcome;
use akode_code_mode_protocol::WaitRequest;
use akode_code_mode_protocol::host::WireCellId;
use akode_code_mode_protocol::host::WireRuntimeResponse;
use akode_code_mode_protocol::host::WireWaitOutcome;
use akode_code_mode_protocol::host::WireWaitRequest;
use super::RemoteSession;
pub(super) fn public_cell_id(generation: u64, cell_id: &WireCellId) -> CellId {
if generation == 1 {
CellId::new(cell_id.as_str().to_string())
} else {
CellId::new(format!("g{generation}:{}", cell_id.as_str()))
}
}
pub(super) fn public_cell_id_from_protocol(generation: u64, cell_id: &CellId) -> CellId {
public_cell_id(generation, &WireCellId::new(cell_id.as_str()))
}
pub(super) fn remote_cell_id(
session: &RemoteSession,
cell_id: &CellId,
) -> Result<WireCellId, String> {
if session.generation == 1 {
if cell_id.as_str().starts_with('g') && cell_id.as_str().contains(':') {
return Err(format!(
"cell {cell_id} belongs to a stale code-mode host generation"
));
}
return Ok(WireCellId::new(cell_id.as_str()));
}
let prefix = format!("g{}:", session.generation);
let Some(remote_id) = cell_id.as_str().strip_prefix(&prefix) else {
return Err(format!(
"cell {cell_id} belongs to a stale code-mode host generation"
));
};
Ok(WireCellId::new(remote_id))
}
pub(super) fn remote_wait_request(
session: &RemoteSession,
request: WaitRequest,
) -> Result<WireWaitRequest, String> {
Ok(WireWaitRequest {
cell_id: remote_cell_id(session, &request.cell_id)?,
yield_time_ms: request.yield_time_ms,
})
}
pub(super) fn public_runtime_response(
generation: u64,
response: RuntimeResponse,
) -> RuntimeResponse {
match response {
RuntimeResponse::Yielded {
cell_id,
content_items,
code_mode_host_duration,
} => RuntimeResponse::Yielded {
cell_id: public_cell_id_from_protocol(generation, &cell_id),
content_items,
code_mode_host_duration,
},
RuntimeResponse::Terminated {
cell_id,
content_items,
code_mode_host_duration,
} => RuntimeResponse::Terminated {
cell_id: public_cell_id_from_protocol(generation, &cell_id),
content_items,
code_mode_host_duration,
},
RuntimeResponse::Result {
cell_id,
content_items,
result_buffered_for,
error_text,
code_mode_host_duration,
} => RuntimeResponse::Result {
cell_id: public_cell_id_from_protocol(generation, &cell_id),
content_items,
result_buffered_for,
error_text,
code_mode_host_duration,
},
}
}
pub(super) fn public_wait_outcome(generation: u64, outcome: WaitOutcome) -> WaitOutcome {
match outcome {
WaitOutcome::LiveCell(response) => {
WaitOutcome::LiveCell(public_runtime_response(generation, response))
}
WaitOutcome::MissingCell(response) => {
WaitOutcome::MissingCell(public_runtime_response(generation, response))
}
}
}
pub(super) fn runtime_response_cell_id(response: &WireRuntimeResponse) -> &WireCellId {
match response {
WireRuntimeResponse::Yielded { cell_id, .. }
| WireRuntimeResponse::Terminated { cell_id, .. }
| WireRuntimeResponse::Result { cell_id, .. } => cell_id,
}
}
pub(super) fn wait_outcome_cell_id(outcome: &WireWaitOutcome) -> &WireCellId {
match outcome {
WireWaitOutcome::LiveCell(response) | WireWaitOutcome::MissingCell(response) => {
runtime_response_cell_id(response)
}
}
}

View File

@@ -0,0 +1,40 @@
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
use super::notify_cell_closed;
use super::session_registry::CellOwner;
struct CleanupInner {
complete: CancellationToken,
}
#[derive(Clone)]
pub(in crate::remote_session) struct SessionCleanup {
inner: Arc<CleanupInner>,
}
impl SessionCleanup {
pub(in crate::remote_session) fn new() -> Self {
Self {
inner: Arc::new(CleanupInner {
complete: CancellationToken::new(),
}),
}
}
pub(super) fn fail(&self, cells: Vec<CellOwner>) {
for owner in cells {
notify_cell_closed(&owner.delegate, &owner.cell_id);
}
self.inner.complete.cancel();
}
pub(in crate::remote_session) async fn wait(&self) {
self.inner.complete.cancelled().await;
}
pub(in crate::remote_session) fn is_complete(&self) -> bool {
self.inner.complete.is_cancelled()
}
}

View File

@@ -0,0 +1,351 @@
use std::sync::Arc;
use akode_code_mode_protocol::CodeModeOutputTruncation;
use akode_code_mode_protocol::CodeModeSessionDelegate;
use akode_code_mode_protocol::CodeModeSessionOptions;
use akode_code_mode_protocol::ExecuteRequest;
use akode_code_mode_protocol::TerminateRequest;
use akode_code_mode_protocol::WaitOutcome;
use akode_code_mode_protocol::WaitRequest;
use akode_code_mode_protocol::host::ClientToHost;
use akode_code_mode_protocol::host::EncodedFrame;
use akode_code_mode_protocol::host::HostRequest;
use akode_code_mode_protocol::host::WireOutputTruncation;
use akode_code_mode_protocol::host::WireSessionCellExecutionLimits;
use akode_code_mode_protocol::host::WireWaitRequest;
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use super::ConnectionDriver;
use super::cell_ids::remote_cell_id;
use super::cell_ids::remote_wait_request;
use super::types::CancellableRequest;
use super::types::DeferredWait;
use super::types::DeliveredExecute;
use super::types::DriverCommand;
use super::types::ObservationYield;
use super::types::PendingRequest;
use super::types::RemoteSession;
impl ConnectionDriver {
pub(super) fn handle_command(&mut self, command: DriverCommand) -> bool {
match command {
DriverCommand::OpenSession {
session,
options,
cleanup,
caller_cancellation,
response_tx,
} => self.open_session(session, options, cleanup, caller_cancellation, response_tx),
DriverCommand::Execute {
session,
request,
delegate,
caller_cancellation,
yield_signal,
response_tx,
} => self.execute(
session,
request,
delegate,
caller_cancellation,
yield_signal,
response_tx,
),
DriverCommand::Wait {
session,
request,
caller_cancellation,
yield_signal,
response_tx,
} => self.wait(
session,
request,
caller_cancellation,
yield_signal,
response_tx,
),
DriverCommand::Terminate {
session,
request,
response_tx,
} => self.terminate(session, request, response_tx),
DriverCommand::ShutdownSession {
session,
response_tx,
} => self.shutdown_session(session, response_tx),
}
}
fn open_session(
&mut self,
session: RemoteSession,
options: CodeModeSessionOptions,
cleanup: super::cleanup::SessionCleanup,
caller_cancellation: CancellationToken,
response_tx: oneshot::Sender<Result<(), String>>,
) -> bool {
if self.sessions.contains(&session.id) || self.requests.contains_pending_open(&session) {
let _ = response_tx.send(Err(format!(
"code-mode session {} is already open",
session.id
)));
return true;
}
let limits = match WireSessionCellExecutionLimits::try_from(options.cell_execution_limits) {
Ok(limits) => limits,
Err(error) => {
let _ = response_tx.send(Err(format!(
"failed to encode code-mode session execution limits: {error}"
)));
return true;
}
};
let request_id = match self.requests.allocate_id() {
Ok(id) => id,
Err(err) => {
let _ = response_tx.send(Err(err));
return false;
}
};
let message = ClientToHost::Request {
id: request_id,
request: HostRequest::OpenSession {
session_id: session.id.clone(),
cell_execution_limits: (limits != WireSessionCellExecutionLimits::default())
.then_some(limits),
output_truncation: (options.output_truncation == CodeModeOutputTruncation::Server)
.then_some(WireOutputTruncation::Server),
},
};
let frame = match EncodedFrame::encode(&message) {
Ok(frame) => frame,
Err(err) => {
let _ = response_tx.send(Err(format!(
"failed to encode code-mode open-session request: {err}"
)));
return true;
}
};
let cancellation = CancellableRequest::new(caller_cancellation);
self.requests.insert_pending(
request_id,
PendingRequest::OpenSession {
session,
cleanup,
cancellation,
response_tx,
},
&self.event_tx,
);
self.queue_frame(frame)
}
fn execute(
&mut self,
session: RemoteSession,
request: ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
caller_cancellation: CancellationToken,
yield_signal: Option<CancellationToken>,
response_tx: oneshot::Sender<Result<DeliveredExecute, String>>,
) -> bool {
if let Err(err) = self.sessions.require_ready(&session) {
let _ = response_tx.send(Err(err));
return true;
}
let request = match request.try_into() {
Ok(request) => request,
Err(err) => {
let _ = response_tx.send(Err(format!(
"failed to encode code-mode execute request: {err}"
)));
return true;
}
};
let request_id = match self.requests.allocate_id() {
Ok(id) => id,
Err(err) => {
let _ = response_tx.send(Err(err));
return false;
}
};
let message = ClientToHost::Request {
id: request_id,
request: HostRequest::Execute {
session_id: session.id.clone(),
request,
},
};
let frame = match EncodedFrame::encode(&message) {
Ok(frame) => frame,
Err(err) => {
let _ = response_tx.send(Err(format!(
"code-mode execute request exceeds the IPC frame limit: {err}"
)));
return true;
}
};
let (initial_response_tx, initial_response_rx) = oneshot::channel();
let cancellation = CancellableRequest::new(caller_cancellation);
self.requests.insert_pending(
request_id,
PendingRequest::Execute {
session,
delegate,
response_tx,
initial_response_tx,
initial_response_rx,
cancellation,
yield_observation: ObservationYield::new(yield_signal),
},
&self.event_tx,
);
self.queue_frame(frame)
}
fn wait(
&mut self,
session: RemoteSession,
request: WaitRequest,
caller_cancellation: CancellationToken,
yield_signal: Option<CancellationToken>,
response_tx: oneshot::Sender<Result<WaitOutcome, String>>,
) -> bool {
if let Err(err) = self.sessions.require_ready(&session) {
let _ = response_tx.send(Err(err));
return true;
}
let max_output_tokens = request.max_output_tokens;
let request = match remote_wait_request(&session, request) {
Ok(request) => request,
Err(err) => {
let _ = response_tx.send(Err(err));
return true;
}
};
if self.requests.has_cancelled_wait(&session, &request.cell_id) {
self.requests.push_deferred_wait(DeferredWait {
session,
request,
max_output_tokens,
caller_cancellation,
yield_signal,
response_tx,
});
return true;
}
self.start_wait(
session,
request,
max_output_tokens,
caller_cancellation,
yield_signal,
response_tx,
)
}
pub(super) fn start_wait(
&mut self,
session: RemoteSession,
request: WireWaitRequest,
max_output_tokens: Option<usize>,
caller_cancellation: CancellationToken,
yield_signal: Option<CancellationToken>,
response_tx: oneshot::Sender<Result<WaitOutcome, String>>,
) -> bool {
let cell_id = request.cell_id.clone();
self.send_request(
HostRequest::Wait {
session_id: session.id.clone(),
request,
max_output_tokens,
},
PendingRequest::Wait {
session,
cell_id,
cancellation: CancellableRequest::new(caller_cancellation),
yield_observation: ObservationYield::new(yield_signal),
response_tx,
},
)
}
fn terminate(
&mut self,
session: RemoteSession,
request: TerminateRequest,
response_tx: oneshot::Sender<Result<WaitOutcome, String>>,
) -> bool {
if let Err(err) = self.sessions.require_ready(&session) {
let _ = response_tx.send(Err(err));
return true;
}
let cell_id = match remote_cell_id(&session, &request.cell_id) {
Ok(cell_id) => cell_id,
Err(err) => {
let _ = response_tx.send(Err(err));
return true;
}
};
let pending_cell_id = cell_id.clone();
self.send_request(
HostRequest::Terminate {
session_id: session.id.clone(),
cell_id,
max_output_tokens: request.max_output_tokens,
},
PendingRequest::Terminate {
session,
cell_id: pending_cell_id,
response_tx,
},
)
}
fn shutdown_session(
&mut self,
session: RemoteSession,
response_tx: oneshot::Sender<Result<(), String>>,
) -> bool {
if let Err(err) = self.sessions.begin_shutdown(&session) {
let _ = response_tx.send(Err(err));
return true;
}
self.send_request(
HostRequest::ShutdownSession {
session_id: session.id.clone(),
},
PendingRequest::ShutdownSession {
session,
response_tx,
},
)
}
pub(super) fn send_request(&mut self, request: HostRequest, pending: PendingRequest) -> bool {
let request_id = match self.requests.allocate_id() {
Ok(id) => id,
Err(err) => {
pending.fail(err);
return false;
}
};
let message = ClientToHost::Request {
id: request_id,
request,
};
let frame = match EncodedFrame::encode(&message) {
Ok(frame) => frame,
Err(err) => {
pending.fail(format!(
"code-mode request exceeds the IPC frame limit: {err}"
));
return true;
}
};
self.requests
.insert_pending(request_id, pending, &self.event_tx);
self.queue_frame(frame)
}
}

View File

@@ -0,0 +1,353 @@
//! Client-side delegate task and closure lifecycle.
//!
//! Cancellation revokes the task's completion path before removing its active-call state. The
//! delegate future may finish later, but it can no longer send a response or affect cell closure.
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use akode_code_mode_protocol::CodeModeNestedToolCall;
use akode_code_mode_protocol::host::ClientToHost;
use akode_code_mode_protocol::host::DelegateRequest;
use akode_code_mode_protocol::host::DelegateRequestId;
use akode_code_mode_protocol::host::DelegateResponse;
use akode_code_mode_protocol::host::EncodedFrame;
use akode_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
use akode_code_mode_protocol::host::SessionId;
use akode_code_mode_protocol::host::WireCellId;
use akode_code_mode_protocol::host::WireResult;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use super::ConnectionDriver;
use super::notify_cell_closed;
use super::session_registry::CellOwner;
use super::session_registry::DelegateTarget;
use super::session_registry::FailedSession;
use super::types::DriverEvent;
const MAX_RECENT_DELEGATE_REQUEST_IDS: usize = 4096;
#[derive(Clone, Eq, Hash, PartialEq)]
struct CellKey {
session_id: akode_code_mode_protocol::host::SessionId,
cell_id: akode_code_mode_protocol::CellId,
}
impl CellKey {
fn for_owner(owner: &CellOwner) -> Self {
Self {
session_id: owner.session_id.clone(),
cell_id: owner.cell_id.clone(),
}
}
}
struct DelegateCall {
cell: CellKey,
cancellation: CancellationToken,
completion_stop: CancellationToken,
}
impl DelegateCall {
fn revoke(&self) {
self.cancellation.cancel();
self.completion_stop.cancel();
}
}
enum DelegateTask {
InvokeTool(CodeModeNestedToolCall),
Notify {
call_id: String,
cell_id: akode_code_mode_protocol::CellId,
text: String,
},
}
enum DelegateStartError {
Duplicate(DelegateRequestId),
CapacityExceeded,
}
pub(super) struct DelegateEffects {
pub(super) response: Option<(DelegateRequestId, Result<DelegateResponse, String>)>,
pub(super) closed_cells: Vec<CellOwner>,
}
impl DelegateEffects {
fn empty() -> Self {
Self {
response: None,
closed_cells: Vec::new(),
}
}
fn append(&mut self, mut other: Self) {
debug_assert!(self.response.is_none());
self.response = other.response.take();
self.closed_cells.append(&mut other.closed_cells);
}
}
pub(super) struct DelegateRuntime {
calls: HashMap<DelegateRequestId, DelegateCall>,
seen_requests: HashSet<DelegateRequestId>,
request_order: VecDeque<DelegateRequestId>,
event_tx: mpsc::Sender<DriverEvent>,
}
impl DelegateRuntime {
pub(super) fn new(event_tx: mpsc::Sender<DriverEvent>) -> Self {
Self {
calls: HashMap::new(),
seen_requests: HashSet::new(),
request_order: VecDeque::new(),
event_tx,
}
}
fn start(
&mut self,
id: DelegateRequestId,
target: DelegateTarget,
request: DelegateRequest,
) -> Result<(), DelegateStartError> {
if self.calls.contains_key(&id) || self.seen_requests.contains(&id) {
return Err(DelegateStartError::Duplicate(id));
}
self.remember_request(id);
if self.calls.len() >= MAX_PENDING_DELEGATE_CALLS {
return Err(DelegateStartError::CapacityExceeded);
}
let cancellation = CancellationToken::new();
let task_request = match request {
DelegateRequest::InvokeTool { invocation } => {
let mut invocation: CodeModeNestedToolCall = invocation.into();
invocation.cell_id = target.cell_id.clone();
DelegateTask::InvokeTool(invocation)
}
DelegateRequest::Notify {
call_id,
cell_id: _,
text,
} => DelegateTask::Notify {
call_id,
cell_id: target.cell_id.clone(),
text,
},
};
let delegate = target.delegate;
let task_cancellation = cancellation.clone();
let delegate_task = tokio::spawn(async move {
match task_request {
DelegateTask::InvokeTool(invocation) => delegate
.invoke_tool(invocation, task_cancellation)
.await
.map(|result| DelegateResponse::ToolResult { result }),
DelegateTask::Notify {
call_id,
cell_id,
text,
} => delegate
.notify(call_id, cell_id, text, task_cancellation)
.await
.map(|()| DelegateResponse::NotificationDelivered),
}
});
let completion_stop = CancellationToken::new();
self.calls.insert(
id,
DelegateCall {
cell: CellKey {
session_id: target.session_id,
cell_id: target.cell_id,
},
cancellation,
completion_stop: completion_stop.clone(),
},
);
let event_tx = self.event_tx.clone();
tokio::spawn(async move {
let result = tokio::select! {
biased;
_ = completion_stop.cancelled() => return,
result = delegate_task => match result {
Ok(result) => result,
Err(err) => Err(format!("code-mode delegate task failed: {err}")),
},
};
tokio::select! {
biased;
_ = completion_stop.cancelled() => {}
_ = event_tx.send(DriverEvent::DelegateCompleted { id, result }) => {}
}
});
Ok(())
}
pub(super) fn cancel(&mut self, id: DelegateRequestId) {
if let Some(call) = self.calls.remove(&id) {
call.revoke();
}
}
pub(super) fn complete(
&mut self,
id: DelegateRequestId,
result: Result<DelegateResponse, String>,
) -> DelegateEffects {
if self.calls.remove(&id).is_none() {
return DelegateEffects::empty();
}
let mut effects = DelegateEffects::empty();
effects.response = Some((id, result));
effects
}
pub(super) fn close_cell(&mut self, owner: CellOwner) -> DelegateEffects {
let key = CellKey::for_owner(&owner);
self.calls.retain(|_, call| {
if call.cell != key {
return true;
}
call.revoke();
false
});
let mut effects = DelegateEffects::empty();
effects.closed_cells.push(owner);
effects
}
pub(super) fn close_cells(&mut self, owners: Vec<CellOwner>) -> DelegateEffects {
let mut effects = DelegateEffects::empty();
for owner in owners {
effects.append(self.close_cell(owner));
}
effects
}
pub(super) fn fail_all(&mut self, failed_sessions: Vec<FailedSession>) {
for (_, call) in self.calls.drain() {
call.revoke();
}
for session in failed_sessions {
session.cleanup.fail(session.cells);
}
}
fn remember_request(&mut self, id: DelegateRequestId) {
self.seen_requests.insert(id);
self.request_order.push_back(id);
while self.request_order.len() > MAX_RECENT_DELEGATE_REQUEST_IDS {
if let Some(expired) = self.request_order.pop_front() {
self.seen_requests.remove(&expired);
}
}
}
}
impl ConnectionDriver {
pub(super) fn start_delegate(
&mut self,
id: DelegateRequestId,
session_id: SessionId,
request: DelegateRequest,
) -> bool {
let wire_cell_id = match &request {
DelegateRequest::InvokeTool { invocation } => &invocation.cell_id,
DelegateRequest::Notify { cell_id, .. } => cell_id,
};
let target = match self.sessions.delegate_target(&session_id, wire_cell_id) {
Ok(target) => target,
Err(err) => return self.send_delegate_response(id, Err(err)),
};
match self.delegates.start(id, target, request) {
Ok(()) => true,
Err(DelegateStartError::Duplicate(id)) => {
self.fail(format!("duplicate code-mode delegate request ID {id:?}"));
false
}
Err(DelegateStartError::CapacityExceeded) => self.send_delegate_response(
id,
Err(format!(
"code-mode host exceeded the limit of {MAX_PENDING_DELEGATE_CALLS} pending delegate calls"
)),
),
}
}
pub(super) fn complete_delegate(
&mut self,
id: DelegateRequestId,
result: Result<DelegateResponse, String>,
) -> bool {
let effects = self.delegates.complete(id, result);
self.apply_delegate_effects(effects)
}
fn send_delegate_response(
&mut self,
id: DelegateRequestId,
result: Result<DelegateResponse, String>,
) -> bool {
let message = ClientToHost::DelegateResponse {
id,
result: WireResult::from_result(result),
};
let frame = match EncodedFrame::encode(&message) {
Ok(frame) => frame,
Err(err) => {
let fallback = ClientToHost::DelegateResponse {
id,
result: WireResult::Err {
message: format!(
"code-mode delegate response exceeds the IPC frame limit: {err}"
),
},
};
match EncodedFrame::encode(&fallback) {
Ok(frame) => frame,
Err(fallback_err) => {
self.fail(format!(
"failed to encode code-mode delegate error response: {fallback_err}"
));
return false;
}
}
}
};
self.queue_frame(frame)
}
pub(super) fn close_cell(&mut self, session_id: SessionId, cell_id: WireCellId) -> bool {
let owner = match self.sessions.remove_cell(&session_id, &cell_id) {
Ok(owner) => owner,
Err(err) => {
self.fail(err);
return false;
}
};
let effects = self.delegates.close_cell(owner);
self.apply_delegate_effects(effects)
}
pub(super) fn close_session_locally(&mut self, session_id: &SessionId) -> DelegateEffects {
self.requests.remove_unclaimed_for_session(session_id);
let owners = self.sessions.remove_session(session_id);
self.delegates.close_cells(owners)
}
pub(super) fn apply_delegate_effects(&mut self, effects: DelegateEffects) -> bool {
if let Some((id, result)) = effects.response
&& !self.send_delegate_response(id, result)
{
return false;
}
for closed in effects.closed_cells {
notify_cell_closed(&closed.delegate, &closed.cell_id);
}
true
}
}

View File

@@ -0,0 +1,198 @@
use std::collections::HashMap;
use std::collections::VecDeque;
use akode_code_mode_protocol::host::RequestId;
use akode_code_mode_protocol::host::SessionId;
use akode_code_mode_protocol::host::WireCellId;
use tokio::sync::mpsc;
use super::types::DeferredWait;
use super::types::DriverEvent;
use super::types::InitialResponse;
use super::types::PendingRequest;
use super::types::RemoteSession;
use super::types::UnclaimedExecute;
pub(super) enum CancellationAction {
Send(RequestId),
Terminate {
request_id: RequestId,
execute: UnclaimedExecute,
},
}
pub(super) struct RequestTracker {
pending: HashMap<RequestId, PendingRequest>,
unclaimed_executes: HashMap<RequestId, UnclaimedExecute>,
initial_responses: HashMap<RequestId, InitialResponse>,
deferred_waits: VecDeque<DeferredWait>,
next_request_id: i64,
}
impl RequestTracker {
pub(super) fn new() -> Self {
Self {
pending: HashMap::new(),
unclaimed_executes: HashMap::new(),
initial_responses: HashMap::new(),
deferred_waits: VecDeque::new(),
next_request_id: 1,
}
}
pub(super) fn contains_pending_open(&self, session: &RemoteSession) -> bool {
self.pending.values().any(|pending| {
matches!(
pending,
PendingRequest::OpenSession {
session: pending_session,
..
} if pending_session.id == session.id
)
})
}
pub(super) fn has_pending_execute_for_session(&self, session_id: &SessionId) -> bool {
self.pending.values().any(|request| {
matches!(
request,
PendingRequest::Execute { session, .. } if session.id == *session_id
)
})
}
pub(super) fn allocate_id(&mut self) -> Result<RequestId, String> {
let id = self.next_request_id;
self.next_request_id = self
.next_request_id
.checked_add(1)
.ok_or_else(|| "code-mode host request ID space exhausted".to_string())?;
Ok(RequestId::new(id))
}
pub(super) fn insert_pending(
&mut self,
id: RequestId,
mut pending: PendingRequest,
event_tx: &mpsc::Sender<DriverEvent>,
) {
if let Some(observation) = pending.yield_observation() {
observation.spawn_watcher(id, event_tx.clone());
}
self.pending.insert(id, pending);
if let Some(cancellation) = self
.pending
.get_mut(&id)
.and_then(PendingRequest::cancellation_mut)
{
cancellation.spawn_watcher(id, event_tx.clone());
}
}
pub(super) fn remove_pending(&mut self, id: RequestId) -> Option<PendingRequest> {
self.pending.remove(&id)
}
pub(super) fn insert_initial_response(&mut self, id: RequestId, response: InitialResponse) {
self.initial_responses.insert(id, response);
}
pub(super) fn remove_initial_response(&mut self, id: RequestId) -> Option<InitialResponse> {
self.initial_responses.remove(&id)
}
pub(super) fn insert_unclaimed_execute(&mut self, id: RequestId, execute: UnclaimedExecute) {
self.unclaimed_executes.insert(id, execute);
}
pub(super) fn claim_execute(&mut self, id: RequestId) {
self.unclaimed_executes.remove(&id);
}
pub(super) fn collect_cancellations(&mut self) -> Vec<CancellationAction> {
let mut actions = self
.pending
.iter_mut()
.filter_map(|(id, pending)| {
let cancellation = pending.cancellation_mut()?;
(cancellation.is_cancelled() && cancellation.mark_reported())
.then_some(CancellationAction::Send(*id))
})
.collect::<Vec<_>>();
actions.extend(
self.unclaimed_executes
.extract_if(|_, execute| {
execute.cancellation.is_cancelled() && execute.cancellation.mark_reported()
})
.map(|(request_id, execute)| CancellationAction::Terminate {
request_id,
execute,
}),
);
actions
}
pub(super) fn mark_cancelled(&mut self, id: RequestId) -> Option<CancellationAction> {
if let Some(cancellation) = self
.pending
.get_mut(&id)
.and_then(PendingRequest::cancellation_mut)
{
return cancellation
.mark_reported()
.then_some(CancellationAction::Send(id));
}
let execute = self.unclaimed_executes.get_mut(&id)?;
if !execute.cancellation.mark_reported() {
return None;
}
self.unclaimed_executes
.remove(&id)
.map(|execute| CancellationAction::Terminate {
request_id: id,
execute,
})
}
pub(super) fn has_cancelled_wait(&self, session: &RemoteSession, cell_id: &WireCellId) -> bool {
self.pending.values().any(|pending| {
matches!(
pending,
PendingRequest::Wait {
session: pending_session,
cell_id: pending_cell_id,
cancellation,
..
} if pending_session == session
&& pending_cell_id == cell_id
&& cancellation.is_cancelled()
)
})
}
pub(super) fn push_deferred_wait(&mut self, wait: DeferredWait) {
self.deferred_waits.push_back(wait);
}
pub(super) fn take_deferred_waits(&mut self) -> VecDeque<DeferredWait> {
std::mem::take(&mut self.deferred_waits)
}
pub(super) fn remove_unclaimed_for_session(&mut self, session_id: &SessionId) {
self.unclaimed_executes
.retain(|_, execute| &execute.session.id != session_id);
}
pub(super) fn fail_all(&mut self, reason: &str) {
for (_, pending) in self.pending.drain() {
pending.fail(reason.to_string());
}
self.unclaimed_executes.clear();
for (_, initial) in self.initial_responses.drain() {
let _ = initial.response_tx.send(Err(reason.to_string()));
}
for wait in self.deferred_waits.drain(..) {
let _ = wait.response_tx.send(Err(reason.to_string()));
}
}
}

View File

@@ -0,0 +1,476 @@
use akode_code_mode_protocol::StartedCell;
use akode_code_mode_protocol::host::ClientToHost;
use akode_code_mode_protocol::host::EncodedFrame;
use akode_code_mode_protocol::host::HostRequest;
use akode_code_mode_protocol::host::HostResponse;
use akode_code_mode_protocol::host::HostToClient;
use akode_code_mode_protocol::host::RequestId;
use akode_code_mode_protocol::host::WireCellId;
use tokio::sync::oneshot;
use super::ConnectionDriver;
use super::cell_ids::public_runtime_response;
use super::cell_ids::public_wait_outcome;
use super::cell_ids::runtime_response_cell_id;
use super::cell_ids::wait_outcome_cell_id;
use super::request_tracker::CancellationAction;
use super::session_registry::CellAdmissionError;
use super::types::DeliveredExecute;
use super::types::InitialResponse;
use super::types::PendingRequest;
use super::types::RemoteSession;
use super::types::UnclaimedExecute;
impl ConnectionDriver {
pub(super) fn flush_deferred_waits(&mut self) -> bool {
let mut deferred = self.requests.take_deferred_waits();
while let Some(wait) = deferred.pop_front() {
if wait.caller_cancellation.is_cancelled() {
let _ = wait
.response_tx
.send(Err("code-mode request cancelled".to_string()));
continue;
}
if self
.requests
.has_cancelled_wait(&wait.session, &wait.request.cell_id)
{
self.requests.push_deferred_wait(wait);
continue;
}
if !self.start_wait(
wait.session,
wait.request,
wait.max_output_tokens,
wait.caller_cancellation,
wait.yield_signal,
wait.response_tx,
) {
for wait in deferred {
let _ = wait
.response_tx
.send(Err("code-mode host connection closed".to_string()));
}
return false;
}
}
true
}
pub(super) fn handle_host_message(&mut self, message: HostToClient) -> bool {
if self.should_defer_host_message(&message) {
if self.deferred_host_messages.len()
>= akode_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS
{
self.fail(
"code-mode host exceeded deferred cross-socket message limit".to_string(),
);
return false;
}
self.deferred_host_messages.push_back(message);
return true;
}
if !self.dispatch_host_message(message) {
return false;
}
for _ in 0..self.deferred_host_messages.len() {
let Some(message) = self.deferred_host_messages.pop_front() else {
break;
};
if self.should_defer_host_message(&message) {
self.deferred_host_messages.push_back(message);
} else if !self.dispatch_host_message(message) {
return false;
}
}
true
}
fn should_defer_host_message(&self, message: &HostToClient) -> bool {
match message {
HostToClient::DelegateRequest {
session_id,
request,
..
} => {
let cell_id = match request {
akode_code_mode_protocol::host::DelegateRequest::InvokeTool { invocation } => {
&invocation.cell_id
}
akode_code_mode_protocol::host::DelegateRequest::Notify { cell_id, .. } => {
cell_id
}
};
!self.sessions.contains_cell(session_id, cell_id)
&& self.requests.has_pending_execute_for_session(session_id)
}
HostToClient::Response { .. }
| HostToClient::InitialResponse { .. }
| HostToClient::CellClosed { .. }
| HostToClient::CancelDelegateRequest { .. }
| HostToClient::HostHello(_)
| HostToClient::HandshakeRejected { .. } => false,
}
}
fn dispatch_host_message(&mut self, message: HostToClient) -> bool {
match message {
HostToClient::Response { id, result } => {
self.complete_request(id, result.into_result())
}
HostToClient::InitialResponse { id, result } => {
self.complete_initial_response(id, result.into_result())
}
HostToClient::DelegateRequest {
id,
session_id,
request,
} => self.start_delegate(id, session_id, request),
HostToClient::CancelDelegateRequest { id } => {
self.deferred_host_messages.retain(|message| {
!matches!(
message,
HostToClient::DelegateRequest { id: deferred_id, .. } if *deferred_id == id
)
});
self.delegates.cancel(id);
true
}
HostToClient::CellClosed {
session_id,
cell_id,
} => self.close_cell(session_id, cell_id),
HostToClient::HostHello(_) | HostToClient::HandshakeRejected { .. } => {
self.fail("code-mode host sent a second handshake response".to_string());
false
}
}
}
fn complete_request(&mut self, id: RequestId, result: Result<HostResponse, String>) -> bool {
let Some(pending) = self.requests.remove_pending(id) else {
self.fail(format!("code-mode host returned unknown request ID {id:?}"));
return false;
};
match pending {
PendingRequest::OpenSession {
session,
cleanup,
cancellation,
response_tx,
} => match result {
Ok(HostResponse::SessionReady { session_id }) if session_id == session.id => {
let abandoned = cancellation.is_cancelled() || response_tx.is_closed();
self.sessions.insert_ready(session.clone(), cleanup);
if abandoned || response_tx.send(Ok(())).is_err() {
return self.shutdown_abandoned_session(session);
}
}
Ok(_) => {
let reason =
"code-mode host returned an invalid open-session response".to_string();
let _ = response_tx.send(Err(reason.clone()));
self.fail(reason);
return false;
}
Err(err) => {
let _ = response_tx.send(Err(err));
}
},
PendingRequest::Execute {
session,
delegate,
response_tx,
initial_response_tx,
initial_response_rx,
cancellation,
yield_observation,
} => match result {
Ok(HostResponse::ExecutionStarted { cell_id }) => {
// The host owns a checked, never-reused ID sequence. Retain only live
// IDs so client memory scales with concurrency, not session lifetime.
let remote_cell_id = cell_id.clone();
let public_id = match self.sessions.admit_cell(&session, cell_id, delegate) {
Ok(public_id) => public_id,
Err(CellAdmissionError::MissingSession) => {
let _ = response_tx
.send(Err("code-mode session closed during execute".to_string()));
return true;
}
Err(CellAdmissionError::DuplicateCell) => {
let reason = format!(
"code-mode host reused live cell {} in session {}",
remote_cell_id.as_str(),
session.id
);
let _ = response_tx.send(Err(reason.clone()));
self.fail(reason);
return false;
}
};
self.requests.insert_initial_response(
id,
InitialResponse {
generation: session.generation,
cell_id: remote_cell_id.clone(),
response_tx: initial_response_tx,
_yield_observation: yield_observation,
},
);
let started = StartedCell::from_result_receiver(public_id, initial_response_rx);
if cancellation.is_cancelled() || response_tx.is_closed() {
return self.terminate_abandoned_cell(session, remote_cell_id);
}
let delivered = DeliveredExecute {
request_id: id,
started,
};
if response_tx.send(Ok(delivered)).is_err() {
return self.terminate_abandoned_cell(session, remote_cell_id);
}
self.requests.insert_unclaimed_execute(
id,
UnclaimedExecute {
session,
cell_id: remote_cell_id,
cancellation,
},
);
}
Ok(_) => {
let reason = "code-mode host returned an invalid execute response".to_string();
let _ = response_tx.send(Err(reason.clone()));
self.fail(reason);
return false;
}
Err(err) => {
let _ = response_tx.send(Err(err));
}
},
PendingRequest::Wait {
session,
cell_id,
cancellation: _,
yield_observation: _,
response_tx,
} => {
let result = match result {
Ok(HostResponse::WaitCompleted { outcome }) => {
if wait_outcome_cell_id(&outcome) != &cell_id {
let reason = format!(
"code-mode host returned cell {} for request targeting {}",
wait_outcome_cell_id(&outcome).as_str(),
cell_id.as_str()
);
let _ = response_tx.send(Err(reason.clone()));
self.fail(reason);
return false;
}
Ok(public_wait_outcome(session.generation, outcome.into()))
}
Ok(_) => {
let reason = "code-mode host returned an invalid cell response".to_string();
let _ = response_tx.send(Err(reason.clone()));
self.fail(reason);
return false;
}
Err(err) => Err(err),
};
let _ = response_tx.send(result);
}
PendingRequest::Terminate {
session,
cell_id,
response_tx,
} => {
let result = match result {
Ok(HostResponse::WaitCompleted { outcome }) => {
if wait_outcome_cell_id(&outcome) != &cell_id {
let reason = format!(
"code-mode host returned cell {} for request targeting {}",
wait_outcome_cell_id(&outcome).as_str(),
cell_id.as_str()
);
let _ = response_tx.send(Err(reason.clone()));
self.fail(reason);
return false;
}
public_wait_outcome(session.generation, outcome.into())
}
Ok(_) => {
let reason = "code-mode host returned an invalid cell response".to_string();
let _ = response_tx.send(Err(reason.clone()));
self.fail(reason);
return false;
}
Err(err) => {
let _ = response_tx.send(Err(err));
return true;
}
};
let _ = response_tx.send(Ok(result));
}
PendingRequest::ShutdownSession {
session,
response_tx,
} => match result {
Ok(HostResponse::SessionClosed { session_id }) if session_id == session.id => {
let effects = self.close_session_locally(&session.id);
if !self.apply_delegate_effects(effects) {
return false;
}
let _ = response_tx.send(Ok(()));
}
Ok(_) => {
let err = "code-mode host returned an invalid shutdown response".to_string();
let _ = response_tx.send(Err(err.clone()));
self.fail(err);
return false;
}
Err(err) => {
let _ = response_tx.send(Err(err.clone()));
self.fail(err);
return false;
}
},
}
true
}
pub(super) fn cancel_dropped_callers(&mut self) -> bool {
for action in self.requests.collect_cancellations() {
if !self.apply_cancellation(action) {
return false;
}
}
true
}
pub(super) fn cancel_request(&mut self, id: RequestId) -> bool {
self.requests
.mark_cancelled(id)
.is_none_or(|action| self.apply_cancellation(action))
}
fn apply_cancellation(&mut self, action: CancellationAction) -> bool {
match action {
CancellationAction::Send(id) => self.send_cancel_request(id),
CancellationAction::Terminate {
request_id,
execute,
} => {
if !self.send_cancel_request(request_id) {
return false;
}
self.terminate_abandoned_cell(execute.session, execute.cell_id)
}
}
}
pub(super) fn yield_request(&mut self, id: RequestId) -> bool {
let frame = match EncodedFrame::encode(&ClientToHost::YieldRequest { id }) {
Ok(frame) => frame,
Err(err) => {
self.fail(format!("failed to encode code-mode yield request: {err}"));
return false;
}
};
self.queue_frame(frame)
}
fn send_cancel_request(&mut self, id: RequestId) -> bool {
let message = ClientToHost::CancelRequest { id };
let frame = match EncodedFrame::encode(&message) {
Ok(frame) => frame,
Err(err) => {
self.fail(format!(
"failed to encode code-mode cancellation request: {err}"
));
return false;
}
};
self.queue_frame(frame)
}
fn shutdown_abandoned_session(&mut self, session: RemoteSession) -> bool {
let Some(should_shutdown) = self.sessions.begin_abandoned_shutdown(&session.id) else {
self.fail(format!(
"code-mode host committed abandoned session {} without local state",
session.id
));
return false;
};
if !should_shutdown {
return true;
}
let (response_tx, response_rx) = oneshot::channel();
drop(response_rx);
self.send_request(
HostRequest::ShutdownSession {
session_id: session.id.clone(),
},
PendingRequest::ShutdownSession {
session,
response_tx,
},
)
}
fn terminate_abandoned_cell(&mut self, session: RemoteSession, cell_id: WireCellId) -> bool {
let Some(is_closing) = self.sessions.is_closing(&session.id) else {
self.fail(format!(
"code-mode host admitted an abandoned cell in unknown session {}",
session.id
));
return false;
};
if is_closing {
return true;
}
let (response_tx, response_rx) = oneshot::channel();
drop(response_rx);
self.send_request(
HostRequest::Terminate {
session_id: session.id.clone(),
cell_id: cell_id.clone(),
max_output_tokens: None,
},
PendingRequest::Terminate {
session,
cell_id,
response_tx,
},
)
}
fn complete_initial_response(
&mut self,
id: RequestId,
result: Result<akode_code_mode_protocol::host::WireRuntimeResponse, String>,
) -> bool {
let Some(initial) = self.requests.remove_initial_response(id) else {
self.fail(format!(
"code-mode host returned initial response for unknown request ID {id:?}"
));
return false;
};
let response = match result {
Ok(response) if runtime_response_cell_id(&response) == &initial.cell_id => {
Ok(public_runtime_response(initial.generation, response.into()))
}
Ok(response) => {
let reason = format!(
"code-mode host returned initial response for cell {} instead of {}",
runtime_response_cell_id(&response).as_str(),
initial.cell_id.as_str()
);
let _ = initial.response_tx.send(Err(reason.clone()));
self.fail(reason);
return false;
}
Err(err) => Err(err),
};
let _ = initial.response_tx.send(response);
true
}
}

View File

@@ -0,0 +1,208 @@
use std::collections::HashMap;
use std::sync::Arc;
use akode_code_mode_protocol::CellId;
use akode_code_mode_protocol::CodeModeSessionDelegate;
use akode_code_mode_protocol::host::SessionId;
use akode_code_mode_protocol::host::WireCellId;
use super::cell_ids::public_cell_id;
use super::cleanup::SessionCleanup;
use super::types::RemoteSession;
pub(super) struct CellOwner {
pub(super) session_id: SessionId,
pub(super) cell_id: CellId,
pub(super) delegate: Arc<dyn CodeModeSessionDelegate>,
}
pub(super) struct DelegateTarget {
pub(super) session_id: SessionId,
pub(super) cell_id: CellId,
pub(super) delegate: Arc<dyn CodeModeSessionDelegate>,
}
pub(super) struct FailedSession {
pub(super) cleanup: SessionCleanup,
pub(super) cells: Vec<CellOwner>,
}
pub(super) enum CellAdmissionError {
MissingSession,
DuplicateCell,
}
struct SessionRecord {
remote: RemoteSession,
cleanup: SessionCleanup,
phase: SessionPhase,
cells: HashMap<WireCellId, CellOwner>,
}
#[derive(Clone, Copy, Eq, PartialEq)]
enum SessionPhase {
Ready,
Closing,
}
pub(super) struct SessionRegistry {
records: HashMap<SessionId, SessionRecord>,
}
impl SessionRegistry {
pub(super) fn new() -> Self {
Self {
records: HashMap::new(),
}
}
pub(super) fn contains(&self, session_id: &SessionId) -> bool {
self.records.contains_key(session_id)
}
pub(super) fn contains_cell(&self, session_id: &SessionId, cell_id: &WireCellId) -> bool {
self.records
.get(session_id)
.is_some_and(|session| session.cells.contains_key(cell_id))
}
pub(super) fn insert_ready(&mut self, session: RemoteSession, cleanup: SessionCleanup) {
self.records.insert(
session.id.clone(),
SessionRecord {
remote: session,
cleanup,
phase: SessionPhase::Ready,
cells: HashMap::new(),
},
);
}
pub(super) fn require_ready(&self, session: &RemoteSession) -> Result<(), String> {
let record = self
.records
.get(&session.id)
.ok_or_else(|| format!("unknown code-mode session {}", session.id))?;
if record.remote != *session {
return Err("stale code-mode session generation".to_string());
}
if record.phase != SessionPhase::Ready {
return Err("code-mode session is shutting down".to_string());
}
Ok(())
}
pub(super) fn begin_shutdown(&mut self, session: &RemoteSession) -> Result<(), String> {
let record = self
.records
.get_mut(&session.id)
.ok_or_else(|| format!("unknown code-mode session {}", session.id))?;
if record.remote != *session {
return Err("stale code-mode session generation".to_string());
}
if record.phase == SessionPhase::Closing {
return Err("code-mode session is already closing".to_string());
}
record.phase = SessionPhase::Closing;
Ok(())
}
pub(super) fn begin_abandoned_shutdown(&mut self, session_id: &SessionId) -> Option<bool> {
let record = self.records.get_mut(session_id)?;
if record.phase == SessionPhase::Closing {
return Some(false);
}
record.phase = SessionPhase::Closing;
Some(true)
}
pub(super) fn is_closing(&self, session_id: &SessionId) -> Option<bool> {
self.records
.get(session_id)
.map(|record| record.phase == SessionPhase::Closing)
}
pub(super) fn admit_cell(
&mut self,
session: &RemoteSession,
cell_id: WireCellId,
delegate: Arc<dyn CodeModeSessionDelegate>,
) -> Result<CellId, CellAdmissionError> {
let Some(record) = self.records.get_mut(&session.id) else {
return Err(CellAdmissionError::MissingSession);
};
if record.cells.contains_key(&cell_id) {
return Err(CellAdmissionError::DuplicateCell);
}
let public_id = public_cell_id(session.generation, &cell_id);
record.cells.insert(
cell_id,
CellOwner {
session_id: session.id.clone(),
cell_id: public_id.clone(),
delegate,
},
);
Ok(public_id)
}
pub(super) fn delegate_target(
&self,
session_id: &SessionId,
cell_id: &WireCellId,
) -> Result<DelegateTarget, String> {
let session = self
.records
.get(session_id)
.ok_or_else(|| format!("code-mode host delegated for unknown session {session_id}"))?;
let owner = session.cells.get(cell_id).ok_or_else(|| {
format!(
"code-mode host delegated for unknown cell {} in session {session_id}",
cell_id.as_str()
)
})?;
Ok(DelegateTarget {
session_id: session_id.clone(),
cell_id: owner.cell_id.clone(),
delegate: Arc::clone(&owner.delegate),
})
}
pub(super) fn remove_cell(
&mut self,
session_id: &SessionId,
cell_id: &WireCellId,
) -> Result<CellOwner, String> {
let session = self.records.get_mut(session_id).ok_or_else(|| {
format!(
"code-mode host closed cell {} in unknown session {session_id}",
cell_id.as_str()
)
})?;
session
.cells
.remove(cell_id)
.ok_or_else(|| format!("code-mode host closed unknown cell in session {session_id}"))
}
pub(super) fn remove_session(&mut self, session_id: &SessionId) -> Vec<CellOwner> {
let Some(session) = self.records.remove(session_id) else {
return Vec::new();
};
session.cells.into_values().collect()
}
pub(super) fn drain(&mut self) -> Vec<FailedSession> {
let sessions = std::mem::take(&mut self.records);
sessions
.into_values()
.map(|session| {
let cells = session.cells.into_values().collect();
FailedSession {
cleanup: session.cleanup,
cells,
}
})
.collect()
}
}

View File

@@ -0,0 +1,244 @@
use std::sync::Arc;
use akode_code_mode_protocol::CodeModeSessionDelegate;
use akode_code_mode_protocol::CodeModeSessionOptions;
use akode_code_mode_protocol::ExecuteRequest;
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::host::DelegateRequestId;
use akode_code_mode_protocol::host::DelegateResponse;
use akode_code_mode_protocol::host::HostToClient;
use akode_code_mode_protocol::host::RequestId;
use akode_code_mode_protocol::host::SessionId;
use akode_code_mode_protocol::host::WireCellId;
use akode_code_mode_protocol::host::WireWaitRequest;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use tokio_util::task::AbortOnDropHandle;
use super::cleanup::SessionCleanup;
#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::remote_session) struct RemoteSession {
pub(in crate::remote_session) id: SessionId,
pub(in crate::remote_session) generation: u64,
}
pub(in crate::remote_session::connection) enum DriverCommand {
OpenSession {
session: RemoteSession,
options: CodeModeSessionOptions,
cleanup: SessionCleanup,
caller_cancellation: CancellationToken,
response_tx: oneshot::Sender<Result<(), String>>,
},
Execute {
session: RemoteSession,
delegate: Arc<dyn CodeModeSessionDelegate>,
request: ExecuteRequest,
caller_cancellation: CancellationToken,
yield_signal: Option<CancellationToken>,
response_tx: oneshot::Sender<Result<DeliveredExecute, String>>,
},
Wait {
session: RemoteSession,
request: WaitRequest,
caller_cancellation: CancellationToken,
yield_signal: Option<CancellationToken>,
response_tx: oneshot::Sender<Result<WaitOutcome, String>>,
},
Terminate {
session: RemoteSession,
request: TerminateRequest,
response_tx: oneshot::Sender<Result<WaitOutcome, String>>,
},
ShutdownSession {
session: RemoteSession,
response_tx: oneshot::Sender<Result<(), String>>,
},
}
pub(in crate::remote_session::connection) enum DriverEvent {
HostMessage(HostToClient),
DelegateCompleted {
id: DelegateRequestId,
result: Result<DelegateResponse, String>,
},
RequestCancelled(RequestId),
YieldRequest(RequestId),
Failed(String),
}
pub(super) struct CancellableRequest {
caller_cancellation: CancellationToken,
watcher_stop: CancellationToken,
reported: bool,
}
impl CancellableRequest {
pub(super) fn new(caller_cancellation: CancellationToken) -> Self {
Self {
caller_cancellation,
watcher_stop: CancellationToken::new(),
reported: false,
}
}
pub(super) fn is_cancelled(&self) -> bool {
self.caller_cancellation.is_cancelled()
}
pub(super) fn mark_reported(&mut self) -> bool {
if self.reported {
return false;
}
self.reported = true;
true
}
pub(super) fn spawn_watcher(&self, id: RequestId, event_tx: mpsc::Sender<DriverEvent>) {
let caller_cancellation = self.caller_cancellation.clone();
let watcher_stop = self.watcher_stop.clone();
tokio::spawn(async move {
tokio::select! {
_ = caller_cancellation.cancelled() => {
let _ = event_tx.send(DriverEvent::RequestCancelled(id)).await;
}
_ = watcher_stop.cancelled() => {}
}
});
}
}
impl Drop for CancellableRequest {
fn drop(&mut self) {
self.watcher_stop.cancel();
}
}
/// Owns the watcher until an observation's final response is received.
pub(super) struct ObservationYield {
signal: Option<CancellationToken>,
watcher: Option<AbortOnDropHandle<()>>,
}
impl ObservationYield {
pub(super) fn new(signal: Option<CancellationToken>) -> Self {
Self {
signal,
watcher: None,
}
}
pub(super) fn spawn_watcher(&mut self, id: RequestId, event_tx: mpsc::Sender<DriverEvent>) {
let Some(signal) = self.signal.take() else {
return;
};
self.watcher = Some(AbortOnDropHandle::new(tokio::spawn(async move {
signal.cancelled().await;
let _ = event_tx.send(DriverEvent::YieldRequest(id)).await;
})));
}
}
pub(super) struct InitialResponse {
pub(super) generation: u64,
pub(super) cell_id: WireCellId,
pub(super) response_tx: oneshot::Sender<Result<RuntimeResponse, String>>,
pub(super) _yield_observation: ObservationYield,
}
pub(in crate::remote_session::connection) struct DeliveredExecute {
pub(in crate::remote_session::connection) request_id: RequestId,
pub(in crate::remote_session::connection) started: StartedCell,
}
pub(super) struct UnclaimedExecute {
pub(super) session: RemoteSession,
pub(super) cell_id: WireCellId,
pub(super) cancellation: CancellableRequest,
}
pub(super) enum PendingRequest {
OpenSession {
session: RemoteSession,
cleanup: SessionCleanup,
cancellation: CancellableRequest,
response_tx: oneshot::Sender<Result<(), String>>,
},
Execute {
session: RemoteSession,
delegate: Arc<dyn CodeModeSessionDelegate>,
response_tx: oneshot::Sender<Result<DeliveredExecute, String>>,
initial_response_tx: oneshot::Sender<Result<RuntimeResponse, String>>,
initial_response_rx: oneshot::Receiver<Result<RuntimeResponse, String>>,
cancellation: CancellableRequest,
yield_observation: ObservationYield,
},
Wait {
session: RemoteSession,
cell_id: WireCellId,
cancellation: CancellableRequest,
yield_observation: ObservationYield,
response_tx: oneshot::Sender<Result<WaitOutcome, String>>,
},
Terminate {
session: RemoteSession,
cell_id: WireCellId,
response_tx: oneshot::Sender<Result<WaitOutcome, String>>,
},
ShutdownSession {
session: RemoteSession,
response_tx: oneshot::Sender<Result<(), String>>,
},
}
pub(super) struct DeferredWait {
pub(super) session: RemoteSession,
pub(super) request: WireWaitRequest,
pub(super) max_output_tokens: Option<usize>,
pub(super) caller_cancellation: CancellationToken,
pub(super) yield_signal: Option<CancellationToken>,
pub(super) response_tx: oneshot::Sender<Result<WaitOutcome, String>>,
}
impl PendingRequest {
pub(super) fn cancellation_mut(&mut self) -> Option<&mut CancellableRequest> {
match self {
Self::OpenSession { cancellation, .. }
| Self::Execute { cancellation, .. }
| Self::Wait { cancellation, .. } => Some(cancellation),
Self::Terminate { .. } | Self::ShutdownSession { .. } => None,
}
}
pub(super) fn yield_observation(&mut self) -> Option<&mut ObservationYield> {
match self {
Self::Execute {
yield_observation, ..
}
| Self::Wait {
yield_observation, ..
} => Some(yield_observation),
_ => None,
}
}
pub(super) fn fail(self, reason: String) {
match self {
Self::OpenSession { response_tx, .. } | Self::ShutdownSession { response_tx, .. } => {
let _ = response_tx.send(Err(reason));
}
Self::Execute { response_tx, .. } => {
let _ = response_tx.send(Err(reason));
}
Self::Wait { response_tx, .. } | Self::Terminate { response_tx, .. } => {
let _ = response_tx.send(Err(reason));
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,28 @@
use akode_code_mode_protocol::host::FramedReader;
use tokio::process::ChildStdout;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use super::driver::DriverEvent;
pub(super) async fn drive_reader(
mut reader: FramedReader<ChildStdout>,
events: mpsc::Sender<DriverEvent>,
cancellation: CancellationToken,
) -> Result<(), String> {
loop {
let message = tokio::select! {
_ = cancellation.cancelled() => return Ok(()),
result = reader.read() => result,
};
let message = match message {
Ok(Some(message)) => message,
Ok(None) => return Err("code-mode host closed its stdout".to_string()),
Err(err) => return Err(format!("failed to read code-mode host message: {err}")),
};
events
.send(DriverEvent::HostMessage(message))
.await
.map_err(|_| "code-mode connection driver closed".to_string())?;
}
}

View File

@@ -0,0 +1,73 @@
//! Restores per-execution trace context for callbacks from the shared stdio host.
//!
//! Keep only a W3C snapshot: retaining the caller's tracing span would extend a yielded
//! exec's duration until its background cell closes. The gRPC transport has its own
//! callback propagation and does not use this wrapper.
//! Instrument manually because `#[instrument]` enters the span before its body runs,
//! which is too late to assign the remote OpenTelemetry parent.
use std::sync::Arc;
use akode_code_mode_protocol::CellId;
use akode_code_mode_protocol::CodeModeNestedToolCall;
use akode_code_mode_protocol::CodeModeSessionDelegate;
use akode_code_mode_protocol::NotificationFuture;
use akode_code_mode_protocol::ToolInvocationFuture;
use akode_protocol::protocol::W3cTraceContext;
use tokio_util::sync::CancellationToken;
use tracing::Instrument;
pub(super) struct TracedCellDelegate {
pub(super) delegate: Arc<dyn CodeModeSessionDelegate>,
pub(super) trace: Option<W3cTraceContext>,
}
impl TracedCellDelegate {
fn with_parent(&self, span: tracing::Span) -> tracing::Span {
// Set the remote parent before entering the span: OTEL starts it on entry.
if let Some(trace) = &self.trace {
akode_otel::set_parent_from_w3c_trace_context(&span, trace);
}
span
}
}
impl CodeModeSessionDelegate for TracedCellDelegate {
fn invoke_tool<'a>(
&'a self,
invocation: CodeModeNestedToolCall,
cancellation_token: CancellationToken,
) -> ToolInvocationFuture<'a> {
let span = self.with_parent(tracing::info_span!(parent: None, "code_mode.stdio.callback"));
Box::pin(
async move {
self.delegate
.invoke_tool(invocation, cancellation_token)
.await
}
.instrument(span),
)
}
fn notify<'a>(
&'a self,
call_id: String,
cell_id: CellId,
text: String,
cancellation_token: CancellationToken,
) -> NotificationFuture<'a> {
let span = self.with_parent(tracing::info_span!(parent: None, "code_mode.stdio.notify"));
Box::pin(
async move {
self.delegate
.notify(call_id, cell_id, text, cancellation_token)
.await
}
.instrument(span),
)
}
fn cell_closed(&self, cell_id: &CellId) {
self.delegate.cell_closed(cell_id);
}
}

View File

@@ -0,0 +1,95 @@
use std::io;
use std::path::PathBuf;
use std::sync::Arc;
use akode_code_mode_protocol::CodeModeSessionProvider;
use pretty_assertions::assert_eq;
use super::ProcessOwnedCodeModeSession;
use super::ProcessOwnedCodeModeSessionProvider;
use super::connection::ConnectionError;
use crate::NoopCodeModeSessionDelegate;
#[test]
fn provider_reuses_its_live_process_host() {
let provider = ProcessOwnedCodeModeSessionProvider::default();
let first = provider.process_host();
let second = provider.process_host();
assert!(Arc::ptr_eq(&first, &second));
}
#[test]
fn missing_host_error_limits_the_displayed_path_to_512_bytes() {
let executable = "codex-code-mode-host-does-not-exist";
let host_program = format!("{}{executable}", "missing-directory/".repeat(/*n*/ 64));
let expected_suffix = &host_program[host_program.len() - (512 - "...".len())..];
let error = ConnectionError::Spawn {
host_program: PathBuf::from(&host_program),
error: io::Error::new(io::ErrorKind::NotFound, "host unavailable"),
};
assert_eq!(
error.to_string(),
format!("failed to spawn code-mode host ...{expected_suffix}: host unavailable")
);
}
#[test]
fn missing_host_error_preserves_utf8_boundaries_when_truncating_the_path() {
let executable = "codex-code-mode-host-does-not-exist";
let host_program = format!("{}{executable}", "🦀".repeat(/*n*/ 256));
let error = ConnectionError::Spawn {
host_program: PathBuf::from(host_program),
error: io::Error::new(io::ErrorKind::NotFound, "host unavailable"),
}
.to_string();
let displayed_path = error
.strip_prefix("failed to spawn code-mode host ")
.and_then(|message| message.strip_suffix(": host unavailable"))
.expect("missing-host error should contain the displayed host path");
assert!(displayed_path.starts_with("..."));
assert!(displayed_path.ends_with(executable));
assert!(displayed_path.len() <= 512);
}
#[tokio::test]
async fn provider_returns_missing_host_error() {
let provider = ProcessOwnedCodeModeSessionProvider::with_host_program(
"codex-code-mode-host-does-not-exist".into(),
);
let error = provider
.create_session()
.await
.err()
.expect("missing host should fail");
assert!(error.contains("failed to spawn code-mode host codex-code-mode-host-does-not-exist"));
}
#[tokio::test]
async fn shutdown_before_open_does_not_spawn_the_host() {
let session = ProcessOwnedCodeModeSession::new();
session.shutdown().await.expect("shutdown session");
let error = session
.execute(
akode_code_mode_protocol::ExecuteRequest {
tool_call_id: "call-1".to_string(),
enabled_tools: Vec::new(),
source: "text('unreachable')".to_string(),
yield_time_ms: None,
max_output_tokens: None,
},
Arc::new(NoopCodeModeSessionDelegate),
/*preempt*/ None,
)
.await
.err()
.expect("shutdown session should reject execution");
assert_eq!(error, "code mode session is shutting down");
}