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

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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,319 @@
//! Tests catalog exec template rendering and runtime description composition.
use super::CodeModeToolKind;
use super::DEFERRED_NESTED_TOOLS_GUIDANCE;
use super::DeferredToolDiscovery;
use super::ImageDetailVisibility;
use super::LEGACY_IMAGE_HELPER_DESCRIPTION;
use super::MCP_TYPESCRIPT_PREAMBLE;
use super::TOOL_SEARCH_GUIDANCE;
use super::ToolDefinition;
use super::UNIFIED_IMAGE_HELPER_DESCRIPTION;
use super::build_exec_tool_description_and_definitions;
use akode_protocol::ToolName;
use akode_protocol::openai_models::CodeModeToolMessages;
use akode_protocol::openai_models::ToolMessage;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::BTreeMap;
#[test]
fn exec_override_renders_only_known_literal_placeholders() {
for (image_detail_visibility, image_helper) in [
(
ImageDetailVisibility::Visible,
LEGACY_IMAGE_HELPER_DESCRIPTION,
),
(
ImageDetailVisibility::Hidden,
UNIFIED_IMAGE_HELPER_DESCRIPTION,
),
] {
let (description, _) = build_exec_tool_description_and_definitions(
&[],
&[],
&BTreeMap::new(),
/*default_exec_yield_time_ms*/ 4567,
/*code_mode_only*/ false,
image_detail_visibility,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some(" \nDefaults to 10000 ms. {{ default_exec_yield_time_ms }} ms.\n{{ image_helper }}\n{{ unknown }} {{default_exec_yield_time_ms}}\t ".to_string()),
..Default::default()
}),
..Default::default()
}),
);
assert_eq!(
description,
format!(
" \nDefaults to 10000 ms. 4567 ms.\n{image_helper}\n{{{{ unknown }}}} {{{{default_exec_yield_time_ms}}}}\t \n\n{DEFERRED_NESTED_TOOLS_GUIDANCE}"
),
);
}
}
#[test]
fn exec_override_preserves_empty_and_whitespace_only_text() {
for description_override in ["", " \n\t "] {
assert_eq!(
build_exec_tool_description_and_definitions(
&[],
&[],
&BTreeMap::new(),
crate::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ true,
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some(description_override.to_string()),
..Default::default()
}),
deferred_nested_tools_guidance: Some(
"No deferred tools; omit this.".to_string()
),
mcp_typescript_preamble: Some("No MCP tools; omit this.".to_string()),
..Default::default()
}),
)
.0,
[
description_override,
"No deferred tools; omit this.",
"Shared MCP Types:\n```ts\nNo MCP tools; omit this.\n```"
]
.into_iter()
.filter(|section| !section.is_empty())
.collect::<Vec<_>>()
.join("\n\n"),
);
}
}
#[test]
fn exec_override_preserves_runtime_sections() {
let enabled_tools = [ToolDefinition {
name: "alpha".to_string(),
tool_name: ToolName::plain("alpha"),
description: "First tool".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
}];
let deferred_tools = [ToolDefinition {
name: "mcp__sample__beta".to_string(),
tool_name: ToolName::namespaced("mcp__sample__", "beta"),
description: "Deferred tool".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
input_schema_max_bytes: None,
output_schema: Some(json!({
"type": "object",
"properties": {
"content": { "type": "array", "items": { "type": "object" } },
"isError": { "type": "boolean" },
"_meta": { "type": "object" }
}
})),
}];
let declaration = "### `alpha`\nFirst tool\n\nexec tool declaration:\n```ts\ndeclare const tools: { alpha(args: unknown): Promise<unknown>; };\n```";
for (code_mode_only, guidance, preamble, expected) in [
(true, Some(""), Some(""), declaration.to_string()),
(
true,
None,
Some(""),
format!("{DEFERRED_NESTED_TOOLS_GUIDANCE}\n\n{declaration}"),
),
(
true,
Some(""),
None,
format!("Shared MCP Types:\n```ts\n{MCP_TYPESCRIPT_PREAMBLE}\n```\n\n{declaration}"),
),
(
true,
Some(" {{ image_helper }}\n"),
Some(" {{ default_exec_yield_time_ms }}\n"),
format!(
" {{{{ image_helper }}}}\n\n\nShared MCP Types:\n```ts\n {{{{ default_exec_yield_time_ms }}}}\n\n```\n\n{declaration}"
),
),
(
false,
Some("Catalog discovery."),
Some("No types outside Code Mode Only."),
"Catalog discovery.".to_string(),
),
] {
assert_eq!(
build_exec_tool_description_and_definitions(
&enabled_tools,
&deferred_tools,
&BTreeMap::new(),
crate::DEFAULT_EXEC_YIELD_TIME_MS,
code_mode_only,
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some(String::new()),
..Default::default()
}),
deferred_nested_tools_guidance: guidance.map(str::to_string),
mcp_typescript_preamble: preamble.map(str::to_string),
..Default::default()
}),
)
.0,
expected,
);
}
}
#[test]
fn ranked_search_guidance_honors_overrides() {
let deferred_tools = [ToolDefinition {
name: "deferred_tool".to_string(),
tool_name: ToolName::plain("deferred_tool"),
description: "Deferred tool".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
}];
for code_mode_only in [false, true] {
for (guidance, expected) in [
(
None,
if code_mode_only {
DEFERRED_NESTED_TOOLS_GUIDANCE.to_string()
} else {
format!("{DEFERRED_NESTED_TOOLS_GUIDANCE}\n\n{TOOL_SEARCH_GUIDANCE}")
},
),
(Some(""), String::new()),
(Some("Catalog discovery."), "Catalog discovery.".to_string()),
] {
let (description, _) = build_exec_tool_description_and_definitions(
&[],
&deferred_tools,
&BTreeMap::new(),
crate::DEFAULT_EXEC_YIELD_TIME_MS,
code_mode_only,
ImageDetailVisibility::Visible,
DeferredToolDiscovery::RankedSearch,
/*incremental_exec_enabled*/ false,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some(String::new()),
..Default::default()
}),
deferred_nested_tools_guidance: guidance.map(str::to_string),
mcp_typescript_preamble: Some(String::new()),
..Default::default()
}),
);
assert_eq!(description, expected);
}
}
}
#[test]
fn mcp_types_stay_stable_when_a_deferred_tool_changes_its_output_schema() {
let mut tool = ToolDefinition {
name: "sample".to_string(),
tool_name: ToolName::plain("sample"),
description: "Deferred tool".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
};
let render = |tool: &ToolDefinition, preamble: Option<&str>| {
build_exec_tool_description_and_definitions(
&[],
std::slice::from_ref(tool),
&BTreeMap::new(),
crate::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ true,
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
Some(&CodeModeToolMessages {
mcp_typescript_preamble: preamble.map(str::to_string),
..Default::default()
}),
)
.0
};
// Keep one deferred tool throughout to isolate this from the independent
// discovery guidance transition when the entire deferred catalog empties.
for preamble in [None, Some("type CustomMcpResult = string;"), Some("")] {
tool.output_schema = None;
let before = render(&tool, preamble);
tool.output_schema = Some(json!({
"type": "object",
"properties": {
"content": { "type": "array", "items": { "type": "object" } },
"isError": { "type": "boolean" },
"_meta": { "type": "object" }
}
}));
assert_eq!(before, render(&tool, preamble));
}
}
#[test]
fn nested_guidance_survives_catalog_changes_and_respects_overrides() {
let deferred_tools = [ToolDefinition {
name: "deferred_echo".to_string(),
tool_name: ToolName::plain("deferred_echo"),
description: "Echo a value.".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
}];
let render = |tools: &[ToolDefinition], code_mode_only, guidance: Option<&str>| {
build_exec_tool_description_and_definitions(
&[],
tools,
&BTreeMap::new(),
crate::DEFAULT_EXEC_YIELD_TIME_MS,
code_mode_only,
ImageDetailVisibility::Visible,
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some(String::new()),
..Default::default()
}),
deferred_nested_tools_guidance: guidance.map(str::to_string),
mcp_typescript_preamble: Some(String::new()),
..Default::default()
}),
)
.0
};
for code_mode_only in [false, true] {
for (guidance, expected) in [
(None, DEFERRED_NESTED_TOOLS_GUIDANCE),
(Some("Catalog discovery."), "Catalog discovery."),
(Some(""), ""),
] {
let prompt = render(&[], code_mode_only, guidance);
assert_eq!(prompt, expected);
assert_eq!(prompt, render(&deferred_tools, code_mode_only, guidance));
}
}
assert!(DEFERRED_NESTED_TOOLS_GUIDANCE.contains("Tool availability can change between calls"));
}

View File

@@ -0,0 +1,319 @@
syntax = "proto3";
package codex.code_mode.v1;
// Hosts stateful JavaScript execution and delegates nested tool calls to the
// session owner. Large tool inputs and outputs stay off the session event
// stream so independent HTTP/2 streams can make progress concurrently.
//
// Execute (including its stream), Wait, and Terminate reserve NOT_FOUND for an
// unknown session_id. Clients may retire the session binding on this status.
// Missing cells use WaitResponse.missing_cell instead.
service CodeModeHost {
// Optional host-level observation. UNIMPLEMENTED means no collector. Sampling
// never opens/closes a session and failures affect only this RPC stream.
rpc GetProcessMetrics(GetProcessMetricsRequest) returns (GetProcessMetricsResponse);
// Opens a session lease. The first event is always SessionOpened; dropping
// this stream closes the session and terminates its active cells.
rpc OpenSession(OpenSessionRequest) returns (stream SessionEvent);
rpc CloseSession(CloseSessionRequest) returns (CloseSessionResponse);
// Each subscription owns an independent stream of matching invocations. An
// empty tool_names filter matches every tool. Each invocation is routed to
// exactly one matching subscription, even when filters overlap.
rpc SubscribeToToolCalls(SubscribeToToolCallsRequest)
returns (stream ToolCall);
// Each result receives its own HTTP/2 stream, preventing a large response
// from blocking unrelated tool completions or session control events.
// NOT_FOUND may identify a missing invocation rather than a missing session.
rpc CompleteToolCall(CompleteToolCallRequest)
returns (CompleteToolCallResponse);
rpc AcknowledgeNotification(AcknowledgeNotificationRequest)
returns (AcknowledgeNotificationResponse);
// Emits ExecutionStarted immediately, followed by one ExecutionOutcome when
// the execution yields, completes, or is terminated.
rpc Execute(ExecuteRequest) returns (stream ExecuteEvent);
rpc Wait(WaitRequest) returns (WaitResponse);
// Ends the current observation early without stopping its cell. The
// corresponding Execute or Wait still returns its ordinary outcome.
rpc YieldObservation(YieldObservationRequest) returns (YieldObservationResponse);
// Acknowledges that a canceled wait has retired before another wait starts.
rpc CancelWait(CancelWaitRequest) returns (CancelWaitResponse);
rpc Terminate(TerminateRequest) returns (WaitResponse);
}
message GetProcessMetricsRequest {}
message GetProcessMetricsResponse {
uint32 process_id = 1;
double process_start_time_seconds = 2;
double cpu_seconds_total = 3;
uint64 resident_memory_bytes = 4;
}
message OpenSessionRequest {
optional SessionCellExecutionLimits cell_execution_limits = 1;
// Absent preserves the legacy client-side truncation behavior.
optional OutputTruncation output_truncation = 2;
// Maximum pending tool callbacks the client can accept.
// Absent preserves the legacy 1,024 callback budget. Hosts may impose a lower
// shared limit, and older hosts ignore this field and retain their own limit.
optional uint32 max_pending_delegate_calls = 3;
}
enum OutputTruncation {
OUTPUT_TRUNCATION_UNSPECIFIED = 0;
OUTPUT_TRUNCATION_CLIENT = 1;
OUTPUT_TRUNCATION_SERVER = 2;
}
message SessionCellExecutionLimits {
optional uint64 max_yield_time_ms = 1;
optional uint64 max_heap_size_bytes = 2;
}
message SessionEvent {
oneof event {
SessionOpened opened = 1;
ToolCallCancelled tool_call_cancelled = 2;
Notification notification = 3;
NotificationCancelled notification_cancelled = 4;
CellClosed cell_closed = 5;
}
}
message SessionOpened {
string session_id = 1;
// Absent (including from an older host) means the client owns truncation.
optional OutputTruncation output_truncation = 2;
}
message CloseSessionRequest {
string session_id = 1;
}
message CloseSessionResponse {}
message SubscribeToToolCallsRequest {
string session_id = 1;
repeated ToolName tool_names = 2;
}
message ToolCall {
string session_id = 1;
// Correlates callbacks with Execute before ExecutionStarted is received.
string execution_id = 2;
string cell_id = 3;
string invocation_id = 4;
string runtime_tool_call_id = 5;
ToolName tool_name = 6;
ToolKind tool_kind = 7;
optional bytes input_json = 8;
// Starts at one and increases independently for each execution.
uint64 sequence = 9;
// The host tool invocation span's W3C parent context for this streamed callback.
// gRPC metadata is fixed when the subscription stream opens, so each call
// carries its own context in the message.
optional string traceparent = 10;
}
message CompleteToolCallRequest {
string session_id = 1;
string invocation_id = 2;
oneof outcome {
ToolCallSucceeded succeeded = 3;
ToolCallFailed failed = 4;
}
}
message ToolCallSucceeded {
bytes output_json = 1;
}
message ToolCallFailed {
string message = 1;
}
message CompleteToolCallResponse {}
message ToolCallCancelled {
string invocation_id = 1;
// Cancellation can arrive before the corresponding ToolCall because session
// control events and tool subscriptions use independent HTTP/2 streams.
}
message Notification {
string notification_id = 1;
string execution_id = 2;
string cell_id = 3;
string call_id = 4;
string text = 5;
}
message NotificationCancelled {
string notification_id = 1;
}
message AcknowledgeNotificationRequest {
string session_id = 1;
string notification_id = 2;
}
message AcknowledgeNotificationResponse {}
message CellClosed {
string execution_id = 1;
string cell_id = 2;
// Last tool-call sequence issued before closure. Clients may retire the cell
// immediately and reject tool calls delivered after its closure.
uint64 final_tool_call_sequence = 3;
}
message ExecuteRequest {
string session_id = 1;
// Chosen by the client so callbacks can be correlated before cell admission.
string execution_id = 2;
string tool_call_id = 3;
string source = 4;
repeated ToolDefinition enabled_tools = 5;
optional uint64 yield_time_ms = 6;
optional uint64 max_output_tokens = 7;
}
message ExecuteEvent {
oneof event {
ExecutionStarted started = 1;
ExecutionOutcome outcome = 2;
}
}
message ExecutionStarted {
string execution_id = 1;
string cell_id = 2;
}
message WaitRequest {
string session_id = 1;
string cell_id = 2;
string wait_id = 3;
uint64 yield_time_ms = 4;
// Only set for a session that selected server-side output truncation.
optional uint64 max_output_tokens = 5;
}
message WaitResponse {
oneof state {
ExecutionOutcome live_cell = 1;
ExecutionOutcome missing_cell = 2;
}
}
message CancelWaitRequest {
string session_id = 1;
string wait_id = 2;
}
message CancelWaitResponse {}
message YieldObservationRequest {
string session_id = 1;
oneof observation {
string execution_id = 2;
string wait_id = 3;
}
}
message YieldObservationResponse {}
message TerminateRequest {
string session_id = 1;
string cell_id = 2;
// The terminating observation has its own output budget.
optional uint64 max_output_tokens = 3;
}
message ExecutionOutcome {
string cell_id = 1;
repeated ContentItem content_items = 2;
// Elapsed monotonic time from receipt of this Execute, Wait, or Terminate
// request until its outcome is ready, before serialization and delivery.
// Includes nested tool waits, but not background time between requests.
// Always supplied by the host; zero is a valid measurement.
uint64 code_mode_host_duration_ns = 6;
oneof outcome {
ExecutionYielded yielded = 3;
ExecutionTerminated terminated = 4;
ExecutionCompleted completed = 5;
}
}
message ExecutionYielded {}
message ExecutionTerminated {}
message ExecutionCompleted {
optional string error_text = 1;
}
message ToolDefinition {
string name = 1;
ToolName tool_name = 2;
string description = 3;
ToolKind kind = 4;
optional bytes input_schema_json = 5;
optional bytes output_schema_json = 6;
}
message ToolName {
string name = 1;
optional string namespace = 2;
}
enum ToolKind {
TOOL_KIND_UNSPECIFIED = 0;
TOOL_KIND_FUNCTION = 1;
TOOL_KIND_FREEFORM = 2;
}
message ContentItem {
oneof item {
TextContent text = 1;
ImageContent image = 2;
AudioContent audio = 3;
}
}
message TextContent {
string text = 1;
}
message ImageContent {
string image_url = 1;
optional ImageDetail detail = 2;
}
message AudioContent {
string audio_url = 1;
}
enum ImageDetail {
IMAGE_DETAIL_UNSPECIFIED = 0;
IMAGE_DETAIL_AUTO = 1;
IMAGE_DETAIL_LOW = 2;
IMAGE_DETAIL_HIGH = 3;
IMAGE_DETAIL_ORIGINAL = 4;
}

View File

@@ -0,0 +1,11 @@
#[cfg(codex_bazel)]
pub use code_mode_proto::codex::code_mode::v1::*;
#[cfg(not(codex_bazel))]
tonic::include_proto!("codex.code_mode.v1");
pub const MAX_IDENTIFIER_BYTES: usize = 256;
/// Decimal nanoseconds a completed result was buffered before a wait or terminate retrieved it.
/// Zero means immediate delivery. Hosts omit this metadata if no completed result was retrieved.
pub const RESULT_BUFFERED_FOR_NS_METADATA: &str = "codex-code-mode-result-buffered-for-ns";

View File

@@ -0,0 +1,170 @@
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
}
}

View File

@@ -0,0 +1,137 @@
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);
}

View File

@@ -0,0 +1,19 @@
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 },
}

View File

@@ -0,0 +1,867 @@
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 {
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()
);
}

View File

@@ -0,0 +1,276 @@
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),
}
}
}

View File

@@ -0,0 +1,86 @@
//! 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";
/// 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;

View File

@@ -0,0 +1,529 @@
use std::num::TryFromIntError;
use std::time::Duration;
use akode_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 {
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 {
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,
}
}
}

View File

@@ -0,0 +1,248 @@
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 {}

View File

@@ -0,0 +1,545 @@
use serde_json::Value as JsonValue;
use std::collections::BTreeMap;
use crate::description::normalize_code_mode_identifier;
// Expose one nested recursive shape, then fall back to `unknown` on the next
// occurrence so generated tool declarations remain finite.
const MAX_LOCAL_REF_EXPANSIONS_PER_PATH: usize = 2;
// Bound repeated refs and DAG fan-out separately from cycle depth so one
// compact schema cannot expand into an arbitrarily large model-visible item.
const MAX_TOTAL_LOCAL_REF_EXPANSIONS: usize = 32;
// Bound individual schema rendering before assembling the final declaration.
pub const DEFAULT_INPUT_SCHEMA_MAX_BYTES: usize = 16_000;
// Charge intermediate render strings as they are built so repeated local refs
// cannot allocate unbounded expanded copies before the final schema cap runs.
const RENDER_WORK_MULTIPLIER: usize = 4;
pub fn render_json_schema_to_typescript(schema: &JsonValue) -> String {
render_json_schema_to_typescript_with_budget(schema, DEFAULT_INPUT_SCHEMA_MAX_BYTES)
}
pub(crate) fn render_json_schema_to_typescript_with_budget(
schema: &JsonValue,
max_bytes: usize,
) -> String {
let rendered = JsonSchemaTypeRenderer::new(schema, max_bytes).render(schema);
if rendered.len() > max_bytes {
"unknown".to_string()
} else {
rendered
}
}
struct JsonSchemaTypeRenderer<'a> {
root: &'a JsonValue,
nested_schema_resource_depth: usize,
active_local_ref_expansions: BTreeMap<String, usize>,
remaining_local_ref_expansions: usize,
remaining_render_work_bytes: usize,
render_work_budget_exhausted: bool,
}
impl<'a> JsonSchemaTypeRenderer<'a> {
fn new(root: &'a JsonValue, max_bytes: usize) -> Self {
Self {
root,
nested_schema_resource_depth: 0,
active_local_ref_expansions: BTreeMap::new(),
remaining_local_ref_expansions: MAX_TOTAL_LOCAL_REF_EXPANSIONS,
remaining_render_work_bytes: max_bytes.saturating_mul(RENDER_WORK_MULTIPLIER),
render_work_budget_exhausted: false,
}
}
fn render(&mut self, schema: &JsonValue) -> String {
if self.render_work_budget_exhausted {
return "unknown".to_string();
}
// A nested `$id` starts a new schema resource. Fragment-only refs below
// it are scoped to that resource, not to the outer document root.
let enters_nested_schema_resource = !std::ptr::eq(schema, self.root)
&& schema
.as_object()
.is_some_and(|map| map.contains_key("$id"));
if enters_nested_schema_resource {
self.nested_schema_resource_depth += 1;
}
let rendered = match schema {
JsonValue::Bool(true) => "unknown".to_string(),
JsonValue::Bool(false) => "never".to_string(),
JsonValue::Object(map) => self.render_map(map),
_ => "unknown".to_string(),
};
if enters_nested_schema_resource {
self.nested_schema_resource_depth -= 1;
}
self.finish_render(rendered)
}
fn render_map(&mut self, map: &serde_json::Map<String, JsonValue>) -> String {
if self.render_work_budget_exhausted {
return "unknown".to_string();
}
if map.contains_key("$ref") {
return self.render_ref(map);
}
if let Some(value) = map.get("const") {
return self.render_literal(value);
}
if let Some(values) = map.get("enum").and_then(JsonValue::as_array) {
let mut rendered = Vec::new();
for value in values {
let literal = self.render_literal(value);
if self.render_work_budget_exhausted {
return "unknown".to_string();
}
if !self.consume_render_work(literal.len()) {
return "unknown".to_string();
}
rendered.push(literal);
}
if !rendered.is_empty() {
return rendered.join(" | ");
}
}
for key in ["anyOf", "oneOf"] {
if let Some(variants) = map.get(key).and_then(JsonValue::as_array) {
let mut rendered = Vec::new();
for variant in variants {
if self.render_work_budget_exhausted {
return "unknown".to_string();
}
rendered.push(self.render(variant));
}
if !rendered.is_empty() {
return rendered.join(" | ");
}
}
}
if let Some(variants) = map.get("allOf").and_then(JsonValue::as_array) {
let mut rendered = Vec::new();
for variant in variants {
if self.render_work_budget_exhausted {
return "unknown".to_string();
}
rendered.push(parenthesize_union_for_intersection(self.render(variant)));
}
if !rendered.is_empty() {
return rendered.join(" & ");
}
}
if let Some(schema_type) = map.get("type") {
if let Some(types) = schema_type.as_array() {
let mut rendered = Vec::new();
for schema_type in types.iter().filter_map(JsonValue::as_str) {
if self.render_work_budget_exhausted {
return "unknown".to_string();
}
rendered.push(self.render_type_keyword(map, schema_type));
}
if !rendered.is_empty() {
return rendered.join(" | ");
}
}
if let Some(schema_type) = schema_type.as_str() {
return self.render_type_keyword(map, schema_type);
}
}
if map.contains_key("properties")
|| map.contains_key("additionalProperties")
|| map.contains_key("required")
{
return self.render_object(map);
}
if map.contains_key("items") || map.contains_key("prefixItems") {
return self.render_array(map);
}
"unknown".to_string()
}
fn render_ref(&mut self, map: &serde_json::Map<String, JsonValue>) -> String {
let referenced_type = if self.nested_schema_resource_depth > 0 {
None
} else {
map.get("$ref")
.and_then(JsonValue::as_str)
.and_then(local_json_pointer)
.and_then(|pointer| {
let active_expansions = self
.active_local_ref_expansions
.get(&pointer)
.copied()
.unwrap_or_default();
if active_expansions >= MAX_LOCAL_REF_EXPANSIONS_PER_PATH {
return Some("unknown".to_string());
}
if self.remaining_local_ref_expansions == 0 {
return Some("unknown".to_string());
}
let root = self.root;
let target = if pointer.is_empty() {
Some(root)
} else {
root.pointer(&pointer)
}?;
self.remaining_local_ref_expansions -= 1;
self.active_local_ref_expansions
.insert(pointer.clone(), active_expansions + 1);
let rendered = self.render(target);
if active_expansions == 0 {
self.active_local_ref_expansions.remove(&pointer);
} else {
self.active_local_ref_expansions
.insert(pointer, active_expansions);
}
Some(rendered)
})
}
.unwrap_or_else(|| "unknown".to_string());
if self.render_work_budget_exhausted {
return "unknown".to_string();
}
let siblings = map
.iter()
.filter(|(key, _)| !matches!(key.as_str(), "$ref" | "$defs" | "definitions"))
.map(|(key, value)| (key.clone(), value.clone()))
.collect();
if !has_renderable_schema_keywords(&siblings) {
return referenced_type;
}
let sibling_type = self.render_map(&siblings);
match (referenced_type.as_str(), sibling_type.as_str()) {
("unknown", _) => sibling_type,
(_, "unknown") => referenced_type,
_ => format!("({referenced_type}) & ({sibling_type})"),
}
}
fn render_type_keyword(
&mut self,
map: &serde_json::Map<String, JsonValue>,
schema_type: &str,
) -> String {
match schema_type {
"string" => "string".to_string(),
"number" | "integer" => "number".to_string(),
"boolean" => "boolean".to_string(),
"null" => "null".to_string(),
"array" => self.render_array(map),
"object" => self.render_object(map),
_ => "unknown".to_string(),
}
}
fn render_array(&mut self, map: &serde_json::Map<String, JsonValue>) -> String {
if let Some(items) = map.get("items") {
let item_type = self.render(items);
if self.render_work_budget_exhausted {
return "unknown".to_string();
}
return format!("Array<{item_type}>");
}
if let Some(items) = map.get("prefixItems").and_then(JsonValue::as_array) {
let mut item_types = Vec::new();
for item in items {
if self.render_work_budget_exhausted {
return "unknown".to_string();
}
item_types.push(self.render(item));
}
if !item_types.is_empty() {
return format!("[{}]", item_types.join(", "));
}
}
"unknown[]".to_string()
}
fn append_additional_properties_line(
&mut self,
lines: &mut Vec<String>,
map: &serde_json::Map<String, JsonValue>,
properties: &serde_json::Map<String, JsonValue>,
line_prefix: &str,
) -> bool {
if let Some(additional_properties) = map.get("additionalProperties") {
let property_type = match additional_properties {
JsonValue::Bool(true) => Some("unknown".to_string()),
JsonValue::Bool(false) => None,
value => Some(self.render(value)),
};
if let Some(property_type) = property_type {
return self.push_render_line(
lines,
format!("{line_prefix}[key: string]: {property_type};"),
);
}
} else if properties.is_empty() {
return self.push_render_line(lines, format!("{line_prefix}[key: string]: unknown;"));
}
true
}
fn render_object_property(
&mut self,
name: &str,
value: &JsonValue,
required: &[&str],
) -> String {
if name.len() > self.remaining_render_work_bytes {
self.render_work_budget_exhausted = true;
return "unknown".to_string();
}
let optional = if required.iter().any(|required_name| required_name == &name) {
""
} else {
"?"
};
let property_name = render_json_schema_property_name(name);
let property_type = self.render(value);
if self.render_work_budget_exhausted {
return "unknown".to_string();
}
format!("{property_name}{optional}: {property_type};")
}
fn render_object(&mut self, map: &serde_json::Map<String, JsonValue>) -> String {
let required = map
.get("required")
.and_then(JsonValue::as_array)
.map(|items| {
items
.iter()
.filter_map(JsonValue::as_str)
.collect::<Vec<_>>()
})
.unwrap_or_default();
let empty_properties = serde_json::Map::new();
let properties = map
.get("properties")
.and_then(JsonValue::as_object)
.unwrap_or(&empty_properties);
let mut sorted_properties = properties.iter().collect::<Vec<_>>();
sorted_properties.sort_unstable_by_key(|(name_a, _)| *name_a);
if sorted_properties
.iter()
.any(|(_, value)| has_property_description(value))
{
let mut lines = Vec::new();
if !self.push_render_line(&mut lines, "{".to_string()) {
return "unknown".to_string();
}
for (name, value) in sorted_properties {
if let Some(description) = value.get("description").and_then(JsonValue::as_str) {
for description_line in description
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
{
if description_line.len().saturating_add(5)
> self.remaining_render_work_bytes
|| !self
.push_render_line(&mut lines, format!(" // {description_line}"))
{
return "unknown".to_string();
}
}
}
let property = self.render_object_property(name, value, &required);
if self.render_work_budget_exhausted
|| !self.push_render_line(&mut lines, format!(" {property}"))
{
return "unknown".to_string();
}
}
if !self.append_additional_properties_line(&mut lines, map, properties, " ")
|| !self.push_render_line(&mut lines, "}".to_string())
{
return "unknown".to_string();
}
return lines.join("\n");
}
let mut lines = Vec::new();
for (name, value) in sorted_properties {
let property = self.render_object_property(name, value, &required);
if self.render_work_budget_exhausted || !self.push_render_line(&mut lines, property) {
return "unknown".to_string();
}
}
if !self.append_additional_properties_line(&mut lines, map, properties, "") {
return "unknown".to_string();
}
if lines.is_empty() {
return "{}".to_string();
}
format!("{{ {} }}", lines.join(" "))
}
fn finish_render(&mut self, rendered: String) -> String {
if self.consume_render_work(rendered.len()) {
rendered
} else {
"unknown".to_string()
}
}
fn render_literal(&mut self, value: &JsonValue) -> String {
if json_literal_serialization_upper_bound(value) > self.remaining_render_work_bytes {
self.render_work_budget_exhausted = true;
"unknown".to_string()
} else {
render_json_schema_literal(value)
}
}
fn consume_render_work(&mut self, rendered_bytes: usize) -> bool {
if rendered_bytes > self.remaining_render_work_bytes {
self.render_work_budget_exhausted = true;
false
} else {
self.remaining_render_work_bytes -= rendered_bytes;
true
}
}
fn push_render_line(&mut self, lines: &mut Vec<String>, line: String) -> bool {
if !self.consume_render_work(line.len()) {
return false;
}
lines.push(line);
true
}
}
fn parenthesize_union_for_intersection(rendered: String) -> String {
if rendered.contains(" | ") {
format!("({rendered})")
} else {
rendered
}
}
fn local_json_pointer(reference: &str) -> Option<String> {
let fragment = reference.strip_prefix('#')?;
let pointer = percent_decode_uri_fragment(fragment)?;
if pointer.is_empty() || pointer.starts_with('/') {
Some(pointer)
} else {
None
}
}
fn percent_decode_uri_fragment(fragment: &str) -> Option<String> {
let bytes = fragment.as_bytes();
let mut decoded = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
if bytes[index] == b'%' {
let high = decode_hex_digit(*bytes.get(index + 1)?)?;
let low = decode_hex_digit(*bytes.get(index + 2)?)?;
decoded.push((high << 4) | low);
index += 3;
} else {
decoded.push(bytes[index]);
index += 1;
}
}
String::from_utf8(decoded).ok()
}
fn decode_hex_digit(digit: u8) -> Option<u8> {
match digit {
b'0'..=b'9' => Some(digit - b'0'),
b'a'..=b'f' => Some(digit - b'a' + 10),
b'A'..=b'F' => Some(digit - b'A' + 10),
_ => None,
}
}
fn has_renderable_schema_keywords(map: &serde_json::Map<String, JsonValue>) -> bool {
[
"const",
"enum",
"anyOf",
"oneOf",
"allOf",
"type",
"properties",
"additionalProperties",
"required",
"items",
"prefixItems",
]
.iter()
.any(|key| map.contains_key(*key))
}
fn has_property_description(value: &JsonValue) -> bool {
value
.get("description")
.and_then(JsonValue::as_str)
.is_some_and(|description| !description.is_empty())
}
fn render_json_schema_property_name(name: &str) -> String {
if normalize_code_mode_identifier(name) == name {
name.to_string()
} else {
serde_json::to_string(name).unwrap_or_else(|_| format!("\"{}\"", name.replace('"', "\\\"")))
}
}
fn render_json_schema_literal(value: &JsonValue) -> String {
serde_json::to_string(value).unwrap_or_else(|_| "unknown".to_string())
}
fn json_literal_serialization_upper_bound(value: &JsonValue) -> usize {
match value {
JsonValue::Null => 4,
JsonValue::Bool(false) => 5,
JsonValue::Bool(true) => 4,
JsonValue::Number(number) => number.to_string().len(),
// JSON escaping can expand one UTF-8 byte to at most one six-byte
// Unicode escape, so this bounds allocation before serialization.
JsonValue::String(string) => string.len().saturating_mul(6).saturating_add(2),
JsonValue::Array(values) => values.iter().fold(2, |size, value| {
size.saturating_add(1)
.saturating_add(json_literal_serialization_upper_bound(value))
}),
JsonValue::Object(map) => map.iter().fold(2, |size, (key, value)| {
size.saturating_add(4)
.saturating_add(key.len().saturating_mul(6))
.saturating_add(json_literal_serialization_upper_bound(value))
}),
}
}
#[cfg(test)]
#[path = "json_schema_types_tests.rs"]
mod tests;

View File

@@ -0,0 +1,200 @@
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn renders_recursive_local_refs_with_escaped_pointer_segments() {
let schema = json!({
"type": "object",
"properties": {
"clauses": {
"type": "array",
"items": { "$ref": "#/$defs/Boolean~1Clause~0v1" }
}
},
"$defs": {
"Boolean/Clause~v1": {
"type": "object",
"properties": {
"query": { "$ref": "#/$defs/Query" }
}
},
"Query": {
"oneOf": [
{ "type": "string" },
{
"type": "object",
"properties": {
"clauses": {
"type": "array",
"items": { "$ref": "#/$defs/Boolean~1Clause~0v1" }
}
}
}
]
}
}
});
let rendered = render_json_schema_to_typescript(&schema);
assert!(rendered.contains("clauses?: Array<{ query?: string | { clauses?: Array<{"));
assert!(rendered.contains("query?: string | { clauses?: Array<unknown>; };"));
}
#[test]
fn renders_ref_siblings_uri_fragments_and_all_of_precedence() {
assert_eq!(
render_json_schema_to_typescript(&json!({
"$ref": "#/$defs/Label",
"enum": ["A"],
"$defs": { "Label": { "type": "string" } }
})),
r#"(string) & ("A")"#
);
assert_eq!(
render_json_schema_to_typescript(&json!({
"$ref": "#/$defs/Foo%20Bar",
"$defs": { "Foo Bar": { "type": "string" } }
})),
"string"
);
assert_eq!(
render_json_schema_to_typescript(&json!({
"allOf": [
{ "$ref": "#/$defs/Choice" },
{ "type": "object", "properties": { "value": { "type": "string" } } }
],
"$defs": {
"Choice": { "oneOf": [{ "type": "string" }, { "type": "number" }] }
}
})),
"(string | number) & { value?: string; }"
);
}
#[test]
fn leaves_local_refs_under_nested_schema_resources_unresolved() {
let schema = json!({
"$defs": {
"Choice": { "type": "string" }
},
"type": "object",
"properties": {
"nested": {
"$id": "urn:nested",
"$defs": {
"Choice": { "type": "number" }
},
"type": "object",
"properties": {
"value": { "$ref": "#/$defs/Choice" }
}
}
}
});
assert_eq!(
render_json_schema_to_typescript(&schema),
"{ nested?: { value?: unknown; }; }"
);
}
#[test]
fn bounds_expansions_without_charging_dangling_refs() {
let mut properties = (0..MAX_TOTAL_LOCAL_REF_EXPANSIONS)
.map(|index| {
(
format!("a_missing_{index}"),
json!({ "$ref": format!("#/$defs/Missing{index}") }),
)
})
.collect::<serde_json::Map<_, _>>();
properties.insert("z_valid".to_string(), json!({ "$ref": "#/$defs/Valid" }));
let schema = json!({
"type": "object",
"properties": properties,
"$defs": { "Valid": { "type": "string" } }
});
let rendered = render_json_schema_to_typescript(&schema);
assert!(rendered.contains("z_valid?: string;"));
let properties = (0..MAX_TOTAL_LOCAL_REF_EXPANSIONS + 2)
.map(|index| {
(
format!("property_{index}"),
json!({ "$ref": "#/$defs/Item" }),
)
})
.collect::<serde_json::Map<_, _>>();
let rendered = render_json_schema_to_typescript(&json!({
"type": "object",
"properties": properties,
"$defs": { "Item": { "type": "string" } }
}));
assert_eq!(
rendered.matches("string").count(),
MAX_TOTAL_LOCAL_REF_EXPANSIONS
);
assert_eq!(rendered.matches("unknown").count(), 2);
}
#[test]
fn repeated_large_ref_expansions_exhaust_render_work_budget() {
let properties = (0..MAX_TOTAL_LOCAL_REF_EXPANSIONS)
.map(|index| {
(
format!("property_{index}"),
json!({ "$ref": "#/$defs/Item" }),
)
})
.collect::<serde_json::Map<_, _>>();
let schema = json!({
"type": "object",
"properties": properties,
"$defs": {
"Item": {
"type": "object",
"properties": {
"value": {
"type": "string",
"description": "x".repeat(DEFAULT_INPUT_SCHEMA_MAX_BYTES / 2)
}
}
}
}
});
let mut renderer = JsonSchemaTypeRenderer::new(&schema, DEFAULT_INPUT_SCHEMA_MAX_BYTES);
assert_eq!(renderer.render(&schema), "unknown");
assert!(renderer.render_work_budget_exhausted);
}
#[test]
fn oversized_ref_literal_exhausts_render_work_budget() {
let schema = json!({
"$ref": "#/$defs/Value",
"$defs": {
"Value": {
"const": "x".repeat(DEFAULT_INPUT_SCHEMA_MAX_BYTES * RENDER_WORK_MULTIPLIER)
}
}
});
let mut renderer = JsonSchemaTypeRenderer::new(&schema, DEFAULT_INPUT_SCHEMA_MAX_BYTES);
assert_eq!(renderer.render(&schema), "unknown");
assert!(renderer.render_work_budget_exhausted);
}
#[test]
fn rendered_schema_has_a_hard_size_cap() {
let description = "x".repeat(DEFAULT_INPUT_SCHEMA_MAX_BYTES);
let schema = json!({
"type": "object",
"properties": {
"value": { "type": "string", "description": description }
}
});
assert_eq!(render_json_schema_to_typescript(&schema), "unknown");
}

View File

@@ -0,0 +1,62 @@
mod description;
pub mod grpc;
pub mod host;
mod json_schema_types;
mod process_metrics;
mod response;
mod runtime;
mod session;
pub use description::CODE_MODE_PRAGMA_PREFIX;
pub use description::CodeModeToolKind;
pub use description::DeferredToolDiscovery;
pub use description::EnabledToolMetadata;
pub use description::ExecDefinition;
pub use description::ImageDetailVisibility;
pub use description::TOOL_SEARCH_GUIDANCE;
pub use description::ToolDefinition;
pub use description::ToolNamespaceDescription;
pub use description::augment_tool_definition;
pub use description::build_exec_tool_description_and_definitions;
pub use description::build_wait_tool_description;
pub use description::enabled_tool_metadata;
pub use description::is_code_mode_nested_tool;
pub use description::normalize_code_mode_identifier;
pub use description::parse_exec_source;
pub use description::render_code_mode_sample;
pub use json_schema_types::DEFAULT_INPUT_SCHEMA_MAX_BYTES;
pub use json_schema_types::render_json_schema_to_typescript;
pub use process_metrics::CodeModeProcessMetrics;
pub use process_metrics::CodeModeProcessMetricsSample;
pub use response::DEFAULT_IMAGE_DETAIL;
pub use response::FunctionCallOutputContentItem;
pub use response::ImageDetail;
pub use runtime::CodeModeNestedToolCall;
pub use runtime::DEFAULT_EXEC_YIELD_TIME_MS;
pub use runtime::DEFAULT_MAX_OUTPUT_TOKENS_PER_EXEC_CALL;
pub use runtime::DEFAULT_WAIT_YIELD_TIME_MS;
pub use runtime::ExecuteRequest;
pub use runtime::ExecuteToPendingOutcome;
pub use runtime::MissingCodeModeHostDuration;
pub use runtime::RuntimeResponse;
pub use runtime::TerminateRequest;
pub use runtime::WaitOutcome;
pub use runtime::WaitRequest;
pub use runtime::WaitToPendingOutcome;
pub use runtime::WaitToPendingRequest;
pub use session::CellId;
pub use session::CodeModeOutputTruncation;
pub use session::CodeModeSession;
pub use session::CodeModeSessionCellExecutionLimits;
pub use session::CodeModeSessionDelegate;
pub use session::CodeModeSessionOptions;
pub use session::CodeModeSessionProvider;
pub use session::CodeModeSessionProviderFuture;
pub use session::CodeModeSessionResultFuture;
pub use session::NoopCodeModeSessionDelegate;
pub use session::NotificationFuture;
pub use session::StartedCell;
pub use session::ToolInvocationFuture;
pub const PUBLIC_TOOL_NAME: &str = "exec";
pub const WAIT_TOOL_NAME: &str = "wait";

View File

@@ -0,0 +1,21 @@
//! Optional process observations, independent of sessions. Process-owned
//! providers observe existing children; remote transports own connection policy.
/// A cumulative observation of one host process, shared across its sessions.
#[derive(Clone, Debug, PartialEq)]
pub struct CodeModeProcessMetrics {
pub process_id: u32,
/// Unix timestamp, stable for this process across all metrics transports.
pub process_start_time_seconds: f64,
pub cpu_seconds_total: f64,
pub resident_memory_bytes: u64,
}
/// Unsupported capability and an absent process are distinct from a failed sample.
#[derive(Clone, Debug, PartialEq)]
pub enum CodeModeProcessMetricsSample {
Unsupported,
/// The process owner knows no host is running; never inferred from an RPC status.
NotRunning,
Snapshot(CodeModeProcessMetrics),
}

View File

@@ -0,0 +1,29 @@
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ImageDetail {
Auto,
Low,
High,
Original,
}
pub const DEFAULT_IMAGE_DETAIL: ImageDetail = ImageDetail::High;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum FunctionCallOutputContentItem {
InputText {
text: String,
},
InputImage {
image_url: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
detail: Option<ImageDetail>,
},
InputAudio {
audio_url: String,
},
}

View File

@@ -0,0 +1,222 @@
use std::error::Error;
use std::fmt;
use std::time::Duration;
use akode_protocol::ToolName;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
use crate::CellId;
use crate::CodeModeToolKind;
use crate::FunctionCallOutputContentItem;
use crate::ToolDefinition;
pub const DEFAULT_EXEC_YIELD_TIME_MS: u64 = 10_000;
pub const DEFAULT_WAIT_YIELD_TIME_MS: u64 = 10_000;
pub const DEFAULT_MAX_OUTPUT_TOKENS_PER_EXEC_CALL: usize = 10_000;
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ExecuteRequest {
pub tool_call_id: String,
pub enabled_tools: Vec<ToolDefinition>,
pub source: String,
pub yield_time_ms: Option<u64>,
pub max_output_tokens: Option<usize>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct WaitRequest {
pub cell_id: CellId,
pub yield_time_ms: u64,
/// Limit for this observation in Server mode; ignored in Client mode.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_output_tokens: Option<usize>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct TerminateRequest {
pub cell_id: CellId,
/// Limit for the final observation in Server mode; ignored in Client mode.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_output_tokens: Option<usize>,
}
impl From<CellId> for TerminateRequest {
fn from(cell_id: CellId) -> Self {
Self {
cell_id,
max_output_tokens: None,
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct WaitToPendingRequest {
pub cell_id: CellId,
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub enum WaitOutcome {
LiveCell(RuntimeResponse),
MissingCell(RuntimeResponse),
}
impl WaitOutcome {
/// How long a completed result waited for retrieval. Zero if it was delivered immediately,
/// or `None` if this wait did not retrieve a completed result.
pub fn result_buffered_for(&self) -> Option<Duration> {
match self {
Self::LiveCell(RuntimeResponse::Result {
result_buffered_for,
..
}) => Some(*result_buffered_for),
Self::LiveCell(_) | Self::MissingCell(_) => None,
}
}
/// Returns timing for this wait or termination request, when supplied by its host.
pub fn code_mode_host_duration(&self) -> Option<Duration> {
match self {
Self::LiveCell(response) | Self::MissingCell(response) => {
response.code_mode_host_duration()
}
}
}
/// Records the enclosing host request's duration before wire conversion.
pub fn with_code_mode_host_duration(self, code_mode_host_duration: Duration) -> Self {
match self {
Self::LiveCell(response) => {
Self::LiveCell(response.with_code_mode_host_duration(code_mode_host_duration))
}
Self::MissingCell(response) => {
Self::MissingCell(response.with_code_mode_host_duration(code_mode_host_duration))
}
}
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub enum ExecuteToPendingOutcome {
Pending {
cell_id: CellId,
content_items: Vec<FunctionCallOutputContentItem>,
pending_tool_call_ids: Vec<String>,
},
Completed(RuntimeResponse),
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub enum WaitToPendingOutcome {
LiveCell(ExecuteToPendingOutcome),
MissingCell(RuntimeResponse),
}
impl From<WaitOutcome> for RuntimeResponse {
fn from(outcome: WaitOutcome) -> Self {
match outcome {
WaitOutcome::LiveCell(response) | WaitOutcome::MissingCell(response) => response,
}
}
}
/// Runtime output with optional timing for the host request that observed it.
///
/// The JavaScript session returns untimed output. The host handler records its
/// complete request duration before conversion; wire conversions preserve that
/// field and reject untimed output. Decoded host responses always contain timing,
/// including measured zero. Raw traces also retain timing when present.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum RuntimeResponse {
Yielded {
cell_id: CellId,
content_items: Vec<FunctionCallOutputContentItem>,
#[serde(skip_serializing_if = "Option::is_none")]
code_mode_host_duration: Option<Duration>,
},
Terminated {
cell_id: CellId,
content_items: Vec<FunctionCallOutputContentItem>,
#[serde(skip_serializing_if = "Option::is_none")]
code_mode_host_duration: Option<Duration>,
},
Result {
cell_id: CellId,
content_items: Vec<FunctionCallOutputContentItem>,
/// None means success; Some (including an empty string) means failure.
/// Client mode supplies the original diagnostic to append before truncation.
/// Server mode includes the diagnostic in the already-budgeted content and
/// supplies an independently bounded copy here for logging; do not append it again.
error_text: Option<String>,
/// Time between completion and retrieval when the result was buffered.
#[serde(default, skip_serializing_if = "Duration::is_zero")]
result_buffered_for: Duration,
#[serde(skip_serializing_if = "Option::is_none")]
code_mode_host_duration: Option<Duration>,
},
}
impl RuntimeResponse {
/// Returns timing for this observation, excluding background work between requests.
pub fn code_mode_host_duration(&self) -> Option<Duration> {
match self {
Self::Yielded {
code_mode_host_duration,
..
}
| Self::Terminated {
code_mode_host_duration,
..
}
| Self::Result {
code_mode_host_duration,
..
} => *code_mode_host_duration,
}
}
/// Records the enclosing host request's duration before wire conversion.
pub fn with_code_mode_host_duration(mut self, code_mode_host_duration: Duration) -> Self {
match &mut self {
Self::Yielded {
code_mode_host_duration: value,
..
}
| Self::Terminated {
code_mode_host_duration: value,
..
}
| Self::Result {
code_mode_host_duration: value,
..
} => *value = Some(code_mode_host_duration),
}
self
}
}
/// An untimed runtime response cannot be encoded for delivery to a host client.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MissingCodeModeHostDuration;
impl fmt::Display for MissingCodeModeHostDuration {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("code-mode response is missing host duration")
}
}
impl Error for MissingCodeModeHostDuration {}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct CodeModeNestedToolCall {
pub cell_id: CellId,
pub runtime_tool_call_id: String,
pub tool_name: ToolName,
pub tool_kind: CodeModeToolKind,
pub input: Option<JsonValue>,
}
#[cfg(test)]
#[path = "runtime_tests.rs"]
mod tests;

View File

@@ -0,0 +1,108 @@
//! Regression coverage for timing metadata at serialization boundaries.
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.
#[test]
fn code_mode_host_duration_survives_runtime_and_stdio_serialization() {
let content_items = vec![FunctionCallOutputContentItem::InputText {
text: "output".to_string(),
}];
for response in [
RuntimeResponse::Yielded {
cell_id: CellId::new("yielded-cell".to_string()),
content_items: content_items.clone(),
code_mode_host_duration: None,
},
RuntimeResponse::Terminated {
cell_id: CellId::new("terminated-cell".to_string()),
content_items: content_items.clone(),
code_mode_host_duration: None,
},
RuntimeResponse::Result {
cell_id: CellId::new("completed-cell".to_string()),
content_items,
result_buffered_for: Duration::ZERO,
error_text: Some("execution failed".to_string()),
code_mode_host_duration: None,
},
] {
for duration in [
None,
Some(Duration::ZERO),
Some(Duration::from_nanos(/*nanos*/ 1_234_567_890)),
Some(Duration::from_nanos(u64::MAX)),
] {
let mut expected = response.clone();
match &mut expected {
RuntimeResponse::Yielded {
code_mode_host_duration,
..
}
| RuntimeResponse::Terminated {
code_mode_host_duration,
..
}
| RuntimeResponse::Result {
code_mode_host_duration,
..
} => *code_mode_host_duration = duration,
}
let payload = serde_json::to_value(&expected).expect("serialize response");
assert_eq!(
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)
);
}
}

View File

@@ -0,0 +1,278 @@
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use crate::CodeModeNestedToolCall;
use crate::ExecuteRequest;
use crate::RuntimeResponse;
use crate::TerminateRequest;
use crate::WaitOutcome;
use crate::WaitRequest;
pub type CodeModeSessionResultFuture<'a, T> =
Pin<Box<dyn Future<Output = Result<T, String>> + Send + 'a>>;
pub type CodeModeSessionProviderFuture<'a> =
CodeModeSessionResultFuture<'a, Arc<dyn CodeModeSession>>;
pub type ToolInvocationFuture<'a> =
Pin<Box<dyn Future<Output = Result<JsonValue, String>> + Send + 'a>>;
pub type NotificationFuture<'a> = Pin<Box<dyn Future<Output = Result<(), String>> + Send + 'a>>;
/// Optional resource limits shared by every cell in one code-mode session.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct CodeModeSessionCellExecutionLimits {
pub max_yield_time_ms: Option<u64>,
pub max_heap_size_bytes: Option<usize>,
}
/// The owner of the output budget for each exec or wait observation.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum CodeModeOutputTruncation {
/// Return raw output; the caller applies its own budget and formatting.
#[default]
Client,
/// The host applies the exec, wait, or terminate observation's budget before
/// transmitting output (10,000 tokens by default). Clients must not truncate
/// it again or append the script error: status and error metadata remain separate.
///
/// A complete observation keeps up to [`crate::host::BOUNDED_OUTPUT_MAX_BYTES`]
/// of text, [`crate::host::BOUNDED_OUTPUT_MAX_IMAGE_BYTES`] of inline image URLs,
/// and [`crate::host::BOUNDED_OUTPUT_MAX_AUDIO_BYTES`] of audio URLs, subject
/// to a separate item limit. While these limits hold, formatting matches
/// Core's client policy. On text overflow the collector keeps a prefix and a
/// rolling tail. Each image or audio clip is admitted if it fits its remaining
/// byte allowance. Eviction at the item limit can free space for later media.
/// Media are indivisible. Bounded loss notices survive even a zero-token budget.
Server,
}
/// Settings shared by every cell in one code-mode session.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct CodeModeSessionOptions {
pub cell_execution_limits: CodeModeSessionCellExecutionLimits,
pub output_truncation: CodeModeOutputTruncation,
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct CellId(String);
impl CellId {
pub fn new(value: String) -> Self {
Self(value)
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl AsRef<str> for CellId {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for CellId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
pub struct StartedCell {
pub cell_id: CellId,
initial_response: CodeModeSessionResultFuture<'static, RuntimeResponse>,
}
impl StartedCell {
pub fn new(cell_id: CellId, initial_response_rx: oneshot::Receiver<RuntimeResponse>) -> Self {
Self::from_future(cell_id, async move {
initial_response_rx
.await
.map_err(|_| "exec runtime ended unexpectedly".to_string())
})
}
pub fn from_result_receiver(
cell_id: CellId,
initial_response_rx: oneshot::Receiver<Result<RuntimeResponse, String>>,
) -> Self {
Self::from_future(cell_id, async move {
initial_response_rx
.await
.map_err(|_| "exec runtime ended unexpectedly".to_string())?
})
}
pub fn from_future(
cell_id: CellId,
initial_response: impl Future<Output = Result<RuntimeResponse, String>> + Send + 'static,
) -> Self {
Self {
cell_id,
initial_response: Box::pin(initial_response),
}
}
pub async fn initial_response(self) -> Result<RuntimeResponse, String> {
self.initial_response.await
}
}
/// Host callbacks owned by one code-mode execution.
///
/// The session retains the supplied delegate while starting and running the cell,
/// including across yields, and releases it through its existing close/cancel paths.
pub trait CodeModeSessionDelegate: Send + Sync {
fn invoke_tool<'a>(
&'a self,
invocation: CodeModeNestedToolCall,
cancellation_token: CancellationToken,
) -> ToolInvocationFuture<'a>;
fn notify<'a>(
&'a self,
call_id: String,
cell_id: CellId,
text: String,
cancellation_token: CancellationToken,
) -> NotificationFuture<'a>;
/// Releases delegate state associated with a cell after it reaches a terminal state.
fn cell_closed(&self, cell_id: &CellId);
}
/// A session delegate for clients that do not expose nested tools or notifications.
pub struct NoopCodeModeSessionDelegate;
impl CodeModeSessionDelegate for NoopCodeModeSessionDelegate {
fn invoke_tool<'a>(
&'a self,
_invocation: CodeModeNestedToolCall,
cancellation_token: CancellationToken,
) -> ToolInvocationFuture<'a> {
Box::pin(async move {
cancellation_token.cancelled().await;
Err("code mode nested tools are unavailable".to_string())
})
}
fn notify<'a>(
&'a self,
_call_id: String,
_cell_id: CellId,
_text: String,
_cancellation_token: CancellationToken,
) -> NotificationFuture<'a> {
Box::pin(async { Ok(()) })
}
fn cell_closed(&self, _cell_id: &CellId) {}
}
/// A durable code-mode session owned by one Codex thread.
///
/// Cells executed in the same session share stored values. Separate sessions
/// must keep those values isolated. Implementations may execute cells
/// in-process or remotely.
pub trait CodeModeSession: Send + Sync {
/// Identifies who applies output truncation for this session's responses.
/// Providers must not change modes when reconnecting to a new host.
fn output_truncation(&self) -> CodeModeOutputTruncation {
CodeModeOutputTruncation::Client
}
/// Executes a cell, yielding its foreground observation if `preempt` is signaled.
/// The cell continues running after its observation yields.
fn execute<'a>(
&'a self,
request: ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
preempt: Option<CancellationToken>,
) -> CodeModeSessionResultFuture<'a, StartedCell>;
/// Waits for a cell, yielding the observation if `preempt` is signaled while the cell continues.
/// Server mode applies the request's output limit; Client mode ignores it.
fn wait<'a>(
&'a self,
request: WaitRequest,
preempt: Option<CancellationToken>,
) -> CodeModeSessionResultFuture<'a, WaitOutcome>;
/// Terminates a cell, applying the request's limit to its final observation
/// in Server mode; Client mode ignores the limit.
fn terminate<'a>(
&'a self,
request: TerminateRequest,
) -> CodeModeSessionResultFuture<'a, WaitOutcome>;
fn shutdown<'a>(&'a self) -> CodeModeSessionResultFuture<'a, ()>;
}
/// Creates code-mode sessions for Codex threads.
///
/// Implementations may share a remote host process across all sessions created
/// by one provider.
pub trait CodeModeSessionProvider: Send + Sync {
/// Reports whether this provider can execute code without starting its host.
fn availability(&self) -> Result<(), String> {
Ok(())
}
/// Observes a host without starting a session. Process-owned providers must
/// not start or replace a host. Network providers may connect or reconnect
/// according to their transport policy. Sampling failures and cancellation
/// must not explicitly reset the shared execution connection.
fn sample_process_metrics(
&self,
) -> CodeModeSessionResultFuture<'_, crate::CodeModeProcessMetricsSample> {
Box::pin(async { Ok(crate::CodeModeProcessMetricsSample::Unsupported) })
}
fn create_session(&self) -> CodeModeSessionProviderFuture<'_>;
/// Creates a session whose cells share the supplied execution limits.
///
/// Existing providers remain compatible with unlimited sessions, but must
/// explicitly implement this method before accepting non-default limits.
fn create_session_with_limits<'a>(
&'a self,
limits: CodeModeSessionCellExecutionLimits,
) -> CodeModeSessionProviderFuture<'a> {
if limits == CodeModeSessionCellExecutionLimits::default() {
self.create_session()
} else {
Box::pin(async {
Err("code-mode session provider does not support resource limits".to_string())
})
}
}
/// Requests output handling for one session, without changing other sessions
/// created by this provider. Server mode requires host support.
fn create_session_with_options<'a>(
&'a self,
options: CodeModeSessionOptions,
) -> CodeModeSessionProviderFuture<'a> {
match options.output_truncation {
CodeModeOutputTruncation::Client => {
self.create_session_with_limits(options.cell_execution_limits)
}
CodeModeOutputTruncation::Server => Box::pin(async {
Err(
"code-mode session provider does not support server output truncation"
.to_string(),
)
}),
}
}
}
#[cfg(test)]
#[path = "session_tests.rs"]
mod tests;

View File

@@ -0,0 +1,19 @@
use pretty_assertions::assert_eq;
use tokio::sync::oneshot;
use super::CellId;
use super::StartedCell;
#[tokio::test]
async fn started_cell_preserves_remote_initial_response_errors() {
let (response_tx, response_rx) = oneshot::channel();
response_tx
.send(Err("remote runtime failed".to_string()))
.expect("initial response receiver should be open");
let started = StartedCell::from_result_receiver(CellId::new("1".to_string()), response_rx);
assert_eq!(
started.initial_response().await,
Err("remote runtime failed".to_string())
);
}