mirror of
https://github.com/openai/codex.git
synced 2026-11-19 22:30:42 +00:00
Use gRPC for all code-mode host connections (#62476)
## What changed Remove the legacy framed stdio protocol and its client and server. Local Codex launches the standalone host with `--listen grpc+stdio://`, which is also the host's default. The `stdio` and `stdio://` aliases now select gRPC over stdio. The `features.code_mode_host_grpc` setting is deprecated and ignored. Carry execution trace context into gRPC tool callbacks and notifications. Reject oversized execute requests before sending them so an encoding failure does not appear as a connection reset. ## Testing Exercise gRPC callback cancellation, trace context across overlapping yielded cells, and isolation of tool preload failures between sessions. Check that both values of the deprecated feature setting are ignored. GitOrigin-RevId: f5faff3901dc60958627f677f50cfad834291b69
This commit is contained in:
committed by
copyberry
parent
083bf59b6b
commit
336dc645fb
@@ -17,7 +17,7 @@ codex-protocol = { workspace = true }
|
||||
prost = "0.14.3"
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { workspace = true, features = ["io-util", "sync"] }
|
||||
tokio = { workspace = true, features = ["sync"] }
|
||||
tokio-util = { workspace = true, features = ["rt"] }
|
||||
tonic = { workspace = true }
|
||||
tonic-prost = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
//! Resource limits shared by the code-mode host, client, and runtime.
|
||||
|
||||
/// Maximum encoded gRPC message size.
|
||||
pub const MAX_FRAME_BYTES: usize = 64 * 1024 * 1024;
|
||||
|
||||
/// Maximum number of unresolved delegate callbacks allowed per host connection.
|
||||
pub const MAX_PENDING_DELEGATE_CALLS: usize = 4_096;
|
||||
|
||||
/// Callback capacity of clients that do not advertise the larger budget.
|
||||
pub const LEGACY_MAX_PENDING_DELEGATE_CALLS: usize = 1_024;
|
||||
|
||||
/// Maximum aggregate text bytes retained per server-truncated observation.
|
||||
pub const BOUNDED_OUTPUT_MAX_BYTES: usize = 1024 * 1024;
|
||||
|
||||
/// Maximum aggregate inline image bytes retained per server-truncated observation.
|
||||
pub const BOUNDED_OUTPUT_MAX_IMAGE_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
/// Maximum aggregate encoded audio URL bytes retained per server-truncated observation.
|
||||
/// Count the whole URL, including the data URL prefix and any base64 payload.
|
||||
/// This leaves heuristic transport headroom but does not bound the complete response.
|
||||
pub const BOUNDED_OUTPUT_MAX_AUDIO_BYTES: usize = 62 * 1024 * 1024;
|
||||
@@ -1,170 +0,0 @@
|
||||
use std::io;
|
||||
use std::mem::size_of;
|
||||
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
/// Maximum JSON payload size accepted for one code-mode host frame.
|
||||
pub const MAX_FRAME_BYTES: usize = 64 * 1024 * 1024;
|
||||
|
||||
/// A serialized IPC frame that has already passed the payload size limit.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct EncodedFrame {
|
||||
payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl EncodedFrame {
|
||||
pub fn encode<T>(message: &T) -> io::Result<Self>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
let payload = serde_json::to_vec(message).map_err(|err| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("failed to encode code-mode IPC frame: {err}"),
|
||||
)
|
||||
})?;
|
||||
if payload.len() > MAX_FRAME_BYTES {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"code-mode IPC frame length {} exceeds {MAX_FRAME_BYTES} bytes",
|
||||
payload.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(Self { payload })
|
||||
}
|
||||
|
||||
/// Returns the complete length-prefixed representation of this frame.
|
||||
pub fn into_framed_bytes(self) -> Vec<u8> {
|
||||
let mut bytes = Vec::with_capacity(size_of::<u32>() + self.payload.len());
|
||||
bytes.extend_from_slice(&(self.payload.len() as u32).to_le_bytes());
|
||||
bytes.extend_from_slice(&self.payload);
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Decodes exactly one complete length-prefixed frame.
|
||||
pub fn decode_framed<T>(bytes: &[u8]) -> io::Result<T>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
{
|
||||
let length_bytes: [u8; size_of::<u32>()] = bytes
|
||||
.get(..size_of::<u32>())
|
||||
.and_then(|length_bytes| length_bytes.try_into().ok())
|
||||
.ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"code-mode IPC frame is missing its length prefix",
|
||||
)
|
||||
})?;
|
||||
let length = u32::from_le_bytes(length_bytes) as usize;
|
||||
if length > MAX_FRAME_BYTES {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("code-mode IPC frame length {length} exceeds {MAX_FRAME_BYTES} bytes"),
|
||||
));
|
||||
}
|
||||
|
||||
let payload = &bytes[size_of::<u32>()..];
|
||||
if payload.len() != length {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"code-mode IPC frame declares {length} payload bytes but contains {}",
|
||||
payload.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
serde_json::from_slice(payload).map_err(|err| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("failed to decode code-mode IPC frame: {err}"),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes JSON messages prefixed by a four-byte little-endian payload length.
|
||||
pub struct FramedReader<R> {
|
||||
reader: R,
|
||||
}
|
||||
|
||||
impl<R> FramedReader<R>
|
||||
where
|
||||
R: AsyncRead + Unpin,
|
||||
{
|
||||
pub fn new(reader: R) -> Self {
|
||||
Self { reader }
|
||||
}
|
||||
|
||||
/// Reads the next frame, returning `None` only for EOF at a frame boundary.
|
||||
pub async fn read<T>(&mut self) -> io::Result<Option<T>>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
{
|
||||
let mut length_bytes = [0_u8; size_of::<u32>()];
|
||||
if self.reader.read(&mut length_bytes[..1]).await? == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
self.reader.read_exact(&mut length_bytes[1..]).await?;
|
||||
|
||||
let length = u32::from_le_bytes(length_bytes) as usize;
|
||||
if length > MAX_FRAME_BYTES {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("code-mode IPC frame length {length} exceeds {MAX_FRAME_BYTES} bytes"),
|
||||
));
|
||||
}
|
||||
|
||||
let mut payload = vec![0; length];
|
||||
self.reader.read_exact(&mut payload).await?;
|
||||
serde_json::from_slice(&payload).map(Some).map_err(|err| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("failed to decode code-mode IPC frame: {err}"),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes JSON messages with a four-byte little-endian payload length.
|
||||
pub struct FramedWriter<W> {
|
||||
writer: W,
|
||||
}
|
||||
|
||||
impl<W> FramedWriter<W>
|
||||
where
|
||||
W: AsyncWrite + Unpin,
|
||||
{
|
||||
pub fn new(writer: W) -> Self {
|
||||
Self { writer }
|
||||
}
|
||||
|
||||
/// Writes and flushes one complete frame.
|
||||
pub async fn write<T>(&mut self, message: &T) -> io::Result<()>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.write_frame(&EncodedFrame::encode(message)?).await
|
||||
}
|
||||
|
||||
/// Writes and flushes a frame encoded before it entered an I/O queue.
|
||||
pub async fn write_frame(&mut self, frame: &EncodedFrame) -> io::Result<()> {
|
||||
let length = u32::try_from(frame.payload.len()).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"code-mode IPC frame length exceeds u32",
|
||||
)
|
||||
})?;
|
||||
|
||||
self.writer.write_all(&length.to_le_bytes()).await?;
|
||||
self.writer.write_all(&frame.payload).await?;
|
||||
self.writer.flush().await
|
||||
}
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
use super::EncodedFrame;
|
||||
use super::FramedReader;
|
||||
use super::FramedWriter;
|
||||
use super::MAX_FRAME_BYTES;
|
||||
|
||||
#[test]
|
||||
fn complete_frame_round_trips_without_a_byte_stream() {
|
||||
let value = json!({"type": "session/open", "sessionId": "session-1"});
|
||||
let bytes = EncodedFrame::encode(&value)
|
||||
.expect("encode frame")
|
||||
.into_framed_bytes();
|
||||
|
||||
assert_eq!(
|
||||
EncodedFrame::decode_framed::<serde_json::Value>(&bytes).expect("decode frame"),
|
||||
value
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn complete_frame_rejects_truncated_and_trailing_payloads() {
|
||||
let value = json!({"value": 1});
|
||||
let bytes = EncodedFrame::encode(&value)
|
||||
.expect("encode frame")
|
||||
.into_framed_bytes();
|
||||
|
||||
let truncated = &bytes[..bytes.len() - 1];
|
||||
let truncated_error = EncodedFrame::decode_framed::<serde_json::Value>(truncated)
|
||||
.expect_err("truncated frame should fail");
|
||||
assert_eq!(truncated_error.kind(), std::io::ErrorKind::InvalidData);
|
||||
|
||||
let mut trailing = bytes;
|
||||
trailing.push(0);
|
||||
let trailing_error = EncodedFrame::decode_framed::<serde_json::Value>(&trailing)
|
||||
.expect_err("frame with trailing bytes should fail");
|
||||
assert_eq!(trailing_error.kind(), std::io::ErrorKind::InvalidData);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn frame_wire_format_is_little_endian_length_prefixed_json() {
|
||||
let (writer, mut reader) = tokio::io::duplex(/*max_buf_size*/ 128);
|
||||
let write = tokio::spawn(async move {
|
||||
FramedWriter::new(writer)
|
||||
.write(&json!({"value": 1}))
|
||||
.await
|
||||
.expect("write frame");
|
||||
});
|
||||
|
||||
let mut bytes = Vec::new();
|
||||
reader.read_to_end(&mut bytes).await.expect("read bytes");
|
||||
write.await.expect("writer task");
|
||||
|
||||
let payload = br#"{"value":1}"#;
|
||||
let mut expected = (payload.len() as u32).to_le_bytes().to_vec();
|
||||
expected.extend_from_slice(payload);
|
||||
assert_eq!(bytes, expected);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fragmented_frame_round_trips() {
|
||||
let value = json!({"type": "session/open", "sessionId": "session-1"});
|
||||
let payload = serde_json::to_vec(&value).expect("serialize");
|
||||
let mut bytes = (payload.len() as u32).to_le_bytes().to_vec();
|
||||
bytes.extend(payload);
|
||||
|
||||
let (mut writer, reader) = tokio::io::duplex(/*max_buf_size*/ 128);
|
||||
let write = tokio::spawn(async move {
|
||||
for byte in bytes {
|
||||
writer.write_all(&[byte]).await.expect("write byte");
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
FramedReader::new(reader)
|
||||
.read::<serde_json::Value>()
|
||||
.await
|
||||
.expect("read frame"),
|
||||
Some(value)
|
||||
);
|
||||
write.await.expect("writer task");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn eof_is_clean_only_at_a_frame_boundary() {
|
||||
let (writer, reader) = tokio::io::duplex(/*max_buf_size*/ 16);
|
||||
drop(writer);
|
||||
assert_eq!(
|
||||
FramedReader::new(reader)
|
||||
.read::<serde_json::Value>()
|
||||
.await
|
||||
.expect("clean eof"),
|
||||
None
|
||||
);
|
||||
|
||||
let (mut writer, reader) = tokio::io::duplex(/*max_buf_size*/ 16);
|
||||
writer
|
||||
.write_all(&[1, 0])
|
||||
.await
|
||||
.expect("write partial header");
|
||||
drop(writer);
|
||||
let err = FramedReader::new(reader)
|
||||
.read::<serde_json::Value>()
|
||||
.await
|
||||
.expect_err("truncated header");
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn oversized_and_malformed_frames_are_rejected() {
|
||||
let (mut writer, reader) = tokio::io::duplex(/*max_buf_size*/ 16);
|
||||
writer
|
||||
.write_all(&((MAX_FRAME_BYTES as u32) + 1).to_le_bytes())
|
||||
.await
|
||||
.expect("write oversized header");
|
||||
let err = FramedReader::new(reader)
|
||||
.read::<serde_json::Value>()
|
||||
.await
|
||||
.expect_err("oversized frame");
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
|
||||
|
||||
let (mut writer, reader) = tokio::io::duplex(/*max_buf_size*/ 16);
|
||||
writer
|
||||
.write_all(&(1_u32).to_le_bytes())
|
||||
.await
|
||||
.expect("write length");
|
||||
writer.write_all(b"{").await.expect("write malformed json");
|
||||
let err = FramedReader::new(reader)
|
||||
.read::<serde_json::Value>()
|
||||
.await
|
||||
.expect_err("malformed frame");
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use super::Capability;
|
||||
use super::SupportedProtocolVersions;
|
||||
|
||||
/// Explains why connection negotiation was rejected before any session opened.
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields, tag = "type", rename_all_fields = "camelCase")]
|
||||
pub enum HandshakeRejectReason {
|
||||
#[serde(rename = "noCompatibleVersion")]
|
||||
NoCompatibleVersion {
|
||||
supported_versions: SupportedProtocolVersions,
|
||||
},
|
||||
#[serde(rename = "missingRequiredCapability")]
|
||||
MissingRequiredCapability { capability: Capability },
|
||||
#[serde(rename = "invalidHello")]
|
||||
InvalidHello { message: String },
|
||||
}
|
||||
@@ -1,868 +0,0 @@
|
||||
use std::fmt::Debug;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
|
||||
use super::Capability;
|
||||
use super::CapabilitySet;
|
||||
use super::ClientHello;
|
||||
use super::ClientToHost;
|
||||
use super::DelegateRequest;
|
||||
use super::DelegateRequestId;
|
||||
use super::DelegateResponse;
|
||||
use super::HandshakeRejectReason;
|
||||
use super::HostHello;
|
||||
use super::HostRequest;
|
||||
use super::HostResponse;
|
||||
use super::HostToClient;
|
||||
use super::ProtocolVersion;
|
||||
use super::RequestId;
|
||||
use super::SessionId;
|
||||
use super::SupportedProtocolVersions;
|
||||
use super::WireCellId;
|
||||
use super::WireContentItem;
|
||||
use super::WireExecuteRequest;
|
||||
use super::WireImageDetail;
|
||||
use super::WireNestedToolCall;
|
||||
use super::WireOutputTruncation;
|
||||
use super::WireResult;
|
||||
use super::WireRuntimeResponse;
|
||||
use super::WireSessionCellExecutionLimits;
|
||||
use super::WireToolDefinition;
|
||||
use super::WireToolKind;
|
||||
use super::WireToolName;
|
||||
use super::WireWaitOutcome;
|
||||
use super::WireWaitRequest;
|
||||
use crate::CodeModeSessionCellExecutionLimits;
|
||||
use crate::ExecuteRequest;
|
||||
|
||||
fn session_id() -> SessionId {
|
||||
SessionId::new("session-1").expect("valid session ID")
|
||||
}
|
||||
|
||||
fn cell_id(value: &str) -> WireCellId {
|
||||
WireCellId::new(value)
|
||||
}
|
||||
|
||||
fn request_id(value: i64) -> RequestId {
|
||||
RequestId::new(value)
|
||||
}
|
||||
|
||||
fn delegate_request_id(value: i64) -> DelegateRequestId {
|
||||
DelegateRequestId::new(value)
|
||||
}
|
||||
|
||||
fn capability(value: &str) -> Capability {
|
||||
Capability::new(value).expect("valid capability")
|
||||
}
|
||||
|
||||
fn supported_versions() -> SupportedProtocolVersions {
|
||||
SupportedProtocolVersions::try_new([ProtocolVersion::V1])
|
||||
.expect("nonempty unique protocol versions")
|
||||
}
|
||||
|
||||
fn assert_wire_round_trip<T>(message: T, encoded: Value)
|
||||
where
|
||||
T: Debug + DeserializeOwned + PartialEq + Serialize,
|
||||
{
|
||||
assert_eq!(serde_json::to_value(&message).expect("serialize"), encoded);
|
||||
assert_eq!(
|
||||
serde_json::from_value::<T>(encoded).expect("deserialize"),
|
||||
message
|
||||
);
|
||||
}
|
||||
|
||||
fn execute_request() -> WireExecuteRequest {
|
||||
WireExecuteRequest {
|
||||
catalog_revision: None,
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: vec![
|
||||
WireToolDefinition {
|
||||
name: "function_tool".to_string(),
|
||||
tool_name: WireToolName {
|
||||
name: "function_tool".to_string(),
|
||||
namespace: None,
|
||||
},
|
||||
description: "function tool".to_string(),
|
||||
kind: WireToolKind::Function,
|
||||
input_schema: Some(json!({ "type": "object" })),
|
||||
output_schema: None,
|
||||
},
|
||||
WireToolDefinition {
|
||||
name: "freeform_tool".to_string(),
|
||||
tool_name: WireToolName {
|
||||
name: "freeform_tool".to_string(),
|
||||
namespace: Some("mcp__sample__".to_string()),
|
||||
},
|
||||
description: "freeform tool".to_string(),
|
||||
kind: WireToolKind::Freeform,
|
||||
input_schema: None,
|
||||
output_schema: Some(json!({ "type": "string" })),
|
||||
},
|
||||
],
|
||||
source: "text('hello');".to_string(),
|
||||
yield_time_ms: Some(25),
|
||||
max_output_tokens: Some(100),
|
||||
}
|
||||
}
|
||||
|
||||
fn content_items() -> Vec<WireContentItem> {
|
||||
vec![
|
||||
WireContentItem::InputText {
|
||||
text: "hello".to_string(),
|
||||
},
|
||||
WireContentItem::InputImage {
|
||||
image_url: "data:image/png;base64,none".to_string(),
|
||||
detail: None,
|
||||
},
|
||||
WireContentItem::InputImage {
|
||||
image_url: "data:image/png;base64,auto".to_string(),
|
||||
detail: Some(WireImageDetail::Auto),
|
||||
},
|
||||
WireContentItem::InputImage {
|
||||
image_url: "data:image/png;base64,low".to_string(),
|
||||
detail: Some(WireImageDetail::Low),
|
||||
},
|
||||
WireContentItem::InputImage {
|
||||
image_url: "data:image/png;base64,high".to_string(),
|
||||
detail: Some(WireImageDetail::High),
|
||||
},
|
||||
WireContentItem::InputImage {
|
||||
image_url: "data:image/png;base64,original".to_string(),
|
||||
detail: Some(WireImageDetail::Original),
|
||||
},
|
||||
WireContentItem::InputAudio {
|
||||
audio_url: "data:audio/wav;base64,YXVkaW8=".to_string(),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn content_items_json() -> Value {
|
||||
json!([
|
||||
{ "type": "input_text", "text": "hello" },
|
||||
{ "type": "input_image", "image_url": "data:image/png;base64,none" },
|
||||
{
|
||||
"type": "input_image",
|
||||
"image_url": "data:image/png;base64,auto",
|
||||
"detail": "auto",
|
||||
},
|
||||
{
|
||||
"type": "input_image",
|
||||
"image_url": "data:image/png;base64,low",
|
||||
"detail": "low",
|
||||
},
|
||||
{
|
||||
"type": "input_image",
|
||||
"image_url": "data:image/png;base64,high",
|
||||
"detail": "high",
|
||||
},
|
||||
{
|
||||
"type": "input_image",
|
||||
"image_url": "data:image/png;base64,original",
|
||||
"detail": "original",
|
||||
},
|
||||
{
|
||||
"type": "input_audio",
|
||||
"audio_url": "data:audio/wav;base64,YXVkaW8=",
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handshake_v1_variants_are_pinned() {
|
||||
assert_wire_round_trip(
|
||||
ClientToHost::ClientHello(
|
||||
ClientHello::new(
|
||||
supported_versions(),
|
||||
CapabilitySet::try_new([capability("required")]).expect("valid required set"),
|
||||
CapabilitySet::try_new([capability("optional")]).expect("valid optional set"),
|
||||
)
|
||||
.expect("disjoint capabilities"),
|
||||
),
|
||||
json!({
|
||||
"type": "connection/hello",
|
||||
"supportedVersions": [1],
|
||||
"requiredCapabilities": ["required"],
|
||||
"optionalCapabilities": ["optional"],
|
||||
}),
|
||||
);
|
||||
assert_wire_round_trip(
|
||||
HostToClient::HostHello(HostHello::new(
|
||||
ProtocolVersion::V1,
|
||||
CapabilitySet::try_new([capability("required")]).expect("valid capabilities"),
|
||||
)),
|
||||
json!({
|
||||
"type": "connection/ready",
|
||||
"selectedVersion": 1,
|
||||
"capabilities": ["required"],
|
||||
}),
|
||||
);
|
||||
for (reason, encoded) in [
|
||||
(
|
||||
HandshakeRejectReason::NoCompatibleVersion {
|
||||
supported_versions: supported_versions(),
|
||||
},
|
||||
json!({
|
||||
"type": "connection/rejected",
|
||||
"reason": {
|
||||
"type": "noCompatibleVersion",
|
||||
"supportedVersions": [1],
|
||||
},
|
||||
}),
|
||||
),
|
||||
(
|
||||
HandshakeRejectReason::MissingRequiredCapability {
|
||||
capability: capability("required"),
|
||||
},
|
||||
json!({
|
||||
"type": "connection/rejected",
|
||||
"reason": {
|
||||
"type": "missingRequiredCapability",
|
||||
"capability": "required",
|
||||
},
|
||||
}),
|
||||
),
|
||||
(
|
||||
HandshakeRejectReason::InvalidHello {
|
||||
message: "invalid hello".to_string(),
|
||||
},
|
||||
json!({
|
||||
"type": "connection/rejected",
|
||||
"reason": {
|
||||
"type": "invalidHello",
|
||||
"message": "invalid hello",
|
||||
},
|
||||
}),
|
||||
),
|
||||
] {
|
||||
assert_wire_round_trip(HostToClient::HandshakeRejected { reason }, encoded);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_session_serializes_optional_cell_execution_limits() {
|
||||
assert_wire_round_trip(
|
||||
HostRequest::OpenSession {
|
||||
session_id: session_id(),
|
||||
cell_execution_limits: Some(WireSessionCellExecutionLimits {
|
||||
max_yield_time_ms: Some(250),
|
||||
max_heap_size_bytes: Some(16 * 1024 * 1024),
|
||||
}),
|
||||
output_truncation: None,
|
||||
},
|
||||
json!({
|
||||
"method": "session/open",
|
||||
"sessionId": "session-1",
|
||||
"cellExecutionLimits": {
|
||||
"maxYieldTimeMs": 250,
|
||||
"maxHeapSizeBytes": 16 * 1024 * 1024,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_cell_execution_limits_convert_between_domain_and_wire() {
|
||||
let domain_limits = CodeModeSessionCellExecutionLimits {
|
||||
max_yield_time_ms: Some(250),
|
||||
max_heap_size_bytes: Some(16_usize * 1024 * 1024),
|
||||
};
|
||||
let wire_limits = WireSessionCellExecutionLimits {
|
||||
max_yield_time_ms: Some(250),
|
||||
max_heap_size_bytes: Some(16_u64 * 1024 * 1024),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
WireSessionCellExecutionLimits::try_from(domain_limits.clone())
|
||||
.expect("domain limits convert to wire limits"),
|
||||
wire_limits
|
||||
);
|
||||
assert_eq!(
|
||||
CodeModeSessionCellExecutionLimits::try_from(wire_limits)
|
||||
.expect("wire limits convert to domain limits"),
|
||||
domain_limits
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_pointer_width = "32")]
|
||||
#[test]
|
||||
fn session_cell_execution_limits_reject_heap_sizes_that_exceed_usize() {
|
||||
let wire_limits = WireSessionCellExecutionLimits {
|
||||
max_yield_time_ms: None,
|
||||
max_heap_size_bytes: Some(u64::from(u32::MAX) + 1),
|
||||
};
|
||||
|
||||
assert!(CodeModeSessionCellExecutionLimits::try_from(wire_limits).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_to_host_v1_variants_are_pinned() {
|
||||
let execute_request = execute_request();
|
||||
for (id, request, encoded_request) in [
|
||||
(
|
||||
request_id(/*value*/ 1),
|
||||
HostRequest::OpenSession {
|
||||
session_id: session_id(),
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
},
|
||||
json!({ "method": "session/open", "sessionId": "session-1" }),
|
||||
),
|
||||
(
|
||||
request_id(/*value*/ 10),
|
||||
HostRequest::OpenSession {
|
||||
session_id: session_id(),
|
||||
cell_execution_limits: None,
|
||||
output_truncation: Some(WireOutputTruncation::Server),
|
||||
},
|
||||
json!({
|
||||
"method": "session/open",
|
||||
"sessionId": "session-1",
|
||||
"outputTruncation": "server",
|
||||
}),
|
||||
),
|
||||
(
|
||||
request_id(/*value*/ 2),
|
||||
HostRequest::Execute {
|
||||
session_id: session_id(),
|
||||
request: execute_request,
|
||||
},
|
||||
json!({
|
||||
"method": "session/execute",
|
||||
"sessionId": "session-1",
|
||||
"request": {
|
||||
"tool_call_id": "call-1",
|
||||
"enabled_tools": [
|
||||
{
|
||||
"name": "function_tool",
|
||||
"tool_name": { "name": "function_tool", "namespace": null },
|
||||
"description": "function tool",
|
||||
"kind": "function",
|
||||
"input_schema": { "type": "object" },
|
||||
"output_schema": null,
|
||||
},
|
||||
{
|
||||
"name": "freeform_tool",
|
||||
"tool_name": {
|
||||
"name": "freeform_tool",
|
||||
"namespace": "mcp__sample__",
|
||||
},
|
||||
"description": "freeform tool",
|
||||
"kind": "freeform",
|
||||
"input_schema": null,
|
||||
"output_schema": { "type": "string" },
|
||||
},
|
||||
],
|
||||
"source": "text('hello');",
|
||||
"yield_time_ms": 25,
|
||||
"max_output_tokens": 100,
|
||||
},
|
||||
}),
|
||||
),
|
||||
(
|
||||
request_id(/*value*/ 3),
|
||||
HostRequest::Wait {
|
||||
session_id: session_id(),
|
||||
request: WireWaitRequest {
|
||||
cell_id: cell_id("cell-1"),
|
||||
yield_time_ms: 50,
|
||||
},
|
||||
max_output_tokens: None,
|
||||
},
|
||||
json!({
|
||||
"method": "session/wait",
|
||||
"sessionId": "session-1",
|
||||
"request": { "cell_id": "cell-1", "yield_time_ms": 50 },
|
||||
}),
|
||||
),
|
||||
(
|
||||
request_id(/*value*/ 4),
|
||||
HostRequest::Terminate {
|
||||
session_id: session_id(),
|
||||
cell_id: cell_id("cell-1"),
|
||||
max_output_tokens: None,
|
||||
},
|
||||
json!({
|
||||
"method": "session/terminate",
|
||||
"sessionId": "session-1",
|
||||
"cellId": "cell-1",
|
||||
}),
|
||||
),
|
||||
(
|
||||
request_id(/*value*/ 5),
|
||||
HostRequest::ShutdownSession {
|
||||
session_id: session_id(),
|
||||
},
|
||||
json!({ "method": "session/shutdown", "sessionId": "session-1" }),
|
||||
),
|
||||
] {
|
||||
assert_wire_round_trip(
|
||||
ClientToHost::Request { id, request },
|
||||
json!({
|
||||
"type": "operation/request",
|
||||
"id": id,
|
||||
"request": encoded_request,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
for (id, result, encoded_result) in [
|
||||
(
|
||||
delegate_request_id(/*value*/ 6),
|
||||
WireResult::Ok {
|
||||
value: DelegateResponse::ToolResult {
|
||||
result: json!({ "answer": 42 }),
|
||||
},
|
||||
},
|
||||
json!({
|
||||
"status": "ok",
|
||||
"value": { "type": "tool/result", "result": { "answer": 42 } },
|
||||
}),
|
||||
),
|
||||
(
|
||||
delegate_request_id(/*value*/ 7),
|
||||
WireResult::Ok {
|
||||
value: DelegateResponse::NotificationDelivered,
|
||||
},
|
||||
json!({
|
||||
"status": "ok",
|
||||
"value": { "type": "notification/delivered" },
|
||||
}),
|
||||
),
|
||||
(
|
||||
delegate_request_id(/*value*/ 8),
|
||||
WireResult::Err {
|
||||
message: "delegate failed".to_string(),
|
||||
},
|
||||
json!({ "status": "error", "message": "delegate failed" }),
|
||||
),
|
||||
] {
|
||||
assert_wire_round_trip(
|
||||
ClientToHost::DelegateResponse { id, result },
|
||||
json!({
|
||||
"type": "delegate/response",
|
||||
"id": id,
|
||||
"result": encoded_result,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
assert_wire_round_trip(
|
||||
ClientToHost::CancelRequest {
|
||||
id: request_id(/*value*/ 9),
|
||||
},
|
||||
json!({
|
||||
"type": "operation/cancel",
|
||||
"id": 9,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_to_client_v1_variants_are_pinned() {
|
||||
for (id, response, encoded_response) in [
|
||||
(
|
||||
request_id(/*value*/ 1),
|
||||
HostResponse::SessionReady {
|
||||
session_id: session_id(),
|
||||
},
|
||||
json!({ "type": "session/ready", "sessionId": "session-1" }),
|
||||
),
|
||||
(
|
||||
request_id(/*value*/ 2),
|
||||
HostResponse::ExecutionStarted {
|
||||
cell_id: cell_id("cell-1"),
|
||||
},
|
||||
json!({ "type": "execution/started", "cellId": "cell-1" }),
|
||||
),
|
||||
(
|
||||
request_id(/*value*/ 3),
|
||||
HostResponse::WaitCompleted {
|
||||
outcome: WireWaitOutcome::LiveCell(WireRuntimeResponse::Yielded {
|
||||
code_mode_host_duration_ns: 0,
|
||||
cell_id: cell_id("cell-1"),
|
||||
content_items: content_items(),
|
||||
}),
|
||||
},
|
||||
json!({
|
||||
"type": "wait/completed",
|
||||
"outcome": {
|
||||
"LiveCell": {
|
||||
"Yielded": {
|
||||
"cell_id": "cell-1",
|
||||
"content_items": content_items_json(),
|
||||
"code_mode_host_duration_ns": 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
(
|
||||
request_id(/*value*/ 4),
|
||||
HostResponse::WaitCompleted {
|
||||
outcome: WireWaitOutcome::MissingCell(WireRuntimeResponse::Result {
|
||||
code_mode_host_duration_ns: 0,
|
||||
cell_id: cell_id("missing-cell"),
|
||||
content_items: Vec::new(),
|
||||
result_buffered_for_ns: 0,
|
||||
error_text: Some("cell not found".to_string()),
|
||||
}),
|
||||
},
|
||||
json!({
|
||||
"type": "wait/completed",
|
||||
"outcome": {
|
||||
"MissingCell": {
|
||||
"Result": {
|
||||
"cell_id": "missing-cell",
|
||||
"content_items": [],
|
||||
"error_text": "cell not found",
|
||||
"result_buffered_for_ns": 0,
|
||||
"code_mode_host_duration_ns": 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
(
|
||||
request_id(/*value*/ 5),
|
||||
HostResponse::SessionClosed {
|
||||
session_id: session_id(),
|
||||
},
|
||||
json!({ "type": "session/closed", "sessionId": "session-1" }),
|
||||
),
|
||||
] {
|
||||
assert_wire_round_trip(
|
||||
HostToClient::Response {
|
||||
id,
|
||||
result: WireResult::Ok { value: response },
|
||||
},
|
||||
json!({
|
||||
"type": "operation/response",
|
||||
"id": id,
|
||||
"result": { "status": "ok", "value": encoded_response },
|
||||
}),
|
||||
);
|
||||
}
|
||||
assert_wire_round_trip(
|
||||
HostToClient::Response {
|
||||
id: request_id(/*value*/ 6),
|
||||
result: WireResult::Err {
|
||||
message: "operation failed".to_string(),
|
||||
},
|
||||
},
|
||||
json!({
|
||||
"type": "operation/response",
|
||||
"id": 6,
|
||||
"result": { "status": "error", "message": "operation failed" },
|
||||
}),
|
||||
);
|
||||
|
||||
assert_wire_round_trip(
|
||||
HostToClient::InitialResponse {
|
||||
id: request_id(/*value*/ 7),
|
||||
result: WireResult::Ok {
|
||||
value: WireRuntimeResponse::Terminated {
|
||||
code_mode_host_duration_ns: 0,
|
||||
cell_id: cell_id("cell-1"),
|
||||
content_items: Vec::new(),
|
||||
},
|
||||
},
|
||||
},
|
||||
json!({
|
||||
"type": "execute/initialResponse",
|
||||
"id": 7,
|
||||
"result": {
|
||||
"status": "ok",
|
||||
"value": {
|
||||
"Terminated": {
|
||||
"cell_id": "cell-1",
|
||||
"content_items": [],
|
||||
"code_mode_host_duration_ns": 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert_wire_round_trip(
|
||||
HostToClient::InitialResponse {
|
||||
id: request_id(/*value*/ 8),
|
||||
result: WireResult::Err {
|
||||
message: "execution failed".to_string(),
|
||||
},
|
||||
},
|
||||
json!({
|
||||
"type": "execute/initialResponse",
|
||||
"id": 8,
|
||||
"result": { "status": "error", "message": "execution failed" },
|
||||
}),
|
||||
);
|
||||
|
||||
assert_wire_round_trip(
|
||||
HostToClient::DelegateRequest {
|
||||
id: delegate_request_id(/*value*/ 9),
|
||||
session_id: session_id(),
|
||||
request: DelegateRequest::InvokeTool {
|
||||
invocation: WireNestedToolCall {
|
||||
cell_id: cell_id("cell-1"),
|
||||
runtime_tool_call_id: "runtime-call-1".to_string(),
|
||||
tool_name: WireToolName {
|
||||
name: "freeform_tool".to_string(),
|
||||
namespace: Some("mcp__sample__".to_string()),
|
||||
},
|
||||
tool_kind: WireToolKind::Freeform,
|
||||
input: Some(json!({ "value": 1 })),
|
||||
},
|
||||
},
|
||||
},
|
||||
json!({
|
||||
"type": "delegate/request",
|
||||
"id": 9,
|
||||
"sessionId": "session-1",
|
||||
"request": {
|
||||
"type": "tool/invoke",
|
||||
"invocation": {
|
||||
"cell_id": "cell-1",
|
||||
"runtime_tool_call_id": "runtime-call-1",
|
||||
"tool_name": {
|
||||
"name": "freeform_tool",
|
||||
"namespace": "mcp__sample__",
|
||||
},
|
||||
"tool_kind": "freeform",
|
||||
"input": { "value": 1 },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert_wire_round_trip(
|
||||
HostToClient::DelegateRequest {
|
||||
id: delegate_request_id(/*value*/ 10),
|
||||
session_id: session_id(),
|
||||
request: DelegateRequest::Notify {
|
||||
call_id: "call-1".to_string(),
|
||||
cell_id: cell_id("cell-1"),
|
||||
text: "important".to_string(),
|
||||
},
|
||||
},
|
||||
json!({
|
||||
"type": "delegate/request",
|
||||
"id": 10,
|
||||
"sessionId": "session-1",
|
||||
"request": {
|
||||
"type": "notification/send",
|
||||
"callId": "call-1",
|
||||
"cellId": "cell-1",
|
||||
"text": "important",
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert_wire_round_trip(
|
||||
HostToClient::CancelDelegateRequest {
|
||||
id: delegate_request_id(/*value*/ 11),
|
||||
},
|
||||
json!({ "type": "delegate/cancel", "id": 11 }),
|
||||
);
|
||||
assert_wire_round_trip(
|
||||
HostToClient::CellClosed {
|
||||
session_id: session_id(),
|
||||
cell_id: cell_id("cell-1"),
|
||||
},
|
||||
json!({
|
||||
"type": "cell/closed",
|
||||
"sessionId": "session-1",
|
||||
"cellId": "cell-1",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn execute_request_integer_bounds_are_enforced() {
|
||||
let wire_request = execute_request();
|
||||
let domain_request = ExecuteRequest::try_from(wire_request.clone())
|
||||
.expect("valid wire request converts to the domain");
|
||||
assert_eq!(
|
||||
WireExecuteRequest::try_from(domain_request.clone())
|
||||
.expect("valid domain request converts to the wire"),
|
||||
wire_request
|
||||
);
|
||||
|
||||
let too_large = ExecuteRequest {
|
||||
max_output_tokens: Some(usize::try_from(i32::MAX).expect("i32::MAX fits usize") + 1),
|
||||
..domain_request
|
||||
};
|
||||
assert!(WireExecuteRequest::try_from(too_large).is_err());
|
||||
|
||||
let negative = WireExecuteRequest {
|
||||
max_output_tokens: Some(-1),
|
||||
..wire_request
|
||||
};
|
||||
assert!(ExecuteRequest::try_from(negative).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_protocol_states_cannot_be_constructed_or_decoded() {
|
||||
assert!(SessionId::new("").is_err());
|
||||
assert!(Capability::new(" ").is_err());
|
||||
assert!(ProtocolVersion::new(/*value*/ 0).is_none());
|
||||
assert!(SupportedProtocolVersions::try_new([]).is_err());
|
||||
assert!(
|
||||
SupportedProtocolVersions::try_new([ProtocolVersion::V1, ProtocolVersion::V1]).is_err()
|
||||
);
|
||||
assert!(CapabilitySet::try_new([capability("same"), capability("same")]).is_err());
|
||||
|
||||
let version_two = ProtocolVersion::new(/*value*/ 2).expect("valid protocol version");
|
||||
let versions = SupportedProtocolVersions::try_new([ProtocolVersion::V1, version_two])
|
||||
.expect("valid versions");
|
||||
assert!(versions.contains(ProtocolVersion::V1));
|
||||
assert_eq!(
|
||||
versions.iter().collect::<Vec<_>>(),
|
||||
vec![ProtocolVersion::V1, version_two]
|
||||
);
|
||||
|
||||
let overlapping = capability("overlapping");
|
||||
assert!(
|
||||
ClientHello::new(
|
||||
supported_versions(),
|
||||
CapabilitySet::try_new([overlapping.clone()]).expect("valid required set"),
|
||||
CapabilitySet::try_new([overlapping]).expect("valid optional set"),
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
|
||||
for invalid in [
|
||||
json!({
|
||||
"type": "operation/request",
|
||||
"id": 1,
|
||||
"request": { "method": "session/open", "sessionId": "" },
|
||||
}),
|
||||
json!({
|
||||
"type": "connection/hello",
|
||||
"supportedVersions": [],
|
||||
"requiredCapabilities": [],
|
||||
"optionalCapabilities": [],
|
||||
}),
|
||||
json!({
|
||||
"type": "connection/hello",
|
||||
"supportedVersions": [1],
|
||||
"requiredCapabilities": ["overlapping"],
|
||||
"optionalCapabilities": ["overlapping"],
|
||||
}),
|
||||
] {
|
||||
assert!(serde_json::from_value::<ClientToHost>(invalid).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_nested_v1_object_rejects_unknown_fields() {
|
||||
assert!(
|
||||
serde_json::from_value::<ClientToHost>(json!({
|
||||
"type": "operation/request",
|
||||
"id": 1,
|
||||
"request": { "method": "session/open", "sessionId": "session-1" },
|
||||
"unexpected": true,
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
serde_json::from_value::<HostRequest>(json!({
|
||||
"method": "session/open",
|
||||
"sessionId": "session-1",
|
||||
"unexpected": true,
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
serde_json::from_value::<HostRequest>(json!({
|
||||
"method": "session/open",
|
||||
"sessionId": "session-1",
|
||||
"cellExecutionLimits": {
|
||||
"maxYieldTimeMs": 250,
|
||||
"unexpected": true,
|
||||
},
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
serde_json::from_value::<WireExecuteRequest>(json!({
|
||||
"tool_call_id": "call-1",
|
||||
"enabled_tools": [],
|
||||
"source": "text('hello');",
|
||||
"yield_time_ms": null,
|
||||
"max_output_tokens": null,
|
||||
"unexpected": true,
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
serde_json::from_value::<WireToolDefinition>(json!({
|
||||
"name": "tool",
|
||||
"tool_name": { "name": "tool", "namespace": null },
|
||||
"description": "tool",
|
||||
"kind": "function",
|
||||
"input_schema": null,
|
||||
"output_schema": null,
|
||||
"unexpected": true,
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
serde_json::from_value::<WireToolName>(json!({
|
||||
"name": "tool",
|
||||
"namespace": null,
|
||||
"unexpected": true,
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
serde_json::from_value::<WireWaitRequest>(json!({
|
||||
"cell_id": "cell-1",
|
||||
"yield_time_ms": 50,
|
||||
"unexpected": true,
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
serde_json::from_value::<WireRuntimeResponse>(json!({
|
||||
"Yielded": {
|
||||
"cell_id": "cell-1",
|
||||
"content_items": [],
|
||||
"code_mode_host_duration_ns": 0,
|
||||
"unexpected": true,
|
||||
},
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
serde_json::from_value::<WireContentItem>(json!({
|
||||
"type": "input_text",
|
||||
"text": "hello",
|
||||
"unexpected": true,
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
serde_json::from_value::<WireNestedToolCall>(json!({
|
||||
"cell_id": "cell-1",
|
||||
"runtime_tool_call_id": "runtime-call-1",
|
||||
"tool_name": { "name": "tool", "namespace": null },
|
||||
"tool_kind": "function",
|
||||
"input": null,
|
||||
"unexpected": true,
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
serde_json::from_value::<HostToClient>(json!({
|
||||
"type": "operation/response",
|
||||
"id": 1,
|
||||
"result": {
|
||||
"status": "ok",
|
||||
"value": { "type": "session/ready", "sessionId": "session-1" },
|
||||
},
|
||||
"unexpected": true,
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
@@ -1,276 +0,0 @@
|
||||
use std::fmt;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value as JsonValue;
|
||||
|
||||
use super::Capability;
|
||||
use super::CapabilitySet;
|
||||
use super::DelegateRequestId;
|
||||
use super::HandshakeRejectReason;
|
||||
use super::ProtocolVersion;
|
||||
use super::RequestId;
|
||||
use super::SessionId;
|
||||
use super::SupportedProtocolVersions;
|
||||
use super::WireCellId;
|
||||
use super::WireExecuteRequest;
|
||||
use super::WireNestedToolCall;
|
||||
use super::WireOutputTruncation;
|
||||
use super::WireRuntimeResponse;
|
||||
use super::WireSessionCellExecutionLimits;
|
||||
use super::WireWaitOutcome;
|
||||
use super::WireWaitRequest;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ClientHello {
|
||||
supported_versions: SupportedProtocolVersions,
|
||||
required_capabilities: CapabilitySet,
|
||||
optional_capabilities: CapabilitySet,
|
||||
}
|
||||
|
||||
impl ClientHello {
|
||||
pub fn new(
|
||||
supported_versions: SupportedProtocolVersions,
|
||||
required_capabilities: CapabilitySet,
|
||||
optional_capabilities: CapabilitySet,
|
||||
) -> Result<Self, ClientHelloError> {
|
||||
if let Some(capability) = required_capabilities
|
||||
.iter()
|
||||
.find(|capability| optional_capabilities.contains(capability))
|
||||
{
|
||||
return Err(ClientHelloError::OverlappingCapability(capability.clone()));
|
||||
}
|
||||
Ok(Self {
|
||||
supported_versions,
|
||||
required_capabilities,
|
||||
optional_capabilities,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn supported_versions(&self) -> &SupportedProtocolVersions {
|
||||
&self.supported_versions
|
||||
}
|
||||
|
||||
pub fn required_capabilities(&self) -> &CapabilitySet {
|
||||
&self.required_capabilities
|
||||
}
|
||||
|
||||
pub fn optional_capabilities(&self) -> &CapabilitySet {
|
||||
&self.optional_capabilities
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
struct ClientHelloWire {
|
||||
supported_versions: SupportedProtocolVersions,
|
||||
required_capabilities: CapabilitySet,
|
||||
optional_capabilities: CapabilitySet,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for ClientHello {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let wire = ClientHelloWire::deserialize(deserializer)?;
|
||||
Self::new(
|
||||
wire.supported_versions,
|
||||
wire.required_capabilities,
|
||||
wire.optional_capabilities,
|
||||
)
|
||||
.map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum ClientHelloError {
|
||||
OverlappingCapability(Capability),
|
||||
}
|
||||
|
||||
impl fmt::Display for ClientHelloError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::OverlappingCapability(capability) => write!(
|
||||
formatter,
|
||||
"capability `{capability}` cannot be both required and optional"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ClientHelloError {}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub struct HostHello {
|
||||
selected_version: ProtocolVersion,
|
||||
capabilities: CapabilitySet,
|
||||
}
|
||||
|
||||
impl HostHello {
|
||||
pub fn new(selected_version: ProtocolVersion, capabilities: CapabilitySet) -> Self {
|
||||
Self {
|
||||
selected_version,
|
||||
capabilities,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn selected_version(&self) -> ProtocolVersion {
|
||||
self.selected_version
|
||||
}
|
||||
|
||||
pub fn capabilities(&self) -> &CapabilitySet {
|
||||
&self.capabilities
|
||||
}
|
||||
}
|
||||
|
||||
/// Messages sent from a client to the code-mode host.
|
||||
#[derive(Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields, tag = "type", rename_all_fields = "camelCase")]
|
||||
pub enum ClientToHost {
|
||||
#[serde(rename = "connection/hello")]
|
||||
ClientHello(ClientHello),
|
||||
#[serde(rename = "operation/request")]
|
||||
Request { id: RequestId, request: HostRequest },
|
||||
#[serde(rename = "operation/cancel")]
|
||||
CancelRequest { id: RequestId },
|
||||
/// Yield the active observation without cancelling its cell.
|
||||
#[serde(rename = "operation/yield")]
|
||||
YieldRequest { id: RequestId },
|
||||
#[serde(rename = "delegate/response")]
|
||||
DelegateResponse {
|
||||
id: DelegateRequestId,
|
||||
result: WireResult<DelegateResponse>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Messages sent from the code-mode host to a client.
|
||||
#[derive(Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields, tag = "type", rename_all_fields = "camelCase")]
|
||||
pub enum HostToClient {
|
||||
#[serde(rename = "connection/ready")]
|
||||
HostHello(HostHello),
|
||||
#[serde(rename = "connection/rejected")]
|
||||
HandshakeRejected { reason: HandshakeRejectReason },
|
||||
#[serde(rename = "operation/response")]
|
||||
Response {
|
||||
id: RequestId,
|
||||
result: WireResult<HostResponse>,
|
||||
},
|
||||
#[serde(rename = "execute/initialResponse")]
|
||||
InitialResponse {
|
||||
id: RequestId,
|
||||
result: WireResult<WireRuntimeResponse>,
|
||||
},
|
||||
#[serde(rename = "delegate/request")]
|
||||
DelegateRequest {
|
||||
id: DelegateRequestId,
|
||||
session_id: SessionId,
|
||||
request: DelegateRequest,
|
||||
},
|
||||
#[serde(rename = "delegate/cancel")]
|
||||
CancelDelegateRequest { id: DelegateRequestId },
|
||||
#[serde(rename = "cell/closed")]
|
||||
CellClosed {
|
||||
session_id: SessionId,
|
||||
cell_id: WireCellId,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields, tag = "method", rename_all_fields = "camelCase")]
|
||||
pub enum HostRequest {
|
||||
#[serde(rename = "session/open")]
|
||||
OpenSession {
|
||||
session_id: SessionId,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
cell_execution_limits: Option<WireSessionCellExecutionLimits>,
|
||||
/// Sent only when output truncation support was agreed at connection hello.
|
||||
/// Omission preserves the legacy session behavior and wire shape.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
output_truncation: Option<WireOutputTruncation>,
|
||||
},
|
||||
#[serde(rename = "session/execute")]
|
||||
Execute {
|
||||
session_id: SessionId,
|
||||
request: WireExecuteRequest,
|
||||
},
|
||||
#[serde(rename = "session/wait")]
|
||||
Wait {
|
||||
session_id: SessionId,
|
||||
request: WireWaitRequest,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
max_output_tokens: Option<usize>,
|
||||
},
|
||||
#[serde(rename = "session/terminate")]
|
||||
Terminate {
|
||||
session_id: SessionId,
|
||||
cell_id: WireCellId,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
max_output_tokens: Option<usize>,
|
||||
},
|
||||
#[serde(rename = "session/shutdown")]
|
||||
ShutdownSession { session_id: SessionId },
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields, tag = "type", rename_all_fields = "camelCase")]
|
||||
pub enum HostResponse {
|
||||
#[serde(rename = "session/ready")]
|
||||
SessionReady { session_id: SessionId },
|
||||
#[serde(rename = "execution/started")]
|
||||
ExecutionStarted { cell_id: WireCellId },
|
||||
#[serde(rename = "wait/completed")]
|
||||
WaitCompleted { outcome: WireWaitOutcome },
|
||||
#[serde(rename = "session/closed")]
|
||||
SessionClosed { session_id: SessionId },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields, tag = "type", rename_all_fields = "camelCase")]
|
||||
pub enum DelegateRequest {
|
||||
#[serde(rename = "tool/invoke")]
|
||||
InvokeTool { invocation: WireNestedToolCall },
|
||||
#[serde(rename = "notification/send")]
|
||||
Notify {
|
||||
call_id: String,
|
||||
cell_id: WireCellId,
|
||||
text: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields, tag = "type", rename_all_fields = "camelCase")]
|
||||
pub enum DelegateResponse {
|
||||
#[serde(rename = "tool/result")]
|
||||
ToolResult { result: JsonValue },
|
||||
#[serde(rename = "notification/delivered")]
|
||||
NotificationDelivered,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields, tag = "status", rename_all_fields = "camelCase")]
|
||||
pub enum WireResult<T> {
|
||||
#[serde(rename = "ok")]
|
||||
Ok { value: T },
|
||||
#[serde(rename = "error")]
|
||||
Err { message: String },
|
||||
}
|
||||
|
||||
impl<T> WireResult<T> {
|
||||
pub fn from_result(result: Result<T, String>) -> Self {
|
||||
match result {
|
||||
Ok(value) => Self::Ok { value },
|
||||
Err(message) => Self::Err { message },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_result(self) -> Result<T, String> {
|
||||
match self {
|
||||
Self::Ok { value } => Ok(value),
|
||||
Self::Err { message } => Err(message),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
//! Messages and framing for the code-mode host boundary.
|
||||
//!
|
||||
//! Protocol version 1 multiplexes session operations and delegate callbacks by
|
||||
//! request ID over one ordered connection.
|
||||
|
||||
mod codec;
|
||||
mod error;
|
||||
mod message;
|
||||
mod payload;
|
||||
mod types;
|
||||
|
||||
/// Maximum number of unresolved delegate callbacks allowed per host connection.
|
||||
pub const MAX_PENDING_DELEGATE_CALLS: usize = 4_096;
|
||||
|
||||
/// Callback capacity of clients that do not advertise the larger budget.
|
||||
pub const LEGACY_MAX_PENDING_DELEGATE_CALLS: usize = 1_024;
|
||||
|
||||
/// Stdio clients that can accept up to 4,096 unresolved delegate callbacks.
|
||||
pub const LARGE_DELEGATE_CAPACITY_CAPABILITY: &str = "delegate-capacity-4096";
|
||||
|
||||
/// Stdio connection support for the optional `session/open.outputTruncation` field.
|
||||
/// Each session selects its own setting after the connection hello.
|
||||
pub const BOUNDED_OUTPUT_CAPABILITY: &str = "bounded-output-v1";
|
||||
/// Session-local catalog revisions on execute requests.
|
||||
pub const TOOL_CATALOG_CAPABILITY: &str = "tool-catalog-revision-v1";
|
||||
/// Maximum aggregate text bytes retained per server-truncated observation.
|
||||
pub const BOUNDED_OUTPUT_MAX_BYTES: usize = 1024 * 1024;
|
||||
|
||||
/// Maximum aggregate inline image bytes retained per server-truncated observation.
|
||||
pub const BOUNDED_OUTPUT_MAX_IMAGE_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
/// Maximum aggregate encoded audio URL bytes retained per server-truncated observation.
|
||||
/// Count the whole URL, including the data URL prefix and any base64 payload.
|
||||
/// This leaves heuristic transport headroom but does not bound the complete response.
|
||||
pub const BOUNDED_OUTPUT_MAX_AUDIO_BYTES: usize = 62 * 1024 * 1024;
|
||||
|
||||
/// Negotiated support for cell execution resource limits on `session/open`.
|
||||
pub const SESSION_RESOURCE_LIMITS_CAPABILITY: &str = "session-cell-execution-resource-limits";
|
||||
|
||||
/// Support for yielding an in-flight execute or wait observation.
|
||||
pub const YIELD_OBSERVATION_CAPABILITY: &str = "yield-observation";
|
||||
|
||||
pub use codec::EncodedFrame;
|
||||
pub use codec::FramedReader;
|
||||
pub use codec::FramedWriter;
|
||||
pub use codec::MAX_FRAME_BYTES;
|
||||
pub use error::HandshakeRejectReason;
|
||||
pub use message::ClientHello;
|
||||
pub use message::ClientHelloError;
|
||||
pub use message::ClientToHost;
|
||||
pub use message::DelegateRequest;
|
||||
pub use message::DelegateResponse;
|
||||
pub use message::HostHello;
|
||||
pub use message::HostRequest;
|
||||
pub use message::HostResponse;
|
||||
pub use message::HostToClient;
|
||||
pub use message::WireResult;
|
||||
pub use payload::WireCellId;
|
||||
pub use payload::WireContentItem;
|
||||
pub use payload::WireExecuteRequest;
|
||||
pub use payload::WireImageDetail;
|
||||
pub use payload::WireNestedToolCall;
|
||||
pub use payload::WireOutputTruncation;
|
||||
pub use payload::WireRuntimeResponse;
|
||||
pub use payload::WireSessionCellExecutionLimits;
|
||||
pub use payload::WireToolDefinition;
|
||||
pub use payload::WireToolKind;
|
||||
pub use payload::WireToolName;
|
||||
pub use payload::WireWaitOutcome;
|
||||
pub use payload::WireWaitRequest;
|
||||
pub use types::Capability;
|
||||
pub use types::CapabilitySet;
|
||||
pub use types::DelegateRequestId;
|
||||
pub use types::DuplicateCapability;
|
||||
pub use types::InvalidIdentifier;
|
||||
pub use types::InvalidSupportedProtocolVersions;
|
||||
pub use types::ProtocolVersion;
|
||||
pub use types::RequestId;
|
||||
pub use types::SessionId;
|
||||
pub use types::SupportedProtocolVersions;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "host_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "codec_tests.rs"]
|
||||
mod codec_tests;
|
||||
@@ -1,533 +0,0 @@
|
||||
use std::num::TryFromIntError;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_protocol::ToolName;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value as JsonValue;
|
||||
|
||||
use crate::CellId;
|
||||
use crate::CodeModeNestedToolCall;
|
||||
use crate::CodeModeOutputTruncation;
|
||||
use crate::CodeModeSessionCellExecutionLimits;
|
||||
use crate::CodeModeToolKind;
|
||||
use crate::ExecuteRequest;
|
||||
use crate::FunctionCallOutputContentItem;
|
||||
use crate::ImageDetail;
|
||||
use crate::MissingCodeModeHostDuration;
|
||||
use crate::RuntimeResponse;
|
||||
use crate::ToolDefinition;
|
||||
use crate::WaitOutcome;
|
||||
use crate::WaitRequest;
|
||||
|
||||
/// The per-cell execution limits carried by a V1 session-open request.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub struct WireSessionCellExecutionLimits {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub max_yield_time_ms: Option<u64>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub max_heap_size_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
impl TryFrom<CodeModeSessionCellExecutionLimits> for WireSessionCellExecutionLimits {
|
||||
type Error = TryFromIntError;
|
||||
|
||||
fn try_from(value: CodeModeSessionCellExecutionLimits) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
max_yield_time_ms: value.max_yield_time_ms,
|
||||
max_heap_size_bytes: value.max_heap_size_bytes.map(u64::try_from).transpose()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<WireSessionCellExecutionLimits> for CodeModeSessionCellExecutionLimits {
|
||||
type Error = TryFromIntError;
|
||||
|
||||
fn try_from(value: WireSessionCellExecutionLimits) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
max_yield_time_ms: value.max_yield_time_ms,
|
||||
max_heap_size_bytes: value.max_heap_size_bytes.map(usize::try_from).transpose()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The output truncation setting carried by a V1 session-open request.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum WireOutputTruncation {
|
||||
Client,
|
||||
Server,
|
||||
}
|
||||
|
||||
impl From<CodeModeOutputTruncation> for WireOutputTruncation {
|
||||
fn from(value: CodeModeOutputTruncation) -> Self {
|
||||
match value {
|
||||
CodeModeOutputTruncation::Client => Self::Client,
|
||||
CodeModeOutputTruncation::Server => Self::Server,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WireOutputTruncation> for CodeModeOutputTruncation {
|
||||
fn from(value: WireOutputTruncation) -> Self {
|
||||
match value {
|
||||
WireOutputTruncation::Client => Self::Client,
|
||||
WireOutputTruncation::Server => Self::Server,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cell identifier with a wire representation owned by protocol V1.
|
||||
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct WireCellId(String);
|
||||
|
||||
impl WireCellId {
|
||||
pub fn new(value: impl Into<String>) -> Self {
|
||||
Self(value.into())
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CellId> for WireCellId {
|
||||
fn from(value: CellId) -> Self {
|
||||
Self(value.as_str().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&CellId> for WireCellId {
|
||||
fn from(value: &CellId) -> Self {
|
||||
Self(value.as_str().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WireCellId> for CellId {
|
||||
fn from(value: WireCellId) -> Self {
|
||||
Self::new(value.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The V1 wire representation of a tool's stable name.
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WireToolName {
|
||||
pub name: String,
|
||||
pub namespace: Option<String>,
|
||||
}
|
||||
|
||||
impl From<ToolName> for WireToolName {
|
||||
fn from(value: ToolName) -> Self {
|
||||
Self {
|
||||
name: value.name,
|
||||
namespace: value.namespace,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WireToolName> for ToolName {
|
||||
fn from(value: WireToolName) -> Self {
|
||||
Self::new(value.namespace, value.name)
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool invocation shape supported by protocol V1.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum WireToolKind {
|
||||
Function,
|
||||
Freeform,
|
||||
}
|
||||
|
||||
impl From<CodeModeToolKind> for WireToolKind {
|
||||
fn from(value: CodeModeToolKind) -> Self {
|
||||
match value {
|
||||
CodeModeToolKind::Function => Self::Function,
|
||||
CodeModeToolKind::Freeform => Self::Freeform,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WireToolKind> for CodeModeToolKind {
|
||||
fn from(value: WireToolKind) -> Self {
|
||||
match value {
|
||||
WireToolKind::Function => Self::Function,
|
||||
WireToolKind::Freeform => Self::Freeform,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A V1 tool definition embedded in an execute request.
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WireToolDefinition {
|
||||
pub name: String,
|
||||
pub tool_name: WireToolName,
|
||||
pub description: String,
|
||||
pub kind: WireToolKind,
|
||||
pub input_schema: Option<JsonValue>,
|
||||
pub output_schema: Option<JsonValue>,
|
||||
}
|
||||
|
||||
impl From<ToolDefinition> for WireToolDefinition {
|
||||
fn from(value: ToolDefinition) -> Self {
|
||||
Self {
|
||||
name: value.name,
|
||||
tool_name: value.tool_name.into(),
|
||||
description: value.description,
|
||||
kind: value.kind.into(),
|
||||
input_schema: value.input_schema,
|
||||
output_schema: value.output_schema,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WireToolDefinition> for ToolDefinition {
|
||||
fn from(value: WireToolDefinition) -> Self {
|
||||
Self {
|
||||
name: value.name,
|
||||
tool_name: value.tool_name.into(),
|
||||
description: value.description,
|
||||
kind: value.kind.into(),
|
||||
input_schema: value.input_schema,
|
||||
input_schema_max_bytes: None,
|
||||
output_schema: value.output_schema,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The complete execute request shape supported by protocol V1.
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WireExecuteRequest {
|
||||
/// A nonempty catalog installs this revision. An empty list references it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub catalog_revision: Option<u64>,
|
||||
pub tool_call_id: String,
|
||||
pub enabled_tools: Vec<WireToolDefinition>,
|
||||
pub source: String,
|
||||
pub yield_time_ms: Option<u64>,
|
||||
pub max_output_tokens: Option<i32>,
|
||||
}
|
||||
|
||||
impl TryFrom<ExecuteRequest> for WireExecuteRequest {
|
||||
type Error = TryFromIntError;
|
||||
|
||||
fn try_from(value: ExecuteRequest) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
catalog_revision: None,
|
||||
tool_call_id: value.tool_call_id,
|
||||
enabled_tools: value.enabled_tools.into_iter().map(Into::into).collect(),
|
||||
source: value.source,
|
||||
yield_time_ms: value.yield_time_ms,
|
||||
max_output_tokens: value.max_output_tokens.map(i32::try_from).transpose()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<WireExecuteRequest> for ExecuteRequest {
|
||||
type Error = TryFromIntError;
|
||||
|
||||
fn try_from(value: WireExecuteRequest) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
tool_call_id: value.tool_call_id,
|
||||
enabled_tools: value.enabled_tools.into_iter().map(Into::into).collect(),
|
||||
source: value.source,
|
||||
yield_time_ms: value.yield_time_ms,
|
||||
max_output_tokens: value.max_output_tokens.map(usize::try_from).transpose()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The nested wait payload for protocol V1. Its optional budget is carried by
|
||||
/// the enclosing `HostRequest::Wait`.
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WireWaitRequest {
|
||||
pub cell_id: WireCellId,
|
||||
pub yield_time_ms: u64,
|
||||
}
|
||||
|
||||
impl From<WaitRequest> for WireWaitRequest {
|
||||
fn from(value: WaitRequest) -> Self {
|
||||
Self {
|
||||
cell_id: value.cell_id.into(),
|
||||
yield_time_ms: value.yield_time_ms,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WireWaitRequest> for WaitRequest {
|
||||
fn from(value: WireWaitRequest) -> Self {
|
||||
Self {
|
||||
cell_id: value.cell_id.into(),
|
||||
yield_time_ms: value.yield_time_ms,
|
||||
max_output_tokens: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Image detail values accepted in a V1 runtime response.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum WireImageDetail {
|
||||
Auto,
|
||||
Low,
|
||||
High,
|
||||
Original,
|
||||
}
|
||||
|
||||
impl From<ImageDetail> for WireImageDetail {
|
||||
fn from(value: ImageDetail) -> Self {
|
||||
match value {
|
||||
ImageDetail::Auto => Self::Auto,
|
||||
ImageDetail::Low => Self::Low,
|
||||
ImageDetail::High => Self::High,
|
||||
ImageDetail::Original => Self::Original,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WireImageDetail> for ImageDetail {
|
||||
fn from(value: WireImageDetail) -> Self {
|
||||
match value {
|
||||
WireImageDetail::Auto => Self::Auto,
|
||||
WireImageDetail::Low => Self::Low,
|
||||
WireImageDetail::High => Self::High,
|
||||
WireImageDetail::Original => Self::Original,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One output item emitted by a V1 runtime response.
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields, tag = "type", rename_all = "snake_case")]
|
||||
pub enum WireContentItem {
|
||||
InputText {
|
||||
text: String,
|
||||
},
|
||||
InputImage {
|
||||
image_url: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
detail: Option<WireImageDetail>,
|
||||
},
|
||||
InputAudio {
|
||||
audio_url: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl From<FunctionCallOutputContentItem> for WireContentItem {
|
||||
fn from(value: FunctionCallOutputContentItem) -> Self {
|
||||
match value {
|
||||
FunctionCallOutputContentItem::InputText { text } => Self::InputText { text },
|
||||
FunctionCallOutputContentItem::InputImage { image_url, detail } => Self::InputImage {
|
||||
image_url,
|
||||
detail: detail.map(Into::into),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputAudio { audio_url } => {
|
||||
Self::InputAudio { audio_url }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WireContentItem> for FunctionCallOutputContentItem {
|
||||
fn from(value: WireContentItem) -> Self {
|
||||
match value {
|
||||
WireContentItem::InputText { text } => Self::InputText { text },
|
||||
WireContentItem::InputImage { image_url, detail } => Self::InputImage {
|
||||
image_url,
|
||||
detail: detail.map(Into::into),
|
||||
},
|
||||
WireContentItem::InputAudio { audio_url } => Self::InputAudio { audio_url },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runtime output returned over the V1 host connection.
|
||||
///
|
||||
/// Host time is required and covers this request, not the cell lifetime. The
|
||||
/// app-server and host run at the same version; no negotiation is needed.
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum WireRuntimeResponse {
|
||||
Yielded {
|
||||
cell_id: WireCellId,
|
||||
content_items: Vec<WireContentItem>,
|
||||
code_mode_host_duration_ns: u64,
|
||||
},
|
||||
Terminated {
|
||||
cell_id: WireCellId,
|
||||
content_items: Vec<WireContentItem>,
|
||||
code_mode_host_duration_ns: u64,
|
||||
},
|
||||
Result {
|
||||
cell_id: WireCellId,
|
||||
content_items: Vec<WireContentItem>,
|
||||
error_text: Option<String>,
|
||||
#[serde(default)]
|
||||
result_buffered_for_ns: u64,
|
||||
code_mode_host_duration_ns: u64,
|
||||
},
|
||||
}
|
||||
|
||||
impl TryFrom<RuntimeResponse> for WireRuntimeResponse {
|
||||
type Error = MissingCodeModeHostDuration;
|
||||
|
||||
/// Preserves the response's timing; the host handler must record it first.
|
||||
fn try_from(value: RuntimeResponse) -> Result<Self, Self::Error> {
|
||||
Ok(match value {
|
||||
RuntimeResponse::Yielded {
|
||||
cell_id,
|
||||
content_items,
|
||||
code_mode_host_duration,
|
||||
} => {
|
||||
let code_mode_host_duration =
|
||||
code_mode_host_duration.ok_or(MissingCodeModeHostDuration)?;
|
||||
Self::Yielded {
|
||||
cell_id: cell_id.into(),
|
||||
content_items: content_items.into_iter().map(Into::into).collect(),
|
||||
code_mode_host_duration_ns: u64::try_from(code_mode_host_duration.as_nanos())
|
||||
.unwrap_or(u64::MAX),
|
||||
}
|
||||
}
|
||||
RuntimeResponse::Terminated {
|
||||
cell_id,
|
||||
content_items,
|
||||
code_mode_host_duration,
|
||||
} => {
|
||||
let code_mode_host_duration =
|
||||
code_mode_host_duration.ok_or(MissingCodeModeHostDuration)?;
|
||||
Self::Terminated {
|
||||
cell_id: cell_id.into(),
|
||||
content_items: content_items.into_iter().map(Into::into).collect(),
|
||||
code_mode_host_duration_ns: u64::try_from(code_mode_host_duration.as_nanos())
|
||||
.unwrap_or(u64::MAX),
|
||||
}
|
||||
}
|
||||
RuntimeResponse::Result {
|
||||
cell_id,
|
||||
content_items,
|
||||
error_text,
|
||||
result_buffered_for,
|
||||
code_mode_host_duration,
|
||||
} => {
|
||||
let code_mode_host_duration =
|
||||
code_mode_host_duration.ok_or(MissingCodeModeHostDuration)?;
|
||||
Self::Result {
|
||||
cell_id: cell_id.into(),
|
||||
content_items: content_items.into_iter().map(Into::into).collect(),
|
||||
error_text,
|
||||
result_buffered_for_ns: u64::try_from(result_buffered_for.as_nanos())
|
||||
.unwrap_or(u64::MAX),
|
||||
code_mode_host_duration_ns: u64::try_from(code_mode_host_duration.as_nanos())
|
||||
.unwrap_or(u64::MAX),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WireRuntimeResponse> for RuntimeResponse {
|
||||
fn from(value: WireRuntimeResponse) -> Self {
|
||||
match value {
|
||||
WireRuntimeResponse::Yielded {
|
||||
cell_id,
|
||||
content_items,
|
||||
code_mode_host_duration_ns,
|
||||
} => Self::Yielded {
|
||||
cell_id: cell_id.into(),
|
||||
content_items: content_items.into_iter().map(Into::into).collect(),
|
||||
code_mode_host_duration: Some(Duration::from_nanos(code_mode_host_duration_ns)),
|
||||
},
|
||||
WireRuntimeResponse::Terminated {
|
||||
cell_id,
|
||||
content_items,
|
||||
code_mode_host_duration_ns,
|
||||
} => Self::Terminated {
|
||||
cell_id: cell_id.into(),
|
||||
content_items: content_items.into_iter().map(Into::into).collect(),
|
||||
code_mode_host_duration: Some(Duration::from_nanos(code_mode_host_duration_ns)),
|
||||
},
|
||||
WireRuntimeResponse::Result {
|
||||
cell_id,
|
||||
content_items,
|
||||
error_text,
|
||||
result_buffered_for_ns,
|
||||
code_mode_host_duration_ns,
|
||||
} => Self::Result {
|
||||
cell_id: cell_id.into(),
|
||||
content_items: content_items.into_iter().map(Into::into).collect(),
|
||||
error_text,
|
||||
result_buffered_for: Duration::from_nanos(result_buffered_for_ns),
|
||||
code_mode_host_duration: Some(Duration::from_nanos(code_mode_host_duration_ns)),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a waited-for cell remained live in protocol V1.
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum WireWaitOutcome {
|
||||
LiveCell(WireRuntimeResponse),
|
||||
MissingCell(WireRuntimeResponse),
|
||||
}
|
||||
|
||||
impl TryFrom<WaitOutcome> for WireWaitOutcome {
|
||||
type Error = MissingCodeModeHostDuration;
|
||||
|
||||
fn try_from(value: WaitOutcome) -> Result<Self, Self::Error> {
|
||||
Ok(match value {
|
||||
WaitOutcome::LiveCell(response) => Self::LiveCell(response.try_into()?),
|
||||
WaitOutcome::MissingCell(response) => Self::MissingCell(response.try_into()?),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WireWaitOutcome> for WaitOutcome {
|
||||
fn from(value: WireWaitOutcome) -> Self {
|
||||
match value {
|
||||
WireWaitOutcome::LiveCell(response) => Self::LiveCell(response.into()),
|
||||
WireWaitOutcome::MissingCell(response) => Self::MissingCell(response.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A nested tool invocation sent over the V1 host connection.
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WireNestedToolCall {
|
||||
pub cell_id: WireCellId,
|
||||
pub runtime_tool_call_id: String,
|
||||
pub tool_name: WireToolName,
|
||||
pub tool_kind: WireToolKind,
|
||||
pub input: Option<JsonValue>,
|
||||
}
|
||||
|
||||
impl From<CodeModeNestedToolCall> for WireNestedToolCall {
|
||||
fn from(value: CodeModeNestedToolCall) -> Self {
|
||||
Self {
|
||||
cell_id: value.cell_id.into(),
|
||||
runtime_tool_call_id: value.runtime_tool_call_id,
|
||||
tool_name: value.tool_name.into(),
|
||||
tool_kind: value.tool_kind.into(),
|
||||
input: value.input,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WireNestedToolCall> for CodeModeNestedToolCall {
|
||||
fn from(value: WireNestedToolCall) -> Self {
|
||||
Self {
|
||||
cell_id: value.cell_id.into(),
|
||||
runtime_tool_call_id: value.runtime_tool_call_id,
|
||||
tool_name: value.tool_name.into(),
|
||||
tool_kind: value.tool_kind.into(),
|
||||
input: value.input,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,248 +0,0 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::fmt;
|
||||
use std::num::NonZeroU32;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Deserializer;
|
||||
use serde::Serialize;
|
||||
use serde::Serializer;
|
||||
use serde::de::Error as _;
|
||||
|
||||
/// Correlates one client operation request with the host's response.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct RequestId(i64);
|
||||
|
||||
impl RequestId {
|
||||
pub const fn new(value: i64) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Correlates one host delegate request with the client's response.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct DelegateRequestId(i64);
|
||||
|
||||
impl DelegateRequestId {
|
||||
pub const fn new(value: i64) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct ProtocolVersion(NonZeroU32);
|
||||
|
||||
impl ProtocolVersion {
|
||||
pub const V1: Self = Self(NonZeroU32::MIN);
|
||||
|
||||
pub const fn new(value: u32) -> Option<Self> {
|
||||
match NonZeroU32::new(value) {
|
||||
Some(value) => Some(Self(value)),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn get(self) -> u32 {
|
||||
self.0.get()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct InvalidIdentifier;
|
||||
|
||||
impl fmt::Display for InvalidIdentifier {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str("identifier must not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InvalidIdentifier {}
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
struct NonEmptyString(String);
|
||||
|
||||
impl NonEmptyString {
|
||||
fn new(value: impl Into<String>) -> Result<Self, InvalidIdentifier> {
|
||||
let value = value.into();
|
||||
if value.trim().is_empty() {
|
||||
Err(InvalidIdentifier)
|
||||
} else {
|
||||
Ok(Self(value))
|
||||
}
|
||||
}
|
||||
|
||||
fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for NonEmptyString {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
self.0.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for NonEmptyString {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Self::new(String::deserialize(deserializer)?).map_err(D::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
/// A named protocol feature advertised during connection negotiation.
|
||||
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Capability(NonEmptyString);
|
||||
|
||||
impl Capability {
|
||||
pub fn new(value: impl Into<String>) -> Result<Self, InvalidIdentifier> {
|
||||
NonEmptyString::new(value).map(Self)
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
self.0.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Capability {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifies one logical code-mode session on a connection.
|
||||
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct SessionId(NonEmptyString);
|
||||
|
||||
impl SessionId {
|
||||
pub fn new(value: impl Into<String>) -> Result<Self, InvalidIdentifier> {
|
||||
NonEmptyString::new(value).map(Self)
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
self.0.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for SessionId {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct CapabilitySet(BTreeSet<Capability>);
|
||||
|
||||
impl CapabilitySet {
|
||||
pub fn empty() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn try_new(
|
||||
capabilities: impl IntoIterator<Item = Capability>,
|
||||
) -> Result<Self, DuplicateCapability> {
|
||||
let mut unique = BTreeSet::new();
|
||||
for capability in capabilities {
|
||||
if !unique.insert(capability.clone()) {
|
||||
return Err(DuplicateCapability { capability });
|
||||
}
|
||||
}
|
||||
Ok(Self(unique))
|
||||
}
|
||||
|
||||
pub fn contains(&self, capability: &Capability) -> bool {
|
||||
self.0.contains(capability)
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> impl Iterator<Item = &Capability> {
|
||||
self.0.iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for CapabilitySet {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Self::try_new(Vec::<Capability>::deserialize(deserializer)?).map_err(D::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct DuplicateCapability {
|
||||
capability: Capability,
|
||||
}
|
||||
|
||||
impl fmt::Display for DuplicateCapability {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(formatter, "duplicate capability `{}`", self.capability)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for DuplicateCapability {}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct SupportedProtocolVersions(BTreeSet<ProtocolVersion>);
|
||||
|
||||
impl SupportedProtocolVersions {
|
||||
pub fn try_new(
|
||||
versions: impl IntoIterator<Item = ProtocolVersion>,
|
||||
) -> Result<Self, InvalidSupportedProtocolVersions> {
|
||||
let mut unique = BTreeSet::new();
|
||||
for version in versions {
|
||||
if !unique.insert(version) {
|
||||
return Err(InvalidSupportedProtocolVersions::Duplicate(version));
|
||||
}
|
||||
}
|
||||
if unique.is_empty() {
|
||||
return Err(InvalidSupportedProtocolVersions::Empty);
|
||||
}
|
||||
Ok(Self(unique))
|
||||
}
|
||||
|
||||
pub fn contains(&self, version: ProtocolVersion) -> bool {
|
||||
self.0.contains(&version)
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> impl Iterator<Item = ProtocolVersion> + '_ {
|
||||
self.0.iter().copied()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for SupportedProtocolVersions {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Self::try_new(Vec::<ProtocolVersion>::deserialize(deserializer)?).map_err(D::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum InvalidSupportedProtocolVersions {
|
||||
Empty,
|
||||
Duplicate(ProtocolVersion),
|
||||
}
|
||||
|
||||
impl fmt::Display for InvalidSupportedProtocolVersions {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Empty => formatter.write_str("at least one protocol version is required"),
|
||||
Self::Duplicate(version) => {
|
||||
write!(formatter, "duplicate protocol version {}", version.get())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InvalidSupportedProtocolVersions {}
|
||||
@@ -4,18 +4,12 @@ use std::time::Duration;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::MissingCodeModeHostDuration;
|
||||
use super::RuntimeResponse;
|
||||
use super::WaitOutcome;
|
||||
use crate::CellId;
|
||||
use crate::FunctionCallOutputContentItem;
|
||||
use crate::host::WireRuntimeResponse;
|
||||
use crate::host::WireWaitOutcome;
|
||||
|
||||
/// Raw runtime serialization preserves absent timing; stdio always carries a
|
||||
/// measured duration, including zero, without changing the response payload.
|
||||
/// Runtime serialization distinguishes absent timing from a measured zero.
|
||||
#[test]
|
||||
fn code_mode_host_duration_survives_runtime_and_stdio_serialization() {
|
||||
fn code_mode_host_duration_survives_runtime_serialization() {
|
||||
let content_items = vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "output".to_string(),
|
||||
}];
|
||||
@@ -65,44 +59,6 @@ fn code_mode_host_duration_survives_runtime_and_stdio_serialization() {
|
||||
serde_json::from_value::<RuntimeResponse>(payload).expect("deserialize response"),
|
||||
expected
|
||||
);
|
||||
|
||||
if duration.is_some() {
|
||||
let wire_payload = serde_json::to_value(
|
||||
WireRuntimeResponse::try_from(expected.clone()).expect("timed response"),
|
||||
)
|
||||
.expect("serialize response over stdio");
|
||||
assert_eq!(
|
||||
RuntimeResponse::from(
|
||||
serde_json::from_value::<WireRuntimeResponse>(wire_payload)
|
||||
.expect("deserialize stdio response")
|
||||
),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Encoding must not turn a missing request measurement into measured zero,
|
||||
/// including when no live cell remains to supply output.
|
||||
#[test]
|
||||
fn stdio_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!(
|
||||
WireRuntimeResponse::try_from(response.clone()),
|
||||
Err(MissingCodeModeHostDuration)
|
||||
);
|
||||
for outcome in [
|
||||
WaitOutcome::LiveCell(response.clone()),
|
||||
WaitOutcome::MissingCell(response),
|
||||
] {
|
||||
assert_eq!(
|
||||
WireWaitOutcome::try_from(outcome),
|
||||
Err(MissingCodeModeHostDuration)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user