Base: codex-main originale (prima del fork aKode)
This commit is contained in:
85
codex-rs/code-mode-host/src/delegate.rs
Normal file
85
codex-rs/code-mode-host/src/delegate.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_code_mode_protocol::CellId;
|
||||
use codex_code_mode_protocol::CodeModeNestedToolCall;
|
||||
use codex_code_mode_protocol::CodeModeSessionDelegate;
|
||||
use codex_code_mode_protocol::NotificationFuture;
|
||||
use codex_code_mode_protocol::ToolInvocationFuture;
|
||||
use codex_code_mode_protocol::host::DelegateRequest;
|
||||
use codex_code_mode_protocol::host::DelegateResponse;
|
||||
use codex_code_mode_protocol::host::SessionId;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::peer::HostPeer;
|
||||
|
||||
pub(super) struct RemoteDelegate {
|
||||
session_id: SessionId,
|
||||
peer: Arc<HostPeer>,
|
||||
}
|
||||
|
||||
impl RemoteDelegate {
|
||||
pub(super) fn new(session_id: SessionId, peer: Arc<HostPeer>) -> Self {
|
||||
Self { session_id, peer }
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeModeSessionDelegate for RemoteDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
invocation: CodeModeNestedToolCall,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
match self
|
||||
.peer
|
||||
.call(
|
||||
self.session_id.clone(),
|
||||
DelegateRequest::InvokeTool {
|
||||
invocation: invocation.into(),
|
||||
},
|
||||
cancellation_token,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
DelegateResponse::ToolResult { result } => Ok(result),
|
||||
DelegateResponse::NotificationDelivered => {
|
||||
Err("code-mode client returned an invalid tool result".to_string())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
call_id: String,
|
||||
cell_id: CellId,
|
||||
text: String,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
match self
|
||||
.peer
|
||||
.call(
|
||||
self.session_id.clone(),
|
||||
DelegateRequest::Notify {
|
||||
call_id,
|
||||
cell_id: cell_id.into(),
|
||||
text,
|
||||
},
|
||||
cancellation_token,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
DelegateResponse::NotificationDelivered => Ok(()),
|
||||
DelegateResponse::ToolResult { .. } => {
|
||||
Err("code-mode client returned an invalid notification result".to_string())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn cell_closed(&self, cell_id: &CellId) {
|
||||
self.peer
|
||||
.close_cell(self.session_id.clone(), cell_id.clone());
|
||||
}
|
||||
}
|
||||
78
codex-rs/code-mode-host/src/grpc/capacity_tests.rs
Normal file
78
codex-rs/code-mode-host/src/grpc/capacity_tests.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
#![cfg(test)]
|
||||
//! Negotiated callback budgets protect older clients on a shared host.
|
||||
|
||||
use codex_code_mode_protocol::grpc as proto;
|
||||
use codex_code_mode_protocol::grpc::code_mode_host_server::CodeModeHost;
|
||||
use codex_code_mode_protocol::host::LEGACY_MAX_PENDING_DELEGATE_CALLS;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tonic::Code;
|
||||
use tonic::Request;
|
||||
|
||||
use super::GrpcCodeModeHost;
|
||||
use super::tests::open_session;
|
||||
|
||||
#[tokio::test]
|
||||
async fn client_callback_capacity_is_isolated_and_reusable() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (legacy_id, _legacy_lease) = open_session(&host).await;
|
||||
let legacy = host.state.session(&legacy_id).expect("legacy session");
|
||||
let legacy_permits = (0..LEGACY_MAX_PENDING_DELEGATE_CALLS)
|
||||
.map(|_| legacy.delegate_permit().expect("legacy callback"))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
legacy.delegate_permit().unwrap_err(),
|
||||
"code-mode session has too many pending delegate calls"
|
||||
);
|
||||
|
||||
let mut lease = host
|
||||
.open_session(Request::new(proto::OpenSessionRequest {
|
||||
max_pending_delegate_calls: Some(2),
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
.expect("open capacity-limited session")
|
||||
.into_inner();
|
||||
let event = lease.next().await.expect("opened event").expect("event");
|
||||
let Some(proto::session_event::Event::Opened(opened)) = event.event else {
|
||||
panic!("expected session opening");
|
||||
};
|
||||
let session = host.state.session(&opened.session_id).expect("session");
|
||||
let first = session.delegate_permit().expect("first callback");
|
||||
let second = session.delegate_permit().expect("second callback");
|
||||
assert_eq!(
|
||||
session.delegate_permit().unwrap_err(),
|
||||
"code-mode session has too many pending delegate calls"
|
||||
);
|
||||
|
||||
drop(first);
|
||||
let replacement = session.delegate_permit().expect("reused callback capacity");
|
||||
drop(legacy_permits);
|
||||
let legacy_replacement = legacy.delegate_permit().expect("reused legacy capacity");
|
||||
drop((second, replacement, legacy_replacement));
|
||||
host.close_session(Request::new(proto::CloseSessionRequest {
|
||||
session_id: opened.session_id,
|
||||
}))
|
||||
.await
|
||||
.expect("close new session");
|
||||
host.close_session(Request::new(proto::CloseSessionRequest {
|
||||
session_id: legacy_id,
|
||||
}))
|
||||
.await
|
||||
.expect("close legacy session");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn zero_callback_capacity_is_rejected_before_opening_a_session() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let result = host
|
||||
.open_session(Request::new(proto::OpenSessionRequest {
|
||||
max_pending_delegate_calls: Some(0),
|
||||
..Default::default()
|
||||
}))
|
||||
.await;
|
||||
let Err(error) = result else {
|
||||
panic!("zero callback capacity must be rejected");
|
||||
};
|
||||
assert_eq!(error.code(), Code::InvalidArgument);
|
||||
}
|
||||
205
codex-rs/code-mode-host/src/grpc/conversions.rs
Normal file
205
codex-rs/code-mode-host/src/grpc/conversions.rs
Normal file
@@ -0,0 +1,205 @@
|
||||
use codex_code_mode_protocol::CodeModeOutputTruncation;
|
||||
use codex_code_mode_protocol::CodeModeSessionCellExecutionLimits;
|
||||
use codex_code_mode_protocol::CodeModeToolKind;
|
||||
use codex_code_mode_protocol::ExecuteRequest;
|
||||
use codex_code_mode_protocol::FunctionCallOutputContentItem;
|
||||
use codex_code_mode_protocol::ImageDetail;
|
||||
use codex_code_mode_protocol::MissingCodeModeHostDuration;
|
||||
use codex_code_mode_protocol::RuntimeResponse;
|
||||
use codex_code_mode_protocol::ToolDefinition;
|
||||
use codex_code_mode_protocol::WaitOutcome;
|
||||
use codex_code_mode_protocol::grpc as proto;
|
||||
use codex_protocol::ToolName;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tonic::Response;
|
||||
use tonic::Status;
|
||||
|
||||
use super::validation;
|
||||
|
||||
pub(super) fn session_limits(
|
||||
limits: Option<proto::SessionCellExecutionLimits>,
|
||||
) -> Result<CodeModeSessionCellExecutionLimits, Status> {
|
||||
let limits = limits.unwrap_or_default();
|
||||
Ok(CodeModeSessionCellExecutionLimits {
|
||||
max_yield_time_ms: limits.max_yield_time_ms,
|
||||
max_heap_size_bytes: limits
|
||||
.max_heap_size_bytes
|
||||
.map(usize::try_from)
|
||||
.transpose()
|
||||
.map_err(|_| Status::invalid_argument("maximum heap size exceeds this platform"))?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn observation_budget(
|
||||
max_output_tokens: Option<u64>,
|
||||
output_truncation: CodeModeOutputTruncation,
|
||||
) -> Result<Option<usize>, Status> {
|
||||
if output_truncation == CodeModeOutputTruncation::Client {
|
||||
return Ok(None);
|
||||
}
|
||||
max_output_tokens
|
||||
.map(|value| {
|
||||
usize::try_from(value)
|
||||
.map_err(|_| Status::invalid_argument("output budget is too large"))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(super) fn execute_request(request: proto::ExecuteRequest) -> Result<ExecuteRequest, Status> {
|
||||
validation::identifier(&request.tool_call_id, "tool call ID")?;
|
||||
Ok(ExecuteRequest {
|
||||
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(usize::try_from)
|
||||
.transpose()
|
||||
.map_err(|_| Status::invalid_argument("maximum output tokens exceeds this platform"))?,
|
||||
})
|
||||
}
|
||||
|
||||
fn tool_definition(definition: proto::ToolDefinition) -> Result<ToolDefinition, Status> {
|
||||
validation::identifier(&definition.name, "tool definition name")?;
|
||||
let name = definition
|
||||
.tool_name
|
||||
.ok_or_else(|| Status::invalid_argument("tool definition is missing its tool name"))?;
|
||||
validation::tool_name(&name)?;
|
||||
Ok(ToolDefinition {
|
||||
name: definition.name,
|
||||
tool_name: ToolName::new(name.namespace, name.name),
|
||||
description: definition.description,
|
||||
kind: match proto::ToolKind::try_from(definition.kind) {
|
||||
Ok(proto::ToolKind::Function) => CodeModeToolKind::Function,
|
||||
Ok(proto::ToolKind::Freeform) => CodeModeToolKind::Freeform,
|
||||
Ok(proto::ToolKind::Unspecified) | Err(_) => {
|
||||
return Err(Status::invalid_argument(
|
||||
"tool definition has an invalid kind",
|
||||
));
|
||||
}
|
||||
},
|
||||
input_schema: json_field(definition.input_schema_json, "input schema")?,
|
||||
input_schema_max_bytes: None,
|
||||
output_schema: json_field(definition.output_schema_json, "output schema")?,
|
||||
})
|
||||
}
|
||||
|
||||
fn json_field(value: Option<Vec<u8>>, field: &str) -> Result<Option<JsonValue>, Status> {
|
||||
value
|
||||
.map(|value| {
|
||||
serde_json::from_slice(&value)
|
||||
.map_err(|error| Status::invalid_argument(format!("invalid tool {field}: {error}")))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Preserves the response's timing; the host handler must record it first.
|
||||
pub(super) fn execution_outcome(
|
||||
response: RuntimeResponse,
|
||||
) -> Result<proto::ExecutionOutcome, MissingCodeModeHostDuration> {
|
||||
let (cell_id, content_items, outcome, code_mode_host_duration) = match response {
|
||||
RuntimeResponse::Yielded {
|
||||
cell_id,
|
||||
content_items,
|
||||
code_mode_host_duration,
|
||||
} => (
|
||||
cell_id,
|
||||
content_items,
|
||||
proto::execution_outcome::Outcome::Yielded(proto::ExecutionYielded {}),
|
||||
code_mode_host_duration,
|
||||
),
|
||||
RuntimeResponse::Terminated {
|
||||
cell_id,
|
||||
content_items,
|
||||
code_mode_host_duration,
|
||||
} => (
|
||||
cell_id,
|
||||
content_items,
|
||||
proto::execution_outcome::Outcome::Terminated(proto::ExecutionTerminated {}),
|
||||
code_mode_host_duration,
|
||||
),
|
||||
RuntimeResponse::Result {
|
||||
cell_id,
|
||||
content_items,
|
||||
error_text,
|
||||
code_mode_host_duration,
|
||||
..
|
||||
} => (
|
||||
cell_id,
|
||||
content_items,
|
||||
proto::execution_outcome::Outcome::Completed(proto::ExecutionCompleted { error_text }),
|
||||
code_mode_host_duration,
|
||||
),
|
||||
};
|
||||
let code_mode_host_duration = code_mode_host_duration.ok_or(MissingCodeModeHostDuration)?;
|
||||
Ok(proto::ExecutionOutcome {
|
||||
cell_id: cell_id.to_string(),
|
||||
content_items: content_items.into_iter().map(content_item).collect(),
|
||||
outcome: Some(outcome),
|
||||
code_mode_host_duration_ns: u64::try_from(code_mode_host_duration.as_nanos())
|
||||
.unwrap_or(u64::MAX),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn wait_response(
|
||||
outcome: WaitOutcome,
|
||||
) -> Result<Response<proto::WaitResponse>, MissingCodeModeHostDuration> {
|
||||
let buffered = outcome.result_buffered_for();
|
||||
let state = match outcome {
|
||||
WaitOutcome::LiveCell(response) => {
|
||||
proto::wait_response::State::LiveCell(execution_outcome(response)?)
|
||||
}
|
||||
WaitOutcome::MissingCell(response) => {
|
||||
proto::wait_response::State::MissingCell(execution_outcome(response)?)
|
||||
}
|
||||
};
|
||||
let mut response = Response::new(proto::WaitResponse { state: Some(state) });
|
||||
if let Some(buffered) = buffered {
|
||||
let nanos = u64::try_from(buffered.as_nanos()).unwrap_or(u64::MAX);
|
||||
response
|
||||
.metadata_mut()
|
||||
.insert(proto::RESULT_BUFFERED_FOR_NS_METADATA, nanos.into());
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
fn content_item(item: FunctionCallOutputContentItem) -> proto::ContentItem {
|
||||
let item = match item {
|
||||
FunctionCallOutputContentItem::InputText { text } => {
|
||||
proto::content_item::Item::Text(proto::TextContent { text })
|
||||
}
|
||||
FunctionCallOutputContentItem::InputImage { image_url, detail } => {
|
||||
proto::content_item::Item::Image(proto::ImageContent {
|
||||
image_url,
|
||||
detail: detail.map(|detail| {
|
||||
(match detail {
|
||||
ImageDetail::Auto => proto::ImageDetail::Auto,
|
||||
ImageDetail::Low => proto::ImageDetail::Low,
|
||||
ImageDetail::High => proto::ImageDetail::High,
|
||||
ImageDetail::Original => proto::ImageDetail::Original,
|
||||
}) as i32
|
||||
}),
|
||||
})
|
||||
}
|
||||
FunctionCallOutputContentItem::InputAudio { audio_url } => {
|
||||
proto::content_item::Item::Audio(proto::AudioContent { audio_url })
|
||||
}
|
||||
};
|
||||
proto::ContentItem { item: Some(item) }
|
||||
}
|
||||
|
||||
pub(super) fn tool_kind(kind: CodeModeToolKind) -> i32 {
|
||||
match kind {
|
||||
CodeModeToolKind::Function => proto::ToolKind::Function as i32,
|
||||
CodeModeToolKind::Freeform => proto::ToolKind::Freeform as i32,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "conversions_tests.rs"]
|
||||
mod tests;
|
||||
176
codex-rs/code-mode-host/src/grpc/conversions_tests.rs
Normal file
176
codex-rs/code-mode-host/src/grpc/conversions_tests.rs
Normal file
@@ -0,0 +1,176 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_code_mode_protocol::CellId;
|
||||
use codex_code_mode_protocol::FunctionCallOutputContentItem;
|
||||
use codex_code_mode_protocol::ImageDetail;
|
||||
use codex_code_mode_protocol::MissingCodeModeHostDuration;
|
||||
use codex_code_mode_protocol::RuntimeResponse;
|
||||
use codex_code_mode_protocol::WaitOutcome;
|
||||
use codex_code_mode_protocol::grpc as proto;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tonic::Code;
|
||||
|
||||
use super::execute_request;
|
||||
use super::execution_outcome;
|
||||
use super::wait_response;
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_names_unknown_tool_kinds_and_invalid_json_schemas() {
|
||||
let definition = proto::ToolDefinition {
|
||||
name: "echo".to_string(),
|
||||
tool_name: None,
|
||||
description: String::new(),
|
||||
kind: proto::ToolKind::Function as i32,
|
||||
input_schema_json: None,
|
||||
output_schema_json: None,
|
||||
};
|
||||
let request = |definition| proto::ExecuteRequest {
|
||||
session_id: "session".to_string(),
|
||||
execution_id: "execution".to_string(),
|
||||
tool_call_id: "call".to_string(),
|
||||
source: String::new(),
|
||||
enabled_tools: vec![definition],
|
||||
yield_time_ms: None,
|
||||
max_output_tokens: None,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
execute_request(request(definition.clone()))
|
||||
.unwrap_err()
|
||||
.code(),
|
||||
Code::InvalidArgument
|
||||
);
|
||||
let definition = proto::ToolDefinition {
|
||||
tool_name: Some(proto::ToolName {
|
||||
name: "echo".to_string(),
|
||||
namespace: Some("tools".to_string()),
|
||||
}),
|
||||
..definition
|
||||
};
|
||||
assert_eq!(
|
||||
execute_request(request(proto::ToolDefinition {
|
||||
kind: proto::ToolKind::Unspecified as i32,
|
||||
..definition.clone()
|
||||
}))
|
||||
.unwrap_err()
|
||||
.code(),
|
||||
Code::InvalidArgument
|
||||
);
|
||||
assert_eq!(
|
||||
execute_request(request(proto::ToolDefinition {
|
||||
input_schema_json: Some(b"not-json".to_vec()),
|
||||
..definition
|
||||
}))
|
||||
.unwrap_err()
|
||||
.code(),
|
||||
Code::InvalidArgument
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_text_image_audio_and_terminal_error_without_losing_details() {
|
||||
let response = wait_response(WaitOutcome::LiveCell(RuntimeResponse::Result {
|
||||
code_mode_host_duration: Some(Duration::from_nanos(/*nanos*/ 123_456_789)),
|
||||
cell_id: CellId::new("cell".to_string()),
|
||||
content_items: vec![
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "hello".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image_url: "data:image/png;base64,YQ==".to_string(),
|
||||
detail: Some(ImageDetail::Original),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputAudio {
|
||||
audio_url: "data:audio/wav;base64,YQ==".to_string(),
|
||||
},
|
||||
],
|
||||
result_buffered_for: Duration::from_nanos(42),
|
||||
error_text: Some("failed".to_string()),
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
response
|
||||
.metadata()
|
||||
.get(proto::RESULT_BUFFERED_FOR_NS_METADATA)
|
||||
.unwrap(),
|
||||
"42"
|
||||
);
|
||||
let state = response.into_inner().state.expect("wait outcome");
|
||||
assert_eq!(
|
||||
state,
|
||||
proto::wait_response::State::LiveCell(proto::ExecutionOutcome {
|
||||
code_mode_host_duration_ns: 123_456_789,
|
||||
cell_id: "cell".to_string(),
|
||||
content_items: vec![
|
||||
proto::ContentItem {
|
||||
item: Some(proto::content_item::Item::Text(proto::TextContent {
|
||||
text: "hello".to_string(),
|
||||
})),
|
||||
},
|
||||
proto::ContentItem {
|
||||
item: Some(proto::content_item::Item::Image(proto::ImageContent {
|
||||
image_url: "data:image/png;base64,YQ==".to_string(),
|
||||
detail: Some(proto::ImageDetail::Original as i32),
|
||||
})),
|
||||
},
|
||||
proto::ContentItem {
|
||||
item: Some(proto::content_item::Item::Audio(proto::AudioContent {
|
||||
audio_url: "data:audio/wav;base64,YQ==".to_string(),
|
||||
})),
|
||||
},
|
||||
],
|
||||
outcome: Some(proto::execution_outcome::Outcome::Completed(
|
||||
proto::ExecutionCompleted {
|
||||
error_text: Some("failed".to_string()),
|
||||
},
|
||||
)),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wait_metadata_distinguishes_an_unbuffered_result_from_no_result() {
|
||||
let result = RuntimeResponse::Result {
|
||||
cell_id: CellId::new("cell".to_string()),
|
||||
content_items: Vec::new(),
|
||||
error_text: None,
|
||||
result_buffered_for: Duration::ZERO,
|
||||
code_mode_host_duration: Some(Duration::ZERO),
|
||||
};
|
||||
for (outcome, expected) in [
|
||||
(WaitOutcome::LiveCell(result.clone()), Some("0")),
|
||||
(WaitOutcome::MissingCell(result), None),
|
||||
] {
|
||||
let response = wait_response(outcome).unwrap();
|
||||
let buffered = response
|
||||
.metadata()
|
||||
.get(proto::RESULT_BUFFERED_FOR_NS_METADATA)
|
||||
.map(|value| value.to_str().unwrap());
|
||||
assert_eq!(buffered, expected);
|
||||
}
|
||||
}
|
||||
|
||||
/// Encoding must not turn a missing request measurement into measured zero,
|
||||
/// including when no live cell remains to supply output.
|
||||
#[test]
|
||||
fn grpc_encoding_rejects_untimed_runtime_output() {
|
||||
let response = RuntimeResponse::Terminated {
|
||||
cell_id: CellId::new("cell".to_string()),
|
||||
content_items: Vec::new(),
|
||||
code_mode_host_duration: None,
|
||||
};
|
||||
assert_eq!(
|
||||
execution_outcome(response.clone()),
|
||||
Err(MissingCodeModeHostDuration)
|
||||
);
|
||||
for outcome in [
|
||||
WaitOutcome::LiveCell(response.clone()),
|
||||
WaitOutcome::MissingCell(response),
|
||||
] {
|
||||
assert_eq!(
|
||||
wait_response(outcome).unwrap_err(),
|
||||
MissingCodeModeHostDuration
|
||||
);
|
||||
}
|
||||
}
|
||||
131
codex-rs/code-mode-host/src/grpc/delegate.rs
Normal file
131
codex-rs/code-mode-host/src/grpc/delegate.rs
Normal file
@@ -0,0 +1,131 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
|
||||
use codex_code_mode_protocol::CellId;
|
||||
use codex_code_mode_protocol::CodeModeNestedToolCall;
|
||||
use codex_code_mode_protocol::CodeModeSessionDelegate;
|
||||
use codex_code_mode_protocol::NotificationFuture;
|
||||
use codex_code_mode_protocol::ToolInvocationFuture;
|
||||
use codex_code_mode_protocol::grpc as proto;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::session::GrpcSession;
|
||||
|
||||
pub(super) struct GrpcDelegate {
|
||||
session: Weak<GrpcSession>,
|
||||
}
|
||||
|
||||
impl GrpcDelegate {
|
||||
pub(super) fn new(session: Weak<GrpcSession>) -> Self {
|
||||
Self { session }
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeModeSessionDelegate for GrpcDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
invocation: CodeModeNestedToolCall,
|
||||
cancellation: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
let session = self
|
||||
.session
|
||||
.upgrade()
|
||||
.ok_or_else(|| "code-mode session is closed".to_string())?;
|
||||
let _permit = session.delegate_permit()?;
|
||||
let execution_id = session
|
||||
.execution_id(invocation.cell_id.as_str(), &cancellation)
|
||||
.await?;
|
||||
let input_json = invocation
|
||||
.input
|
||||
.as_ref()
|
||||
.map(serde_json::to_vec)
|
||||
.transpose()
|
||||
.map_err(|error| format!("failed to encode code-mode tool input: {error}"))?;
|
||||
let invocation_id = Uuid::new_v4();
|
||||
let (response, receiver) = oneshot::channel();
|
||||
session
|
||||
.dispatch_tool(
|
||||
invocation,
|
||||
execution_id,
|
||||
invocation_id,
|
||||
input_json,
|
||||
response,
|
||||
&cancellation,
|
||||
)
|
||||
.await?;
|
||||
let mut pending = PendingToolCall {
|
||||
session: Arc::clone(&session),
|
||||
id: Some(invocation_id),
|
||||
};
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
result = receiver => result
|
||||
.map_err(|_| "code-mode client closed before returning tool output".to_string())?,
|
||||
_ = cancellation.cancelled() => {
|
||||
Err("code mode delegate request cancelled".to_string())
|
||||
}
|
||||
_ = session.closed.cancelled() => {
|
||||
Err("code-mode session closed before returning tool output".to_string())
|
||||
}
|
||||
};
|
||||
if result.is_ok() {
|
||||
pending.id = None;
|
||||
}
|
||||
result
|
||||
})
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
call_id: String,
|
||||
cell_id: CellId,
|
||||
text: String,
|
||||
cancellation: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
let session = self
|
||||
.session
|
||||
.upgrade()
|
||||
.ok_or_else(|| "code-mode session is closed".to_string())?;
|
||||
let _permit = session.delegate_permit()?;
|
||||
let execution_id = session
|
||||
.execution_id(cell_id.as_str(), &cancellation)
|
||||
.await?;
|
||||
let notification_id = Uuid::new_v4();
|
||||
session
|
||||
.send_event(
|
||||
proto::session_event::Event::Notification(proto::Notification {
|
||||
notification_id: notification_id.to_string(),
|
||||
execution_id,
|
||||
cell_id: cell_id.to_string(),
|
||||
call_id,
|
||||
text,
|
||||
}),
|
||||
&cancellation,
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
|
||||
fn cell_closed(&self, cell_id: &CellId) {
|
||||
if let Some(session) = self.session.upgrade() {
|
||||
session.close_cell(cell_id.as_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PendingToolCall {
|
||||
session: Arc<GrpcSession>,
|
||||
id: Option<Uuid>,
|
||||
}
|
||||
|
||||
impl Drop for PendingToolCall {
|
||||
fn drop(&mut self) {
|
||||
if let Some(id) = self.id.take() {
|
||||
self.session.cancel_invocation(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
151
codex-rs/code-mode-host/src/grpc/events.rs
Normal file
151
codex-rs/code-mode-host/src/grpc/events.rs
Normal file
@@ -0,0 +1,151 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_code_mode_protocol::grpc as proto;
|
||||
use codex_code_mode_protocol::host::MAX_FRAME_BYTES;
|
||||
use codex_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use prost::Message;
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::TryAcquireError;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::TaskTracker;
|
||||
use tonic::Status;
|
||||
|
||||
use crate::MAX_ACTIVE_CELLS;
|
||||
|
||||
const MAX_BUFFERED_CONTROL_EVENTS: usize = MAX_PENDING_DELEGATE_CALLS * 2 + MAX_ACTIVE_CELLS;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct EventSender {
|
||||
sender: mpsc::UnboundedSender<QueuedEvent>,
|
||||
permits: Arc<Semaphore>,
|
||||
closed: CancellationToken,
|
||||
writer: TaskTracker,
|
||||
}
|
||||
|
||||
struct QueuedEvent {
|
||||
message: proto::SessionEvent,
|
||||
_queue_permit: OwnedSemaphorePermit,
|
||||
_cell_permit: Option<OwnedSemaphorePermit>,
|
||||
}
|
||||
|
||||
impl EventSender {
|
||||
pub(super) fn new(
|
||||
output: mpsc::Sender<Result<proto::SessionEvent, Status>>,
|
||||
closed: CancellationToken,
|
||||
) -> Self {
|
||||
let (sender, mut receiver) = mpsc::unbounded_channel::<QueuedEvent>();
|
||||
let writer_closed = closed.clone();
|
||||
let writer = TaskTracker::new();
|
||||
writer.spawn(async move {
|
||||
loop {
|
||||
let event = tokio::select! {
|
||||
_ = writer_closed.cancelled() => return,
|
||||
event = receiver.recv() => match event {
|
||||
Some(event) => event,
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
let QueuedEvent {
|
||||
message,
|
||||
_queue_permit,
|
||||
_cell_permit,
|
||||
} = event;
|
||||
tokio::select! {
|
||||
_ = writer_closed.cancelled() => return,
|
||||
result = output.send(Ok(message)) => {
|
||||
if result.is_err() {
|
||||
writer_closed.cancel();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(_queue_permit);
|
||||
drop(_cell_permit);
|
||||
}
|
||||
});
|
||||
writer.close();
|
||||
Self {
|
||||
sender,
|
||||
permits: Arc::new(Semaphore::new(MAX_BUFFERED_CONTROL_EVENTS)),
|
||||
closed,
|
||||
writer,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn shutdown(&self) {
|
||||
self.closed.cancel();
|
||||
self.writer.wait().await;
|
||||
}
|
||||
|
||||
pub(super) async fn send(
|
||||
&self,
|
||||
event: proto::session_event::Event,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<(), String> {
|
||||
let message = validate_event(event)?;
|
||||
let permit = tokio::select! {
|
||||
biased;
|
||||
_ = self.closed.cancelled() => {
|
||||
return Err("code-mode session event stream is closed".to_string());
|
||||
}
|
||||
_ = cancellation.cancelled() => {
|
||||
return Err("code-mode session event was cancelled".to_string());
|
||||
}
|
||||
permit = Arc::clone(&self.permits).acquire_owned() => permit
|
||||
.map_err(|_| "code-mode session event queue is closed".to_string())?,
|
||||
};
|
||||
self.enqueue(message, permit, /*cell_permit*/ None)
|
||||
}
|
||||
|
||||
pub(super) fn send_now(
|
||||
&self,
|
||||
event: proto::session_event::Event,
|
||||
cell_permit: Option<OwnedSemaphorePermit>,
|
||||
) -> Result<(), String> {
|
||||
let message = validate_event(event)?;
|
||||
if self.closed.is_cancelled() {
|
||||
return Err("code-mode session event stream is closed".to_string());
|
||||
}
|
||||
match Arc::clone(&self.permits).try_acquire_owned() {
|
||||
Ok(permit) => self.enqueue(message, permit, cell_permit),
|
||||
Err(TryAcquireError::NoPermits) => {
|
||||
self.closed.cancel();
|
||||
Err("code-mode session event queue is full".to_string())
|
||||
}
|
||||
Err(TryAcquireError::Closed) => {
|
||||
self.closed.cancel();
|
||||
Err("code-mode session event queue is closed".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn enqueue(
|
||||
&self,
|
||||
message: proto::SessionEvent,
|
||||
permit: OwnedSemaphorePermit,
|
||||
cell_permit: Option<OwnedSemaphorePermit>,
|
||||
) -> Result<(), String> {
|
||||
self.sender
|
||||
.send(QueuedEvent {
|
||||
message,
|
||||
_queue_permit: permit,
|
||||
_cell_permit: cell_permit,
|
||||
})
|
||||
.map_err(|_| {
|
||||
self.closed.cancel();
|
||||
"code-mode session event stream is closed".to_string()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_event(event: proto::session_event::Event) -> Result<proto::SessionEvent, String> {
|
||||
let message = proto::SessionEvent { event: Some(event) };
|
||||
if message.encoded_len() > MAX_FRAME_BYTES {
|
||||
return Err(format!(
|
||||
"code-mode session event exceeds the {MAX_FRAME_BYTES}-byte gRPC message limit"
|
||||
));
|
||||
}
|
||||
Ok(message)
|
||||
}
|
||||
552
codex-rs/code-mode-host/src/grpc/mod.rs
Normal file
552
codex-rs/code-mode-host/src/grpc/mod.rs
Normal file
@@ -0,0 +1,552 @@
|
||||
mod conversions;
|
||||
mod delegate;
|
||||
mod events;
|
||||
mod routing;
|
||||
mod session;
|
||||
mod validation;
|
||||
mod waits;
|
||||
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_code_mode_protocol::CellId;
|
||||
use codex_code_mode_protocol::CodeModeOutputTruncation;
|
||||
use codex_code_mode_protocol::CodeModeSession;
|
||||
use codex_code_mode_protocol::CodeModeSessionOptions;
|
||||
use codex_code_mode_protocol::TerminateRequest;
|
||||
use codex_code_mode_protocol::WaitRequest;
|
||||
use codex_code_mode_protocol::grpc as proto;
|
||||
use codex_code_mode_protocol::grpc::code_mode_host_server::CodeModeHost;
|
||||
use codex_code_mode_protocol::host::LEGACY_MAX_PENDING_DELEGATE_CALLS;
|
||||
use codex_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use futures::Stream;
|
||||
use futures::StreamExt;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tonic::Request;
|
||||
use tonic::Response;
|
||||
use tonic::Status;
|
||||
use tracing::Instrument;
|
||||
|
||||
use self::session::GrpcHostState;
|
||||
use self::session::GrpcSession;
|
||||
use self::waits::WaitRegistration;
|
||||
|
||||
type GrpcStream<T> = Pin<Box<dyn Stream<Item = Result<T, Status>> + Send + 'static>>;
|
||||
type GrpcFuture<'a, T> = Pin<Box<dyn Future<Output = Result<Response<T>, Status>> + Send + 'a>>;
|
||||
|
||||
fn trace_context_from_request<T>(request: &Request<T>) -> Option<W3cTraceContext> {
|
||||
request
|
||||
.metadata()
|
||||
.get("traceparent")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(|traceparent| W3cTraceContext {
|
||||
traceparent: Some(traceparent.to_string()),
|
||||
tracestate: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Serves transport-independent, leased code-mode sessions over gRPC.
|
||||
#[derive(Clone)]
|
||||
pub struct GrpcCodeModeHost {
|
||||
state: Arc<GrpcHostState>,
|
||||
process_metrics: Option<Arc<crate::process_metrics::ProcessMetrics>>,
|
||||
}
|
||||
|
||||
impl GrpcCodeModeHost {
|
||||
/// Creates a host with independent session, execution, and callback limits.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
state: Arc::new(GrpcHostState::new()),
|
||||
process_metrics: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Uses a collector whose resources were prepared before sandbox entry.
|
||||
pub fn with_process_metrics(collector: crate::CodeModeProcessMetricsCollector) -> Self {
|
||||
Self {
|
||||
process_metrics: Some(Arc::new(crate::process_metrics::ProcessMetrics::new(
|
||||
collector,
|
||||
))),
|
||||
..Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
async fn open_session_request(
|
||||
&self,
|
||||
request: proto::OpenSessionRequest,
|
||||
) -> Result<Response<GrpcStream<proto::SessionEvent>>, Status> {
|
||||
let _permit = self.state.request_permit()?;
|
||||
let max_pending_delegate_calls = request
|
||||
.max_pending_delegate_calls
|
||||
.map(|limit| limit as usize)
|
||||
.unwrap_or(LEGACY_MAX_PENDING_DELEGATE_CALLS)
|
||||
.min(MAX_PENDING_DELEGATE_CALLS);
|
||||
if max_pending_delegate_calls == 0 {
|
||||
return Err(Status::invalid_argument(
|
||||
"callback capacity must be positive",
|
||||
));
|
||||
}
|
||||
let limits = conversions::session_limits(request.cell_execution_limits)?;
|
||||
let output_truncation = match request
|
||||
.output_truncation
|
||||
.map(proto::OutputTruncation::try_from)
|
||||
.transpose()
|
||||
.map_err(|_| Status::invalid_argument("unknown code-mode output truncation mode"))?
|
||||
{
|
||||
None | Some(proto::OutputTruncation::Unspecified | proto::OutputTruncation::Client) => {
|
||||
CodeModeOutputTruncation::Client
|
||||
}
|
||||
Some(proto::OutputTruncation::Server) => CodeModeOutputTruncation::Server,
|
||||
};
|
||||
Ok(Response::new(self.state.open_session(
|
||||
CodeModeSessionOptions {
|
||||
cell_execution_limits: limits,
|
||||
output_truncation,
|
||||
},
|
||||
max_pending_delegate_calls,
|
||||
)?))
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
name = "code_mode_host.grpc.close_session",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(
|
||||
otel.name = "code_mode_host.grpc.close_session",
|
||||
session.id = %request.session_id,
|
||||
)
|
||||
)]
|
||||
async fn close_session_request(
|
||||
&self,
|
||||
request: proto::CloseSessionRequest,
|
||||
) -> Result<Response<proto::CloseSessionResponse>, Status> {
|
||||
let _permit = self.state.control_permit()?;
|
||||
self.state.close_session(&request.session_id).await?;
|
||||
Ok(Response::new(proto::CloseSessionResponse {}))
|
||||
}
|
||||
|
||||
async fn subscribe_request(
|
||||
&self,
|
||||
request: proto::SubscribeToToolCallsRequest,
|
||||
) -> Result<Response<GrpcStream<proto::ToolCall>>, Status> {
|
||||
let _permit = self.state.request_permit()?;
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
Ok(Response::new(session.subscribe(request.tool_names)?))
|
||||
}
|
||||
|
||||
async fn complete_tool_request(
|
||||
&self,
|
||||
request: proto::CompleteToolCallRequest,
|
||||
) -> Result<Response<proto::CompleteToolCallResponse>, Status> {
|
||||
let _permit = self.state.control_permit()?;
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
let invocation_id = validation::uuid(&request.invocation_id, "tool invocation ID")?;
|
||||
let result = match request.outcome {
|
||||
Some(proto::complete_tool_call_request::Outcome::Succeeded(result)) => Ok(
|
||||
serde_json::from_slice(&result.output_json).map_err(|error| {
|
||||
Status::invalid_argument(format!("invalid code-mode tool output JSON: {error}"))
|
||||
})?,
|
||||
),
|
||||
Some(proto::complete_tool_call_request::Outcome::Failed(error)) => Err(error.message),
|
||||
None => {
|
||||
return Err(Status::invalid_argument(
|
||||
"tool completion is missing its outcome",
|
||||
));
|
||||
}
|
||||
};
|
||||
session.complete_invocation(invocation_id, result)?;
|
||||
Ok(Response::new(proto::CompleteToolCallResponse {}))
|
||||
}
|
||||
|
||||
async fn acknowledge_notification_request(
|
||||
&self,
|
||||
request: proto::AcknowledgeNotificationRequest,
|
||||
) -> Result<Response<proto::AcknowledgeNotificationResponse>, Status> {
|
||||
let _permit = self.state.control_permit()?;
|
||||
self.state.session(&request.session_id)?;
|
||||
validation::uuid(&request.notification_id, "notification ID")?;
|
||||
Ok(Response::new(proto::AcknowledgeNotificationResponse {}))
|
||||
}
|
||||
|
||||
async fn execute_request(
|
||||
&self,
|
||||
request: proto::ExecuteRequest,
|
||||
callback_traceparent: Option<String>,
|
||||
) -> Result<Response<GrpcStream<proto::ExecuteEvent>>, Status> {
|
||||
let received_at = Instant::now();
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
validation::identifier(&request.execution_id, "execution ID")?;
|
||||
let request_permit = self.state.request_permit()?;
|
||||
let execution_id = request.execution_id.clone();
|
||||
let request = conversions::execute_request(request)?;
|
||||
let cell_permit = self.state.cell_permit()?;
|
||||
let yield_signal = session.reserve_execution(&execution_id)?;
|
||||
let mut admission = ExecutionAdmission {
|
||||
session: Arc::clone(&session),
|
||||
execution_id: Some(execution_id.clone()),
|
||||
};
|
||||
let started = tokio::select! {
|
||||
_ = session.closed.cancelled() => {
|
||||
return Err(Status::cancelled("code-mode session is closed"));
|
||||
}
|
||||
result = session.runtime.execute(request, Arc::new(delegate::GrpcDelegate::new(Arc::downgrade(&session))), Some(yield_signal)) => {
|
||||
result.map_err(Status::failed_precondition)?
|
||||
}
|
||||
};
|
||||
let cell_id = started.cell_id.clone();
|
||||
session.admit_execution(
|
||||
execution_id.clone(),
|
||||
cell_id.to_string(),
|
||||
cell_permit,
|
||||
callback_traceparent,
|
||||
)?;
|
||||
|
||||
let (sender, receiver) = mpsc::channel(/*buffer*/ 2);
|
||||
sender
|
||||
.try_send(Ok(proto::ExecuteEvent {
|
||||
event: Some(proto::execute_event::Event::Started(
|
||||
proto::ExecutionStarted {
|
||||
execution_id,
|
||||
cell_id: cell_id.to_string(),
|
||||
},
|
||||
)),
|
||||
}))
|
||||
.map_err(|_| Status::internal("failed to publish code-mode execution admission"))?;
|
||||
let outcome_span = tracing::Span::current();
|
||||
tokio::spawn(
|
||||
async move {
|
||||
let _request_permit = request_permit;
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = sender.closed() => {}
|
||||
response = started.initial_response() => {
|
||||
// Freeze timing before conversion or transport backpressure.
|
||||
let code_mode_host_duration = received_at.elapsed();
|
||||
let event = response.and_then(|response| {
|
||||
let response = response.with_code_mode_host_duration(code_mode_host_duration);
|
||||
let outcome = conversions::execution_outcome(response)
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(proto::ExecuteEvent {
|
||||
event: Some(proto::execute_event::Event::Outcome(outcome)),
|
||||
})
|
||||
}).map_err(Status::internal);
|
||||
let _ = sender.send(event).await;
|
||||
}
|
||||
_ = session.closed.cancelled() => {}
|
||||
}
|
||||
}
|
||||
.instrument(outcome_span),
|
||||
);
|
||||
|
||||
let stream = ReceiverStream::new(receiver).inspect(move |event| {
|
||||
if matches!(
|
||||
event,
|
||||
Ok(proto::ExecuteEvent {
|
||||
event: Some(proto::execute_event::Event::Outcome(_)),
|
||||
})
|
||||
) {
|
||||
admission.disarm();
|
||||
}
|
||||
});
|
||||
Ok(Response::new(Box::pin(stream)))
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
name = "code_mode_host.grpc.wait",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(
|
||||
otel.name = "code_mode_host.grpc.wait",
|
||||
session.id = %request.session_id,
|
||||
cell.id = %request.cell_id,
|
||||
wait.id = %request.wait_id,
|
||||
)
|
||||
)]
|
||||
async fn wait_request(
|
||||
&self,
|
||||
request: proto::WaitRequest,
|
||||
) -> Result<Response<proto::WaitResponse>, Status> {
|
||||
let received_at = Instant::now();
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
validation::identifier(&request.cell_id, "cell ID")?;
|
||||
validation::identifier(&request.wait_id, "wait ID")?;
|
||||
let _permit = self.state.request_permit()?;
|
||||
let max_output_tokens = conversions::observation_budget(
|
||||
request.max_output_tokens,
|
||||
session.runtime.output_truncation(),
|
||||
)?;
|
||||
let registration = WaitRegistration::new(Arc::clone(&session), request.wait_id)?;
|
||||
let request = WaitRequest {
|
||||
cell_id: CellId::new(request.cell_id),
|
||||
yield_time_ms: request.yield_time_ms,
|
||||
max_output_tokens,
|
||||
};
|
||||
let outcome = tokio::select! {
|
||||
biased;
|
||||
_ = registration.cancellation().cancelled() => {
|
||||
return Err(Status::cancelled("code-mode wait was cancelled"));
|
||||
}
|
||||
_ = session.closed.cancelled() => {
|
||||
return Err(Status::cancelled("code-mode session is closed"));
|
||||
}
|
||||
outcome = session.runtime.wait(request, Some(registration.yield_signal())) => {
|
||||
outcome.map_err(Status::failed_precondition)?
|
||||
}
|
||||
};
|
||||
let outcome = outcome.with_code_mode_host_duration(received_at.elapsed());
|
||||
conversions::wait_response(outcome).map_err(|error| Status::internal(error.to_string()))
|
||||
}
|
||||
|
||||
async fn cancel_wait_request(
|
||||
&self,
|
||||
request: proto::CancelWaitRequest,
|
||||
) -> Result<Response<proto::CancelWaitResponse>, Status> {
|
||||
let _permit = self.state.control_permit()?;
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
validation::identifier(&request.wait_id, "wait ID")?;
|
||||
session.cancel_wait(&request.wait_id).await?;
|
||||
Ok(Response::new(proto::CancelWaitResponse {}))
|
||||
}
|
||||
|
||||
async fn yield_observation_request(
|
||||
&self,
|
||||
request: proto::YieldObservationRequest,
|
||||
) -> Result<Response<proto::YieldObservationResponse>, Status> {
|
||||
let _permit = self.state.control_permit()?;
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
match request.observation {
|
||||
Some(proto::yield_observation_request::Observation::ExecutionId(id)) => {
|
||||
session.yield_execution(&id)?;
|
||||
}
|
||||
Some(proto::yield_observation_request::Observation::WaitId(id)) => {
|
||||
session.yield_wait(&id)?;
|
||||
}
|
||||
None => return Err(Status::invalid_argument("missing code-mode observation ID")),
|
||||
}
|
||||
Ok(Response::new(proto::YieldObservationResponse {}))
|
||||
}
|
||||
|
||||
async fn terminate_request(
|
||||
&self,
|
||||
request: proto::TerminateRequest,
|
||||
) -> Result<Response<proto::WaitResponse>, Status> {
|
||||
let received_at = Instant::now();
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
validation::identifier(&request.cell_id, "cell ID")?;
|
||||
let _permit = self.state.request_permit()?;
|
||||
let max_output_tokens = conversions::observation_budget(
|
||||
request.max_output_tokens,
|
||||
session.runtime.output_truncation(),
|
||||
)?;
|
||||
let outcome = session
|
||||
.terminate(TerminateRequest {
|
||||
cell_id: CellId::new(request.cell_id),
|
||||
max_output_tokens,
|
||||
})
|
||||
.await?;
|
||||
let outcome = outcome.with_code_mode_host_duration(received_at.elapsed());
|
||||
conversions::wait_response(outcome).map_err(|error| Status::internal(error.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GrpcCodeModeHost {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeModeHost for GrpcCodeModeHost {
|
||||
fn get_process_metrics<'a, 'async_trait>(
|
||||
&'a self,
|
||||
_request: Request<proto::GetProcessMetricsRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::GetProcessMetricsResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(async move {
|
||||
self.process_metrics
|
||||
.as_ref()
|
||||
.ok_or_else(|| Status::unimplemented("process metrics are unsupported"))?
|
||||
.sample()
|
||||
.await
|
||||
})
|
||||
}
|
||||
|
||||
type OpenSessionStream = GrpcStream<proto::SessionEvent>;
|
||||
type SubscribeToToolCallsStream = GrpcStream<proto::ToolCall>;
|
||||
type ExecuteStream = GrpcStream<proto::ExecuteEvent>;
|
||||
|
||||
fn open_session<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::OpenSessionRequest>,
|
||||
) -> GrpcFuture<'async_trait, Self::OpenSessionStream>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
let trace = trace_context_from_request(&request);
|
||||
let request = request.into_inner();
|
||||
let open_session_span = tracing::info_span!("code_mode_host.grpc.open_session");
|
||||
if let Some(trace) = trace.as_ref() {
|
||||
codex_otel::set_parent_from_w3c_trace_context(&open_session_span, trace);
|
||||
}
|
||||
Box::pin(
|
||||
self.open_session_request(request)
|
||||
.instrument(open_session_span),
|
||||
)
|
||||
}
|
||||
|
||||
fn close_session<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::CloseSessionRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::CloseSessionResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.close_session_request(request.into_inner()))
|
||||
}
|
||||
|
||||
fn subscribe_to_tool_calls<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::SubscribeToToolCallsRequest>,
|
||||
) -> GrpcFuture<'async_trait, Self::SubscribeToToolCallsStream>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.subscribe_request(request.into_inner()))
|
||||
}
|
||||
|
||||
fn complete_tool_call<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::CompleteToolCallRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::CompleteToolCallResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.complete_tool_request(request.into_inner()))
|
||||
}
|
||||
|
||||
fn acknowledge_notification<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::AcknowledgeNotificationRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::AcknowledgeNotificationResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.acknowledge_notification_request(request.into_inner()))
|
||||
}
|
||||
|
||||
fn execute<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::ExecuteRequest>,
|
||||
) -> GrpcFuture<'async_trait, Self::ExecuteStream>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
let trace = trace_context_from_request(&request);
|
||||
let request = request.into_inner();
|
||||
let execute_span = tracing::info_span!(
|
||||
"code_mode_host.grpc.execute",
|
||||
otel.name = "code_mode_host.grpc.execute",
|
||||
session.id = %request.session_id,
|
||||
execution.id = %request.execution_id,
|
||||
call_id = %request.tool_call_id,
|
||||
);
|
||||
if let Some(trace) = trace.as_ref() {
|
||||
codex_otel::set_parent_from_w3c_trace_context(&execute_span, trace);
|
||||
}
|
||||
let callback_traceparent =
|
||||
codex_otel::span_w3c_trace_context(&execute_span).and_then(|trace| trace.traceparent);
|
||||
Box::pin(
|
||||
self.execute_request(request, callback_traceparent)
|
||||
.instrument(execute_span),
|
||||
)
|
||||
}
|
||||
|
||||
fn wait<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::WaitRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::WaitResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.wait_request(request.into_inner()))
|
||||
}
|
||||
|
||||
fn cancel_wait<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::CancelWaitRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::CancelWaitResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.cancel_wait_request(request.into_inner()))
|
||||
}
|
||||
|
||||
fn yield_observation<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::YieldObservationRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::YieldObservationResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.yield_observation_request(request.into_inner()))
|
||||
}
|
||||
|
||||
fn terminate<'a, 'async_trait>(
|
||||
&'a self,
|
||||
request: Request<proto::TerminateRequest>,
|
||||
) -> GrpcFuture<'async_trait, proto::WaitResponse>
|
||||
where
|
||||
'a: 'async_trait,
|
||||
Self: 'async_trait,
|
||||
{
|
||||
Box::pin(self.terminate_request(request.into_inner()))
|
||||
}
|
||||
}
|
||||
|
||||
struct ExecutionAdmission {
|
||||
session: Arc<GrpcSession>,
|
||||
execution_id: Option<String>,
|
||||
}
|
||||
|
||||
impl ExecutionAdmission {
|
||||
fn disarm(&mut self) {
|
||||
if let Some(execution_id) = self.execution_id.take() {
|
||||
self.session.retire_execution_observation(&execution_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ExecutionAdmission {
|
||||
fn drop(&mut self) {
|
||||
if let Some(execution_id) = self.execution_id.take() {
|
||||
self.session.abandon_execution(&execution_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "service_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "robustness_tests.rs"]
|
||||
mod robustness_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "capacity_tests.rs"]
|
||||
mod capacity_tests;
|
||||
686
codex-rs/code-mode-host/src/grpc/robustness_tests.rs
Normal file
686
codex-rs/code-mode-host/src/grpc/robustness_tests.rs
Normal file
@@ -0,0 +1,686 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_code_mode_protocol::CellId;
|
||||
use codex_code_mode_protocol::CodeModeNestedToolCall;
|
||||
use codex_code_mode_protocol::CodeModeToolKind;
|
||||
use codex_code_mode_protocol::grpc as proto;
|
||||
use codex_code_mode_protocol::grpc::code_mode_host_server::CodeModeHost;
|
||||
use codex_code_mode_protocol::host::MAX_FRAME_BYTES;
|
||||
use codex_protocol::ToolName;
|
||||
use futures::FutureExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tonic::Code;
|
||||
use tonic::Request;
|
||||
use tonic::Status;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::ExecutionAdmission;
|
||||
use super::GrpcCodeModeHost;
|
||||
use super::tests::execute_events;
|
||||
use super::tests::execute_request;
|
||||
use super::tests::open_session;
|
||||
use super::tests::tool;
|
||||
use super::validation::MAX_IDENTIFIER_BYTES;
|
||||
use super::validation::MAX_TOOL_FILTERS;
|
||||
use crate::MAX_ACTIVE_CELLS;
|
||||
use crate::MAX_IN_FLIGHT_REQUESTS;
|
||||
use crate::OUTGOING_CHANNEL_CAPACITY;
|
||||
|
||||
fn assert_invalid<T>(result: Result<T, Status>) {
|
||||
match result {
|
||||
Ok(_) => panic!("expected an oversized gRPC field to be rejected"),
|
||||
Err(error) => assert_eq!(error.code(), Code::InvalidArgument),
|
||||
}
|
||||
}
|
||||
|
||||
fn invocation(cell_id: &str, name: &str) -> CodeModeNestedToolCall {
|
||||
CodeModeNestedToolCall {
|
||||
cell_id: CellId::new(cell_id.to_string()),
|
||||
runtime_tool_call_id: "runtime-call".to_string(),
|
||||
tool_name: ToolName::plain(name),
|
||||
tool_kind: CodeModeToolKind::Function,
|
||||
input: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_oversized_identifiers_and_subscription_filters() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let oversized_id = "x".repeat(MAX_IDENTIFIER_BYTES + 1);
|
||||
|
||||
assert_invalid(
|
||||
host.close_session(Request::new(proto::CloseSessionRequest {
|
||||
session_id: oversized_id.clone(),
|
||||
}))
|
||||
.await,
|
||||
);
|
||||
assert_invalid(
|
||||
host.close_session(Request::new(proto::CloseSessionRequest {
|
||||
session_id: "not-a-uuid".to_string(),
|
||||
}))
|
||||
.await,
|
||||
);
|
||||
assert_invalid(
|
||||
host.complete_tool_call(Request::new(proto::CompleteToolCallRequest {
|
||||
session_id: session_id.clone(),
|
||||
invocation_id: "not-a-uuid".to_string(),
|
||||
outcome: Some(proto::complete_tool_call_request::Outcome::Succeeded(
|
||||
proto::ToolCallSucceeded {
|
||||
output_json: b"null".to_vec(),
|
||||
},
|
||||
)),
|
||||
}))
|
||||
.await,
|
||||
);
|
||||
assert_invalid(
|
||||
host.acknowledge_notification(Request::new(proto::AcknowledgeNotificationRequest {
|
||||
session_id: session_id.clone(),
|
||||
notification_id: "not-a-uuid".to_string(),
|
||||
}))
|
||||
.await,
|
||||
);
|
||||
assert_invalid(
|
||||
host.execute(Request::new(execute_request(
|
||||
&session_id,
|
||||
&oversized_id,
|
||||
"text(\"hello\");",
|
||||
)))
|
||||
.await,
|
||||
);
|
||||
assert_invalid(
|
||||
host.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: oversized_id,
|
||||
namespace: None,
|
||||
}],
|
||||
}))
|
||||
.await,
|
||||
);
|
||||
assert_invalid(
|
||||
host.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![
|
||||
proto::ToolName {
|
||||
name: "echo".to_string(),
|
||||
namespace: None,
|
||||
};
|
||||
MAX_TOOL_FILTERS + 1
|
||||
],
|
||||
}))
|
||||
.await,
|
||||
);
|
||||
|
||||
assert!(host.state.session(&session_id).is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_execution_before_admission_releases_its_reservation() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let session = host.state.session(&session_id).expect("open session");
|
||||
let execution_id = "execution-abandoned-before-admission".to_string();
|
||||
session
|
||||
.reserve_execution(&execution_id)
|
||||
.expect("reserve execution");
|
||||
|
||||
drop(ExecutionAdmission {
|
||||
session: Arc::clone(&session),
|
||||
execution_id: Some(execution_id.clone()),
|
||||
});
|
||||
|
||||
let error = session
|
||||
.admit_execution(
|
||||
execution_id,
|
||||
"cell".to_string(),
|
||||
host.state.cell_permit().expect("reserve cell permit"),
|
||||
/*traceparent*/ None,
|
||||
)
|
||||
.expect_err("abandoned execution must not admit a runtime cell");
|
||||
assert_eq!(error.code(), Code::Cancelled);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_an_unread_buffered_execution_outcome_retires_its_cell() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, mut events) = open_session(&host).await;
|
||||
let execution = host
|
||||
.execute(Request::new(execute_request(
|
||||
&session_id,
|
||||
"execution-abandoned",
|
||||
"await new Promise(() => {});",
|
||||
)))
|
||||
.await
|
||||
.expect("start execution")
|
||||
.into_inner();
|
||||
let _reserved_permits = (0..MAX_IN_FLIGHT_REQUESTS - 1)
|
||||
.map(|_| host.state.request_permit().expect("reserve request permit"))
|
||||
.collect::<Vec<_>>();
|
||||
let _execution_permit = tokio::time::timeout(Duration::from_secs(/*secs*/ 2), async {
|
||||
loop {
|
||||
if let Ok(permit) = host.state.request_permit() {
|
||||
return permit;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("execution outcome should be buffered before dropping its unread stream");
|
||||
|
||||
drop(execution);
|
||||
|
||||
assert_eq!(
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 2), events.next())
|
||||
.await
|
||||
.expect("abandoned cell should close")
|
||||
.expect("cell closed event")
|
||||
.expect("session event"),
|
||||
proto::SessionEvent {
|
||||
event: Some(proto::session_event::Event::CellClosed(proto::CellClosed {
|
||||
execution_id: "execution-abandoned".to_string(),
|
||||
cell_id: "1".to_string(),
|
||||
final_tool_call_sequence: 0,
|
||||
})),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_a_session_releases_buffered_cell_permits() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let session = host.state.session(&session_id).expect("open session");
|
||||
let mut permits = (0..MAX_ACTIVE_CELLS)
|
||||
.map(|_| {
|
||||
host.state
|
||||
.cell_permit()
|
||||
.expect("reserve active-cell permit")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
session
|
||||
.send_event_now(
|
||||
proto::session_event::Event::CellClosed(proto::CellClosed {
|
||||
execution_id: "execution-queued".to_string(),
|
||||
cell_id: "1".to_string(),
|
||||
final_tool_call_sequence: 0,
|
||||
}),
|
||||
permits.pop(),
|
||||
)
|
||||
.expect("queue cell closure");
|
||||
|
||||
host.close_session(Request::new(proto::CloseSessionRequest { session_id }))
|
||||
.await
|
||||
.expect("close session");
|
||||
|
||||
assert!(
|
||||
host.state.cell_permit().is_ok(),
|
||||
"closing a session must release its queued active-cell permits"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_a_lease_after_its_host_shuts_down_closes_the_session() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, lease) = open_session(&host).await;
|
||||
let session = host.state.session(&session_id).expect("open session");
|
||||
|
||||
drop(host);
|
||||
drop(lease);
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 2), session.closed.cancelled())
|
||||
.await
|
||||
.expect("dropping a lease must close its session after the host disappears");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_closure_cancels_pending_termination() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let (cell_id, mut execution) = execute_events(
|
||||
&host,
|
||||
execute_request(
|
||||
&session_id,
|
||||
"execution-termination",
|
||||
"await new Promise(() => {});",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
execution.next().await.expect("execution outcome").unwrap();
|
||||
let session = host.state.session(&session_id).expect("open session");
|
||||
let termination = host.terminate(Request::new(proto::TerminateRequest {
|
||||
session_id,
|
||||
cell_id,
|
||||
max_output_tokens: None,
|
||||
}));
|
||||
tokio::pin!(termination);
|
||||
assert!(termination.as_mut().now_or_never().is_none());
|
||||
|
||||
session.closed.cancel();
|
||||
let error = termination
|
||||
.await
|
||||
.expect_err("closed sessions must bound termination");
|
||||
|
||||
assert_eq!(error.code(), Code::Cancelled);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn oversized_encoded_tool_invocation_fails_without_closing_its_session() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let mut subscription = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: Vec::new(),
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let (cell_id, mut execution) = execute_events(
|
||||
&host,
|
||||
execute_request(
|
||||
&session_id,
|
||||
"execution-oversized",
|
||||
"await new Promise(() => {});",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
execution.next().await.unwrap().unwrap();
|
||||
let session = host.state.session(&session_id).unwrap();
|
||||
let cancellation = CancellationToken::new();
|
||||
let (response, _receiver) = oneshot::channel();
|
||||
|
||||
let error = session
|
||||
.dispatch_tool(
|
||||
invocation(&cell_id, "echo"),
|
||||
"execution-oversized".to_string(),
|
||||
Uuid::new_v4(),
|
||||
Some(vec![0; MAX_FRAME_BYTES]),
|
||||
response,
|
||||
&cancellation,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.contains("gRPC message limit"));
|
||||
assert!(host.state.session(&session_id).is_ok());
|
||||
assert!(!session.closed.is_cancelled());
|
||||
|
||||
let (response, _receiver) = oneshot::channel();
|
||||
let invocation_id = Uuid::new_v4();
|
||||
session
|
||||
.dispatch_tool(
|
||||
invocation(&cell_id, "echo"),
|
||||
"execution-oversized".to_string(),
|
||||
invocation_id,
|
||||
Some(b"{}".to_vec()),
|
||||
response,
|
||||
&cancellation,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let delivered = subscription.next().await.unwrap().unwrap();
|
||||
assert_eq!(delivered.invocation_id, invocation_id.to_string());
|
||||
assert_eq!(delivered.sequence, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unmatched_tool_subscription_fails_without_closing_its_session() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let _unrelated = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: "other".to_string(),
|
||||
namespace: None,
|
||||
}],
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let (cell_id, mut execution) = execute_events(
|
||||
&host,
|
||||
execute_request(
|
||||
&session_id,
|
||||
"execution-unmatched",
|
||||
"await new Promise(() => {});",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
execution.next().await.unwrap().unwrap();
|
||||
let session = host.state.session(&session_id).unwrap();
|
||||
let cancellation = CancellationToken::new();
|
||||
let (response, _receiver) = oneshot::channel();
|
||||
|
||||
assert!(
|
||||
session
|
||||
.dispatch_tool(
|
||||
invocation(&cell_id, "echo"),
|
||||
"execution-unmatched".to_string(),
|
||||
Uuid::new_v4(),
|
||||
Some(b"{}".to_vec()),
|
||||
response,
|
||||
&cancellation,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(host.state.session(&session_id).is_ok());
|
||||
assert!(!session.closed.is_cancelled());
|
||||
|
||||
let mut matching = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id,
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: "echo".to_string(),
|
||||
namespace: None,
|
||||
}],
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let (response, _receiver) = oneshot::channel();
|
||||
let invocation_id = Uuid::new_v4();
|
||||
session
|
||||
.dispatch_tool(
|
||||
invocation(&cell_id, "echo"),
|
||||
"execution-unmatched".to_string(),
|
||||
invocation_id,
|
||||
Some(b"{}".to_vec()),
|
||||
response,
|
||||
&cancellation,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let delivered = matching.next().await.unwrap().unwrap();
|
||||
assert_eq!(delivered.invocation_id, invocation_id.to_string());
|
||||
assert_eq!(delivered.sequence, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_selected_subscription_retries_another_matching_subscription() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let mut first = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: Vec::new(),
|
||||
}))
|
||||
.await
|
||||
.expect("subscribe first tool stream")
|
||||
.into_inner();
|
||||
let mut second = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: Vec::new(),
|
||||
}))
|
||||
.await
|
||||
.expect("subscribe second tool stream")
|
||||
.into_inner();
|
||||
let (cell_id, mut execution) = execute_events(
|
||||
&host,
|
||||
execute_request(
|
||||
&session_id,
|
||||
"execution-retry",
|
||||
"await new Promise(() => {});",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
execution.next().await.expect("execution outcome").unwrap();
|
||||
let session = host.state.session(&session_id).expect("open session");
|
||||
let subscriptions = session
|
||||
.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.subscriptions
|
||||
.iter()
|
||||
.map(|subscription| (subscription.id, subscription.sender.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
for (_, sender) in &subscriptions {
|
||||
for _ in 0..OUTGOING_CHANNEL_CAPACITY {
|
||||
sender
|
||||
.try_send(Ok(proto::ToolCall::default()))
|
||||
.expect("fill subscription queue");
|
||||
}
|
||||
}
|
||||
let cancellation = CancellationToken::new();
|
||||
let (response, _receiver) = oneshot::channel();
|
||||
let invocation_id = Uuid::new_v4();
|
||||
let dispatch = session.dispatch_tool(
|
||||
invocation(&cell_id, "echo"),
|
||||
"execution-retry".to_string(),
|
||||
invocation_id,
|
||||
/*input_json*/ None,
|
||||
response,
|
||||
&cancellation,
|
||||
);
|
||||
tokio::pin!(dispatch);
|
||||
assert!(dispatch.as_mut().now_or_never().is_none());
|
||||
session
|
||||
.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.subscriptions
|
||||
.retain(|subscription| subscription.id != subscriptions[0].0);
|
||||
|
||||
first.next().await.expect("free first reservation").unwrap();
|
||||
assert!(dispatch.as_mut().now_or_never().is_none());
|
||||
second
|
||||
.next()
|
||||
.await
|
||||
.expect("free surviving reservation")
|
||||
.unwrap();
|
||||
dispatch.await.expect("retry surviving subscription");
|
||||
|
||||
for _ in 1..OUTGOING_CHANNEL_CAPACITY {
|
||||
second.next().await.expect("drain buffered call").unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
second
|
||||
.next()
|
||||
.await
|
||||
.expect("retried invocation")
|
||||
.unwrap()
|
||||
.invocation_id,
|
||||
invocation_id.to_string()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn saturated_subscription_does_not_block_independently_filtered_tools() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let mut slow = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: "slow".to_string(),
|
||||
namespace: None,
|
||||
}],
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let mut fast = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: "fast".to_string(),
|
||||
namespace: None,
|
||||
}],
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let (cell_id, mut execution) = execute_events(
|
||||
&host,
|
||||
execute_request(
|
||||
&session_id,
|
||||
"execution-backpressure",
|
||||
"await new Promise(() => {});",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
execution.next().await.unwrap().unwrap();
|
||||
let session = host.state.session(&session_id).unwrap();
|
||||
let cancellation = CancellationToken::new();
|
||||
let mut responses = Vec::new();
|
||||
|
||||
for _ in 0..OUTGOING_CHANNEL_CAPACITY {
|
||||
let (response, receiver) = oneshot::channel();
|
||||
responses.push(receiver);
|
||||
session
|
||||
.dispatch_tool(
|
||||
invocation(&cell_id, "slow"),
|
||||
"execution-backpressure".to_string(),
|
||||
Uuid::new_v4(),
|
||||
/*input_json*/ None,
|
||||
response,
|
||||
&cancellation,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let blocked_session = Arc::clone(&session);
|
||||
let blocked_cell = cell_id.clone();
|
||||
let blocked_cancellation = cancellation.clone();
|
||||
let (response, receiver) = oneshot::channel();
|
||||
responses.push(receiver);
|
||||
let blocked = tokio::spawn(async move {
|
||||
blocked_session
|
||||
.dispatch_tool(
|
||||
invocation(&blocked_cell, "slow"),
|
||||
"execution-backpressure".to_string(),
|
||||
Uuid::new_v4(),
|
||||
/*input_json*/ None,
|
||||
response,
|
||||
&blocked_cancellation,
|
||||
)
|
||||
.await
|
||||
});
|
||||
tokio::task::yield_now().await;
|
||||
assert!(!blocked.is_finished());
|
||||
|
||||
let (response, receiver) = oneshot::channel();
|
||||
responses.push(receiver);
|
||||
let invocation_id = Uuid::new_v4();
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
session.dispatch_tool(
|
||||
invocation(&cell_id, "fast"),
|
||||
"execution-backpressure".to_string(),
|
||||
invocation_id,
|
||||
/*input_json*/ None,
|
||||
response,
|
||||
&cancellation,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("saturated subscription must not block another tool")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fast.next().await.unwrap().unwrap().invocation_id,
|
||||
invocation_id.to_string()
|
||||
);
|
||||
|
||||
slow.next().await.unwrap().unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(1), blocked)
|
||||
.await
|
||||
.expect("draining the subscription should release its blocked invocation")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_subscriptions_only_retires_sessions_with_unread_calls() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let idle = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: Vec::new(),
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
drop(idle);
|
||||
|
||||
let session = host.state.session(&session_id).unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 2), async {
|
||||
while !session.state.lock().unwrap().subscriptions.is_empty() {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("idle subscription should be removed without retiring its session");
|
||||
assert!(host.state.session(&session_id).is_ok());
|
||||
|
||||
let first = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: Vec::new(),
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let mut second = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: Vec::new(),
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let mut request = execute_request(
|
||||
&session_id,
|
||||
"execution-subscription-drop",
|
||||
r#"await tools.echo({attempt: 1});"#,
|
||||
);
|
||||
request.yield_time_ms = Some(/*value*/ 10_000);
|
||||
request.enabled_tools = vec![tool("echo")];
|
||||
let (_cell_id, mut execution) = execute_events(&host, request).await;
|
||||
let first_subscription_id = session.state.lock().unwrap().subscriptions[0].id;
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 2), async {
|
||||
loop {
|
||||
let owned = session
|
||||
.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.pending_invocations
|
||||
.values()
|
||||
.any(|invocation| invocation.subscription_id == first_subscription_id);
|
||||
if owned {
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("first subscription should own an unread tool call");
|
||||
drop(first);
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 2), async {
|
||||
while host.state.session(&session_id).is_ok() {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("losing an unread call must retire its lease without leaving a sequence gap");
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 2), second.next())
|
||||
.await
|
||||
.expect("other subscriptions should close with their lease")
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 2), execution.next())
|
||||
.await
|
||||
.expect("execution should retire with its lease")
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
253
codex-rs/code-mode-host/src/grpc/routing.rs
Normal file
253
codex-rs/code-mode-host/src/grpc/routing.rs
Normal file
@@ -0,0 +1,253 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use codex_code_mode_protocol::CodeModeNestedToolCall;
|
||||
use codex_code_mode_protocol::grpc as proto;
|
||||
use codex_code_mode_protocol::host::MAX_FRAME_BYTES;
|
||||
use codex_protocol::ToolName;
|
||||
use futures::StreamExt;
|
||||
use futures::stream::FuturesUnordered;
|
||||
use prost::Message;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tonic::Status;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::GrpcStream;
|
||||
use super::conversions;
|
||||
use super::session::GrpcSession;
|
||||
use super::session::PendingInvocation;
|
||||
use super::session::ToolSubscription;
|
||||
use super::validation;
|
||||
use crate::OUTGOING_CHANNEL_CAPACITY;
|
||||
|
||||
const MAX_SUBSCRIPTIONS: usize = 128;
|
||||
|
||||
impl GrpcSession {
|
||||
pub(super) fn subscribe(
|
||||
self: &Arc<Self>,
|
||||
filters: Vec<proto::ToolName>,
|
||||
) -> Result<GrpcStream<proto::ToolCall>, Status> {
|
||||
validation::tool_filters(&filters)?;
|
||||
let id = Uuid::new_v4();
|
||||
let (sender, receiver) = mpsc::channel(OUTGOING_CHANNEL_CAPACITY);
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if self.closed.is_cancelled() {
|
||||
return Err(Status::cancelled("code-mode session is closed"));
|
||||
}
|
||||
if state.subscriptions.len() >= MAX_SUBSCRIPTIONS {
|
||||
return Err(Status::resource_exhausted(
|
||||
"code-mode session has too many tool subscriptions",
|
||||
));
|
||||
}
|
||||
state.subscriptions.push(ToolSubscription {
|
||||
id,
|
||||
filters,
|
||||
sender: sender.clone(),
|
||||
});
|
||||
drop(state);
|
||||
|
||||
let session = Arc::downgrade(self);
|
||||
let closed = self.closed.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::select! {
|
||||
_ = sender.closed() => {}
|
||||
_ = closed.cancelled() => return,
|
||||
}
|
||||
if let Some(session) = session.upgrade() {
|
||||
let abandoned = {
|
||||
let mut state = session.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
state
|
||||
.subscriptions
|
||||
.retain(|subscription| subscription.id != id);
|
||||
state
|
||||
.pending_invocations
|
||||
.extract_if(|_, invocation| invocation.subscription_id == id)
|
||||
.map(|(_, invocation)| invocation)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
if !abandoned.is_empty() {
|
||||
// A buffered call may never have reached the client. Closing
|
||||
// the lease avoids replaying a possibly delivered invocation
|
||||
// or leaving an unfillable execution-sequence gap.
|
||||
session.closed.cancel();
|
||||
}
|
||||
for invocation in abandoned {
|
||||
let _ = invocation.response.send(Err(
|
||||
"code-mode tool subscription closed before returning tool output"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(Box::pin(ReceiverStream::new(receiver)))
|
||||
}
|
||||
|
||||
pub(super) async fn dispatch_tool(
|
||||
&self,
|
||||
invocation: CodeModeNestedToolCall,
|
||||
execution_id: String,
|
||||
invocation_id: Uuid,
|
||||
input_json: Option<Vec<u8>>,
|
||||
response: oneshot::Sender<Result<JsonValue, String>>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<(), String> {
|
||||
let cell_id = invocation.cell_id.to_string();
|
||||
let tool_name = proto::ToolName {
|
||||
name: invocation.tool_name.name,
|
||||
namespace: invocation.tool_name.namespace,
|
||||
};
|
||||
let canonical_tool_name =
|
||||
ToolName::new(tool_name.namespace.clone(), tool_name.name.clone())
|
||||
.with_default_namespace();
|
||||
let (sequence, traceparent, subscriptions) = {
|
||||
let state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let Some(execution) = state.cells.get(&cell_id) else {
|
||||
return Err("code-mode cell closed before dispatching its tool call".to_string());
|
||||
};
|
||||
let sequence = execution.tool_call_sequence.checked_add(1).ok_or_else(|| {
|
||||
"code-mode execution tool-call sequence was exhausted".to_string()
|
||||
})?;
|
||||
let count = state.subscriptions.len();
|
||||
let subscriptions = (0..count)
|
||||
.map(|offset| &state.subscriptions[(state.next_subscription + offset) % count])
|
||||
.filter(|subscription| {
|
||||
subscription.filters.is_empty()
|
||||
|| subscription.filters.iter().any(|filter| {
|
||||
ToolName::new(filter.namespace.clone(), filter.name.clone())
|
||||
.with_default_namespace()
|
||||
== canonical_tool_name
|
||||
})
|
||||
})
|
||||
.map(|subscription| (subscription.id, subscription.sender.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
(sequence, execution.traceparent.clone(), subscriptions)
|
||||
};
|
||||
// The saved traceparent belongs to the outer execution. Prefer the runtime's
|
||||
// per-tool span so the callback is nested under its invocation, with the
|
||||
// execution context as a fallback when no current span context is available.
|
||||
let traceparent = codex_otel::current_span_w3c_trace_context()
|
||||
.and_then(|trace| trace.traceparent)
|
||||
.or(traceparent);
|
||||
if subscriptions.is_empty() {
|
||||
return Err("no code-mode tool subscription matches the requested tool".to_string());
|
||||
}
|
||||
let mut message = proto::ToolCall {
|
||||
session_id: self.id.to_string(),
|
||||
execution_id,
|
||||
cell_id: cell_id.clone(),
|
||||
invocation_id: invocation_id.to_string(),
|
||||
runtime_tool_call_id: invocation.runtime_tool_call_id,
|
||||
tool_name: Some(tool_name.clone()),
|
||||
tool_kind: conversions::tool_kind(invocation.tool_kind),
|
||||
input_json,
|
||||
sequence,
|
||||
traceparent,
|
||||
};
|
||||
if message.encoded_len() > MAX_FRAME_BYTES {
|
||||
return Err(format!(
|
||||
"code-mode tool invocation exceeds the {MAX_FRAME_BYTES}-byte gRPC message limit"
|
||||
));
|
||||
}
|
||||
|
||||
let mut reservations =
|
||||
subscriptions
|
||||
.into_iter()
|
||||
.map(|(id, sender)| async move {
|
||||
sender.reserve_owned().await.map(|permit| (id, permit))
|
||||
})
|
||||
.collect::<FuturesUnordered<_>>();
|
||||
loop {
|
||||
let (subscription_id, permit) = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => {
|
||||
return Err("code mode delegate request cancelled".to_string());
|
||||
}
|
||||
_ = self.closed.cancelled() => {
|
||||
return Err("code-mode session closed before dispatching its tool call".to_string());
|
||||
}
|
||||
reservation = reservations.next() => match reservation {
|
||||
Some(Ok(reservation)) => reservation,
|
||||
Some(Err(_)) => continue,
|
||||
None => {
|
||||
return Err("matching code-mode tool subscriptions are unavailable".to_string());
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let Some(subscription_index) = state.subscriptions.iter().position(|subscription| {
|
||||
subscription.id == subscription_id && !subscription.sender.is_closed()
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
let Some(execution) = state.cells.get_mut(&cell_id) else {
|
||||
return Err("code-mode cell closed before dispatching its tool call".to_string());
|
||||
};
|
||||
let sequence = execution.tool_call_sequence.checked_add(1).ok_or_else(|| {
|
||||
"code-mode execution tool-call sequence was exhausted".to_string()
|
||||
})?;
|
||||
message.sequence = sequence;
|
||||
if message.encoded_len() > MAX_FRAME_BYTES {
|
||||
return Err(format!(
|
||||
"code-mode tool invocation exceeds the {MAX_FRAME_BYTES}-byte gRPC message limit"
|
||||
));
|
||||
}
|
||||
execution.tool_call_sequence = sequence;
|
||||
state.pending_invocations.insert(
|
||||
invocation_id,
|
||||
PendingInvocation {
|
||||
subscription_id,
|
||||
response,
|
||||
},
|
||||
);
|
||||
state.seen_invocations.remember(invocation_id);
|
||||
state.next_subscription = (subscription_index + 1) % state.subscriptions.len();
|
||||
permit.send(Ok(message));
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn complete_invocation(
|
||||
&self,
|
||||
invocation_id: Uuid,
|
||||
result: Result<JsonValue, String>,
|
||||
) -> Result<(), Status> {
|
||||
let response = {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match state.pending_invocations.remove(&invocation_id) {
|
||||
Some(invocation) => Some(invocation.response),
|
||||
None if state.seen_invocations.contains(&invocation_id) => None,
|
||||
None => {
|
||||
return Err(Status::not_found(format!(
|
||||
"unknown code-mode tool invocation {invocation_id}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(response) = response {
|
||||
let _ = response.send(result);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn cancel_invocation(&self, invocation_id: Uuid) {
|
||||
let pending = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.pending_invocations
|
||||
.remove(&invocation_id);
|
||||
if pending.is_some() {
|
||||
let _ = self.send_event_now(
|
||||
proto::session_event::Event::ToolCallCancelled(proto::ToolCallCancelled {
|
||||
invocation_id: invocation_id.to_string(),
|
||||
}),
|
||||
/*cell_permit*/ None,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
618
codex-rs/code-mode-host/src/grpc/service_tests.rs
Normal file
618
codex-rs/code-mode-host/src/grpc/service_tests.rs
Normal file
@@ -0,0 +1,618 @@
|
||||
use super::GrpcCodeModeHost;
|
||||
use super::GrpcStream;
|
||||
use codex_code_mode_protocol::grpc as proto;
|
||||
use codex_code_mode_protocol::grpc::code_mode_host_server::CodeModeHost;
|
||||
use futures::FutureExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tonic::Code;
|
||||
use tonic::Request;
|
||||
|
||||
pub(super) async fn open_session(
|
||||
host: &GrpcCodeModeHost,
|
||||
) -> (String, GrpcStream<proto::SessionEvent>) {
|
||||
let (opened, stream) = open_session_with_truncation(host, /*output_truncation*/ None).await;
|
||||
(opened.session_id, stream)
|
||||
}
|
||||
|
||||
async fn open_session_with_truncation(
|
||||
host: &GrpcCodeModeHost,
|
||||
output_truncation: Option<i32>,
|
||||
) -> (proto::SessionOpened, GrpcStream<proto::SessionEvent>) {
|
||||
let mut stream = host
|
||||
.open_session(Request::new(proto::OpenSessionRequest {
|
||||
max_pending_delegate_calls: None,
|
||||
cell_execution_limits: None,
|
||||
output_truncation,
|
||||
}))
|
||||
.await
|
||||
.expect("open code-mode session")
|
||||
.into_inner();
|
||||
let event = stream
|
||||
.next()
|
||||
.await
|
||||
.expect("session opened event")
|
||||
.expect("session event");
|
||||
let Some(proto::session_event::Event::Opened(opened)) = event.event else {
|
||||
panic!("expected the first session event to open its lease");
|
||||
};
|
||||
(opened, stream)
|
||||
}
|
||||
|
||||
pub(super) fn execute_request(
|
||||
session_id: &str,
|
||||
execution_id: &str,
|
||||
source: &str,
|
||||
) -> proto::ExecuteRequest {
|
||||
proto::ExecuteRequest {
|
||||
session_id: session_id.to_string(),
|
||||
execution_id: execution_id.to_string(),
|
||||
tool_call_id: "outer-call".to_string(),
|
||||
source: source.to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
yield_time_ms: Some(1),
|
||||
max_output_tokens: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn tool(name: &str) -> proto::ToolDefinition {
|
||||
proto::ToolDefinition {
|
||||
name: name.to_string(),
|
||||
tool_name: Some(proto::ToolName {
|
||||
name: name.to_string(),
|
||||
namespace: None,
|
||||
}),
|
||||
description: String::new(),
|
||||
kind: proto::ToolKind::Function as i32,
|
||||
input_schema_json: None,
|
||||
output_schema_json: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn execute_events(
|
||||
host: &GrpcCodeModeHost,
|
||||
request: proto::ExecuteRequest,
|
||||
) -> (String, GrpcStream<proto::ExecuteEvent>) {
|
||||
let mut stream = host
|
||||
.execute(Request::new(request))
|
||||
.await
|
||||
.expect("execute cell")
|
||||
.into_inner();
|
||||
let event = stream
|
||||
.next()
|
||||
.await
|
||||
.expect("execution started event")
|
||||
.expect("execution event");
|
||||
let Some(proto::execute_event::Event::Started(started)) = event.event else {
|
||||
panic!("expected execution admission before its outcome");
|
||||
};
|
||||
(started.cell_id, stream)
|
||||
}
|
||||
|
||||
fn only_text(items: &[proto::ContentItem]) -> &str {
|
||||
let [
|
||||
proto::ContentItem {
|
||||
item: Some(proto::content_item::Item::Text(text)),
|
||||
},
|
||||
] = items
|
||||
else {
|
||||
panic!("expected one text item, got {items:?}");
|
||||
};
|
||||
&text.text
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn execute_stream_starts_immediately_and_wait_preserves_missing_cells() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, mut session_events) = open_session(&host).await;
|
||||
let mut request = execute_request(
|
||||
&session_id,
|
||||
"execution-1",
|
||||
r#"text("before"); yield_control(); text("after");"#,
|
||||
);
|
||||
request.yield_time_ms = Some(60_000);
|
||||
let (cell_id, mut execution) = execute_events(&host, request).await;
|
||||
|
||||
let yielded = execution.next().await.unwrap().unwrap();
|
||||
let Some(proto::execute_event::Event::Outcome(yielded_outcome)) = &yielded.event else {
|
||||
panic!("expected execution outcome");
|
||||
};
|
||||
assert_eq!(
|
||||
yielded,
|
||||
proto::ExecuteEvent {
|
||||
event: Some(proto::execute_event::Event::Outcome(
|
||||
proto::ExecutionOutcome {
|
||||
code_mode_host_duration_ns: yielded_outcome.code_mode_host_duration_ns,
|
||||
cell_id: cell_id.clone(),
|
||||
content_items: vec![proto::ContentItem {
|
||||
item: Some(proto::content_item::Item::Text(proto::TextContent {
|
||||
text: "before".to_string(),
|
||||
})),
|
||||
}],
|
||||
outcome: Some(proto::execution_outcome::Outcome::Yielded(
|
||||
proto::ExecutionYielded {},
|
||||
)),
|
||||
}
|
||||
)),
|
||||
}
|
||||
);
|
||||
let completed = host
|
||||
.wait(Request::new(proto::WaitRequest {
|
||||
session_id: session_id.clone(),
|
||||
cell_id: cell_id.clone(),
|
||||
wait_id: "wait-1".to_string(),
|
||||
yield_time_ms: 60_000,
|
||||
max_output_tokens: None,
|
||||
}))
|
||||
.await
|
||||
.expect("wait for completion")
|
||||
.into_inner();
|
||||
let Some(proto::wait_response::State::LiveCell(completed_outcome)) = &completed.state else {
|
||||
panic!("expected live-cell wait outcome");
|
||||
};
|
||||
assert_eq!(
|
||||
completed,
|
||||
proto::WaitResponse {
|
||||
state: Some(proto::wait_response::State::LiveCell(
|
||||
proto::ExecutionOutcome {
|
||||
code_mode_host_duration_ns: completed_outcome.code_mode_host_duration_ns,
|
||||
cell_id: cell_id.clone(),
|
||||
content_items: vec![proto::ContentItem {
|
||||
item: Some(proto::content_item::Item::Text(proto::TextContent {
|
||||
text: "after".to_string(),
|
||||
})),
|
||||
}],
|
||||
outcome: Some(proto::execution_outcome::Outcome::Completed(
|
||||
proto::ExecutionCompleted { error_text: None },
|
||||
)),
|
||||
}
|
||||
)),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
session_events.next().await.unwrap().unwrap(),
|
||||
proto::SessionEvent {
|
||||
event: Some(proto::session_event::Event::CellClosed(proto::CellClosed {
|
||||
execution_id: "execution-1".to_string(),
|
||||
cell_id: cell_id.clone(),
|
||||
final_tool_call_sequence: 0,
|
||||
})),
|
||||
}
|
||||
);
|
||||
|
||||
let missing = host
|
||||
.wait(Request::new(proto::WaitRequest {
|
||||
session_id,
|
||||
cell_id: "missing-cell".to_string(),
|
||||
wait_id: "wait-missing".to_string(),
|
||||
yield_time_ms: 1,
|
||||
max_output_tokens: None,
|
||||
}))
|
||||
.await
|
||||
.expect("missing cells remain successful wait outcomes")
|
||||
.into_inner();
|
||||
assert!(matches!(
|
||||
missing.state,
|
||||
Some(proto::wait_response::State::MissingCell(_))
|
||||
));
|
||||
}
|
||||
|
||||
/// Missing, empty, and explicit default namespaces identify the same subscribed tool.
|
||||
#[tokio::test]
|
||||
async fn filtered_subscriptions_match_default_namespace_aliases() {
|
||||
let aliases = [
|
||||
(None, Some("functions".to_string())),
|
||||
(Some(String::new()), None),
|
||||
(Some("functions".to_string()), Some(String::new())),
|
||||
];
|
||||
|
||||
for (tool_namespace, filter_namespace) in aliases {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let mut subscription = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: "echo".to_string(),
|
||||
namespace: filter_namespace,
|
||||
}],
|
||||
}))
|
||||
.await
|
||||
.expect("subscribe with a default-namespace alias")
|
||||
.into_inner();
|
||||
let mut request = execute_request(
|
||||
&session_id,
|
||||
"default-namespace",
|
||||
"text(await tools.echo({}));",
|
||||
);
|
||||
request.yield_time_ms = Some(/*value*/ 60_000);
|
||||
let mut enabled_tool = tool("echo");
|
||||
enabled_tool.tool_name = Some(proto::ToolName {
|
||||
name: "echo".to_string(),
|
||||
namespace: tool_namespace.clone(),
|
||||
});
|
||||
request.enabled_tools = vec![enabled_tool];
|
||||
let (_cell_id, mut execution) = execute_events(&host, request).await;
|
||||
|
||||
let invocation = subscription
|
||||
.next()
|
||||
.await
|
||||
.expect("matching default-namespace invocation")
|
||||
.expect("tool invocation");
|
||||
assert_eq!(
|
||||
invocation.tool_name,
|
||||
Some(proto::ToolName {
|
||||
name: "echo".to_string(),
|
||||
namespace: tool_namespace,
|
||||
})
|
||||
);
|
||||
host.complete_tool_call(Request::new(proto::CompleteToolCallRequest {
|
||||
session_id,
|
||||
invocation_id: invocation.invocation_id,
|
||||
outcome: Some(proto::complete_tool_call_request::Outcome::Succeeded(
|
||||
proto::ToolCallSucceeded {
|
||||
output_json: br#""done""#.to_vec(),
|
||||
},
|
||||
)),
|
||||
}))
|
||||
.await
|
||||
.expect("complete the matching tool call");
|
||||
assert!(matches!(
|
||||
execution.next().await,
|
||||
Some(Ok(proto::ExecuteEvent {
|
||||
event: Some(proto::execute_event::Event::Outcome(
|
||||
proto::ExecutionOutcome {
|
||||
outcome: Some(proto::execution_outcome::Outcome::Completed(_)),
|
||||
..
|
||||
}
|
||||
)),
|
||||
}))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn filtered_subscriptions_receive_ordered_calls_and_unary_completions() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, mut session_events) = open_session(&host).await;
|
||||
let mut matching = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: "echo".to_string(),
|
||||
namespace: None,
|
||||
}],
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let mut unrelated = host
|
||||
.subscribe_to_tool_calls(Request::new(proto::SubscribeToToolCallsRequest {
|
||||
session_id: session_id.clone(),
|
||||
tool_names: vec![proto::ToolName {
|
||||
name: "other".to_string(),
|
||||
namespace: None,
|
||||
}],
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
let mut request = execute_request(
|
||||
&session_id,
|
||||
"execution-tools",
|
||||
r#"text(await tools.echo({value: 1})); text(await tools.echo({value: 2}));"#,
|
||||
);
|
||||
request.yield_time_ms = Some(60_000);
|
||||
request.enabled_tools = vec![tool("echo")];
|
||||
let (cell_id, mut execution) = execute_events(&host, request).await;
|
||||
|
||||
for sequence in [1, 2] {
|
||||
let invocation = matching.next().await.unwrap().unwrap();
|
||||
assert_eq!(invocation.session_id, session_id);
|
||||
assert_eq!(invocation.execution_id, "execution-tools");
|
||||
assert_eq!(invocation.cell_id, cell_id);
|
||||
assert_eq!(invocation.sequence, sequence);
|
||||
assert_eq!(
|
||||
invocation.input_json,
|
||||
Some(format!(r#"{{"value":{sequence}}}"#).into_bytes())
|
||||
);
|
||||
assert!(unrelated.next().now_or_never().is_none());
|
||||
host.complete_tool_call(Request::new(proto::CompleteToolCallRequest {
|
||||
session_id: session_id.clone(),
|
||||
invocation_id: invocation.invocation_id,
|
||||
outcome: Some(proto::complete_tool_call_request::Outcome::Succeeded(
|
||||
proto::ToolCallSucceeded {
|
||||
output_json: format!(r#""result-{sequence}""#).into_bytes(),
|
||||
},
|
||||
)),
|
||||
}))
|
||||
.await
|
||||
.expect("complete delegated tool");
|
||||
}
|
||||
|
||||
let outcome = execution.next().await.unwrap().unwrap();
|
||||
assert!(matches!(
|
||||
outcome.event,
|
||||
Some(proto::execute_event::Event::Outcome(
|
||||
proto::ExecutionOutcome {
|
||||
outcome: Some(proto::execution_outcome::Outcome::Completed(_)),
|
||||
..
|
||||
}
|
||||
))
|
||||
));
|
||||
assert_eq!(
|
||||
session_events.next().await.unwrap().unwrap(),
|
||||
proto::SessionEvent {
|
||||
event: Some(proto::session_event::Event::CellClosed(proto::CellClosed {
|
||||
execution_id: "execution-tools".to_string(),
|
||||
cell_id,
|
||||
final_tool_call_sequence: 2,
|
||||
})),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_before_wait_admission_is_preserved() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let (cell_id, mut execution) = execute_events(
|
||||
&host,
|
||||
execute_request(
|
||||
&session_id,
|
||||
"execution-wait",
|
||||
"await new Promise(() => {});",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
execution.next().await.unwrap().unwrap();
|
||||
|
||||
host.cancel_wait(Request::new(proto::CancelWaitRequest {
|
||||
session_id: session_id.clone(),
|
||||
wait_id: "pre-cancelled".to_string(),
|
||||
}))
|
||||
.await
|
||||
.expect("record cancellation before wait admission");
|
||||
let cancelled = host
|
||||
.wait(Request::new(proto::WaitRequest {
|
||||
session_id: session_id.clone(),
|
||||
cell_id: cell_id.clone(),
|
||||
wait_id: "pre-cancelled".to_string(),
|
||||
yield_time_ms: 60_000,
|
||||
max_output_tokens: Some(0),
|
||||
}))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(cancelled.code(), Code::Cancelled);
|
||||
|
||||
host.terminate(Request::new(proto::TerminateRequest {
|
||||
session_id,
|
||||
cell_id,
|
||||
max_output_tokens: Some(0),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn yield_before_observation_registration_is_remembered() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, _events) = open_session(&host).await;
|
||||
let session = host.state.session(&session_id).unwrap();
|
||||
for observation in [
|
||||
proto::yield_observation_request::Observation::ExecutionId("exec".to_string()),
|
||||
proto::yield_observation_request::Observation::WaitId("wait".to_string()),
|
||||
] {
|
||||
host.yield_observation(Request::new(proto::YieldObservationRequest {
|
||||
session_id: session_id.clone(),
|
||||
observation: Some(observation),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
assert!(session.reserve_execution("exec").unwrap().is_cancelled());
|
||||
let wait = super::waits::WaitRegistration::new(session, "wait".to_string()).unwrap();
|
||||
assert!(wait.yield_signal().is_cancelled());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notifications_do_not_delay_cell_completion() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (session_id, mut session_events) = open_session(&host).await;
|
||||
let mut request = execute_request(
|
||||
&session_id,
|
||||
"execution-notify",
|
||||
r#"notify("pending"); text("done");"#,
|
||||
);
|
||||
request.yield_time_ms = Some(60_000);
|
||||
let (cell_id, mut execution) = execute_events(&host, request).await;
|
||||
let event = session_events.next().await.unwrap().unwrap();
|
||||
let Some(proto::session_event::Event::Notification(notification)) = event.event else {
|
||||
panic!("expected pending notification");
|
||||
};
|
||||
assert_eq!(notification.execution_id, "execution-notify");
|
||||
assert_eq!(notification.cell_id, cell_id);
|
||||
assert_eq!(notification.call_id, "outer-call");
|
||||
assert_eq!(notification.text, "pending");
|
||||
assert!(matches!(
|
||||
execution.next().await.unwrap().unwrap().event,
|
||||
Some(proto::execute_event::Event::Outcome(
|
||||
proto::ExecutionOutcome {
|
||||
outcome: Some(proto::execution_outcome::Outcome::Completed(_)),
|
||||
..
|
||||
}
|
||||
))
|
||||
));
|
||||
assert_eq!(
|
||||
session_events.next().await.unwrap().unwrap(),
|
||||
proto::SessionEvent {
|
||||
event: Some(proto::session_event::Event::CellClosed(proto::CellClosed {
|
||||
execution_id: "execution-notify".to_string(),
|
||||
cell_id,
|
||||
final_tool_call_sequence: 0,
|
||||
})),
|
||||
}
|
||||
);
|
||||
host.acknowledge_notification(Request::new(proto::AcknowledgeNotificationRequest {
|
||||
session_id,
|
||||
notification_id: notification.notification_id,
|
||||
}))
|
||||
.await
|
||||
.expect("legacy notification acknowledgments remain accepted");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn output_truncation_is_a_session_setting_and_omitting_it_keeps_legacy_output() {
|
||||
for (output_truncation, bounded_output) in [
|
||||
(None, false),
|
||||
(Some(proto::OutputTruncation::Unspecified.into()), false),
|
||||
(Some(proto::OutputTruncation::Client.into()), false),
|
||||
(Some(proto::OutputTruncation::Server.into()), true),
|
||||
] {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (opened, _lease) = open_session_with_truncation(&host, output_truncation).await;
|
||||
assert_eq!(
|
||||
opened.output_truncation,
|
||||
bounded_output.then_some(proto::OutputTruncation::Server.into()),
|
||||
);
|
||||
let mut request = execute_request(
|
||||
&opened.session_id,
|
||||
"execution",
|
||||
"text('x'.repeat(2 * 1024 * 1024));",
|
||||
);
|
||||
request.yield_time_ms = Some(60_000);
|
||||
let (_, mut execution) = execute_events(&host, request).await;
|
||||
let outcome = execution
|
||||
.next()
|
||||
.await
|
||||
.expect("outcome event")
|
||||
.expect("outcome");
|
||||
let Some(proto::execute_event::Event::Outcome(outcome)) = outcome.event else {
|
||||
panic!("expected execution outcome");
|
||||
};
|
||||
assert!(matches!(
|
||||
outcome.outcome,
|
||||
Some(proto::execution_outcome::Outcome::Completed(_))
|
||||
));
|
||||
assert_eq!(
|
||||
outcome.content_items.iter().any(
|
||||
|item| matches!(&item.item, Some(proto::content_item::Item::Text(text))
|
||||
if text.text.starts_with("[Code Mode session output limit reached: omitted "))
|
||||
),
|
||||
bounded_output
|
||||
);
|
||||
if !bounded_output {
|
||||
assert_eq!(
|
||||
only_text(&outcome.content_items),
|
||||
"x".repeat(2 * 1024 * 1024)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn server_output_budgets_follow_exec_wait_and_terminate_over_grpc() {
|
||||
for (execution_id, after_yield) in [
|
||||
("failed", "throw '0123456789'.repeat(8);"),
|
||||
(
|
||||
"terminated",
|
||||
"text('0123456789'.repeat(8)); notify('ready to terminate'); await new Promise(() => {});",
|
||||
),
|
||||
] {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let (opened, mut lease) =
|
||||
open_session_with_truncation(&host, Some(proto::OutputTruncation::Server.into())).await;
|
||||
let source = format!("text('0123456789'.repeat(4)); yield_control(); {after_yield}");
|
||||
let mut request = execute_request(&opened.session_id, execution_id, &source);
|
||||
request.yield_time_ms = Some(60_000);
|
||||
request.max_output_tokens = Some(5);
|
||||
let (cell_id, mut execution) = execute_events(&host, request).await;
|
||||
let Some(proto::execute_event::Event::Outcome(first)) =
|
||||
execution.next().await.unwrap().unwrap().event
|
||||
else {
|
||||
panic!("expected execution outcome");
|
||||
};
|
||||
assert_eq!(first.cell_id, cell_id);
|
||||
assert!(matches!(
|
||||
first.outcome,
|
||||
Some(proto::execution_outcome::Outcome::Yielded(_))
|
||||
));
|
||||
assert_eq!(
|
||||
only_text(&first.content_items),
|
||||
"Warning: truncated output (original token count: 10)\nTotal output lines: 1\n\n0123456789…5 tokens truncated…0123456789"
|
||||
);
|
||||
|
||||
let response = if execution_id == "failed" {
|
||||
host.wait(Request::new(proto::WaitRequest {
|
||||
session_id: opened.session_id,
|
||||
cell_id: cell_id.clone(),
|
||||
wait_id: "wait-after-yield".to_string(),
|
||||
yield_time_ms: 60_000,
|
||||
max_output_tokens: Some(7),
|
||||
}))
|
||||
.await
|
||||
.expect("script failures are completed results, not RPC failures")
|
||||
.into_inner()
|
||||
} else {
|
||||
// The event is ordered after text in the runtime FIFO, so the
|
||||
// termination observes it without a sleep or racing the cell.
|
||||
assert!(matches!(
|
||||
lease.next().await.unwrap().unwrap().event,
|
||||
Some(proto::session_event::Event::Notification(
|
||||
proto::Notification { text, .. }
|
||||
)) if text == "ready to terminate"
|
||||
));
|
||||
host.terminate(Request::new(proto::TerminateRequest {
|
||||
session_id: opened.session_id,
|
||||
cell_id: cell_id.clone(),
|
||||
max_output_tokens: Some(7),
|
||||
}))
|
||||
.await
|
||||
.expect("terminate with an independent output budget")
|
||||
.into_inner()
|
||||
};
|
||||
let Some(proto::wait_response::State::LiveCell(last)) = response.state else {
|
||||
panic!("expected final observation from the live cell");
|
||||
};
|
||||
let expected_text = if execution_id == "failed" {
|
||||
let Some(proto::execution_outcome::Outcome::Completed(proto::ExecutionCompleted {
|
||||
error_text: Some(diagnostic),
|
||||
})) = &last.outcome
|
||||
else {
|
||||
panic!(
|
||||
"expected completed failure with a diagnostic, got {:?}",
|
||||
last.outcome
|
||||
);
|
||||
};
|
||||
assert_eq!(diagnostic, &"0123456789".repeat(8));
|
||||
"Warning: truncated output (original token count: 24)\nTotal output lines: 2\n\nScript error:\n…17 tokens truncated…67890123456789"
|
||||
} else {
|
||||
assert_eq!(
|
||||
last.outcome,
|
||||
Some(proto::execution_outcome::Outcome::Terminated(
|
||||
proto::ExecutionTerminated {}
|
||||
))
|
||||
);
|
||||
"Warning: truncated output (original token count: 20)\nTotal output lines: 1\n\n01234567890123…13 tokens truncated…67890123456789"
|
||||
};
|
||||
assert_eq!(last.cell_id, cell_id);
|
||||
assert_eq!(only_text(&last.content_items), expected_text);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_output_truncation_is_rejected_before_opening_a_session() {
|
||||
let host = GrpcCodeModeHost::new();
|
||||
let result = host
|
||||
.open_session(Request::new(proto::OpenSessionRequest {
|
||||
max_pending_delegate_calls: None,
|
||||
cell_execution_limits: None,
|
||||
output_truncation: Some(42),
|
||||
}))
|
||||
.await;
|
||||
let Err(status) = result else {
|
||||
panic!("unknown truncation mode should be rejected");
|
||||
};
|
||||
assert_eq!(status.code(), Code::InvalidArgument);
|
||||
}
|
||||
487
codex-rs/code-mode-host/src/grpc/session.rs
Normal file
487
codex-rs/code-mode-host/src/grpc/session.rs
Normal file
@@ -0,0 +1,487 @@
|
||||
use std::borrow::Borrow;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::VecDeque;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::hash::Hash;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::Weak;
|
||||
|
||||
use codex_code_mode_protocol::CellId;
|
||||
use codex_code_mode_protocol::CodeModeOutputTruncation;
|
||||
use codex_code_mode_protocol::CodeModeSession;
|
||||
use codex_code_mode_protocol::CodeModeSessionOptions;
|
||||
use codex_code_mode_protocol::TerminateRequest;
|
||||
use codex_code_mode_protocol::WaitOutcome;
|
||||
use codex_code_mode_protocol::grpc as proto;
|
||||
use codex_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use codex_code_mode_runtime::InProcessCodeModeSession;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tonic::Status;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::GrpcStream;
|
||||
use super::events::EventSender;
|
||||
use super::validation;
|
||||
use super::waits::ActiveWait;
|
||||
use crate::HostLimits;
|
||||
use crate::MAX_ACTIVE_CELLS;
|
||||
use crate::MAX_IN_FLIGHT_REQUESTS;
|
||||
use crate::MAX_RECENT_REQUEST_IDS;
|
||||
use crate::OUTGOING_CHANNEL_CAPACITY;
|
||||
|
||||
pub(super) struct GrpcHostState {
|
||||
sessions: Mutex<HashMap<Uuid, Arc<GrpcSession>>>,
|
||||
limits: HostLimits,
|
||||
delegate_permits: Arc<Semaphore>,
|
||||
control_permits: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
pub(super) struct GrpcSession {
|
||||
pub(super) id: Uuid,
|
||||
pub(super) runtime: Arc<InProcessCodeModeSession>,
|
||||
pub(super) closed: CancellationToken,
|
||||
pub(super) state: Mutex<SessionState>,
|
||||
events: EventSender,
|
||||
cells_changed: Notify,
|
||||
delegate_permits: Arc<Semaphore>,
|
||||
client_delegate_permits: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct SessionState {
|
||||
pub(super) cells: HashMap<String, ExecutionState>,
|
||||
pending_executions: HashSet<String>,
|
||||
pending_closures: HashSet<String>,
|
||||
pub(super) seen_executions: BoundedIds,
|
||||
pub(super) execution_yields: HashMap<String, CancellationToken>,
|
||||
pub(super) yielded_executions: BoundedIds,
|
||||
pub(super) subscriptions: Vec<ToolSubscription>,
|
||||
pub(super) next_subscription: usize,
|
||||
pub(super) pending_invocations: HashMap<Uuid, PendingInvocation>,
|
||||
pub(super) seen_invocations: BoundedIds<Uuid>,
|
||||
pub(super) waits: HashMap<String, ActiveWait>,
|
||||
pub(super) seen_waits: BoundedIds,
|
||||
pub(super) cancelled_waits: BoundedIds,
|
||||
pub(super) yielded_waits: BoundedIds,
|
||||
}
|
||||
|
||||
pub(super) struct ExecutionState {
|
||||
pub(super) execution_id: String,
|
||||
pub(super) traceparent: Option<String>,
|
||||
pub(super) tool_call_sequence: u64,
|
||||
permit: OwnedSemaphorePermit,
|
||||
}
|
||||
|
||||
pub(super) struct ToolSubscription {
|
||||
pub(super) id: Uuid,
|
||||
pub(super) filters: Vec<proto::ToolName>,
|
||||
pub(super) sender: mpsc::Sender<Result<proto::ToolCall, Status>>,
|
||||
}
|
||||
|
||||
pub(super) struct PendingInvocation {
|
||||
pub(super) subscription_id: Uuid,
|
||||
pub(super) response: oneshot::Sender<Result<JsonValue, String>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct BoundedIds<T = String> {
|
||||
ids: HashSet<T>,
|
||||
order: VecDeque<T>,
|
||||
}
|
||||
|
||||
impl GrpcHostState {
|
||||
pub(super) fn new() -> Self {
|
||||
Self {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
limits: HostLimits::new(),
|
||||
delegate_permits: Arc::new(Semaphore::new(MAX_PENDING_DELEGATE_CALLS)),
|
||||
control_permits: Arc::new(Semaphore::new(MAX_IN_FLIGHT_REQUESTS)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn open_session(
|
||||
self: &Arc<Self>,
|
||||
options: CodeModeSessionOptions,
|
||||
max_pending_delegate_calls: usize,
|
||||
) -> Result<GrpcStream<proto::SessionEvent>, Status> {
|
||||
let id = Uuid::new_v4();
|
||||
let (events, receiver) = mpsc::channel(OUTGOING_CHANNEL_CAPACITY);
|
||||
let closed = CancellationToken::new();
|
||||
let event_sender = EventSender::new(events.clone(), closed.clone());
|
||||
let session = GrpcSession::new(
|
||||
id,
|
||||
event_sender,
|
||||
closed,
|
||||
Arc::clone(&self.delegate_permits),
|
||||
options,
|
||||
max_pending_delegate_calls,
|
||||
);
|
||||
events
|
||||
.try_send(Ok(proto::SessionEvent {
|
||||
event: Some(proto::session_event::Event::Opened(proto::SessionOpened {
|
||||
session_id: id.to_string(),
|
||||
output_truncation: match session.runtime.output_truncation() {
|
||||
CodeModeOutputTruncation::Server => {
|
||||
Some(proto::OutputTruncation::Server.into())
|
||||
}
|
||||
CodeModeOutputTruncation::Client => None,
|
||||
},
|
||||
})),
|
||||
}))
|
||||
.map_err(|_| Status::internal("failed to publish the opened code-mode session"))?;
|
||||
let mut sessions = self.sessions.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
sessions.insert(id, Arc::clone(&session));
|
||||
drop(sessions);
|
||||
|
||||
let host = Arc::downgrade(self);
|
||||
tokio::spawn(async move {
|
||||
tokio::select! {
|
||||
_ = events.closed() => {}
|
||||
_ = session.closed.cancelled() => {}
|
||||
}
|
||||
if let Some(host) = host.upgrade() {
|
||||
host.close_lease(id, &session).await;
|
||||
} else {
|
||||
let _ = session.shutdown().await;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Box::pin(ReceiverStream::new(receiver)))
|
||||
}
|
||||
|
||||
pub(super) fn session(&self, id: &str) -> Result<Arc<GrpcSession>, Status> {
|
||||
let session_id = validation::uuid(id, "session ID")?;
|
||||
self.sessions
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.get(&session_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| Status::not_found(format!("unknown code-mode session {id}")))
|
||||
}
|
||||
|
||||
pub(super) async fn close_session(&self, id: &str) -> Result<(), Status> {
|
||||
let session_id = validation::uuid(id, "session ID")?;
|
||||
let session = self
|
||||
.sessions
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(&session_id)
|
||||
.ok_or_else(|| Status::not_found(format!("unknown code-mode session {id}")))?;
|
||||
session.shutdown().await
|
||||
}
|
||||
|
||||
async fn close_lease(&self, id: Uuid, expected: &Arc<GrpcSession>) {
|
||||
let session = {
|
||||
let mut sessions = self.sessions.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if sessions
|
||||
.get(&id)
|
||||
.is_some_and(|session| Arc::ptr_eq(session, expected))
|
||||
{
|
||||
sessions.remove(&id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(session) = session {
|
||||
let _ = session.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn request_permit(&self) -> Result<OwnedSemaphorePermit, Status> {
|
||||
self.limits.request_permit().map_err(|_| {
|
||||
Status::resource_exhausted("code-mode host has too many in-flight requests")
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn cell_permit(&self) -> Result<OwnedSemaphorePermit, Status> {
|
||||
self.limits
|
||||
.cell_permit()
|
||||
.map_err(|_| Status::resource_exhausted("code-mode host has too many active cells"))
|
||||
}
|
||||
|
||||
pub(super) fn control_permit(&self) -> Result<OwnedSemaphorePermit, Status> {
|
||||
Arc::clone(&self.control_permits)
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| {
|
||||
Status::resource_exhausted("code-mode host has too many in-flight control requests")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl GrpcSession {
|
||||
fn new(
|
||||
id: Uuid,
|
||||
events: EventSender,
|
||||
closed: CancellationToken,
|
||||
delegate_permits: Arc<Semaphore>,
|
||||
options: CodeModeSessionOptions,
|
||||
max_pending_delegate_calls: usize,
|
||||
) -> Arc<Self> {
|
||||
Arc::new_cyclic(|weak: &Weak<Self>| {
|
||||
let failure_session = weak.clone();
|
||||
let failure_handler = Arc::new(move |reason: String| {
|
||||
if let Some(session) = failure_session.upgrade() {
|
||||
tracing::warn!(session_id = %session.id, "code-mode host session failed: {reason}");
|
||||
session.closed.cancel();
|
||||
}
|
||||
});
|
||||
Self {
|
||||
id,
|
||||
runtime: Arc::new(InProcessCodeModeSession::with_options(
|
||||
options,
|
||||
Some(failure_handler),
|
||||
)),
|
||||
closed,
|
||||
state: Mutex::new(SessionState::default()),
|
||||
events,
|
||||
cells_changed: Notify::new(),
|
||||
delegate_permits,
|
||||
client_delegate_permits: Arc::new(Semaphore::new(max_pending_delegate_calls)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn shutdown(&self) -> Result<(), Status> {
|
||||
self.closed.cancel();
|
||||
{
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
for wait in state.waits.values() {
|
||||
wait.cancellation.cancel();
|
||||
}
|
||||
state.pending_invocations.clear();
|
||||
state.subscriptions.clear();
|
||||
}
|
||||
let result = self.runtime.shutdown().await.map_err(Status::internal);
|
||||
self.events.shutdown().await;
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.cells
|
||||
.clear();
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) async fn terminate(&self, request: TerminateRequest) -> Result<WaitOutcome, Status> {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.closed.cancelled() => {
|
||||
Err(Status::cancelled("code-mode session is closed"))
|
||||
}
|
||||
result = self.runtime.terminate(request) => {
|
||||
result.map_err(Status::failed_precondition)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn reserve_execution(
|
||||
&self,
|
||||
execution_id: &str,
|
||||
) -> Result<CancellationToken, Status> {
|
||||
validation::identifier(execution_id, "execution ID")?;
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if self.closed.is_cancelled() {
|
||||
return Err(Status::cancelled("code-mode session is closed"));
|
||||
}
|
||||
if state.pending_executions.contains(execution_id)
|
||||
|| state
|
||||
.cells
|
||||
.values()
|
||||
.any(|execution| execution.execution_id == execution_id)
|
||||
|| !state.seen_executions.remember(execution_id.to_string())
|
||||
{
|
||||
return Err(Status::already_exists(format!(
|
||||
"code-mode execution ID `{execution_id}` was reused"
|
||||
)));
|
||||
}
|
||||
state.pending_executions.insert(execution_id.to_string());
|
||||
let yield_signal = CancellationToken::new();
|
||||
if state.yielded_executions.remove(execution_id) {
|
||||
yield_signal.cancel();
|
||||
}
|
||||
state
|
||||
.execution_yields
|
||||
.insert(execution_id.to_string(), yield_signal.clone());
|
||||
Ok(yield_signal)
|
||||
}
|
||||
|
||||
pub(super) fn admit_execution(
|
||||
&self,
|
||||
execution_id: String,
|
||||
cell_id: String,
|
||||
permit: OwnedSemaphorePermit,
|
||||
traceparent: Option<String>,
|
||||
) -> Result<(), Status> {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if !state.pending_executions.remove(&execution_id) {
|
||||
return Err(Status::cancelled("code-mode execution was abandoned"));
|
||||
}
|
||||
let Entry::Vacant(entry) = state.cells.entry(cell_id.clone()) else {
|
||||
return Err(Status::internal(
|
||||
"code-mode runtime reused an active cell ID",
|
||||
));
|
||||
};
|
||||
entry.insert(ExecutionState {
|
||||
execution_id,
|
||||
traceparent,
|
||||
tool_call_sequence: 0,
|
||||
permit,
|
||||
});
|
||||
let closed = state.pending_closures.remove(&cell_id);
|
||||
let closed_execution = closed.then(|| state.cells.remove(&cell_id)).flatten();
|
||||
drop(state);
|
||||
self.cells_changed.notify_waiters();
|
||||
if let Some(execution) = closed_execution {
|
||||
self.send_cell_closed(&cell_id, execution);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn abandon_execution(self: &Arc<Self>, execution_id: &str) {
|
||||
let cell_id = {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
state.pending_executions.remove(execution_id);
|
||||
state.execution_yields.remove(execution_id);
|
||||
state
|
||||
.cells
|
||||
.iter()
|
||||
.find(|(_, execution)| execution.execution_id == execution_id)
|
||||
.map(|(cell_id, _)| cell_id.clone())
|
||||
};
|
||||
if let Some(cell_id) = cell_id {
|
||||
let session = Arc::clone(self);
|
||||
tokio::spawn(async move {
|
||||
let _ = session.terminate(CellId::new(cell_id).into()).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn execution_id(
|
||||
&self,
|
||||
cell_id: &str,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<String, String> {
|
||||
loop {
|
||||
let changed = self.cells_changed.notified();
|
||||
if let Some(execution_id) = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.cells
|
||||
.get(cell_id)
|
||||
.map(|execution| execution.execution_id.clone())
|
||||
{
|
||||
return Ok(execution_id);
|
||||
}
|
||||
tokio::select! {
|
||||
_ = self.closed.cancelled() => {
|
||||
return Err("code-mode session closed before cell admission".to_string());
|
||||
}
|
||||
_ = cancellation.cancelled() => {
|
||||
return Err("code-mode callback was cancelled before cell admission".to_string());
|
||||
}
|
||||
_ = changed => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn close_cell(&self, cell_id: &str) {
|
||||
let execution = {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match state.cells.remove(cell_id) {
|
||||
Some(execution) => Some(execution),
|
||||
None if state.pending_closures.len() < MAX_ACTIVE_CELLS => {
|
||||
state.pending_closures.insert(cell_id.to_string());
|
||||
None
|
||||
}
|
||||
None => {
|
||||
self.closed.cancel();
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(execution) = execution {
|
||||
self.send_cell_closed(cell_id, execution);
|
||||
}
|
||||
}
|
||||
|
||||
fn send_cell_closed(&self, cell_id: &str, execution: ExecutionState) {
|
||||
let _ = self.send_event_now(
|
||||
proto::session_event::Event::CellClosed(proto::CellClosed {
|
||||
execution_id: execution.execution_id,
|
||||
cell_id: cell_id.to_string(),
|
||||
final_tool_call_sequence: execution.tool_call_sequence,
|
||||
}),
|
||||
Some(execution.permit),
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn delegate_permit(&self) -> Result<[OwnedSemaphorePermit; 2], String> {
|
||||
let client = Arc::clone(&self.client_delegate_permits)
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| "code-mode session has too many pending delegate calls".to_string())?;
|
||||
let host = Arc::clone(&self.delegate_permits)
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| "code-mode host has too many pending delegate calls".to_string())?;
|
||||
Ok([client, host])
|
||||
}
|
||||
|
||||
pub(super) async fn send_event(
|
||||
&self,
|
||||
event: proto::session_event::Event,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<(), String> {
|
||||
self.events.send(event, cancellation).await
|
||||
}
|
||||
|
||||
pub(super) fn send_event_now(
|
||||
&self,
|
||||
event: proto::session_event::Event,
|
||||
cell_permit: Option<OwnedSemaphorePermit>,
|
||||
) -> Result<(), String> {
|
||||
self.events.send_now(event, cell_permit)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> BoundedIds<T>
|
||||
where
|
||||
T: Clone + Eq + Hash,
|
||||
{
|
||||
pub(super) fn remember(&mut self, id: T) -> bool {
|
||||
if !self.ids.insert(id.clone()) {
|
||||
return false;
|
||||
}
|
||||
self.order.push_back(id);
|
||||
while self.order.len() > MAX_RECENT_REQUEST_IDS {
|
||||
if let Some(expired) = self.order.pop_front() {
|
||||
self.ids.remove(&expired);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn contains<Q>(&self, id: &Q) -> bool
|
||||
where
|
||||
T: Borrow<Q>,
|
||||
Q: Eq + Hash + ?Sized,
|
||||
{
|
||||
self.ids.contains(id)
|
||||
}
|
||||
|
||||
pub(super) fn remove<Q>(&mut self, id: &Q) -> bool
|
||||
where
|
||||
T: Borrow<Q>,
|
||||
Q: Eq + Hash + ?Sized,
|
||||
{
|
||||
self.ids.remove(id)
|
||||
}
|
||||
}
|
||||
50
codex-rs/code-mode-host/src/grpc/validation.rs
Normal file
50
codex-rs/code-mode-host/src/grpc/validation.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use codex_code_mode_protocol::grpc as proto;
|
||||
use tonic::Status;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(super) use codex_code_mode_protocol::grpc::MAX_IDENTIFIER_BYTES;
|
||||
pub(super) const MAX_TOOL_FILTERS: usize = 64;
|
||||
|
||||
pub(super) fn identifier(value: &str, field: &str) -> Result<(), Status> {
|
||||
if value.is_empty() {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"code-mode {field} must not be empty"
|
||||
)));
|
||||
}
|
||||
bounded(value, MAX_IDENTIFIER_BYTES, field)
|
||||
}
|
||||
|
||||
pub(super) fn uuid(value: &str, field: &str) -> Result<Uuid, Status> {
|
||||
identifier(value, field)?;
|
||||
Uuid::parse_str(value)
|
||||
.map_err(|_| Status::invalid_argument(format!("code-mode {field} must be a UUID")))
|
||||
}
|
||||
|
||||
pub(super) fn bounded(value: &str, maximum: usize, field: &str) -> Result<(), Status> {
|
||||
if value.len() > maximum {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"code-mode {field} exceeds {maximum} bytes"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn tool_name(name: &proto::ToolName) -> Result<(), Status> {
|
||||
identifier(&name.name, "tool name")?;
|
||||
if let Some(namespace) = name.namespace.as_deref() {
|
||||
bounded(namespace, MAX_IDENTIFIER_BYTES, "tool namespace")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn tool_filters(filters: &[proto::ToolName]) -> Result<(), Status> {
|
||||
if filters.len() > MAX_TOOL_FILTERS {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"code-mode tool subscription exceeds {MAX_TOOL_FILTERS} filters"
|
||||
)));
|
||||
}
|
||||
for filter in filters {
|
||||
tool_name(filter)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
135
codex-rs/code-mode-host/src/grpc/waits.rs
Normal file
135
codex-rs/code-mode-host/src/grpc/waits.rs
Normal file
@@ -0,0 +1,135 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tonic::Status;
|
||||
|
||||
use super::session::GrpcSession;
|
||||
use super::validation;
|
||||
|
||||
pub(super) struct ActiveWait {
|
||||
pub(super) cancellation: CancellationToken,
|
||||
pub(super) yield_signal: CancellationToken,
|
||||
retired: CancellationToken,
|
||||
}
|
||||
|
||||
pub(super) struct WaitRegistration {
|
||||
session: Arc<GrpcSession>,
|
||||
id: String,
|
||||
cancellation: CancellationToken,
|
||||
yield_signal: CancellationToken,
|
||||
retired: CancellationToken,
|
||||
}
|
||||
|
||||
impl WaitRegistration {
|
||||
pub(super) fn new(session: Arc<GrpcSession>, id: String) -> Result<Self, Status> {
|
||||
validation::identifier(&id, "wait ID")?;
|
||||
let cancellation = CancellationToken::new();
|
||||
let yield_signal = CancellationToken::new();
|
||||
let retired = CancellationToken::new();
|
||||
let mut state = session.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if session.closed.is_cancelled() {
|
||||
return Err(Status::cancelled("code-mode session is closed"));
|
||||
}
|
||||
if state.waits.contains_key(&id) || !state.seen_waits.remember(id.clone()) {
|
||||
return Err(Status::already_exists(format!(
|
||||
"code-mode wait ID `{id}` was reused"
|
||||
)));
|
||||
}
|
||||
if state.cancelled_waits.remove(&id) {
|
||||
state.yielded_waits.remove(&id);
|
||||
return Err(Status::cancelled("code-mode wait was cancelled"));
|
||||
}
|
||||
if state.yielded_waits.remove(&id) {
|
||||
yield_signal.cancel();
|
||||
}
|
||||
state.waits.insert(
|
||||
id.clone(),
|
||||
ActiveWait {
|
||||
cancellation: cancellation.clone(),
|
||||
yield_signal: yield_signal.clone(),
|
||||
retired: retired.clone(),
|
||||
},
|
||||
);
|
||||
drop(state);
|
||||
Ok(Self {
|
||||
session,
|
||||
id,
|
||||
cancellation,
|
||||
yield_signal,
|
||||
retired,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn cancellation(&self) -> &CancellationToken {
|
||||
&self.cancellation
|
||||
}
|
||||
|
||||
pub(super) fn yield_signal(&self) -> CancellationToken {
|
||||
self.yield_signal.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WaitRegistration {
|
||||
fn drop(&mut self) {
|
||||
self.session
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.waits
|
||||
.remove(&self.id);
|
||||
self.retired.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
impl GrpcSession {
|
||||
pub(super) fn yield_execution(&self, id: &str) -> Result<(), Status> {
|
||||
validation::identifier(id, "execution ID")?;
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(signal) = state.execution_yields.get(id) {
|
||||
signal.cancel();
|
||||
} else if !state.seen_executions.contains(id) {
|
||||
state.yielded_executions.remember(id.to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn yield_wait(&self, id: &str) -> Result<(), Status> {
|
||||
validation::identifier(id, "wait ID")?;
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(wait) = state.waits.get(id) {
|
||||
wait.yield_signal.cancel();
|
||||
} else if !state.seen_waits.contains(id) {
|
||||
state.yielded_waits.remember(id.to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn retire_execution_observation(&self, id: &str) {
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.execution_yields
|
||||
.remove(id);
|
||||
}
|
||||
|
||||
pub(super) async fn cancel_wait(&self, id: &str) -> Result<(), Status> {
|
||||
validation::identifier(id, "wait ID")?;
|
||||
let active = {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(wait) = state.waits.get(id) {
|
||||
Some((wait.cancellation.clone(), wait.retired.clone()))
|
||||
} else {
|
||||
if !state.seen_waits.contains(id) {
|
||||
state.cancelled_waits.remember(id.to_string());
|
||||
}
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some((cancellation, retired)) = active {
|
||||
cancellation.cancel();
|
||||
retired.cancelled().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
88
codex-rs/code-mode-host/src/grpc_stdio.rs
Normal file
88
codex-rs/code-mode-host/src/grpc_stdio.rs
Normal file
@@ -0,0 +1,88 @@
|
||||
//! Serves one HTTP/2 gRPC connection on stdin/stdout. Stdout contains only protocol
|
||||
//! bytes, and closing the connection stops the host rather than accepting another client.
|
||||
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::task::Context;
|
||||
use std::task::Poll;
|
||||
|
||||
use anyhow::Context as _;
|
||||
use anyhow::Result;
|
||||
use codex_code_mode_protocol::grpc::code_mode_host_server::CodeModeHostServer;
|
||||
use codex_code_mode_protocol::host::MAX_FRAME_BYTES;
|
||||
use futures::StreamExt;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::io::ReadBuf;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tonic::transport::Server;
|
||||
use tonic::transport::server::Connected;
|
||||
|
||||
use crate::GrpcCodeModeHost;
|
||||
|
||||
pub(crate) async fn run(host: GrpcCodeModeHost) -> Result<()> {
|
||||
let closed = CancellationToken::new();
|
||||
let connection = StdioConnection {
|
||||
io: tokio::io::join(tokio::io::stdin(), tokio::io::stdout()),
|
||||
closed: closed.clone(),
|
||||
};
|
||||
// Keep the incoming stream open while the single connection is being served.
|
||||
let incoming = futures::stream::once(async { Ok::<_, io::Error>(connection) })
|
||||
.chain(futures::stream::pending());
|
||||
let server = Server::builder()
|
||||
.add_service(
|
||||
CodeModeHostServer::new(host)
|
||||
.max_decoding_message_size(MAX_FRAME_BYTES)
|
||||
.max_encoding_message_size(MAX_FRAME_BYTES),
|
||||
)
|
||||
.serve_with_incoming(incoming);
|
||||
tokio::select! {
|
||||
result = server => result.context("code-mode gRPC stdio connection failed"),
|
||||
_ = closed.cancelled() => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
struct StdioConnection {
|
||||
io: tokio::io::Join<tokio::io::Stdin, tokio::io::Stdout>,
|
||||
closed: CancellationToken,
|
||||
}
|
||||
|
||||
impl Connected for StdioConnection {
|
||||
type ConnectInfo = ();
|
||||
|
||||
fn connect_info(&self) -> Self::ConnectInfo {}
|
||||
}
|
||||
|
||||
impl AsyncRead for StdioConnection {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.io).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for StdioConnection {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Pin::new(&mut self.io).poll_write(cx, buf)
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.io).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.io).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StdioConnection {
|
||||
fn drop(&mut self) {
|
||||
self.closed.cancel();
|
||||
}
|
||||
}
|
||||
71
codex-rs/code-mode-host/src/grpc_transport.rs
Normal file
71
codex-rs/code-mode-host/src/grpc_transport.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
use std::io;
|
||||
use std::io::Write as _;
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use axum::extract::Request;
|
||||
use axum::http::Method;
|
||||
use axum::http::StatusCode;
|
||||
use axum::http::Version;
|
||||
use axum::middleware;
|
||||
use axum::middleware::Next;
|
||||
use axum::routing::get;
|
||||
use codex_code_mode_protocol::grpc::code_mode_host_server::CodeModeHostServer;
|
||||
use codex_code_mode_protocol::host::MAX_FRAME_BYTES;
|
||||
use tokio::net::TcpListener;
|
||||
use tonic::service::Routes;
|
||||
use tonic::transport::Server;
|
||||
use tonic::transport::server::TcpIncoming;
|
||||
use tracing::info;
|
||||
|
||||
use crate::GrpcCodeModeHost;
|
||||
|
||||
pub(super) async fn run_tcp_listener(
|
||||
bind_address: SocketAddr,
|
||||
host: GrpcCodeModeHost,
|
||||
) -> Result<()> {
|
||||
let listener = bind_tcp_listener(bind_address).await?;
|
||||
let local_address = listener
|
||||
.local_addr()
|
||||
.context("failed to read code-mode gRPC listen address")?;
|
||||
info!("codex-code-mode-host listening on http://{local_address}");
|
||||
println!("http://{local_address}");
|
||||
io::stdout()
|
||||
.flush()
|
||||
.context("failed to publish code-mode gRPC listen address")?;
|
||||
|
||||
let routes = Routes::new(
|
||||
CodeModeHostServer::new(host)
|
||||
.send_compressed(tonic::codec::CompressionEncoding::Zstd)
|
||||
.max_decoding_message_size(MAX_FRAME_BYTES)
|
||||
.max_encoding_message_size(MAX_FRAME_BYTES),
|
||||
)
|
||||
.into_axum_router()
|
||||
.route("/healthz", get(|| async { StatusCode::OK }))
|
||||
.layer(middleware::from_fn(
|
||||
|request: Request, next: Next| async move {
|
||||
if request.version() != Version::HTTP_2
|
||||
&& (request.method() != Method::GET || request.uri().path() != "/healthz")
|
||||
{
|
||||
return Err(StatusCode::HTTP_VERSION_NOT_SUPPORTED);
|
||||
}
|
||||
|
||||
Ok(next.run(request).await)
|
||||
},
|
||||
));
|
||||
|
||||
Server::builder()
|
||||
.accept_http1(/*accept_http1*/ true)
|
||||
.add_routes(routes.into())
|
||||
.serve_with_incoming(listener)
|
||||
.await
|
||||
.context("code-mode gRPC TCP listener failed")
|
||||
}
|
||||
|
||||
pub(super) async fn bind_tcp_listener(bind_address: SocketAddr) -> Result<TcpIncoming> {
|
||||
let listener = TcpListener::bind(bind_address)
|
||||
.await
|
||||
.with_context(|| format!("failed to bind code-mode gRPC host to {bind_address}"))?;
|
||||
Ok(TcpIncoming::from(listener).with_nodelay(Some(true)))
|
||||
}
|
||||
816
codex-rs/code-mode-host/src/host_tests.rs
Normal file
816
codex-rs/code-mode-host/src/host_tests.rs
Normal file
@@ -0,0 +1,816 @@
|
||||
use std::collections::HashMap;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::task::Context;
|
||||
use std::task::Poll;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_code_mode_protocol::CodeModeSessionOptions;
|
||||
use codex_code_mode_protocol::TerminateRequest;
|
||||
use codex_code_mode_protocol::host::BOUNDED_OUTPUT_CAPABILITY;
|
||||
use codex_code_mode_protocol::host::Capability;
|
||||
use codex_code_mode_protocol::host::CapabilitySet;
|
||||
use codex_code_mode_protocol::host::ClientHello;
|
||||
use codex_code_mode_protocol::host::ClientToHost;
|
||||
use codex_code_mode_protocol::host::EncodedFrame;
|
||||
use codex_code_mode_protocol::host::FramedReader;
|
||||
use codex_code_mode_protocol::host::FramedWriter;
|
||||
use codex_code_mode_protocol::host::HandshakeRejectReason;
|
||||
use codex_code_mode_protocol::host::HostHello;
|
||||
use codex_code_mode_protocol::host::HostRequest;
|
||||
use codex_code_mode_protocol::host::HostResponse;
|
||||
use codex_code_mode_protocol::host::HostToClient;
|
||||
use codex_code_mode_protocol::host::LARGE_DELEGATE_CAPACITY_CAPABILITY;
|
||||
use codex_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use codex_code_mode_protocol::host::ProtocolVersion;
|
||||
use codex_code_mode_protocol::host::RequestId;
|
||||
use codex_code_mode_protocol::host::SESSION_RESOURCE_LIMITS_CAPABILITY;
|
||||
use codex_code_mode_protocol::host::SessionId;
|
||||
use codex_code_mode_protocol::host::SupportedProtocolVersions;
|
||||
use codex_code_mode_protocol::host::WireContentItem;
|
||||
use codex_code_mode_protocol::host::WireExecuteRequest;
|
||||
use codex_code_mode_protocol::host::WireOutputTruncation;
|
||||
use codex_code_mode_protocol::host::WireResult;
|
||||
use codex_code_mode_protocol::host::WireRuntimeResponse;
|
||||
use codex_code_mode_protocol::host::WireWaitOutcome;
|
||||
use codex_code_mode_protocol::host::WireWaitRequest;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::TaskTracker;
|
||||
|
||||
use super::HostLimits;
|
||||
use super::HostState;
|
||||
use super::MAX_IN_FLIGHT_REQUESTS;
|
||||
use super::MAX_RECENT_REQUEST_IDS;
|
||||
use super::RequestKind;
|
||||
use super::RequestRegistry;
|
||||
use super::SeenSessionIds;
|
||||
use super::peer::HostPeer;
|
||||
use super::run;
|
||||
|
||||
fn client_hello(
|
||||
versions: impl IntoIterator<Item = ProtocolVersion>,
|
||||
required_capabilities: CapabilitySet,
|
||||
) -> ClientToHost {
|
||||
ClientToHost::ClientHello(
|
||||
ClientHello::new(
|
||||
SupportedProtocolVersions::try_new(versions).expect("supported versions"),
|
||||
required_capabilities,
|
||||
CapabilitySet::empty(),
|
||||
)
|
||||
.expect("client hello"),
|
||||
)
|
||||
}
|
||||
|
||||
fn session_id(value: &str) -> SessionId {
|
||||
SessionId::new(value).expect("session ID")
|
||||
}
|
||||
|
||||
fn request_id(value: i64) -> RequestId {
|
||||
RequestId::new(value)
|
||||
}
|
||||
|
||||
async fn decode_frame(frame: EncodedFrame) -> HostToClient {
|
||||
let (reader, writer) = tokio::io::duplex(/*max_buf_size*/ 4096);
|
||||
let writer = tokio::spawn(async move {
|
||||
FramedWriter::new(writer)
|
||||
.write_frame(&frame)
|
||||
.await
|
||||
.expect("write encoded frame");
|
||||
});
|
||||
let message = FramedReader::new(reader)
|
||||
.read()
|
||||
.await
|
||||
.expect("read encoded frame")
|
||||
.expect("encoded frame message");
|
||||
writer.await.expect("frame writer task");
|
||||
message
|
||||
}
|
||||
|
||||
fn execute_request(source: &str) -> WireExecuteRequest {
|
||||
WireExecuteRequest {
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
source: source.to_string(),
|
||||
yield_time_ms: Some(60_000),
|
||||
max_output_tokens: Some(1_000),
|
||||
}
|
||||
}
|
||||
|
||||
async fn next_response(reader: &mut FramedReader<impl AsyncRead + Unpin>) -> HostToClient {
|
||||
loop {
|
||||
match reader
|
||||
.read()
|
||||
.await
|
||||
.expect("host response")
|
||||
.expect("host connected")
|
||||
{
|
||||
HostToClient::CellClosed { .. } => {}
|
||||
message => return message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn handshake_and_multiple_session_lifecycles_are_ordered() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 4096);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
|
||||
writer
|
||||
.write(&client_hello([ProtocolVersion::V1], CapabilitySet::empty()))
|
||||
.await
|
||||
.expect("write hello");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("read hello"),
|
||||
Some(HostToClient::HostHello(HostHello::new(
|
||||
ProtocolVersion::V1,
|
||||
CapabilitySet::empty(),
|
||||
)))
|
||||
);
|
||||
|
||||
for (request_id, id) in [
|
||||
(request_id(/*value*/ 1), "session-1"),
|
||||
(request_id(/*value*/ 2), "session-2"),
|
||||
] {
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id,
|
||||
request: HostRequest::OpenSession {
|
||||
session_id: session_id(id),
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("open session");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("session ready"),
|
||||
Some(HostToClient::Response {
|
||||
id: request_id,
|
||||
result: WireResult::Ok {
|
||||
value: HostResponse::SessionReady {
|
||||
session_id: session_id(id),
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
for (request_id, id) in [
|
||||
(request_id(/*value*/ 3), "session-1"),
|
||||
(request_id(/*value*/ 4), "session-2"),
|
||||
] {
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id,
|
||||
request: HostRequest::ShutdownSession {
|
||||
session_id: session_id(id),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("shutdown session");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("session closed"),
|
||||
Some(HostToClient::Response {
|
||||
id: request_id,
|
||||
result: WireResult::Ok {
|
||||
value: HostResponse::SessionClosed {
|
||||
session_id: session_id(id),
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
drop(writer);
|
||||
drop(reader);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disconnect_cancels_a_backpressured_host_writer() {
|
||||
let (host_reader, client_writer) = tokio::io::duplex(/*max_buf_size*/ 4096);
|
||||
let (blocked_tx, blocked_rx) = oneshot::channel();
|
||||
let host = tokio::spawn(run(
|
||||
host_reader,
|
||||
BlockingWriter {
|
||||
blocked_tx: Some(blocked_tx),
|
||||
handshake_flushed: false,
|
||||
},
|
||||
));
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
|
||||
writer
|
||||
.write(&client_hello([ProtocolVersion::V1], CapabilitySet::empty()))
|
||||
.await
|
||||
.expect("write client hello");
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id(/*value*/ 1),
|
||||
request: HostRequest::OpenSession {
|
||||
session_id: session_id("backpressured-session"),
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("write session-open request");
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(1), blocked_rx)
|
||||
.await
|
||||
.expect("host writer should reach backpressure")
|
||||
.expect("host writer should report backpressure");
|
||||
|
||||
writer
|
||||
.write(&client_hello([ProtocolVersion::V1], CapabilitySet::empty()))
|
||||
.await
|
||||
.expect("write invalid second client hello");
|
||||
|
||||
let error = tokio::time::timeout(Duration::from_secs(1), host)
|
||||
.await
|
||||
.expect("disconnect should cancel the backpressured writer")
|
||||
.expect("host task should finish")
|
||||
.expect_err("a second client hello should fail the connection");
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"received a second code-mode client hello"
|
||||
);
|
||||
}
|
||||
|
||||
struct BlockingWriter {
|
||||
blocked_tx: Option<oneshot::Sender<()>>,
|
||||
handshake_flushed: bool,
|
||||
}
|
||||
|
||||
impl AsyncWrite for BlockingWriter {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
_cx: &mut Context<'_>,
|
||||
bytes: &[u8],
|
||||
) -> Poll<std::io::Result<usize>> {
|
||||
if self.handshake_flushed {
|
||||
if let Some(blocked_tx) = self.blocked_tx.take() {
|
||||
let _ = blocked_tx.send(());
|
||||
}
|
||||
Poll::Pending
|
||||
} else {
|
||||
Poll::Ready(Ok(bytes.len()))
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
self.handshake_flushed = true;
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn supported_capabilities_are_negotiated_when_optional_or_required() {
|
||||
for capability in [
|
||||
SESSION_RESOURCE_LIMITS_CAPABILITY,
|
||||
BOUNDED_OUTPUT_CAPABILITY,
|
||||
LARGE_DELEGATE_CAPACITY_CAPABILITY,
|
||||
] {
|
||||
let capability = Capability::new(capability).expect("supported capability");
|
||||
let host_capabilities =
|
||||
CapabilitySet::try_new([capability.clone()]).expect("host capabilities");
|
||||
|
||||
for (required, optional) in [
|
||||
(
|
||||
CapabilitySet::empty(),
|
||||
CapabilitySet::try_new([capability]).expect("optional capabilities"),
|
||||
),
|
||||
(host_capabilities.clone(), CapabilitySet::empty()),
|
||||
] {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 1024);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
|
||||
writer
|
||||
.write(&ClientToHost::ClientHello(
|
||||
ClientHello::new(
|
||||
SupportedProtocolVersions::try_new([ProtocolVersion::V1])
|
||||
.expect("supported versions"),
|
||||
required,
|
||||
optional,
|
||||
)
|
||||
.expect("client hello"),
|
||||
))
|
||||
.await
|
||||
.expect("write hello");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("host hello"),
|
||||
Some(HostToClient::HostHello(HostHello::new(
|
||||
ProtocolVersion::V1,
|
||||
host_capabilities.clone(),
|
||||
)))
|
||||
);
|
||||
|
||||
drop(writer);
|
||||
drop(reader);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn output_selection_is_per_session() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 4096);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
writer
|
||||
.write(&client_hello([ProtocolVersion::V1], CapabilitySet::empty()))
|
||||
.await
|
||||
.expect("write hello");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("host hello"),
|
||||
Some(HostToClient::HostHello(HostHello::new(
|
||||
ProtocolVersion::V1,
|
||||
CapabilitySet::empty(),
|
||||
)))
|
||||
);
|
||||
for (id, name, output_truncation) in [
|
||||
(1, "client", None),
|
||||
(2, "server", Some(WireOutputTruncation::Server)),
|
||||
] {
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id(id),
|
||||
request: HostRequest::OpenSession {
|
||||
session_id: session_id(name),
|
||||
cell_execution_limits: None,
|
||||
output_truncation,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("open session");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("session ready"),
|
||||
Some(HostToClient::Response {
|
||||
id: request_id(id),
|
||||
result: WireResult::Ok {
|
||||
value: HostResponse::SessionReady {
|
||||
session_id: session_id(name),
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
for (id, name, expected_text, expected_wait) in [
|
||||
(
|
||||
3,
|
||||
"client",
|
||||
"0123456789012345678901234567890123456789",
|
||||
"01234567890123456789012345678901234567890123456789012345678901234567890123456789",
|
||||
),
|
||||
(
|
||||
4,
|
||||
"server",
|
||||
"Warning: truncated output (original token count: 10)\nTotal output lines: 1\n\n0123456789…5 tokens truncated…0123456789",
|
||||
"Warning: truncated output (original token count: 20)\nTotal output lines: 1\n\n01234567890123…13 tokens truncated…67890123456789",
|
||||
),
|
||||
] {
|
||||
let mut request = execute_request(
|
||||
"text('0123456789'.repeat(4)); yield_control(); text('0123456789'.repeat(8));",
|
||||
);
|
||||
request.max_output_tokens = Some(5);
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id(id),
|
||||
request: HostRequest::Execute {
|
||||
session_id: session_id(name),
|
||||
request,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("execute");
|
||||
// Admission is sent before start_cell can send its initial result.
|
||||
assert!(matches!(
|
||||
next_response(&mut reader).await,
|
||||
HostToClient::Response {
|
||||
id: actual_id,
|
||||
result: WireResult::Ok { value: HostResponse::ExecutionStarted { .. } },
|
||||
} if actual_id == request_id(id)
|
||||
));
|
||||
let HostToClient::InitialResponse {
|
||||
id: actual_id,
|
||||
result:
|
||||
WireResult::Ok {
|
||||
value:
|
||||
WireRuntimeResponse::Yielded {
|
||||
cell_id,
|
||||
content_items,
|
||||
..
|
||||
},
|
||||
},
|
||||
} = next_response(&mut reader).await
|
||||
else {
|
||||
panic!("expected initial yield");
|
||||
};
|
||||
assert_eq!(actual_id, request_id(id));
|
||||
assert_eq!(
|
||||
content_items,
|
||||
vec![WireContentItem::InputText {
|
||||
text: expected_text.to_string()
|
||||
}]
|
||||
);
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id(id + 2),
|
||||
request: HostRequest::Wait {
|
||||
session_id: session_id(name),
|
||||
request: WireWaitRequest {
|
||||
cell_id,
|
||||
yield_time_ms: 60_000,
|
||||
},
|
||||
// A supplied budget only affects Server mode and belongs
|
||||
// to this observation, not the preceding exec.
|
||||
max_output_tokens: Some(7),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("wait");
|
||||
let HostToClient::Response {
|
||||
id: actual_id,
|
||||
result:
|
||||
WireResult::Ok {
|
||||
value:
|
||||
HostResponse::WaitCompleted {
|
||||
outcome:
|
||||
WireWaitOutcome::LiveCell(WireRuntimeResponse::Result {
|
||||
content_items,
|
||||
error_text,
|
||||
..
|
||||
}),
|
||||
},
|
||||
},
|
||||
} = next_response(&mut reader).await
|
||||
else {
|
||||
panic!("expected final wait");
|
||||
};
|
||||
assert_eq!(actual_id, request_id(id + 2));
|
||||
assert_eq!(error_text, None);
|
||||
assert_eq!(
|
||||
content_items,
|
||||
vec![WireContentItem::InputText {
|
||||
text: expected_wait.to_string()
|
||||
}]
|
||||
);
|
||||
}
|
||||
drop(writer);
|
||||
drop(reader);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn incompatible_or_invalid_handshake_is_rejected() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 1024);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
let version_two = ProtocolVersion::new(/*value*/ 2).expect("protocol version");
|
||||
|
||||
writer
|
||||
.write(&client_hello([version_two], CapabilitySet::empty()))
|
||||
.await
|
||||
.expect("write hello");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("rejection"),
|
||||
Some(HostToClient::HandshakeRejected {
|
||||
reason: HandshakeRejectReason::NoCompatibleVersion {
|
||||
supported_versions: SupportedProtocolVersions::try_new([ProtocolVersion::V1])
|
||||
.expect("host versions"),
|
||||
},
|
||||
})
|
||||
);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 1024);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id(/*value*/ 1),
|
||||
request: HostRequest::OpenSession {
|
||||
session_id: session_id("session-1"),
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("write invalid first message");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("rejection"),
|
||||
Some(HostToClient::HandshakeRejected {
|
||||
reason: HandshakeRejectReason::InvalidHello {
|
||||
message: "first message must be connection/hello".to_string(),
|
||||
},
|
||||
})
|
||||
);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unsupported_required_capability_is_rejected() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 1024);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
let capability = Capability::new("required").expect("capability");
|
||||
|
||||
writer
|
||||
.write(&client_hello(
|
||||
[ProtocolVersion::V1],
|
||||
CapabilitySet::try_new([capability.clone()]).expect("capabilities"),
|
||||
))
|
||||
.await
|
||||
.expect("write hello");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("rejection"),
|
||||
Some(HostToClient::HandshakeRejected {
|
||||
reason: HandshakeRejectReason::MissingRequiredCapability { capability },
|
||||
})
|
||||
);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_id_cannot_be_reused_after_shutdown() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 2048);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
writer
|
||||
.write(&client_hello([ProtocolVersion::V1], CapabilitySet::empty()))
|
||||
.await
|
||||
.expect("write hello");
|
||||
reader
|
||||
.read::<HostToClient>()
|
||||
.await
|
||||
.expect("read hello")
|
||||
.expect("host hello");
|
||||
|
||||
let id = session_id("session-1");
|
||||
for (request_id, request) in [
|
||||
(
|
||||
request_id(/*value*/ 1),
|
||||
HostRequest::OpenSession {
|
||||
session_id: id.clone(),
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
request_id(/*value*/ 2),
|
||||
HostRequest::ShutdownSession {
|
||||
session_id: id.clone(),
|
||||
},
|
||||
),
|
||||
] {
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id,
|
||||
request,
|
||||
})
|
||||
.await
|
||||
.expect("session request");
|
||||
reader
|
||||
.read::<HostToClient>()
|
||||
.await
|
||||
.expect("session response")
|
||||
.expect("session response message");
|
||||
}
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id(/*value*/ 3),
|
||||
request: HostRequest::OpenSession {
|
||||
session_id: id,
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("reuse session ID");
|
||||
assert_eq!(
|
||||
reader.read::<HostToClient>().await.expect("reuse response"),
|
||||
Some(HostToClient::Response {
|
||||
id: request_id(/*value*/ 3),
|
||||
result: WireResult::Err {
|
||||
message: "code-mode session ID `session-1` was reused".to_string(),
|
||||
},
|
||||
})
|
||||
);
|
||||
drop(writer);
|
||||
drop(reader);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_history_is_bounded() {
|
||||
let mut requests = RequestRegistry::default();
|
||||
let duplicate = request_id(/*value*/ -1);
|
||||
requests
|
||||
.start(duplicate, RequestKind::OpenSession)
|
||||
.expect("start duplicate probe");
|
||||
assert!(requests.start(duplicate, RequestKind::OpenSession).is_err());
|
||||
requests.finish(duplicate);
|
||||
for value in 1..=MAX_RECENT_REQUEST_IDS as i64 + 100 {
|
||||
let id = request_id(value);
|
||||
requests
|
||||
.start(id, RequestKind::Wait)
|
||||
.expect("start request");
|
||||
requests.cancel(id);
|
||||
requests.finish(id);
|
||||
}
|
||||
assert!(requests.active.is_empty());
|
||||
assert_eq!(requests.recent.len(), MAX_RECENT_REQUEST_IDS);
|
||||
assert_eq!(requests.recent_order.len(), MAX_RECENT_REQUEST_IDS);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_task_panic_disconnects_host() {
|
||||
let (outgoing_tx, _outgoing_rx) = mpsc::channel(/*max_capacity*/ 1);
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
let state = HostState {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
limits: Arc::new(HostLimits::new()),
|
||||
seen_session_ids: Mutex::new(SeenSessionIds::default()),
|
||||
requests: Mutex::new(RequestRegistry::default()),
|
||||
request_tasks: TaskTracker::new(),
|
||||
closing: AtomicBool::new(false),
|
||||
peer: Arc::clone(&peer),
|
||||
};
|
||||
let task = state.request_tasks.spawn(async {
|
||||
panic!("request panic probe");
|
||||
});
|
||||
state.supervise_request_task(task);
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(1), peer.disconnected())
|
||||
.await
|
||||
.expect("request panic should disconnect host");
|
||||
assert!(
|
||||
peer.failure()
|
||||
.expect("request failure")
|
||||
.contains("request task failed")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn execute_request_id_remains_active_until_initial_response() {
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(/*max_capacity*/ 4);
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
let state = Arc::new(HostState {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
limits: Arc::new(HostLimits::new()),
|
||||
seen_session_ids: Mutex::new(SeenSessionIds::default()),
|
||||
requests: Mutex::new(RequestRegistry::default()),
|
||||
request_tasks: TaskTracker::new(),
|
||||
closing: AtomicBool::new(false),
|
||||
peer,
|
||||
});
|
||||
let session_id = session_id("session-1");
|
||||
state
|
||||
.open_session(session_id.clone(), CodeModeSessionOptions::default())
|
||||
.expect("open session");
|
||||
let request_id = request_id(/*value*/ 1);
|
||||
|
||||
state
|
||||
.spawn_request(
|
||||
request_id,
|
||||
HostRequest::Execute {
|
||||
session_id: session_id.clone(),
|
||||
request: execute_request("await new Promise(() => {});"),
|
||||
},
|
||||
)
|
||||
.expect("spawn execute request");
|
||||
let started = decode_frame(outgoing_rx.recv().await.expect("execution started frame")).await;
|
||||
let HostToClient::Response {
|
||||
id,
|
||||
result:
|
||||
WireResult::Ok {
|
||||
value: HostResponse::ExecutionStarted { cell_id },
|
||||
},
|
||||
} = started
|
||||
else {
|
||||
panic!("expected execution started response");
|
||||
};
|
||||
assert_eq!(id, request_id);
|
||||
assert!(
|
||||
state
|
||||
.requests
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.active
|
||||
.contains_key(&request_id)
|
||||
);
|
||||
|
||||
state
|
||||
.session(&session_id)
|
||||
.expect("session")
|
||||
.terminate(TerminateRequest {
|
||||
cell_id: cell_id.into(),
|
||||
max_output_tokens: None,
|
||||
})
|
||||
.await
|
||||
.expect("terminate cell");
|
||||
state.disconnect().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn active_cell_limit_rejects_execute_without_disconnecting() {
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(/*max_capacity*/ 1);
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
let state = HostState {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
limits: Arc::new(HostLimits {
|
||||
request_permits: Arc::new(Semaphore::new(MAX_IN_FLIGHT_REQUESTS)),
|
||||
active_cell_permits: Arc::new(Semaphore::new(/*permits*/ 0)),
|
||||
}),
|
||||
seen_session_ids: Mutex::new(SeenSessionIds::default()),
|
||||
requests: Mutex::new(RequestRegistry::default()),
|
||||
request_tasks: TaskTracker::new(),
|
||||
closing: AtomicBool::new(false),
|
||||
peer: Arc::clone(&peer),
|
||||
};
|
||||
let session_id = session_id("session-1");
|
||||
state
|
||||
.open_session(session_id.clone(), CodeModeSessionOptions::default())
|
||||
.expect("open session");
|
||||
let request_id = request_id(/*value*/ 1);
|
||||
|
||||
state
|
||||
.handle_request(
|
||||
request_id,
|
||||
HostRequest::Execute {
|
||||
session_id,
|
||||
request: execute_request("text(\"hello\");"),
|
||||
},
|
||||
CancellationToken::new(),
|
||||
CancellationToken::new(),
|
||||
Instant::now(),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
decode_frame(outgoing_rx.recv().await.expect("execute response frame")).await,
|
||||
HostToClient::Response {
|
||||
id: request_id,
|
||||
result: WireResult::Err {
|
||||
message: "code-mode host has too many active cells".to_string(),
|
||||
},
|
||||
}
|
||||
);
|
||||
assert!(!peer.is_disconnected());
|
||||
state.disconnect().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cell_forwarding_panic_disconnects_host() {
|
||||
let (outgoing_tx, _outgoing_rx) = mpsc::channel(/*max_capacity*/ 1);
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
peer.spawn_critical("cell forwarding", async {
|
||||
panic!("cell forwarding panic probe");
|
||||
});
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(1), peer.disconnected())
|
||||
.await
|
||||
.expect("cell panic should disconnect host");
|
||||
assert!(
|
||||
peer.failure()
|
||||
.expect("cell failure")
|
||||
.contains("cell forwarding task failed")
|
||||
);
|
||||
}
|
||||
798
codex-rs/code-mode-host/src/lib.rs
Normal file
798
codex-rs/code-mode-host/src/lib.rs
Normal file
@@ -0,0 +1,798 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_code_mode_protocol::CodeModeOutputTruncation;
|
||||
use codex_code_mode_protocol::CodeModeSessionCellExecutionLimits;
|
||||
use codex_code_mode_protocol::CodeModeSessionOptions;
|
||||
use codex_code_mode_protocol::TerminateRequest;
|
||||
use codex_code_mode_protocol::WaitRequest;
|
||||
use codex_code_mode_protocol::host::BOUNDED_OUTPUT_CAPABILITY;
|
||||
use codex_code_mode_protocol::host::Capability;
|
||||
use codex_code_mode_protocol::host::CapabilitySet;
|
||||
use codex_code_mode_protocol::host::ClientToHost;
|
||||
use codex_code_mode_protocol::host::EncodedFrame;
|
||||
use codex_code_mode_protocol::host::FramedReader;
|
||||
use codex_code_mode_protocol::host::FramedWriter;
|
||||
use codex_code_mode_protocol::host::HandshakeRejectReason;
|
||||
use codex_code_mode_protocol::host::HostHello;
|
||||
use codex_code_mode_protocol::host::HostRequest;
|
||||
use codex_code_mode_protocol::host::HostResponse;
|
||||
use codex_code_mode_protocol::host::HostToClient;
|
||||
use codex_code_mode_protocol::host::LARGE_DELEGATE_CAPACITY_CAPABILITY;
|
||||
use codex_code_mode_protocol::host::LEGACY_MAX_PENDING_DELEGATE_CALLS;
|
||||
use codex_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use codex_code_mode_protocol::host::ProtocolVersion;
|
||||
use codex_code_mode_protocol::host::RequestId;
|
||||
use codex_code_mode_protocol::host::SESSION_RESOURCE_LIMITS_CAPABILITY;
|
||||
use codex_code_mode_protocol::host::SessionId;
|
||||
use codex_code_mode_protocol::host::SupportedProtocolVersions;
|
||||
use codex_code_mode_protocol::host::WireWaitOutcome;
|
||||
use codex_code_mode_protocol::host::YIELD_OBSERVATION_CAPABILITY;
|
||||
use codex_code_mode_runtime::InProcessCodeModeSession;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::TryAcquireError;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::TaskTracker;
|
||||
|
||||
use self::delegate::RemoteDelegate;
|
||||
use self::peer::HostPeer;
|
||||
|
||||
pub use self::grpc::GrpcCodeModeHost;
|
||||
pub use self::process_metrics::CodeModeProcessMetricsCollector;
|
||||
pub use self::transport::DEFAULT_LISTEN_URL;
|
||||
pub use codex_code_mode_protocol::CodeModeProcessMetrics;
|
||||
|
||||
mod delegate;
|
||||
mod grpc;
|
||||
mod grpc_stdio;
|
||||
mod grpc_transport;
|
||||
mod peer;
|
||||
mod process_metrics;
|
||||
mod transport;
|
||||
|
||||
// A host is shared by independent chats and all their subagents.
|
||||
// Test live V8 isolates before increasing this, not just cell permit capacity.
|
||||
const MAX_ACTIVE_CELLS: usize = 2_048;
|
||||
// Leave observation and control headroom during a full callback-completion burst.
|
||||
const MAX_IN_FLIGHT_REQUESTS: usize = MAX_PENDING_DELEGATE_CALLS * 2;
|
||||
const MAX_RECENT_REQUEST_IDS: usize = 4096;
|
||||
const MAX_RECENT_SESSION_IDS: usize = 4096;
|
||||
const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
// Allow a full callback-completion burst plus concurrent control messages.
|
||||
const OUTGOING_CHANNEL_CAPACITY: usize = MAX_PENDING_DELEGATE_CALLS * 2;
|
||||
|
||||
enum NegotiatedConnection {
|
||||
Rejected,
|
||||
Accepted { max_pending_delegate_calls: usize },
|
||||
}
|
||||
|
||||
struct HostLimits {
|
||||
request_permits: Arc<Semaphore>,
|
||||
active_cell_permits: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl HostLimits {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
request_permits: Arc::new(Semaphore::new(MAX_IN_FLIGHT_REQUESTS)),
|
||||
active_cell_permits: Arc::new(Semaphore::new(MAX_ACTIVE_CELLS)),
|
||||
}
|
||||
}
|
||||
|
||||
fn request_permit(&self) -> Result<OwnedSemaphorePermit, TryAcquireError> {
|
||||
Arc::clone(&self.request_permits).try_acquire_owned()
|
||||
}
|
||||
|
||||
fn cell_permit(&self) -> Result<OwnedSemaphorePermit, TryAcquireError> {
|
||||
Arc::clone(&self.active_cell_permits).try_acquire_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the code-mode host on its configured stdio or gRPC transport.
|
||||
#[tracing::instrument(
|
||||
name = "code_mode_host.run_main",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(otel.name = "code_mode_host.run_main")
|
||||
)]
|
||||
pub async fn run_main(listen_url: &str) -> Result<()> {
|
||||
transport::run_transport(listen_url, GrpcCodeModeHost::new()).await
|
||||
}
|
||||
|
||||
/// Runs with an optional gRPC metrics collector initialized before sandbox entry.
|
||||
/// The legacy stdio transport remains unchanged.
|
||||
pub async fn run_main_with_process_metrics(
|
||||
listen_url: &str,
|
||||
collector: CodeModeProcessMetricsCollector,
|
||||
) -> Result<()> {
|
||||
transport::run_transport(
|
||||
listen_url,
|
||||
GrpcCodeModeHost::with_process_metrics(collector),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Runs one code-mode host connection over the process standard streams.
|
||||
pub async fn run_stdio() -> Result<()> {
|
||||
run(tokio::io::stdin(), tokio::io::stdout()).await
|
||||
}
|
||||
|
||||
/// Runs one code-mode host connection over an ordered input/output pair.
|
||||
async fn run<R, W>(reader: R, writer: W) -> Result<()>
|
||||
where
|
||||
R: AsyncRead + Send + Unpin + 'static,
|
||||
W: AsyncWrite + Send + Unpin + 'static,
|
||||
{
|
||||
let mut reader = FramedReader::new(reader);
|
||||
let mut writer = FramedWriter::new(writer);
|
||||
let max_pending_delegate_calls = match negotiate(&mut reader, &mut writer).await? {
|
||||
NegotiatedConnection::Rejected => return Ok(()),
|
||||
NegotiatedConnection::Accepted {
|
||||
max_pending_delegate_calls,
|
||||
} => max_pending_delegate_calls,
|
||||
};
|
||||
let (outgoing_tx, outgoing_rx) = mpsc::channel::<EncodedFrame>(OUTGOING_CHANNEL_CAPACITY);
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, max_pending_delegate_calls));
|
||||
let state = Arc::new(HostState {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
limits: Arc::new(HostLimits::new()),
|
||||
seen_session_ids: Mutex::new(SeenSessionIds::default()),
|
||||
requests: Mutex::new(RequestRegistry::default()),
|
||||
request_tasks: TaskTracker::new(),
|
||||
closing: AtomicBool::new(false),
|
||||
peer: Arc::clone(&peer),
|
||||
});
|
||||
let writer_disconnected = peer.disconnection_token();
|
||||
let writer_task =
|
||||
tokio::spawn(async move { drive_writer(writer, outgoing_rx, writer_disconnected).await });
|
||||
let writer_peer = Arc::clone(&peer);
|
||||
let writer_supervisor = tokio::spawn(async move {
|
||||
match writer_task.await {
|
||||
Ok(Ok(())) if !writer_peer.is_disconnected() => {
|
||||
writer_peer.fail("code-mode writer task exited unexpectedly".to_string());
|
||||
}
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(err)) => {
|
||||
writer_peer.fail(format!("code-mode writer task failed: {err:#}"));
|
||||
}
|
||||
Err(err) => {
|
||||
writer_peer.fail(format!("code-mode writer task failed: {err}"));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let input_result = async {
|
||||
loop {
|
||||
let message = tokio::select! {
|
||||
biased;
|
||||
_ = peer.disconnected() => break,
|
||||
message = reader.read() => message.context("failed to read code-mode client message")?,
|
||||
};
|
||||
let Some(message) = message else {
|
||||
break;
|
||||
};
|
||||
match message {
|
||||
ClientToHost::ClientHello(_) => {
|
||||
anyhow::bail!("received a second code-mode client hello");
|
||||
}
|
||||
ClientToHost::Request { id, request } => {
|
||||
state.spawn_request(id, request)?;
|
||||
}
|
||||
ClientToHost::CancelRequest { id } => {
|
||||
state.cancel_request(id);
|
||||
}
|
||||
ClientToHost::YieldRequest { id } => {
|
||||
state.yield_request(id);
|
||||
}
|
||||
ClientToHost::DelegateResponse { id, result } => {
|
||||
peer.complete(id, result.into_result()).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok::<(), anyhow::Error>(())
|
||||
}
|
||||
.await;
|
||||
|
||||
peer.disconnect();
|
||||
if tokio::time::timeout(SHUTDOWN_TIMEOUT, state.disconnect())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
peer.fail("timed out shutting down code-mode host state".to_string());
|
||||
}
|
||||
drop(state);
|
||||
tokio::time::timeout(SHUTDOWN_TIMEOUT, writer_supervisor)
|
||||
.await
|
||||
.context("timed out supervising code-mode writer task")?
|
||||
.context("code-mode writer supervisor task failed")?;
|
||||
let failure = peer.failure();
|
||||
drop(peer);
|
||||
input_result?;
|
||||
if let Some(failure) = failure {
|
||||
anyhow::bail!(failure);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn drive_writer<W: AsyncWrite + Unpin>(
|
||||
mut writer: FramedWriter<W>,
|
||||
mut outgoing: mpsc::Receiver<EncodedFrame>,
|
||||
disconnected: CancellationToken,
|
||||
) -> Result<()> {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = disconnected.cancelled() => return Ok(()),
|
||||
frame = outgoing.recv() => {
|
||||
let Some(frame) = frame else {
|
||||
return Ok(());
|
||||
};
|
||||
tokio::select! {
|
||||
_ = disconnected.cancelled() => return Ok(()),
|
||||
result = writer.write_frame(&frame) => {
|
||||
result.context("failed to write code-mode host message")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn negotiate<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
reader: &mut FramedReader<R>,
|
||||
writer: &mut FramedWriter<W>,
|
||||
) -> Result<NegotiatedConnection> {
|
||||
let Some(first_message) = reader
|
||||
.read()
|
||||
.await
|
||||
.context("failed to read code-mode client hello")?
|
||||
else {
|
||||
return Ok(NegotiatedConnection::Rejected);
|
||||
};
|
||||
let ClientToHost::ClientHello(client_hello) = first_message else {
|
||||
writer
|
||||
.write(&HostToClient::HandshakeRejected {
|
||||
reason: HandshakeRejectReason::InvalidHello {
|
||||
message: "first message must be connection/hello".to_string(),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.context("failed to reject invalid code-mode client hello")?;
|
||||
return Ok(NegotiatedConnection::Rejected);
|
||||
};
|
||||
|
||||
let supported_versions = SupportedProtocolVersions::try_new([ProtocolVersion::V1])?;
|
||||
if !client_hello
|
||||
.supported_versions()
|
||||
.contains(ProtocolVersion::V1)
|
||||
{
|
||||
writer
|
||||
.write(&HostToClient::HandshakeRejected {
|
||||
reason: HandshakeRejectReason::NoCompatibleVersion { supported_versions },
|
||||
})
|
||||
.await
|
||||
.context("failed to reject incompatible code-mode client")?;
|
||||
return Ok(NegotiatedConnection::Rejected);
|
||||
}
|
||||
|
||||
let host_capabilities = CapabilitySet::try_new(
|
||||
[
|
||||
SESSION_RESOURCE_LIMITS_CAPABILITY,
|
||||
YIELD_OBSERVATION_CAPABILITY,
|
||||
BOUNDED_OUTPUT_CAPABILITY,
|
||||
LARGE_DELEGATE_CAPACITY_CAPABILITY,
|
||||
]
|
||||
.into_iter()
|
||||
.map(Capability::new)
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.into_iter()
|
||||
.filter(|capability| {
|
||||
client_hello.required_capabilities().contains(capability)
|
||||
|| client_hello.optional_capabilities().contains(capability)
|
||||
}),
|
||||
)?;
|
||||
if let Some(capability) = client_hello
|
||||
.required_capabilities()
|
||||
.iter()
|
||||
.find(|capability| !host_capabilities.contains(capability))
|
||||
{
|
||||
writer
|
||||
.write(&HostToClient::HandshakeRejected {
|
||||
reason: HandshakeRejectReason::MissingRequiredCapability {
|
||||
capability: capability.clone(),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.context("failed to reject unsupported code-mode capability")?;
|
||||
return Ok(NegotiatedConnection::Rejected);
|
||||
}
|
||||
|
||||
let max_pending_delegate_calls =
|
||||
if host_capabilities.contains(&Capability::new(LARGE_DELEGATE_CAPACITY_CAPABILITY)?) {
|
||||
MAX_PENDING_DELEGATE_CALLS
|
||||
} else {
|
||||
LEGACY_MAX_PENDING_DELEGATE_CALLS
|
||||
};
|
||||
let hello = HostHello::new(ProtocolVersion::V1, host_capabilities);
|
||||
writer
|
||||
.write(&HostToClient::HostHello(hello))
|
||||
.await
|
||||
.context("failed to write code-mode host hello")?;
|
||||
Ok(NegotiatedConnection::Accepted {
|
||||
max_pending_delegate_calls,
|
||||
})
|
||||
}
|
||||
|
||||
struct HostState {
|
||||
sessions: Mutex<HashMap<SessionId, Arc<InProcessCodeModeSession>>>,
|
||||
limits: Arc<HostLimits>,
|
||||
seen_session_ids: Mutex<SeenSessionIds>,
|
||||
requests: Mutex<RequestRegistry>,
|
||||
request_tasks: TaskTracker,
|
||||
closing: AtomicBool,
|
||||
peer: Arc<HostPeer>,
|
||||
}
|
||||
|
||||
impl HostState {
|
||||
fn spawn_request(
|
||||
self: &Arc<Self>,
|
||||
request_id: RequestId,
|
||||
request: HostRequest,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
// Include host admission and scheduling before the runtime observes the request.
|
||||
let received_at = Instant::now();
|
||||
let request_kind = RequestKind::from(&request);
|
||||
let (cancellation, yield_signal) = self
|
||||
.requests
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.start(request_id, request_kind)?;
|
||||
let Ok(permit) = self.limits.request_permit() else {
|
||||
self.respond(
|
||||
request_id,
|
||||
Err("code-mode host has too many in-flight requests".to_string()),
|
||||
);
|
||||
self.finish_request(request_id);
|
||||
return Ok(());
|
||||
};
|
||||
let state = Arc::clone(self);
|
||||
let request_task = self.request_tasks.spawn(async move {
|
||||
let _permit = permit;
|
||||
state
|
||||
.handle_request(request_id, request, cancellation, yield_signal, received_at)
|
||||
.await;
|
||||
state.finish_request(request_id);
|
||||
});
|
||||
self.supervise_request_task(request_task);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn supervise_request_task(&self, task: tokio::task::JoinHandle<()>) {
|
||||
let peer = Arc::clone(&self.peer);
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = task.await {
|
||||
peer.fail(format!("code-mode request task failed: {err}"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
name = "code_mode_host.request",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(
|
||||
otel.name = "code_mode_host.request",
|
||||
request.kind = RequestKind::from(&request).as_str(),
|
||||
request.id = ?request_id,
|
||||
call_id = tracing::field::Empty,
|
||||
)
|
||||
)]
|
||||
async fn handle_request(
|
||||
&self,
|
||||
request_id: RequestId,
|
||||
request: HostRequest,
|
||||
cancellation: CancellationToken,
|
||||
yield_signal: CancellationToken,
|
||||
received_at: Instant,
|
||||
) {
|
||||
if let HostRequest::Execute { request, .. } = &request {
|
||||
tracing::Span::current().record("call_id", request.tool_call_id.as_str());
|
||||
}
|
||||
if self.closing.load(Ordering::Acquire) {
|
||||
self.respond(
|
||||
request_id,
|
||||
Err("code-mode host is shutting down".to_string()),
|
||||
);
|
||||
return;
|
||||
}
|
||||
match request {
|
||||
HostRequest::OpenSession {
|
||||
session_id,
|
||||
cell_execution_limits,
|
||||
output_truncation,
|
||||
} => {
|
||||
let result = CodeModeSessionCellExecutionLimits::try_from(
|
||||
cell_execution_limits.unwrap_or_default(),
|
||||
)
|
||||
.map_err(|error| format!("invalid code-mode session execution limits: {error}"))
|
||||
.and_then(|limits| {
|
||||
self.open_session(
|
||||
session_id.clone(),
|
||||
CodeModeSessionOptions {
|
||||
cell_execution_limits: limits,
|
||||
output_truncation: output_truncation
|
||||
.map(CodeModeOutputTruncation::from)
|
||||
.unwrap_or_default(),
|
||||
},
|
||||
)
|
||||
})
|
||||
.map(|()| HostResponse::SessionReady { session_id });
|
||||
self.respond(request_id, result);
|
||||
}
|
||||
HostRequest::Execute {
|
||||
session_id,
|
||||
request,
|
||||
} => {
|
||||
if cancellation.is_cancelled() {
|
||||
self.respond(request_id, Err("code-mode request cancelled".to_string()));
|
||||
return;
|
||||
}
|
||||
let request = match request.try_into() {
|
||||
Ok(request) => request,
|
||||
Err(err) => {
|
||||
self.respond(
|
||||
request_id,
|
||||
Err(format!("invalid code-mode execute request: {err}")),
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let session = match self.session(&session_id) {
|
||||
Ok(session) => session,
|
||||
Err(err) => {
|
||||
self.respond(request_id, Err(err));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let Ok(active_cell_permit) = self.limits.cell_permit() else {
|
||||
self.respond(
|
||||
request_id,
|
||||
Err("code-mode host has too many active cells".to_string()),
|
||||
);
|
||||
return;
|
||||
};
|
||||
let delegate = Arc::new(RemoteDelegate::new(
|
||||
session_id.clone(),
|
||||
Arc::clone(&self.peer),
|
||||
));
|
||||
let result = session.execute(request, delegate, Some(yield_signal)).await;
|
||||
match result {
|
||||
Ok(started) => {
|
||||
let cell_id = started.cell_id.clone();
|
||||
self.respond(
|
||||
request_id,
|
||||
Ok(HostResponse::ExecutionStarted {
|
||||
cell_id: cell_id.into(),
|
||||
}),
|
||||
);
|
||||
let initial_response_sent = self.peer.start_cell(
|
||||
session_id,
|
||||
request_id,
|
||||
started,
|
||||
active_cell_permit,
|
||||
received_at,
|
||||
);
|
||||
let _ = initial_response_sent.await;
|
||||
}
|
||||
Err(err) => self.respond(request_id, Err(err)),
|
||||
}
|
||||
}
|
||||
HostRequest::Wait {
|
||||
session_id,
|
||||
request,
|
||||
max_output_tokens,
|
||||
} => {
|
||||
let result = match self.session(&session_id) {
|
||||
Ok(session) => {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => {
|
||||
Err("code-mode request cancelled".to_string())
|
||||
}
|
||||
result = session.wait(WaitRequest {
|
||||
max_output_tokens,
|
||||
..request.into()
|
||||
}, Some(yield_signal)) => result.and_then(|outcome| {
|
||||
let outcome = outcome.with_code_mode_host_duration(received_at.elapsed());
|
||||
Ok(HostResponse::WaitCompleted {
|
||||
outcome: WireWaitOutcome::try_from(outcome)
|
||||
.map_err(|error| error.to_string())?,
|
||||
})
|
||||
}),
|
||||
}
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
};
|
||||
self.respond(request_id, result);
|
||||
}
|
||||
HostRequest::Terminate {
|
||||
session_id,
|
||||
cell_id,
|
||||
max_output_tokens,
|
||||
} => {
|
||||
let result = match self.session(&session_id) {
|
||||
Ok(session) => session
|
||||
.terminate(TerminateRequest {
|
||||
cell_id: cell_id.into(),
|
||||
max_output_tokens,
|
||||
})
|
||||
.await
|
||||
.and_then(|outcome| {
|
||||
let outcome =
|
||||
outcome.with_code_mode_host_duration(received_at.elapsed());
|
||||
Ok(HostResponse::WaitCompleted {
|
||||
outcome: WireWaitOutcome::try_from(outcome)
|
||||
.map_err(|error| error.to_string())?,
|
||||
})
|
||||
}),
|
||||
Err(err) => Err(err),
|
||||
};
|
||||
self.respond(request_id, result);
|
||||
}
|
||||
HostRequest::ShutdownSession { session_id } => {
|
||||
let session = self
|
||||
.sessions
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(&session_id);
|
||||
let result = match session {
|
||||
Some(session) => match session.shutdown().await {
|
||||
Ok(()) => {
|
||||
self.peer.wait_for_session_cells(&session_id).await;
|
||||
Ok(HostResponse::SessionClosed { session_id })
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
None => Err(format!("unknown code-mode session {session_id}")),
|
||||
};
|
||||
self.respond(request_id, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn open_session(
|
||||
&self,
|
||||
session_id: SessionId,
|
||||
options: CodeModeSessionOptions,
|
||||
) -> Result<(), String> {
|
||||
let mut sessions = self.sessions.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if sessions.contains_key(&session_id) {
|
||||
return Err(format!(
|
||||
"code-mode session ID `{session_id}` is already open"
|
||||
));
|
||||
}
|
||||
if self.closing.load(Ordering::Acquire) {
|
||||
return Err("code-mode host is shutting down".to_string());
|
||||
}
|
||||
if !self
|
||||
.seen_session_ids
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remember(session_id.clone())
|
||||
{
|
||||
return Err(format!("code-mode session ID `{session_id}` was reused"));
|
||||
}
|
||||
let peer = Arc::downgrade(&self.peer);
|
||||
let task_failure_handler = Arc::new(move |reason| {
|
||||
if let Some(peer) = peer.upgrade() {
|
||||
peer.fail(reason);
|
||||
}
|
||||
});
|
||||
sessions.insert(
|
||||
session_id,
|
||||
Arc::new(InProcessCodeModeSession::with_options(
|
||||
options,
|
||||
Some(task_failure_handler),
|
||||
)),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn session(&self, session_id: &SessionId) -> Result<Arc<InProcessCodeModeSession>, String> {
|
||||
self.sessions
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.get(session_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("unknown code-mode session {session_id}"))
|
||||
}
|
||||
|
||||
fn respond(&self, id: RequestId, result: Result<HostResponse, String>) {
|
||||
self.peer.respond(id, result);
|
||||
}
|
||||
|
||||
fn cancel_request(&self, request_id: RequestId) {
|
||||
self.requests
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.cancel(request_id);
|
||||
}
|
||||
|
||||
fn yield_request(&self, request_id: RequestId) {
|
||||
self.requests
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.yield_observation(request_id);
|
||||
}
|
||||
|
||||
fn finish_request(&self, request_id: RequestId) {
|
||||
self.requests
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.finish(request_id);
|
||||
}
|
||||
|
||||
async fn disconnect(&self) {
|
||||
self.closing.store(true, Ordering::Release);
|
||||
self.requests
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.cancel_all();
|
||||
self.request_tasks.close();
|
||||
self.request_tasks.wait().await;
|
||||
let sessions = self
|
||||
.sessions
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.drain()
|
||||
.map(|(_, session)| session)
|
||||
.collect::<Vec<_>>();
|
||||
for session in sessions {
|
||||
let _ = session.shutdown().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum RequestKind {
|
||||
OpenSession,
|
||||
Execute,
|
||||
Wait,
|
||||
Terminate,
|
||||
ShutdownSession,
|
||||
}
|
||||
|
||||
impl RequestKind {
|
||||
fn from(request: &HostRequest) -> Self {
|
||||
match request {
|
||||
HostRequest::OpenSession { .. } => Self::OpenSession,
|
||||
HostRequest::Execute { .. } => Self::Execute,
|
||||
HostRequest::Wait { .. } => Self::Wait,
|
||||
HostRequest::Terminate { .. } => Self::Terminate,
|
||||
HostRequest::ShutdownSession { .. } => Self::ShutdownSession,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_cancellable(self) -> bool {
|
||||
matches!(self, Self::Execute | Self::Wait)
|
||||
}
|
||||
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::OpenSession => "open_session",
|
||||
Self::Execute => "execute",
|
||||
Self::Wait => "wait",
|
||||
Self::Terminate => "terminate",
|
||||
Self::ShutdownSession => "shutdown_session",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ActiveRequest {
|
||||
kind: RequestKind,
|
||||
cancellation: CancellationToken,
|
||||
yield_signal: CancellationToken,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RequestRegistry {
|
||||
active: HashMap<RequestId, ActiveRequest>,
|
||||
recent: HashSet<RequestId>,
|
||||
recent_order: VecDeque<RequestId>,
|
||||
}
|
||||
|
||||
impl RequestRegistry {
|
||||
fn start(
|
||||
&mut self,
|
||||
request_id: RequestId,
|
||||
kind: RequestKind,
|
||||
) -> Result<(CancellationToken, CancellationToken), anyhow::Error> {
|
||||
if self.active.contains_key(&request_id) || self.recent.contains(&request_id) {
|
||||
anyhow::bail!("duplicate code-mode request ID {request_id:?}");
|
||||
}
|
||||
let cancellation = CancellationToken::new();
|
||||
let yield_signal = CancellationToken::new();
|
||||
self.active.insert(
|
||||
request_id,
|
||||
ActiveRequest {
|
||||
kind,
|
||||
cancellation: cancellation.clone(),
|
||||
yield_signal: yield_signal.clone(),
|
||||
},
|
||||
);
|
||||
Ok((cancellation, yield_signal))
|
||||
}
|
||||
|
||||
fn cancel(&mut self, request_id: RequestId) {
|
||||
if let Some(request) = self.active.get(&request_id)
|
||||
&& request.kind.is_cancellable()
|
||||
{
|
||||
request.cancellation.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
fn yield_observation(&self, request_id: RequestId) {
|
||||
if let Some(request) = self.active.get(&request_id)
|
||||
&& matches!(request.kind, RequestKind::Execute | RequestKind::Wait)
|
||||
{
|
||||
request.yield_signal.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&mut self, request_id: RequestId) {
|
||||
if self.active.remove(&request_id).is_none() {
|
||||
return;
|
||||
}
|
||||
self.recent.insert(request_id);
|
||||
self.recent_order.push_back(request_id);
|
||||
while self.recent_order.len() > MAX_RECENT_REQUEST_IDS {
|
||||
if let Some(expired) = self.recent_order.pop_front() {
|
||||
self.recent.remove(&expired);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_all(&self) {
|
||||
for request in self.active.values() {
|
||||
request.cancellation.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SeenSessionIds {
|
||||
ids: HashSet<SessionId>,
|
||||
order: VecDeque<SessionId>,
|
||||
}
|
||||
|
||||
impl SeenSessionIds {
|
||||
fn remember(&mut self, session_id: SessionId) -> bool {
|
||||
if !self.ids.insert(session_id.clone()) {
|
||||
return false;
|
||||
}
|
||||
self.order.push_back(session_id);
|
||||
while self.order.len() > MAX_RECENT_SESSION_IDS {
|
||||
if let Some(expired) = self.order.pop_front() {
|
||||
self.ids.remove(&expired);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "host_tests.rs"]
|
||||
mod tests;
|
||||
128
codex-rs/code-mode-host/src/main.rs
Normal file
128
codex-rs/code-mode-host/src/main.rs
Normal file
@@ -0,0 +1,128 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use clap::Parser;
|
||||
use codex_otel::OtelExporter;
|
||||
use codex_otel::OtelHttpProtocol;
|
||||
use codex_otel::OtelProvider;
|
||||
use codex_otel::OtelSettings;
|
||||
use codex_otel_trace_websocket::TraceWebSocket;
|
||||
use tracing_subscriber::Layer;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
|
||||
const OTEL_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 5);
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
struct Cli {
|
||||
#[arg(
|
||||
long,
|
||||
hide = true,
|
||||
conflicts_with_all = ["listen", "otel_trace_listen", "otel_trace_exporter"]
|
||||
)]
|
||||
codex_ui_plugin_process: bool,
|
||||
|
||||
/// Transport endpoint: `stdio`, `stdio://`, `grpc+stdio://`, or `grpc://IP:PORT`.
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "URL",
|
||||
default_value = codex_code_mode_host::DEFAULT_LISTEN_URL
|
||||
)]
|
||||
listen: String,
|
||||
|
||||
/// Optional WebSocket endpoint that streams only raw OTLP trace batches.
|
||||
#[arg(long, value_name = "URL")]
|
||||
otel_trace_listen: Option<String>,
|
||||
|
||||
/// Optional OTLP/HTTP JSON trace exporter endpoint, analogous to
|
||||
/// `otel.trace_exporter` in app-server configuration.
|
||||
#[arg(long, value_name = "URL", conflicts_with = "otel_trace_listen")]
|
||||
otel_trace_exporter: Option<String>,
|
||||
}
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn run(cli: Cli) -> anyhow::Result<()> {
|
||||
let mut trace_transport = if let Some(trace_listen) = cli.otel_trace_listen.as_deref() {
|
||||
Some(TraceWebSocket::start(trace_listen).await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let trace_exporter_endpoint = trace_transport
|
||||
.as_ref()
|
||||
.map(TraceWebSocket::exporter_endpoint)
|
||||
.or(cli.otel_trace_exporter.as_deref());
|
||||
let otel = trace_exporter_endpoint
|
||||
.map(build_trace_provider)
|
||||
.transpose()?;
|
||||
let otel_layer = otel.as_ref().and_then(OtelProvider::tracing_layer);
|
||||
tracing_subscriber::registry()
|
||||
.with(
|
||||
tracing_subscriber::fmt::layer()
|
||||
.with_writer(std::io::stderr)
|
||||
.with_ansi(false)
|
||||
.with_filter(tracing_subscriber::filter::LevelFilter::INFO),
|
||||
)
|
||||
.with(otel_layer)
|
||||
.init();
|
||||
if let Some(trace_transport) = trace_transport.as_ref() {
|
||||
let listen_addr = trace_transport.listen_addr();
|
||||
tracing::info!("codex-code-mode-host OTEL trace websocket listening on ws://{listen_addr}");
|
||||
}
|
||||
tracing::info_span!(
|
||||
"code_mode_host.startup",
|
||||
otel.name = "code_mode_host.startup"
|
||||
)
|
||||
.in_scope(|| {});
|
||||
|
||||
let main_transport = codex_code_mode_host::run_main(&cli.listen);
|
||||
let result = match trace_transport.as_mut() {
|
||||
Some(trace_transport) => tokio::select! {
|
||||
result = main_transport => result,
|
||||
result = trace_transport.wait_for_failure() => result,
|
||||
},
|
||||
None => main_transport.await,
|
||||
};
|
||||
if let Some(otel) = otel
|
||||
&& let Err(error) = otel.shutdown_with_timeout(OTEL_SHUTDOWN_TIMEOUT).await
|
||||
{
|
||||
tracing::warn!(%error, "failed to finish code-mode host telemetry shutdown");
|
||||
}
|
||||
drop(trace_transport);
|
||||
result
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let cli = Cli::parse();
|
||||
if cli.codex_ui_plugin_process {
|
||||
return codex_code_mode_runtime::run_ui_sandbox().map_err(Into::into);
|
||||
}
|
||||
run(cli)
|
||||
}
|
||||
|
||||
fn build_trace_provider(endpoint: &str) -> anyhow::Result<OtelProvider> {
|
||||
OtelProvider::try_new(&OtelSettings {
|
||||
http_client_factory: codex_http_client::HttpClientFactory::new(
|
||||
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
),
|
||||
environment: "code-mode-host".to_string(),
|
||||
service_name: "codex-code-mode-host".to_string(),
|
||||
service_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
codex_home: PathBuf::from("/tmp"),
|
||||
exporter: OtelExporter::None,
|
||||
trace_exporter: OtelExporter::OtlpHttp {
|
||||
endpoint: endpoint.to_string(),
|
||||
headers: HashMap::new(),
|
||||
protocol: OtelHttpProtocol::Json,
|
||||
tls: None,
|
||||
},
|
||||
metrics_exporter: OtelExporter::None,
|
||||
runtime_metrics: false,
|
||||
span_attributes: HashMap::new(),
|
||||
tracestate: BTreeMap::new(),
|
||||
})
|
||||
.map_err(|error| anyhow::anyhow!("failed to build code-mode host OTEL provider: {error}"))?
|
||||
.context("code-mode host OTEL trace provider was unexpectedly disabled")
|
||||
}
|
||||
566
codex-rs/code-mode-host/src/peer.rs
Normal file
566
codex-rs/code-mode-host/src/peer.rs
Normal file
@@ -0,0 +1,566 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::atomic::AtomicI64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_code_mode_protocol::CellId;
|
||||
use codex_code_mode_protocol::StartedCell;
|
||||
use codex_code_mode_protocol::host::DelegateRequest;
|
||||
use codex_code_mode_protocol::host::DelegateRequestId;
|
||||
use codex_code_mode_protocol::host::DelegateResponse;
|
||||
use codex_code_mode_protocol::host::EncodedFrame;
|
||||
use codex_code_mode_protocol::host::HostToClient;
|
||||
use codex_code_mode_protocol::host::RequestId;
|
||||
use codex_code_mode_protocol::host::SessionId;
|
||||
use codex_code_mode_protocol::host::WireResult;
|
||||
use codex_code_mode_protocol::host::WireRuntimeResponse;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
const CELL_MESSAGE_CAPACITY: usize = 128;
|
||||
|
||||
pub(super) struct HostPeer {
|
||||
outgoing_tx: mpsc::Sender<EncodedFrame>,
|
||||
pending: Mutex<HashMap<DelegateRequestId, PendingDelegate>>,
|
||||
delegate_permits: Arc<Semaphore>,
|
||||
cell_routes: StdMutex<HashMap<(SessionId, CellId), CellRoute>>,
|
||||
cell_routes_changed: Notify,
|
||||
next_request_id: AtomicI64,
|
||||
disconnected: CancellationToken,
|
||||
failure: StdMutex<Option<String>>,
|
||||
}
|
||||
|
||||
struct PendingDelegate {
|
||||
response_tx: oneshot::Sender<Result<DelegateResponse, String>>,
|
||||
dispatched: bool,
|
||||
_permit: OwnedSemaphorePermit,
|
||||
}
|
||||
|
||||
enum CellRoute {
|
||||
Pending(VecDeque<CellMessage>),
|
||||
Active(mpsc::Sender<CellMessage>),
|
||||
}
|
||||
|
||||
enum CellMessage {
|
||||
Delegate {
|
||||
id: DelegateRequestId,
|
||||
request: DelegateRequest,
|
||||
dispatched_tx: oneshot::Sender<Result<(), String>>,
|
||||
},
|
||||
Closed,
|
||||
}
|
||||
|
||||
struct InitialRequest {
|
||||
id: RequestId,
|
||||
received_at: Instant,
|
||||
}
|
||||
|
||||
impl HostPeer {
|
||||
pub(super) fn new(
|
||||
outgoing_tx: mpsc::Sender<EncodedFrame>,
|
||||
max_pending_delegate_calls: usize,
|
||||
) -> Self {
|
||||
Self {
|
||||
outgoing_tx,
|
||||
pending: Mutex::new(HashMap::new()),
|
||||
delegate_permits: Arc::new(Semaphore::new(max_pending_delegate_calls)),
|
||||
cell_routes: StdMutex::new(HashMap::new()),
|
||||
cell_routes_changed: Notify::new(),
|
||||
next_request_id: AtomicI64::new(1),
|
||||
disconnected: CancellationToken::new(),
|
||||
failure: StdMutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn send(&self, message: HostToClient) -> Result<(), PeerSendError> {
|
||||
let frame = EncodedFrame::encode(&message)
|
||||
.map_err(|err| PeerSendError::Payload(err.to_string()))?;
|
||||
self.send_frame(frame)
|
||||
}
|
||||
|
||||
pub(super) fn respond(
|
||||
&self,
|
||||
id: RequestId,
|
||||
result: Result<codex_code_mode_protocol::host::HostResponse, String>,
|
||||
) {
|
||||
let message = HostToClient::Response {
|
||||
id,
|
||||
result: WireResult::from_result(result),
|
||||
};
|
||||
if let Err(PeerSendError::Payload(err)) = self.send(message) {
|
||||
let _ = self.send(HostToClient::Response {
|
||||
id,
|
||||
result: WireResult::Err {
|
||||
message: format!("code-mode host response exceeds the IPC frame limit: {err}"),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn initial_response(&self, id: RequestId, result: Result<WireRuntimeResponse, String>) {
|
||||
let message = HostToClient::InitialResponse {
|
||||
id,
|
||||
result: WireResult::from_result(result),
|
||||
};
|
||||
if let Err(PeerSendError::Payload(err)) = self.send(message) {
|
||||
let _ = self.send(HostToClient::InitialResponse {
|
||||
id,
|
||||
result: WireResult::Err {
|
||||
message: format!(
|
||||
"code-mode initial response exceeds the IPC frame limit: {err}"
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn call(
|
||||
self: &Arc<Self>,
|
||||
session_id: SessionId,
|
||||
request: DelegateRequest,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> Result<DelegateResponse, String> {
|
||||
if self.disconnected.is_cancelled() {
|
||||
return Err("code-mode client connection closed".to_string());
|
||||
}
|
||||
let Ok(permit) = Arc::clone(&self.delegate_permits).try_acquire_owned() else {
|
||||
return Err("code-mode host has too many pending delegate calls".to_string());
|
||||
};
|
||||
let id = DelegateRequestId::new(self.next_request_id.fetch_add(1, Ordering::Relaxed));
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
self.pending.lock().await.insert(
|
||||
id,
|
||||
PendingDelegate {
|
||||
response_tx,
|
||||
dispatched: false,
|
||||
_permit: permit,
|
||||
},
|
||||
);
|
||||
let mut pending = PendingDelegateRequest::new(Arc::clone(self), id);
|
||||
let cell_id = match &request {
|
||||
DelegateRequest::InvokeTool { invocation } => invocation.cell_id.clone().into(),
|
||||
DelegateRequest::Notify { cell_id, .. } => cell_id.clone().into(),
|
||||
};
|
||||
let (dispatched_tx, dispatched_rx) = oneshot::channel();
|
||||
if let Err(err) = self.route_cell_message(
|
||||
(session_id, cell_id),
|
||||
CellMessage::Delegate {
|
||||
id,
|
||||
request,
|
||||
dispatched_tx,
|
||||
},
|
||||
) {
|
||||
self.pending.lock().await.remove(&id);
|
||||
pending.disarm();
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let dispatched = tokio::select! {
|
||||
dispatched = dispatched_rx => dispatched.map_err(|_| {
|
||||
"code-mode cell route closed before dispatching delegate request".to_string()
|
||||
})?,
|
||||
_ = self.disconnected.cancelled() => {
|
||||
self.pending.lock().await.remove(&id);
|
||||
pending.disarm();
|
||||
return Err("code-mode client connection closed".to_string());
|
||||
}
|
||||
};
|
||||
if let Err(err) = dispatched {
|
||||
self.pending.lock().await.remove(&id);
|
||||
pending.disarm();
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
response = response_rx => {
|
||||
pending.disarm();
|
||||
response.map_err(|_| {
|
||||
"code-mode client closed before returning delegate output".to_string()
|
||||
})?
|
||||
}
|
||||
_ = cancellation_token.cancelled() => {
|
||||
if self.remove_pending(id).await.is_some() {
|
||||
let _ = self.send(HostToClient::CancelDelegateRequest { id });
|
||||
}
|
||||
pending.disarm();
|
||||
Err("code mode delegate request cancelled".to_string())
|
||||
}
|
||||
_ = self.disconnected.cancelled() => {
|
||||
self.pending.lock().await.remove(&id);
|
||||
pending.disarm();
|
||||
Err("code-mode client connection closed".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn complete(
|
||||
&self,
|
||||
id: DelegateRequestId,
|
||||
response: Result<DelegateResponse, String>,
|
||||
) {
|
||||
if let Some(pending) = self.remove_pending(id).await {
|
||||
let _ = pending.response_tx.send(response);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn start_cell(
|
||||
self: &Arc<Self>,
|
||||
session_id: SessionId,
|
||||
request_id: RequestId,
|
||||
started: StartedCell,
|
||||
active_cell_permit: OwnedSemaphorePermit,
|
||||
received_at: Instant,
|
||||
) -> oneshot::Receiver<()> {
|
||||
let (initial_response_sent_tx, initial_response_sent_rx) = oneshot::channel();
|
||||
let key = (session_id, started.cell_id.clone());
|
||||
let (messages_tx, messages_rx) = mpsc::channel(CELL_MESSAGE_CAPACITY);
|
||||
let previous = self
|
||||
.cell_routes
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.insert(key.clone(), CellRoute::Active(messages_tx.clone()));
|
||||
match previous {
|
||||
Some(CellRoute::Pending(messages)) => {
|
||||
for message in messages {
|
||||
if messages_tx.try_send(message).is_err() {
|
||||
self.disconnect();
|
||||
return initial_response_sent_rx;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(CellRoute::Active(_)) => {
|
||||
self.disconnect();
|
||||
return initial_response_sent_rx;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
let peer = Arc::clone(self);
|
||||
self.spawn_critical("cell forwarding", async move {
|
||||
drive_cell(
|
||||
peer,
|
||||
key,
|
||||
InitialRequest {
|
||||
id: request_id,
|
||||
received_at,
|
||||
},
|
||||
started,
|
||||
messages_rx,
|
||||
initial_response_sent_tx,
|
||||
active_cell_permit,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
initial_response_sent_rx
|
||||
}
|
||||
|
||||
pub(super) fn close_cell(&self, session_id: SessionId, cell_id: CellId) {
|
||||
let _ = self.route_cell_message((session_id, cell_id), CellMessage::Closed);
|
||||
}
|
||||
|
||||
pub(super) fn disconnect(&self) {
|
||||
self.disconnected.cancel();
|
||||
}
|
||||
|
||||
pub(super) fn fail(&self, reason: String) {
|
||||
let mut failure = self.failure.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if failure.is_none() {
|
||||
*failure = Some(reason);
|
||||
}
|
||||
drop(failure);
|
||||
self.disconnect();
|
||||
}
|
||||
|
||||
pub(super) fn failure(&self) -> Option<String> {
|
||||
self.failure
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub(super) fn is_disconnected(&self) -> bool {
|
||||
self.disconnected.is_cancelled()
|
||||
}
|
||||
|
||||
pub(super) async fn disconnected(&self) {
|
||||
self.disconnected.cancelled().await;
|
||||
}
|
||||
|
||||
pub(super) fn disconnection_token(&self) -> CancellationToken {
|
||||
self.disconnected.clone()
|
||||
}
|
||||
|
||||
pub(super) async fn wait_for_session_cells(&self, session_id: &SessionId) {
|
||||
loop {
|
||||
let changed = self.cell_routes_changed.notified();
|
||||
if !self
|
||||
.cell_routes
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.keys()
|
||||
.any(|(route_session_id, _)| route_session_id == session_id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
tokio::select! {
|
||||
_ = changed => {}
|
||||
_ = self.disconnected.cancelled() => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_delegate_if_pending(
|
||||
&self,
|
||||
id: DelegateRequestId,
|
||||
session_id: SessionId,
|
||||
request: DelegateRequest,
|
||||
dispatched_tx: oneshot::Sender<Result<(), String>>,
|
||||
) {
|
||||
let result = {
|
||||
let mut pending = self.pending.lock().await;
|
||||
let Some(pending) = pending.get_mut(&id) else {
|
||||
let _ = dispatched_tx.send(Err(
|
||||
"code-mode delegate request was cancelled before dispatch".to_string(),
|
||||
));
|
||||
return;
|
||||
};
|
||||
match self.send(HostToClient::DelegateRequest {
|
||||
id,
|
||||
session_id,
|
||||
request,
|
||||
}) {
|
||||
Ok(()) => {
|
||||
pending.dispatched = true;
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => Err(err.to_string()),
|
||||
}
|
||||
};
|
||||
let _ = dispatched_tx.send(result);
|
||||
}
|
||||
|
||||
fn route_cell_message(
|
||||
&self,
|
||||
key: (SessionId, CellId),
|
||||
message: CellMessage,
|
||||
) -> Result<(), String> {
|
||||
use std::collections::hash_map::Entry;
|
||||
|
||||
let result = match self
|
||||
.cell_routes
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.entry(key)
|
||||
{
|
||||
Entry::Occupied(mut entry) => match entry.get_mut() {
|
||||
CellRoute::Pending(messages) if messages.len() < CELL_MESSAGE_CAPACITY => {
|
||||
messages.push_back(message);
|
||||
Ok(())
|
||||
}
|
||||
CellRoute::Pending(_) => Err("code-mode cell message queue is full".to_string()),
|
||||
CellRoute::Active(sender) => sender
|
||||
.try_send(message)
|
||||
.map_err(|_| "code-mode cell message queue is unavailable".to_string()),
|
||||
},
|
||||
Entry::Vacant(entry) => {
|
||||
entry.insert(CellRoute::Pending(VecDeque::from([message])));
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
if result.is_err() {
|
||||
self.disconnect();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn remove_pending(&self, id: DelegateRequestId) -> Option<PendingDelegate> {
|
||||
self.pending.lock().await.remove(&id)
|
||||
}
|
||||
|
||||
pub(super) fn spawn_critical<F>(self: &Arc<Self>, task_name: &'static str, future: F)
|
||||
where
|
||||
F: std::future::Future<Output = ()> + Send + 'static,
|
||||
{
|
||||
let task = tokio::spawn(future);
|
||||
let peer = Arc::clone(self);
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = task.await {
|
||||
peer.fail(format!("code-mode {task_name} task failed: {err}"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn send_frame(&self, frame: EncodedFrame) -> Result<(), PeerSendError> {
|
||||
match self.outgoing_tx.try_send(frame) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(mpsc::error::TrySendError::Full(_)) => {
|
||||
self.disconnect();
|
||||
Err(PeerSendError::Unavailable(
|
||||
"code-mode host outgoing queue is full".to_string(),
|
||||
))
|
||||
}
|
||||
Err(mpsc::error::TrySendError::Closed(_)) => {
|
||||
self.disconnect();
|
||||
Err(PeerSendError::Unavailable(
|
||||
"code-mode client connection closed".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn drive_cell(
|
||||
peer: Arc<HostPeer>,
|
||||
key: (SessionId, CellId),
|
||||
request: InitialRequest,
|
||||
started: StartedCell,
|
||||
mut messages_rx: mpsc::Receiver<CellMessage>,
|
||||
initial_response_sent_tx: oneshot::Sender<()>,
|
||||
_active_cell_permit: OwnedSemaphorePermit,
|
||||
) {
|
||||
let mut initial_response_sent_tx = Some(initial_response_sent_tx);
|
||||
let initial_response = started.initial_response();
|
||||
tokio::pin!(initial_response);
|
||||
let closed = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut initial_response => {
|
||||
// Freeze the request duration before response conversion or delivery.
|
||||
let code_mode_host_duration = request.received_at.elapsed();
|
||||
peer.initial_response(
|
||||
request.id,
|
||||
result.and_then(|response| {
|
||||
let response = response.with_code_mode_host_duration(code_mode_host_duration);
|
||||
WireRuntimeResponse::try_from(response).map_err(|error| error.to_string())
|
||||
}),
|
||||
);
|
||||
if let Some(initial_response_sent_tx) = initial_response_sent_tx.take() {
|
||||
let _ = initial_response_sent_tx.send(());
|
||||
}
|
||||
break false;
|
||||
}
|
||||
message = messages_rx.recv() => match message {
|
||||
Some(CellMessage::Delegate {
|
||||
id,
|
||||
request,
|
||||
dispatched_tx,
|
||||
}) => {
|
||||
peer.send_delegate_if_pending(id, key.0.clone(), request, dispatched_tx).await;
|
||||
}
|
||||
Some(CellMessage::Closed) | None => break true,
|
||||
},
|
||||
_ = peer.disconnected.cancelled() => {
|
||||
peer.remove_cell_route(&key);
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if closed {
|
||||
let result = initial_response.await;
|
||||
let code_mode_host_duration = request.received_at.elapsed();
|
||||
peer.initial_response(
|
||||
request.id,
|
||||
result.and_then(|response| {
|
||||
let response = response.with_code_mode_host_duration(code_mode_host_duration);
|
||||
WireRuntimeResponse::try_from(response).map_err(|error| error.to_string())
|
||||
}),
|
||||
);
|
||||
if let Some(initial_response_sent_tx) = initial_response_sent_tx.take() {
|
||||
let _ = initial_response_sent_tx.send(());
|
||||
}
|
||||
} else {
|
||||
loop {
|
||||
tokio::select! {
|
||||
message = messages_rx.recv() => match message {
|
||||
Some(CellMessage::Delegate {
|
||||
id,
|
||||
request,
|
||||
dispatched_tx,
|
||||
}) => {
|
||||
peer.send_delegate_if_pending(id, key.0.clone(), request, dispatched_tx).await;
|
||||
}
|
||||
Some(CellMessage::Closed) | None => break,
|
||||
},
|
||||
_ = peer.disconnected.cancelled() => {
|
||||
peer.remove_cell_route(&key);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = peer.send(HostToClient::CellClosed {
|
||||
session_id: key.0.clone(),
|
||||
cell_id: (&key.1).into(),
|
||||
});
|
||||
peer.remove_cell_route(&key);
|
||||
}
|
||||
|
||||
impl HostPeer {
|
||||
fn remove_cell_route(&self, key: &(SessionId, CellId)) {
|
||||
let removed = self
|
||||
.cell_routes
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(key);
|
||||
if removed.is_some() {
|
||||
self.cell_routes_changed.notify_waiters();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) enum PeerSendError {
|
||||
Payload(String),
|
||||
Unavailable(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for PeerSendError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Payload(message) | Self::Unavailable(message) => formatter.write_str(message),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PendingDelegateRequest {
|
||||
peer: Arc<HostPeer>,
|
||||
id: Option<DelegateRequestId>,
|
||||
}
|
||||
|
||||
impl PendingDelegateRequest {
|
||||
fn new(peer: Arc<HostPeer>, id: DelegateRequestId) -> Self {
|
||||
Self { peer, id: Some(id) }
|
||||
}
|
||||
|
||||
fn disarm(&mut self) {
|
||||
self.id = None;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PendingDelegateRequest {
|
||||
fn drop(&mut self) {
|
||||
let Some(id) = self.id.take() else {
|
||||
return;
|
||||
};
|
||||
let peer = Arc::clone(&self.peer);
|
||||
tokio::spawn(async move {
|
||||
if let Some(pending) = peer.remove_pending(id).await
|
||||
&& pending.dispatched
|
||||
{
|
||||
let _ = peer.send(HostToClient::CancelDelegateRequest { id });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "peer_tests.rs"]
|
||||
mod tests;
|
||||
99
codex-rs/code-mode-host/src/peer_tests.rs
Normal file
99
codex-rs/code-mode-host/src/peer_tests.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_code_mode_protocol::CellId;
|
||||
use codex_code_mode_protocol::RuntimeResponse;
|
||||
use codex_code_mode_protocol::StartedCell;
|
||||
use codex_code_mode_protocol::host::DelegateRequest;
|
||||
use codex_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use codex_code_mode_protocol::host::RequestId;
|
||||
use codex_code_mode_protocol::host::SessionId;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::oneshot::error::TryRecvError;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::HostPeer;
|
||||
|
||||
fn session_id(value: &str) -> SessionId {
|
||||
SessionId::new(value).expect("session ID")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn start_cell_reports_when_initial_response_is_enqueued() {
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(/*max_capacity*/ 4);
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
let cell_id = CellId::new("cell-1".to_string());
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
let started = StartedCell::new(cell_id.clone(), response_rx);
|
||||
let active_cell_permits = Arc::new(Semaphore::new(/*permits*/ 1));
|
||||
let active_cell_permit = Arc::clone(&active_cell_permits)
|
||||
.try_acquire_owned()
|
||||
.expect("active cell permit");
|
||||
|
||||
let mut initial_response_sent = peer.start_cell(
|
||||
session_id("session-1"),
|
||||
RequestId::new(/*value*/ 1),
|
||||
started,
|
||||
active_cell_permit,
|
||||
Instant::now(),
|
||||
);
|
||||
assert_eq!(initial_response_sent.try_recv(), Err(TryRecvError::Empty));
|
||||
|
||||
response_tx
|
||||
.send(RuntimeResponse::Result {
|
||||
code_mode_host_duration: None,
|
||||
cell_id: cell_id.clone(),
|
||||
content_items: Vec::new(),
|
||||
result_buffered_for: Duration::ZERO,
|
||||
error_text: None,
|
||||
})
|
||||
.expect("initial response receiver");
|
||||
initial_response_sent
|
||||
.await
|
||||
.expect("initial response completion");
|
||||
outgoing_rx.recv().await.expect("initial response frame");
|
||||
assert_eq!(active_cell_permits.available_permits(), 0);
|
||||
|
||||
peer.close_cell(session_id("session-1"), cell_id);
|
||||
let permit = tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
Arc::clone(&active_cell_permits).acquire_owned(),
|
||||
)
|
||||
.await
|
||||
.expect("cell permit should be released")
|
||||
.expect("cell permit semaphore should remain open");
|
||||
drop(permit);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pending_delegate_limit_rejects_call_without_disconnecting() {
|
||||
let (outgoing_tx, _outgoing_rx) = mpsc::channel(/*max_capacity*/ 1);
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
let permits = Arc::clone(&peer.delegate_permits)
|
||||
.acquire_many_owned(MAX_PENDING_DELEGATE_CALLS as u32)
|
||||
.await
|
||||
.expect("delegate permits");
|
||||
|
||||
let result = peer
|
||||
.call(
|
||||
session_id("session-1"),
|
||||
DelegateRequest::Notify {
|
||||
call_id: "call-1".to_string(),
|
||||
cell_id: CellId::new("cell-1".to_string()).into(),
|
||||
text: "hello".to_string(),
|
||||
},
|
||||
CancellationToken::new(),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
Err("code-mode host has too many pending delegate calls".to_string())
|
||||
);
|
||||
assert!(!peer.is_disconnected());
|
||||
drop(permits);
|
||||
}
|
||||
69
codex-rs/code-mode-host/src/process_metrics.rs
Normal file
69
codex-rs/code-mode-host/src/process_metrics.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
//! Isolates optional synchronous metrics collection from the HTTP/2 driver and
|
||||
//! session admission. A stuck collector occupies at most one detached thread,
|
||||
//! which is never joined during host or Tokio runtime shutdown.
|
||||
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::panic::catch_unwind;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_code_mode_protocol::CodeModeProcessMetrics;
|
||||
use codex_code_mode_protocol::grpc;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::oneshot;
|
||||
use tonic::Response;
|
||||
use tonic::Status;
|
||||
|
||||
/// Collectors capture any resources they need before the host enters its sandbox.
|
||||
/// They must be bounded, read-only observations that do not acquire execution
|
||||
/// locks. Isolation covers unwinding panics and stalled collection, not process
|
||||
/// aborts, resource exhaustion, or interference through shared state. A collector
|
||||
/// that never returns disables further sampling for this host; it is not retried
|
||||
/// on another thread, and its worker is not joined during Tokio runtime shutdown.
|
||||
pub type CodeModeProcessMetricsCollector =
|
||||
Arc<dyn Fn() -> Result<CodeModeProcessMetrics, String> + Send + Sync>;
|
||||
|
||||
pub(crate) struct ProcessMetrics {
|
||||
collector: CodeModeProcessMetricsCollector,
|
||||
permits: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl ProcessMetrics {
|
||||
pub(crate) fn new(collector: CodeModeProcessMetricsCollector) -> Self {
|
||||
Self {
|
||||
collector,
|
||||
permits: Arc::new(Semaphore::new(/*permits*/ 1)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn sample(&self) -> Result<Response<grpc::GetProcessMetricsResponse>, Status> {
|
||||
let permit = self
|
||||
.permits
|
||||
.clone()
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| Status::resource_exhausted("process metrics collector is busy"))?;
|
||||
let collector = self.collector.clone();
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
// Do not use Tokio's blocking pool: runtime drop joins running blocking
|
||||
// tasks even after the request times out. Dropping this thread's handle
|
||||
// detaches it; the permit still bounds abandoned collection to one thread.
|
||||
std::thread::Builder::new()
|
||||
.name("code-mode-metrics".to_string())
|
||||
.spawn(move || {
|
||||
let result = catch_unwind(AssertUnwindSafe(|| collector()));
|
||||
drop(permit);
|
||||
let _ = sender.send(result);
|
||||
})
|
||||
.map_err(|_| Status::internal("process metrics worker could not start"))?;
|
||||
let snapshot = receiver
|
||||
.await
|
||||
.map_err(|_| Status::internal("process metrics worker ended"))?
|
||||
.map_err(|_| Status::internal("process metrics collector panicked"))?
|
||||
.map_err(|_| Status::internal("process metrics collection failed"))?;
|
||||
Ok(Response::new(grpc::GetProcessMetricsResponse {
|
||||
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,
|
||||
}))
|
||||
}
|
||||
}
|
||||
52
codex-rs/code-mode-host/src/transport.rs
Normal file
52
codex-rs/code-mode-host/src/transport.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
|
||||
use crate::grpc_transport;
|
||||
|
||||
/// The default transport retains the standalone host's original stdio behavior.
|
||||
pub const DEFAULT_LISTEN_URL: &str = "stdio";
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
enum ListenTransport {
|
||||
Stdio,
|
||||
GrpcStdio,
|
||||
Grpc(SocketAddr),
|
||||
}
|
||||
|
||||
pub(crate) async fn run_transport(listen_url: &str, host: crate::GrpcCodeModeHost) -> Result<()> {
|
||||
match parse_listen_url(listen_url)? {
|
||||
ListenTransport::Stdio => crate::run_stdio().await,
|
||||
ListenTransport::GrpcStdio => crate::grpc_stdio::run(host).await,
|
||||
ListenTransport::Grpc(bind_address) => {
|
||||
grpc_transport::run_tcp_listener(bind_address, host).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_listen_url(listen_url: &str) -> Result<ListenTransport> {
|
||||
if listen_url == "grpc+stdio://" {
|
||||
return Ok(ListenTransport::GrpcStdio);
|
||||
}
|
||||
if matches!(listen_url, "stdio" | "stdio://") {
|
||||
return Ok(ListenTransport::Stdio);
|
||||
}
|
||||
|
||||
if let Some(socket_addr) = listen_url.strip_prefix("grpc://") {
|
||||
return socket_addr
|
||||
.parse::<SocketAddr>()
|
||||
.map(ListenTransport::Grpc)
|
||||
.with_context(|| {
|
||||
format!("invalid gRPC --listen URL `{listen_url}`; expected `grpc://IP:PORT`")
|
||||
});
|
||||
}
|
||||
|
||||
anyhow::bail!(
|
||||
"unsupported --listen URL `{listen_url}`; expected `grpc://IP:PORT`, `grpc+stdio://`, `stdio`, or `stdio://`"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "transport_tests.rs"]
|
||||
mod tests;
|
||||
63
codex-rs/code-mode-host/src/transport_tests.rs
Normal file
63
codex-rs/code-mode-host/src/transport_tests.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use super::ListenTransport;
|
||||
use super::parse_listen_url;
|
||||
use crate::grpc_transport::bind_tcp_listener;
|
||||
|
||||
#[tokio::test]
|
||||
async fn grpc_listener_disables_nagle() {
|
||||
let bind_address = "127.0.0.1:0"
|
||||
.parse()
|
||||
.expect("gRPC test listener should have a valid bind address");
|
||||
let mut listener = bind_tcp_listener(bind_address)
|
||||
.await
|
||||
.expect("gRPC test listener should bind");
|
||||
let local_addr = listener
|
||||
.local_addr()
|
||||
.expect("gRPC test listener should have a local address");
|
||||
let _client = TcpStream::connect(local_addr)
|
||||
.await
|
||||
.expect("gRPC test client should connect");
|
||||
let nodelay = listener
|
||||
.next()
|
||||
.await
|
||||
.expect("gRPC test listener should accept a connection")
|
||||
.expect("gRPC test listener should return a valid socket")
|
||||
.nodelay()
|
||||
.expect("accepted gRPC socket should expose TCP_NODELAY");
|
||||
|
||||
assert!(nodelay);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_listen_url_accepts_stdio_transports() {
|
||||
assert_eq!(
|
||||
parse_listen_url("stdio").expect("stdio listen URL should parse"),
|
||||
ListenTransport::Stdio
|
||||
);
|
||||
assert_eq!(
|
||||
parse_listen_url("stdio://").expect("stdio URL should parse"),
|
||||
ListenTransport::Stdio
|
||||
);
|
||||
assert_eq!(
|
||||
parse_listen_url("grpc+stdio://").expect("gRPC stdio URL should parse"),
|
||||
ListenTransport::GrpcStdio
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_listen_url_rejects_invalid_transports() {
|
||||
let invalid_address = parse_listen_url("grpc://localhost:9000")
|
||||
.expect_err("gRPC listener requires an IP address");
|
||||
assert!(
|
||||
invalid_address
|
||||
.to_string()
|
||||
.contains("expected `grpc://IP:PORT`")
|
||||
);
|
||||
|
||||
let unsupported =
|
||||
parse_listen_url("http://127.0.0.1:9000").expect_err("HTTP is not a listen transport");
|
||||
assert!(unsupported.to_string().contains("unsupported --listen URL"));
|
||||
}
|
||||
Reference in New Issue
Block a user