mirror of
https://github.com/openai/codex.git
synced 2026-11-29 00:00:54 +00:00
code-mode: use client cell ids and linear observations
This commit is contained in:
Generated
-2
@@ -2499,11 +2499,9 @@ dependencies = [
|
||||
"deno_core_icudata",
|
||||
"pretty_assertions",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"v8",
|
||||
]
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ pub use runtime::CreateCellRequest;
|
||||
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::ObservationGeneration;
|
||||
pub use runtime::ObserveOutcome;
|
||||
pub use runtime::ObserveRequest;
|
||||
pub use runtime::RuntimeResponse;
|
||||
|
||||
@@ -14,7 +14,7 @@ pub const DEFAULT_MAX_OUTPUT_TOKENS_PER_EXEC_CALL: usize = 10_000;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
pub struct CreateCellRequest {
|
||||
pub idempotency_key: String,
|
||||
pub cell_id: CellId,
|
||||
pub tool_call_id: String,
|
||||
pub enabled_tools: Vec<ToolDefinition>,
|
||||
pub source: String,
|
||||
@@ -22,11 +22,34 @@ pub struct CreateCellRequest {
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
pub struct ObserveRequest {
|
||||
pub idempotency_key: String,
|
||||
pub cell_id: CellId,
|
||||
pub generation: ObservationGeneration,
|
||||
pub yield_time_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct ObservationGeneration(u64);
|
||||
|
||||
impl ObservationGeneration {
|
||||
pub const INITIAL: Self = Self(0);
|
||||
|
||||
pub const fn new(value: u64) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
|
||||
pub const fn get(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub const fn next(self) -> Option<Self> {
|
||||
match self.0.checked_add(1) {
|
||||
Some(value) => Some(Self(value)),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A valid result of observing a cell.
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(tag = "type")]
|
||||
|
||||
@@ -34,7 +34,7 @@ fn image(image_url: &str, detail: Option<ImageDetail>) -> FunctionCallOutputCont
|
||||
#[test]
|
||||
fn requests_round_trip_with_exact_tool_and_namespace_fields() {
|
||||
let create = CreateCellRequest {
|
||||
idempotency_key: "thread-3:response-call-7".to_string(),
|
||||
cell_id: CellId::new("cell-a7".to_string()),
|
||||
tool_call_id: "response-call-7".to_string(),
|
||||
enabled_tools: vec![
|
||||
ToolDefinition {
|
||||
@@ -62,7 +62,7 @@ fn requests_round_trip_with_exact_tool_and_namespace_fields() {
|
||||
assert_json_round_trip(
|
||||
&create,
|
||||
json!({
|
||||
"idempotency_key": "thread-3:response-call-7",
|
||||
"cell_id": "cell-a7",
|
||||
"tool_call_id": "response-call-7",
|
||||
"enabled_tools": [
|
||||
{
|
||||
@@ -91,13 +91,13 @@ fn requests_round_trip_with_exact_tool_and_namespace_fields() {
|
||||
|
||||
assert_json_round_trip(
|
||||
&ObserveRequest {
|
||||
idempotency_key: "thread-3:wait-call-2".to_string(),
|
||||
cell_id: CellId::new("cell-a7".to_string()),
|
||||
generation: ObservationGeneration::new(/*value*/ 3),
|
||||
yield_time_ms: 250,
|
||||
},
|
||||
json!({
|
||||
"idempotency_key": "thread-3:wait-call-2",
|
||||
"cell_id": "cell-a7",
|
||||
"generation": 3,
|
||||
"yield_time_ms": 250,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -20,11 +20,9 @@ codex-code-mode-protocol = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
deno_core_icudata = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] }
|
||||
tokio-util = { workspace = true, features = ["rt"] }
|
||||
tracing = { workspace = true }
|
||||
uuid = { workspace = true, features = ["v4"] }
|
||||
v8 = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -12,7 +12,7 @@ use crate::session_runtime::ToolKind as CellToolKind;
|
||||
|
||||
pub(super) fn runtime_request(request: CellRequest) -> CreateCellRequest {
|
||||
CreateCellRequest {
|
||||
idempotency_key: request.idempotency_key,
|
||||
cell_id: codex_code_mode_protocol::CellId::new(request.cell_id.as_str().to_string()),
|
||||
tool_call_id: request.tool_call_id,
|
||||
enabled_tools: request
|
||||
.enabled_tools
|
||||
|
||||
@@ -5,6 +5,7 @@ use std::sync::atomic::Ordering;
|
||||
use std::sync::mpsc as std_mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_code_mode_protocol::CellId;
|
||||
use codex_code_mode_protocol::CreateCellRequest;
|
||||
use codex_code_mode_protocol::FunctionCallOutputContentItem;
|
||||
use pretty_assertions::assert_eq;
|
||||
@@ -125,7 +126,7 @@ fn spawn_cell_actor_harness_with_policy<H: CellHost>(
|
||||
let (runtime_tx, runtime_pause_tx, runtime_terminate_handle) = spawn_runtime(
|
||||
HashMap::new(),
|
||||
CreateCellRequest {
|
||||
idempotency_key: "cell-actor-harness".to_string(),
|
||||
cell_id: CellId::new("cell-actor-harness".to_string()),
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
source: "await new Promise(() => {});".to_string(),
|
||||
|
||||
@@ -347,11 +347,12 @@ mod tests {
|
||||
use super::RuntimeControlCommand;
|
||||
use super::RuntimeEvent;
|
||||
use super::spawn_runtime;
|
||||
use crate::CellId;
|
||||
use crate::FunctionCallOutputContentItem;
|
||||
|
||||
fn execute_request(source: &str) -> CreateCellRequest {
|
||||
CreateCellRequest {
|
||||
idempotency_key: format!("call_1:{source}"),
|
||||
cell_id: CellId::new(format!("call_1:{source}")),
|
||||
tool_call_id: "call_1".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
source: source.to_string(),
|
||||
|
||||
@@ -14,6 +14,7 @@ use codex_code_mode_protocol::CreateCellRequest;
|
||||
use codex_code_mode_protocol::FunctionCallOutputContentItem;
|
||||
use codex_code_mode_protocol::ImageDetail;
|
||||
use codex_code_mode_protocol::NotificationFuture;
|
||||
use codex_code_mode_protocol::ObservationGeneration;
|
||||
use codex_code_mode_protocol::ObserveOutcome;
|
||||
use codex_code_mode_protocol::ObserveRequest;
|
||||
#[cfg(test)]
|
||||
@@ -96,7 +97,7 @@ impl CodeModeSessionProvider for InProcessCodeModeSessionProvider {
|
||||
|
||||
pub struct CodeModeService {
|
||||
runtime: Arc<SessionRuntime<ProtocolDelegate>>,
|
||||
observations: Mutex<HashMap<String, ObservationRecord>>,
|
||||
observations: Mutex<HashMap<CellId, ObservationRecord>>,
|
||||
#[cfg(test)]
|
||||
pending_generations: Mutex<HashMap<runtime::CellId, runtime::PendingGeneration>>,
|
||||
}
|
||||
@@ -146,20 +147,61 @@ impl CodeModeService {
|
||||
}
|
||||
|
||||
pub async fn observe(&self, request: ObserveRequest) -> Result<ObserveOutcome, String> {
|
||||
let idempotency_key = request.idempotency_key.clone();
|
||||
let cell_id = request.cell_id.clone();
|
||||
let mut result_rx = {
|
||||
let mut observations = self.observations.lock().await;
|
||||
if let Some(existing) = observations.get(&idempotency_key) {
|
||||
if existing.request != request {
|
||||
if let Some(existing) = observations.get(&cell_id) {
|
||||
if existing.request.generation == request.generation {
|
||||
if existing.request != request {
|
||||
return Err(format!(
|
||||
"observation generation {} for cell {cell_id} was reused for a different request",
|
||||
request.generation.get()
|
||||
));
|
||||
}
|
||||
existing.result_rx.clone()
|
||||
} else {
|
||||
let Some(next_generation) = existing.request.generation.next() else {
|
||||
return Err(format!(
|
||||
"observation generation exhausted for cell {cell_id}"
|
||||
));
|
||||
};
|
||||
if request.generation != next_generation {
|
||||
return Err(format!(
|
||||
"expected observation generation {} for cell {cell_id}, got {}",
|
||||
next_generation.get(),
|
||||
request.generation.get()
|
||||
));
|
||||
}
|
||||
if existing.result_rx.borrow().is_none() {
|
||||
return Err(format!(
|
||||
"observation generation {} for cell {cell_id} is still pending",
|
||||
existing.request.generation.get()
|
||||
));
|
||||
}
|
||||
let (result_tx, result_rx) = watch::channel(None);
|
||||
observations.insert(
|
||||
cell_id,
|
||||
ObservationRecord {
|
||||
request: request.clone(),
|
||||
result_rx: result_rx.clone(),
|
||||
},
|
||||
);
|
||||
let runtime = Arc::clone(&self.runtime);
|
||||
tokio::spawn(async move {
|
||||
let result = begin_observe_runtime(runtime, request).await.await;
|
||||
result_tx.send_replace(Some(result));
|
||||
});
|
||||
result_rx
|
||||
}
|
||||
} else {
|
||||
if request.generation != ObservationGeneration::INITIAL {
|
||||
return Err(format!(
|
||||
"observation idempotency key `{idempotency_key}` was reused for a different request"
|
||||
"first observation for cell {cell_id} must use generation 0"
|
||||
));
|
||||
}
|
||||
existing.result_rx.clone()
|
||||
} else {
|
||||
let (result_tx, result_rx) = watch::channel(None);
|
||||
observations.insert(
|
||||
idempotency_key,
|
||||
cell_id,
|
||||
ObservationRecord {
|
||||
request: request.clone(),
|
||||
result_rx: result_rx.clone(),
|
||||
@@ -289,8 +331,8 @@ async fn begin_observe_runtime(
|
||||
request: ObserveRequest,
|
||||
) -> CodeModeSessionResultFuture<'static, ObserveOutcome> {
|
||||
let ObserveRequest {
|
||||
idempotency_key: _,
|
||||
cell_id,
|
||||
generation: _,
|
||||
yield_time_ms,
|
||||
} = request;
|
||||
let runtime_cell_id = runtime_cell_id(&cell_id);
|
||||
@@ -412,7 +454,7 @@ impl runtime::SessionRuntimeDelegate for ProtocolDelegate {
|
||||
|
||||
fn runtime_request(request: CreateCellRequest) -> runtime::CreateCellRequest {
|
||||
runtime::CreateCellRequest {
|
||||
idempotency_key: request.idempotency_key,
|
||||
cell_id: runtime_cell_id(&request.cell_id),
|
||||
tool_call_id: request.tool_call_id,
|
||||
enabled_tools: request
|
||||
.enabled_tools
|
||||
|
||||
@@ -218,7 +218,7 @@ fn cell_id(value: &str) -> CellId {
|
||||
|
||||
fn execute_request(source: &str) -> CreateCellRequest {
|
||||
CreateCellRequest {
|
||||
idempotency_key: format!("call-1:{source}"),
|
||||
cell_id: cell_id("1"),
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
source: source.to_string(),
|
||||
@@ -237,8 +237,8 @@ async fn execute_with_yield_time(
|
||||
let cell_id = service.create_cell(request).await.unwrap();
|
||||
service
|
||||
.observe(ObserveRequest {
|
||||
idempotency_key: format!("observe:{cell_id}"),
|
||||
cell_id,
|
||||
generation: ObservationGeneration::INITIAL,
|
||||
yield_time_ms,
|
||||
})
|
||||
.await
|
||||
@@ -291,12 +291,12 @@ async fn create_retry_returns_the_cell_from_the_original_ambiguous_request() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_observation_is_replayed_by_its_idempotency_key() {
|
||||
async fn cancelled_observation_is_replayed_by_its_generation() {
|
||||
let (delegate, mut events_rx) = BlockingDelegate::new();
|
||||
let service = Arc::new(CodeModeService::with_delegate(delegate.clone()));
|
||||
let created_cell_id = service
|
||||
.create_cell(CreateCellRequest {
|
||||
idempotency_key: "ambiguous-observation-cell".to_string(),
|
||||
cell_id: cell_id("1"),
|
||||
enabled_tools: vec![blocking_tool()],
|
||||
source: r#"await tools.block({}); text("done");"#.to_string(),
|
||||
..execute_request("")
|
||||
@@ -305,8 +305,8 @@ async fn cancelled_observation_is_replayed_by_its_idempotency_key() {
|
||||
.unwrap();
|
||||
assert_eq!(next_event(&mut events_rx).await, DelegateEvent::ToolStarted);
|
||||
let request = ObserveRequest {
|
||||
idempotency_key: "lost-observation-response".to_string(),
|
||||
cell_id: created_cell_id,
|
||||
generation: ObservationGeneration::INITIAL,
|
||||
yield_time_ms: 60_000,
|
||||
};
|
||||
|
||||
@@ -321,7 +321,7 @@ async fn cancelled_observation_is_replayed_by_its_idempotency_key() {
|
||||
.observations
|
||||
.lock()
|
||||
.await
|
||||
.contains_key("lost-observation-response")
|
||||
.contains_key(&cell_id("1"))
|
||||
{
|
||||
break;
|
||||
}
|
||||
@@ -346,6 +346,69 @@ async fn cancelled_observation_is_replayed_by_its_idempotency_key() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn next_observation_generation_evicts_the_previous_result() {
|
||||
let service = CodeModeService::new();
|
||||
let first = execute_with_yield_time(
|
||||
&service,
|
||||
CreateCellRequest {
|
||||
source: r#"text("before"); yield_control(); text("after");"#.to_string(),
|
||||
..execute_request("")
|
||||
},
|
||||
/*yield_time_ms*/ 60_000,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
first,
|
||||
RuntimeResponse::Yielded {
|
||||
cell_id: cell_id("1"),
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "before".to_string(),
|
||||
}],
|
||||
}
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
service
|
||||
.observe(ObserveRequest {
|
||||
cell_id: cell_id("1"),
|
||||
generation: ObservationGeneration::new(/*value*/ 1),
|
||||
yield_time_ms: 60_000,
|
||||
})
|
||||
.await
|
||||
.unwrap(),
|
||||
ObserveOutcome::Completed {
|
||||
cell_id: cell_id("1"),
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "after".to_string(),
|
||||
}],
|
||||
error_text: None,
|
||||
}
|
||||
);
|
||||
|
||||
{
|
||||
let observations = service.observations.lock().await;
|
||||
assert_eq!(observations.len(), 1);
|
||||
assert_eq!(
|
||||
observations
|
||||
.get(&cell_id("1"))
|
||||
.map(|record| record.request.generation),
|
||||
Some(ObservationGeneration::new(/*value*/ 1))
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
service
|
||||
.observe(ObserveRequest {
|
||||
cell_id: cell_id("1"),
|
||||
generation: ObservationGeneration::INITIAL,
|
||||
yield_time_ms: 60_000,
|
||||
})
|
||||
.await
|
||||
.unwrap_err(),
|
||||
"expected observation generation 2 for cell 1, got 0"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn yields_and_resumes() {
|
||||
let service = CodeModeService::new();
|
||||
@@ -371,8 +434,8 @@ async fn yields_and_resumes() {
|
||||
assert_eq!(
|
||||
service
|
||||
.observe(ObserveRequest {
|
||||
idempotency_key: "observe-after-yield".to_string(),
|
||||
cell_id: cell_id("1"),
|
||||
generation: ObservationGeneration::new(/*value*/ 1),
|
||||
yield_time_ms: 60_000,
|
||||
})
|
||||
.await
|
||||
@@ -410,8 +473,8 @@ await tools.block({});
|
||||
assert_eq!(
|
||||
service
|
||||
.observe(ObserveRequest {
|
||||
idempotency_key: "yield-boundary".to_string(),
|
||||
cell_id: cell_id.clone(),
|
||||
generation: ObservationGeneration::INITIAL,
|
||||
yield_time_ms: 60_000,
|
||||
})
|
||||
.await
|
||||
@@ -428,8 +491,8 @@ await tools.block({});
|
||||
assert_eq!(
|
||||
service
|
||||
.observe(ObserveRequest {
|
||||
idempotency_key: "completion-boundary".to_string(),
|
||||
cell_id: cell_id.clone(),
|
||||
generation: ObservationGeneration::new(/*value*/ 1),
|
||||
yield_time_ms: 60_000,
|
||||
})
|
||||
.await
|
||||
@@ -458,8 +521,8 @@ async fn background_completion_notifies_the_delegate_without_another_observation
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
service.observe(ObserveRequest {
|
||||
idempotency_key: "background-completion".to_string(),
|
||||
cell_id: created_cell_id.clone(),
|
||||
generation: ObservationGeneration::INITIAL,
|
||||
yield_time_ms: 1,
|
||||
}),
|
||||
)
|
||||
@@ -550,7 +613,7 @@ async fn observed_natural_completion_wins_over_termination() {
|
||||
let response = create_and_observe_to_pending(
|
||||
&service,
|
||||
CreateCellRequest {
|
||||
idempotency_key: format!("completion-probe-{probe_generation}"),
|
||||
cell_id: cell_id(&format!("completion-probe-{probe_generation}")),
|
||||
..execute_request(r#"text(String(load("finished")));"#)
|
||||
},
|
||||
)
|
||||
@@ -662,7 +725,10 @@ await tools.block({});
|
||||
assert_eq!(
|
||||
execute_with_yield_time(
|
||||
&service,
|
||||
execute_request(r#"text(String(load("candidate")));"#),
|
||||
CreateCellRequest {
|
||||
cell_id: cell_id("2"),
|
||||
..execute_request(r#"text(String(load("candidate")));"#)
|
||||
},
|
||||
/*yield_time_ms*/ 60_000,
|
||||
)
|
||||
.await,
|
||||
@@ -766,8 +832,8 @@ async fn create_cell_returns_before_natural_completion() {
|
||||
.unwrap();
|
||||
assert_eq!(created_cell_id, cell_id("1"));
|
||||
let mut observation = Box::pin(service.observe(ObserveRequest {
|
||||
idempotency_key: "blocked-notification".to_string(),
|
||||
cell_id: created_cell_id,
|
||||
generation: ObservationGeneration::INITIAL,
|
||||
yield_time_ms: 60_000,
|
||||
}));
|
||||
|
||||
@@ -839,16 +905,16 @@ async fn second_observer_is_rejected_without_displacing_the_first() {
|
||||
|
||||
let first_observer = service
|
||||
.begin_observe(ObserveRequest {
|
||||
idempotency_key: "first-observer".to_string(),
|
||||
cell_id: cell_id("1"),
|
||||
generation: ObservationGeneration::new(/*value*/ 1),
|
||||
yield_time_ms: 60_000,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
service
|
||||
.observe(ObserveRequest {
|
||||
idempotency_key: "second-observer".to_string(),
|
||||
cell_id: cell_id("1"),
|
||||
generation: ObservationGeneration::new(/*value*/ 1),
|
||||
yield_time_ms: 60_000,
|
||||
})
|
||||
.await
|
||||
@@ -892,8 +958,8 @@ async fn natural_completion_cleans_up_callbacks_before_responding() {
|
||||
assert_eq!(
|
||||
service
|
||||
.observe(ObserveRequest {
|
||||
idempotency_key: "observe-created-cell".to_string(),
|
||||
cell_id: created_cell_id,
|
||||
generation: ObservationGeneration::INITIAL,
|
||||
yield_time_ms: 60_000,
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -8,6 +8,7 @@ use super::CodeModeNestedToolCall;
|
||||
use super::CodeModeService;
|
||||
use super::CodeModeSessionDelegate;
|
||||
use super::NotificationFuture;
|
||||
use super::ObservationGeneration;
|
||||
use super::ObserveOutcome;
|
||||
use super::ObserveRequest;
|
||||
use super::ObserveToPendingOutcome;
|
||||
@@ -169,7 +170,7 @@ impl CodeModeSessionDelegate for RecordingDelegate {
|
||||
|
||||
fn execute_request(source: &str) -> CreateCellRequest {
|
||||
CreateCellRequest {
|
||||
idempotency_key: format!("call_1:{source}"),
|
||||
cell_id: cell_id("1"),
|
||||
tool_call_id: "call_1".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
source: source.to_string(),
|
||||
@@ -203,8 +204,8 @@ async fn execute_with_yield_time(
|
||||
let cell_id = service.create_cell(request).await.unwrap();
|
||||
service
|
||||
.observe(ObserveRequest {
|
||||
idempotency_key: format!("observe:{cell_id}"),
|
||||
cell_id,
|
||||
generation: ObservationGeneration::INITIAL,
|
||||
yield_time_ms,
|
||||
})
|
||||
.await
|
||||
@@ -259,7 +260,7 @@ async fn stored_values_are_shared_between_cells_but_not_sessions() {
|
||||
let write_response = execute(
|
||||
&first_session,
|
||||
CreateCellRequest {
|
||||
idempotency_key: "write-shared-value".to_string(),
|
||||
cell_id: cell_id("1"),
|
||||
source: r#"store("key", "visible");"#.to_string(),
|
||||
..execute_request("")
|
||||
},
|
||||
@@ -269,7 +270,7 @@ async fn stored_values_are_shared_between_cells_but_not_sessions() {
|
||||
let same_session = execute(
|
||||
&first_session,
|
||||
CreateCellRequest {
|
||||
idempotency_key: "read-shared-value".to_string(),
|
||||
cell_id: cell_id("2"),
|
||||
source: r#"text(String(load("key")));"#.to_string(),
|
||||
..execute_request("")
|
||||
},
|
||||
@@ -278,7 +279,7 @@ async fn stored_values_are_shared_between_cells_but_not_sessions() {
|
||||
let other_session = execute(
|
||||
&second_session,
|
||||
CreateCellRequest {
|
||||
idempotency_key: "read-other-session-value".to_string(),
|
||||
cell_id: cell_id("1"),
|
||||
source: r#"text(String(load("key")));"#.to_string(),
|
||||
..execute_request("")
|
||||
},
|
||||
@@ -1090,8 +1091,8 @@ async fn observe_reports_missing_cell_separately_from_runtime_results() {
|
||||
|
||||
let response = service
|
||||
.observe(ObserveRequest {
|
||||
idempotency_key: "observe-missing".to_string(),
|
||||
cell_id: cell_id("missing"),
|
||||
generation: ObservationGeneration::INITIAL,
|
||||
yield_time_ms: 1,
|
||||
})
|
||||
.await
|
||||
@@ -1108,7 +1109,7 @@ async fn observe_reports_missing_cell_separately_from_runtime_results() {
|
||||
#[test]
|
||||
fn protocol_requests_map_to_runtime_requests_field_for_field() {
|
||||
let request = CreateCellRequest {
|
||||
idempotency_key: "thread-3:response-call-7".to_string(),
|
||||
cell_id: cell_id("cell-a7"),
|
||||
tool_call_id: "response-call-7".to_string(),
|
||||
enabled_tools: vec![
|
||||
ToolDefinition {
|
||||
@@ -1134,7 +1135,7 @@ fn protocol_requests_map_to_runtime_requests_field_for_field() {
|
||||
assert_eq!(
|
||||
runtime_request(request),
|
||||
runtime::CreateCellRequest {
|
||||
idempotency_key: "thread-3:response-call-7".to_string(),
|
||||
cell_id: runtime::CellId::new("cell-a7"),
|
||||
tool_call_id: "response-call-7".to_string(),
|
||||
enabled_tools: vec![
|
||||
runtime::ToolDefinition {
|
||||
|
||||
@@ -5,13 +5,10 @@ use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::Value as JsonValue;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::OnceCell;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
@@ -51,9 +48,6 @@ type RuntimeEventFuture = Pin<Box<dyn Future<Output = Result<CellEvent, Error>>
|
||||
type PausableRuntimeEventFuture =
|
||||
Pin<Box<dyn Future<Output = Result<PausableCellEvent, Error>> + Send + 'static>>;
|
||||
|
||||
const CELL_ID_ALPHABET: &[u8; 32] = b"0123456789abcdefghjkmnpqrstvwxyz";
|
||||
const CELL_ID_LENGTH: usize = 16;
|
||||
|
||||
/// Owns all cells and shared state for one transport-neutral code-mode session.
|
||||
pub struct SessionRuntime<D: SessionRuntimeDelegate> {
|
||||
inner: Arc<Inner<D>>,
|
||||
@@ -62,18 +56,17 @@ pub struct SessionRuntime<D: SessionRuntimeDelegate> {
|
||||
struct Inner<D: SessionRuntimeDelegate> {
|
||||
stored_values: Mutex<HashMap<String, JsonValue>>,
|
||||
cells: Mutex<HashMap<CellId, RegisteredCell>>,
|
||||
created_cells: Mutex<HashMap<String, Arc<OnceCell<IdempotentCell>>>>,
|
||||
created_cells: Mutex<HashMap<CellId, Arc<OnceCell<IdempotentCell>>>>,
|
||||
cell_tasks: TaskTracker,
|
||||
shutdown_token: CancellationToken,
|
||||
delegate: Arc<D>,
|
||||
cell_id_namespace: CellIdNamespace,
|
||||
next_cell_id: AtomicU64,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct IdempotentCell {
|
||||
id: CellId,
|
||||
kind: CellKind,
|
||||
request: CreateCellRequest,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -97,23 +90,8 @@ impl RegisteredCell {
|
||||
}
|
||||
}
|
||||
|
||||
enum CellIdNamespace {
|
||||
Runtime(uuid::Uuid),
|
||||
#[cfg(test)]
|
||||
Unscoped,
|
||||
}
|
||||
|
||||
impl<D: SessionRuntimeDelegate> SessionRuntime<D> {
|
||||
pub fn new(delegate: Arc<D>) -> Self {
|
||||
Self::with_cell_id_namespace(delegate, CellIdNamespace::Runtime(uuid::Uuid::new_v4()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new_for_test(delegate: Arc<D>) -> Self {
|
||||
Self::with_cell_id_namespace(delegate, CellIdNamespace::Unscoped)
|
||||
}
|
||||
|
||||
fn with_cell_id_namespace(delegate: Arc<D>, cell_id_namespace: CellIdNamespace) -> Self {
|
||||
Self {
|
||||
inner: Arc::new(Inner {
|
||||
stored_values: Mutex::new(HashMap::new()),
|
||||
@@ -122,12 +100,15 @@ impl<D: SessionRuntimeDelegate> SessionRuntime<D> {
|
||||
cell_tasks: TaskTracker::new(),
|
||||
shutdown_token: CancellationToken::new(),
|
||||
delegate,
|
||||
cell_id_namespace,
|
||||
next_cell_id: AtomicU64::new(1),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new_for_test(delegate: Arc<D>) -> Self {
|
||||
Self::new(delegate)
|
||||
}
|
||||
|
||||
pub fn is_alive(&self) -> bool {
|
||||
!self.inner.shutdown_token.is_cancelled()
|
||||
}
|
||||
@@ -234,32 +215,6 @@ impl<D: SessionRuntimeDelegate> SessionRuntime<D> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn allocate_cell_id(&self) -> CellId {
|
||||
let sequence = self.inner.next_cell_id.fetch_add(1, Ordering::Relaxed);
|
||||
let value = match &self.inner.cell_id_namespace {
|
||||
CellIdNamespace::Runtime(runtime_id) => {
|
||||
let digest = Sha256::new()
|
||||
.chain_update(runtime_id.as_bytes())
|
||||
.chain_update(sequence.to_be_bytes())
|
||||
.finalize();
|
||||
let mut encoded = String::with_capacity(CELL_ID_LENGTH);
|
||||
for chunk in digest[..10].chunks_exact(5) {
|
||||
let chunk_bits = chunk
|
||||
.iter()
|
||||
.fold(0_u64, |value, byte| (value << 8) | u64::from(*byte));
|
||||
for shift in (0..40).step_by(5).rev() {
|
||||
let index = ((chunk_bits >> shift) & 0x1f) as usize;
|
||||
encoded.push(char::from(CELL_ID_ALPHABET[index]));
|
||||
}
|
||||
}
|
||||
encoded
|
||||
}
|
||||
#[cfg(test)]
|
||||
CellIdNamespace::Unscoped => sequence.to_string(),
|
||||
};
|
||||
CellId::new(value)
|
||||
}
|
||||
|
||||
async fn start_cell(
|
||||
&self,
|
||||
request: CreateCellRequest,
|
||||
@@ -269,7 +224,7 @@ impl<D: SessionRuntimeDelegate> SessionRuntime<D> {
|
||||
if self.inner.shutdown_token.is_cancelled() {
|
||||
return Err(Error::ShuttingDown);
|
||||
}
|
||||
let cell_id = self.allocate_cell_id();
|
||||
let cell_id = request.cell_id.clone();
|
||||
let stored_values = self.inner.stored_values.lock().await.clone();
|
||||
let host = Arc::new(RuntimeCellHost {
|
||||
cell_id: cell_id.clone(),
|
||||
@@ -303,7 +258,8 @@ impl<D: SessionRuntimeDelegate> SessionRuntime<D> {
|
||||
execution_policy: CellExecutionPolicy,
|
||||
kind: CellKind,
|
||||
) -> Result<CellId, Error> {
|
||||
let key = request.idempotency_key.clone();
|
||||
let key = request.cell_id.clone();
|
||||
let expected_request = request.clone();
|
||||
let created_cell = {
|
||||
let mut created_cells = self.inner.created_cells.lock().await;
|
||||
Arc::clone(
|
||||
@@ -314,8 +270,13 @@ impl<D: SessionRuntimeDelegate> SessionRuntime<D> {
|
||||
};
|
||||
let existing = created_cell
|
||||
.get_or_try_init(|| async move {
|
||||
let stored_request = request.clone();
|
||||
let id = self.start_cell(request, execution_policy, kind).await?;
|
||||
Ok::<IdempotentCell, Error>(IdempotentCell { id, kind })
|
||||
Ok::<IdempotentCell, Error>(IdempotentCell {
|
||||
id,
|
||||
kind,
|
||||
request: stored_request,
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
if existing.kind != kind {
|
||||
@@ -325,6 +286,9 @@ impl<D: SessionRuntimeDelegate> SessionRuntime<D> {
|
||||
actual: existing.kind,
|
||||
});
|
||||
}
|
||||
if existing.request != expected_request {
|
||||
return Err(Error::ConflictingCreate(existing.id.clone()));
|
||||
}
|
||||
Ok(existing.id.clone())
|
||||
}
|
||||
|
||||
|
||||
@@ -145,7 +145,7 @@ async fn default_policy_resolves_tools_before_the_first_observation() {
|
||||
let runtime = SessionRuntime::new(Arc::new(ImmediateToolDelegate { invocations_tx }));
|
||||
let cell = runtime
|
||||
.create_cell(CreateCellRequest {
|
||||
idempotency_key: "default-policy".to_string(),
|
||||
cell_id: CellId::new("default-policy"),
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: vec![tool_definition("first"), tool_definition("second")],
|
||||
source: r#"
|
||||
@@ -183,7 +183,7 @@ text("done");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_create_retries_return_the_same_cell_for_an_idempotency_key() {
|
||||
async fn concurrent_create_retries_return_the_same_caller_supplied_cell() {
|
||||
let runtime = SessionRuntime::new(Arc::new(RecordingDelegate));
|
||||
let source = "await new Promise(() => {});";
|
||||
let (first, retry) = tokio::join!(
|
||||
@@ -195,6 +195,12 @@ async fn concurrent_create_retries_return_the_same_cell_for_an_idempotency_key()
|
||||
|
||||
assert_eq!(retry, first);
|
||||
assert_eq!(runtime.inner.cells.lock().await.len(), 1);
|
||||
let mut conflicting_request = execute_request("different source");
|
||||
conflicting_request.cell_id = first.id().clone();
|
||||
assert_eq!(
|
||||
runtime.create_cell(conflicting_request).await,
|
||||
Err(Error::ConflictingCreate(first.id().clone()))
|
||||
);
|
||||
assert_eq!(
|
||||
runtime.create_pausable_cell(execute_request(source)).await,
|
||||
Err(Error::WrongCellKind {
|
||||
@@ -217,7 +223,7 @@ async fn pausable_cell_supports_a_synchronous_host_driver() {
|
||||
}));
|
||||
let cell = runtime
|
||||
.create_pausable_cell(CreateCellRequest {
|
||||
idempotency_key: "synchronous-driver".to_string(),
|
||||
cell_id: CellId::new("synchronous-driver"),
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: vec![tool_definition("first"), tool_definition("second")],
|
||||
source: r#"
|
||||
@@ -322,7 +328,7 @@ async fn pending_frontier_reports_only_authoritatively_outstanding_parallel_tool
|
||||
}));
|
||||
let cell = runtime
|
||||
.create_pausable_cell(CreateCellRequest {
|
||||
idempotency_key: "authoritative-outstanding".to_string(),
|
||||
cell_id: CellId::new("authoritative-outstanding"),
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: vec![tool_definition("first"), tool_definition("second")],
|
||||
source: r#"
|
||||
@@ -400,7 +406,7 @@ async fn pausable_cell_drains_a_parallel_host_frontier_without_duplicate_output(
|
||||
}));
|
||||
let cell = runtime
|
||||
.create_pausable_cell(CreateCellRequest {
|
||||
idempotency_key: "parallel-drain".to_string(),
|
||||
cell_id: CellId::new("parallel-drain"),
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: vec![tool_definition("first"), tool_definition("second")],
|
||||
source: r#"
|
||||
@@ -490,7 +496,7 @@ async fn cell_capabilities_reject_ids_of_the_other_kind() {
|
||||
.unwrap();
|
||||
let pausable = runtime
|
||||
.create_pausable_cell(CreateCellRequest {
|
||||
idempotency_key: "pausable-cell".to_string(),
|
||||
cell_id: CellId::new("pausable-cell"),
|
||||
..execute_request("await new Promise(() => {});")
|
||||
})
|
||||
.await
|
||||
@@ -525,7 +531,7 @@ async fn pending_observation_waits_for_resumed_work_to_reach_a_new_frontier() {
|
||||
}));
|
||||
let cell = runtime
|
||||
.create_pausable_cell(CreateCellRequest {
|
||||
idempotency_key: "pending-observation".to_string(),
|
||||
cell_id: CellId::new("pending-observation"),
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: vec![tool_definition("blocked")],
|
||||
source: r#"
|
||||
@@ -623,7 +629,7 @@ async fn termination_rejects_a_waiting_store_commit_before_the_next_cell_can_loa
|
||||
|
||||
let reader = runtime
|
||||
.create_cell(CreateCellRequest {
|
||||
idempotency_key: "reader".to_string(),
|
||||
cell_id: CellId::new("reader"),
|
||||
tool_call_id: "reader".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
source: r#"text(String(load("candidate")));"#.to_string(),
|
||||
@@ -644,7 +650,7 @@ async fn termination_rejects_a_waiting_store_commit_before_the_next_cell_can_loa
|
||||
|
||||
fn execute_request(source: &str) -> CreateCellRequest {
|
||||
CreateCellRequest {
|
||||
idempotency_key: format!("call-1:{source}"),
|
||||
cell_id: CellId::new(format!("call-1:{source}")),
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
source: source.to_string(),
|
||||
@@ -721,7 +727,7 @@ async fn termination_aborts_a_non_cooperative_tool_callback() {
|
||||
let runtime = SessionRuntime::new(Arc::new(NonCooperativeToolDelegate { invocations_tx }));
|
||||
let cell = runtime
|
||||
.create_cell(CreateCellRequest {
|
||||
idempotency_key: "non-cooperative-termination".to_string(),
|
||||
cell_id: CellId::new("non-cooperative-termination"),
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: vec![tool_definition("blocked")],
|
||||
source: "await tools.blocked({});".to_string(),
|
||||
@@ -750,7 +756,7 @@ async fn shutdown_aborts_a_non_cooperative_tool_callback() {
|
||||
let runtime = SessionRuntime::new(Arc::new(NonCooperativeToolDelegate { invocations_tx }));
|
||||
runtime
|
||||
.create_cell(CreateCellRequest {
|
||||
idempotency_key: "non-cooperative-shutdown".to_string(),
|
||||
cell_id: CellId::new("non-cooperative-shutdown"),
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: vec![tool_definition("blocked")],
|
||||
source: "await tools.blocked({});".to_string(),
|
||||
@@ -771,7 +777,7 @@ async fn shutdown_aborts_a_non_cooperative_tool_callback() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cell_ids_are_unique_across_runtime_instances() {
|
||||
async fn caller_supplied_cell_ids_are_scoped_to_the_runtime_session() {
|
||||
let first_runtime = SessionRuntime::new(Arc::new(RecordingDelegate));
|
||||
let second_runtime = SessionRuntime::new(Arc::new(RecordingDelegate));
|
||||
let first_cell_id = first_runtime
|
||||
@@ -783,16 +789,7 @@ async fn cell_ids_are_unique_across_runtime_instances() {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_ne!(first_cell_id, second_cell_id);
|
||||
for cell in [&first_cell_id, &second_cell_id] {
|
||||
assert_eq!(cell.id().as_str().len(), CELL_ID_LENGTH);
|
||||
assert!(
|
||||
cell.id()
|
||||
.as_str()
|
||||
.bytes()
|
||||
.all(|byte| CELL_ID_ALPHABET.contains(&byte))
|
||||
);
|
||||
}
|
||||
assert_eq!(first_cell_id, second_cell_id);
|
||||
|
||||
first_runtime.shutdown().await.unwrap();
|
||||
second_runtime.shutdown().await.unwrap();
|
||||
|
||||
@@ -160,17 +160,17 @@ pub enum ImageDetail {
|
||||
|
||||
/// Transport-neutral input for creating a cell.
|
||||
///
|
||||
/// The owning session assigns the cell ID when it admits the request.
|
||||
#[derive(Debug, PartialEq)]
|
||||
/// The caller assigns the cell ID before requesting admission.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CreateCellRequest {
|
||||
pub idempotency_key: String,
|
||||
pub cell_id: CellId,
|
||||
pub tool_call_id: String,
|
||||
pub enabled_tools: Vec<ToolDefinition>,
|
||||
pub source: String,
|
||||
}
|
||||
|
||||
/// Tool metadata exposed to code running inside a cell.
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ToolDefinition {
|
||||
pub name: String,
|
||||
pub tool_name: ToolName,
|
||||
@@ -234,6 +234,7 @@ pub trait SessionRuntimeDelegate: Send + Sync + 'static {
|
||||
pub enum Error {
|
||||
ShuttingDown,
|
||||
DuplicateCell(CellId),
|
||||
ConflictingCreate(CellId),
|
||||
MissingCell(CellId),
|
||||
BusyObserver(CellId),
|
||||
AlreadyTerminating(CellId),
|
||||
@@ -256,6 +257,12 @@ impl fmt::Display for Error {
|
||||
match self {
|
||||
Self::ShuttingDown => formatter.write_str("code mode session is shutting down"),
|
||||
Self::DuplicateCell(cell_id) => write!(formatter, "exec cell {cell_id} already exists"),
|
||||
Self::ConflictingCreate(cell_id) => {
|
||||
write!(
|
||||
formatter,
|
||||
"exec cell {cell_id} was created with different parameters"
|
||||
)
|
||||
}
|
||||
Self::MissingCell(cell_id) => write!(formatter, "exec cell {cell_id} not found"),
|
||||
Self::BusyObserver(cell_id) => {
|
||||
write!(
|
||||
|
||||
@@ -5,6 +5,7 @@ use codex_code_mode::CellId;
|
||||
use codex_code_mode::CodeModeService;
|
||||
use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::CreateCellRequest;
|
||||
use codex_code_mode::ObservationGeneration;
|
||||
use codex_code_mode::ObserveOutcome;
|
||||
use codex_code_mode::ObserveRequest;
|
||||
|
||||
@@ -42,9 +43,10 @@ fn terminal_notification_before_readiness_does_not_reopen_the_dispatch_gate() {
|
||||
async fn background_completion_removes_the_dispatch_gate_without_another_observation() {
|
||||
let broker = Arc::new(CodeModeDispatchBroker::new());
|
||||
let service = CodeModeService::with_delegate(broker.clone());
|
||||
let requested_cell_id = CellId::new("cell-a7".to_string());
|
||||
let cell_id = service
|
||||
.create_cell(CreateCellRequest {
|
||||
idempotency_key: "delegate-cleanup-cell".to_string(),
|
||||
cell_id: requested_cell_id,
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
source: concat!(
|
||||
@@ -60,8 +62,8 @@ async fn background_completion_removes_the_dispatch_gate_without_another_observa
|
||||
assert_eq!(
|
||||
service
|
||||
.observe(ObserveRequest {
|
||||
idempotency_key: "delegate-cleanup-observation".to_string(),
|
||||
cell_id: cell_id.clone(),
|
||||
generation: ObservationGeneration::INITIAL,
|
||||
yield_time_ms: 1,
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -40,19 +40,7 @@ impl CodeModeExecuteHandler {
|
||||
let enabled_tools =
|
||||
codex_tools::collect_code_mode_tool_definitions(&self.nested_tool_specs);
|
||||
let started_at = std::time::Instant::now();
|
||||
let idempotency_key = format!("{}:{call_id}", exec.session.thread_id());
|
||||
let cell_id = exec
|
||||
.session
|
||||
.services
|
||||
.code_mode_service
|
||||
.create_cell(codex_code_mode::CreateCellRequest {
|
||||
idempotency_key: idempotency_key.clone(),
|
||||
tool_call_id: call_id.clone(),
|
||||
enabled_tools,
|
||||
source: args.code.clone(),
|
||||
})
|
||||
.await
|
||||
.map_err(FunctionCallError::RespondToModel)?;
|
||||
let cell_id = super::cell_id_for_tool_call(&exec.session.thread_id().to_string(), &call_id);
|
||||
let runtime_cell_id = cell_id.to_string();
|
||||
let code_cell_trace = exec
|
||||
.session
|
||||
@@ -70,6 +58,21 @@ impl CodeModeExecuteHandler {
|
||||
code_cell_trace.clone(),
|
||||
)
|
||||
.map_err(FunctionCallError::RespondToModel)?;
|
||||
let cell_id = exec
|
||||
.session
|
||||
.services
|
||||
.code_mode_service
|
||||
.create_cell(codex_code_mode::CreateCellRequest {
|
||||
cell_id,
|
||||
tool_call_id: call_id.clone(),
|
||||
enabled_tools,
|
||||
source: args.code.clone(),
|
||||
})
|
||||
.await
|
||||
.map_err(|error| {
|
||||
initial_observation_guard.finish_with_error(&error);
|
||||
FunctionCallError::RespondToModel(error)
|
||||
})?;
|
||||
exec.session
|
||||
.services
|
||||
.code_mode_service
|
||||
@@ -78,13 +81,11 @@ impl CodeModeExecuteHandler {
|
||||
.session
|
||||
.services
|
||||
.code_mode_service
|
||||
.observe(codex_code_mode::ObserveRequest {
|
||||
idempotency_key,
|
||||
cell_id: cell_id.clone(),
|
||||
yield_time_ms: args
|
||||
.yield_time_ms
|
||||
.observe(
|
||||
cell_id.clone(),
|
||||
args.yield_time_ms
|
||||
.unwrap_or(codex_code_mode::DEFAULT_EXEC_YIELD_TIME_MS),
|
||||
})
|
||||
)
|
||||
.await;
|
||||
let response: codex_code_mode::RuntimeResponse = match observed {
|
||||
Ok(outcome) => outcome.into(),
|
||||
|
||||
@@ -5,13 +5,16 @@ mod response_adapter;
|
||||
mod wait_handler;
|
||||
pub(crate) mod wait_spec;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_code_mode::CellId;
|
||||
use codex_code_mode::CodeModeNestedToolCall;
|
||||
use codex_code_mode::CodeModeSession;
|
||||
use codex_code_mode::CodeModeToolKind;
|
||||
use codex_code_mode::ObservationGeneration;
|
||||
use codex_code_mode::RuntimeResponse;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use serde_json::Value as JsonValue;
|
||||
@@ -61,6 +64,7 @@ pub(crate) struct ExecContext {
|
||||
pub(crate) struct CodeModeService {
|
||||
session: Option<Arc<dyn CodeModeSession>>,
|
||||
dispatch_broker: Arc<CodeModeDispatchBroker>,
|
||||
observation_generations: Mutex<HashMap<CellId, ObservationGeneration>>,
|
||||
}
|
||||
|
||||
struct InitialObservationGuard {
|
||||
@@ -128,6 +132,7 @@ impl CodeModeService {
|
||||
dispatch_broker.clone(),
|
||||
))),
|
||||
dispatch_broker,
|
||||
observation_generations: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,14 +140,50 @@ impl CodeModeService {
|
||||
&self,
|
||||
request: codex_code_mode::CreateCellRequest,
|
||||
) -> Result<CellId, String> {
|
||||
self.session()?.create_cell(request).await
|
||||
let requested_cell_id = request.cell_id.clone();
|
||||
let admitted_cell_id = self.session()?.create_cell(request).await?;
|
||||
if admitted_cell_id != requested_cell_id {
|
||||
return Err(format!(
|
||||
"code-mode host admitted cell {admitted_cell_id} for requested cell {requested_cell_id}"
|
||||
));
|
||||
}
|
||||
self.observation_generations
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.entry(admitted_cell_id.clone())
|
||||
.or_insert(ObservationGeneration::INITIAL);
|
||||
Ok(admitted_cell_id)
|
||||
}
|
||||
|
||||
pub(crate) async fn observe(
|
||||
&self,
|
||||
request: codex_code_mode::ObserveRequest,
|
||||
cell_id: CellId,
|
||||
yield_time_ms: u64,
|
||||
) -> Result<codex_code_mode::ObserveOutcome, String> {
|
||||
self.session()?.observe(request).await
|
||||
let generation = self
|
||||
.observation_generations
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get(&cell_id)
|
||||
.copied()
|
||||
.unwrap_or(ObservationGeneration::INITIAL);
|
||||
let outcome = self
|
||||
.session()?
|
||||
.observe(codex_code_mode::ObserveRequest {
|
||||
cell_id: cell_id.clone(),
|
||||
generation,
|
||||
yield_time_ms,
|
||||
})
|
||||
.await?;
|
||||
let next_generation = generation.next().ok_or_else(|| {
|
||||
format!("observation generation exhausted for code-mode cell {cell_id}")
|
||||
})?;
|
||||
let mut generations = self
|
||||
.observation_generations
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
generations.insert(cell_id, next_generation);
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
pub(crate) async fn terminate(
|
||||
@@ -153,10 +194,15 @@ impl CodeModeService {
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) -> Result<(), String> {
|
||||
match &self.session {
|
||||
let result = match &self.session {
|
||||
Some(session) => session.shutdown().await,
|
||||
None => Ok(()),
|
||||
}
|
||||
};
|
||||
self.observation_generations
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clear();
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn mark_cell_ready_for_dispatch(&self, cell_id: &codex_code_mode::CellId) {
|
||||
@@ -198,6 +244,30 @@ impl CodeModeService {
|
||||
}
|
||||
}
|
||||
|
||||
fn cell_id_for_tool_call(thread_id: &str, call_id: &str) -> CellId {
|
||||
use sha1::Digest;
|
||||
|
||||
const CELL_ID_ALPHABET: &[u8; 32] = b"0123456789abcdefghjkmnpqrstvwxyz";
|
||||
const CELL_ID_LENGTH: usize = 16;
|
||||
|
||||
let digest = sha1::Sha1::new()
|
||||
.chain_update(thread_id.as_bytes())
|
||||
.chain_update([0])
|
||||
.chain_update(call_id.as_bytes())
|
||||
.finalize();
|
||||
let mut encoded = String::with_capacity(CELL_ID_LENGTH);
|
||||
for chunk in digest[..10].chunks_exact(5) {
|
||||
let chunk_bits = chunk
|
||||
.iter()
|
||||
.fold(0_u64, |value, byte| (value << 8) | u64::from(*byte));
|
||||
for shift in (0..40).step_by(5).rev() {
|
||||
let index = ((chunk_bits >> shift) & 0x1f) as usize;
|
||||
encoded.push(char::from(CELL_ID_ALPHABET[index]));
|
||||
}
|
||||
}
|
||||
CellId::new(encoded)
|
||||
}
|
||||
|
||||
pub(super) async fn handle_runtime_response(
|
||||
exec: &ExecContext,
|
||||
response: RuntimeResponse,
|
||||
@@ -382,6 +452,7 @@ mod tests {
|
||||
use super::CodeModeDispatchBroker;
|
||||
use super::InitialObservationGuard;
|
||||
use super::build_nested_tool_payload;
|
||||
use super::cell_id_for_tool_call;
|
||||
use super::truncate_code_mode_result;
|
||||
use crate::tools::context::ToolPayload;
|
||||
use codex_code_mode::CellId;
|
||||
@@ -494,6 +565,27 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_id_is_compact_and_stable_for_a_resumed_thread() {
|
||||
let thread_id = "019f2f5a-7b6c-7000-8000-000000000001";
|
||||
let first = cell_id_for_tool_call(thread_id, "call-42");
|
||||
let resumed = cell_id_for_tool_call(thread_id, "call-42");
|
||||
|
||||
assert_eq!(resumed, first);
|
||||
assert_eq!(first.as_str().len(), 16);
|
||||
assert!(
|
||||
first
|
||||
.as_str()
|
||||
.bytes()
|
||||
.all(|byte| b"0123456789abcdefghjkmnpqrstvwxyz".contains(&byte))
|
||||
);
|
||||
assert_ne!(cell_id_for_tool_call(thread_id, "call-43"), first);
|
||||
assert_ne!(
|
||||
cell_id_for_tool_call("019f2f5a-7b6c-7000-8000-000000000002", "call-42"),
|
||||
first
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_initial_observation_guard_terminates_the_cell() {
|
||||
let session = Arc::new(RecordingCodeModeSession {
|
||||
|
||||
@@ -66,7 +66,6 @@ impl CodeModeWaitHandler {
|
||||
let ToolInvocation {
|
||||
session,
|
||||
turn,
|
||||
call_id,
|
||||
tool_name,
|
||||
payload,
|
||||
..
|
||||
@@ -77,7 +76,6 @@ impl CodeModeWaitHandler {
|
||||
if tool_name.namespace.is_none() && tool_name.name.as_str() == WAIT_TOOL_NAME =>
|
||||
{
|
||||
let args: ExecWaitArgs = parse_arguments(&arguments)?;
|
||||
let idempotency_key = format!("{}:{call_id}", session.thread_id());
|
||||
let exec = ExecContext { session, turn };
|
||||
let started_at = std::time::Instant::now();
|
||||
let cell_id = codex_code_mode::CellId::new(args.cell_id);
|
||||
@@ -100,11 +98,7 @@ impl CodeModeWaitHandler {
|
||||
.session
|
||||
.services
|
||||
.code_mode_service
|
||||
.observe(codex_code_mode::ObserveRequest {
|
||||
idempotency_key,
|
||||
cell_id,
|
||||
yield_time_ms: args.yield_time_ms,
|
||||
})
|
||||
.observe(cell_id, args.yield_time_ms)
|
||||
.await
|
||||
.map_err(FunctionCallError::RespondToModel)?;
|
||||
let cell_was_present =
|
||||
|
||||
Reference in New Issue
Block a user