mirror of
https://github.com/openai/codex.git
synced 2026-11-19 22:30:42 +00:00
Support tool-specific JavaScript preloads in Code Mode (#62430)
## What changed Let in-process sessions and hosts using stdio or gRPC supply trusted JavaScript helpers. Run each helper before the cell's module in the same V8 context, only when the cell exposes a unique matching binding with the expected tool name and namespace. Report ambiguous bindings and preload failures as bounded cell errors. Suppress V8 diagnostics on stdout so they cannot corrupt stdio protocol frames. ## Testing Add coverage for per-session helper selection, exact tool matching, ambiguous bindings, and bounded compile and execution errors. A stdio subprocess test checks that a failed preload leaves another session on the same connection usable. Allow more time for existing CLI and MCP integration tests to connect, start their test server, or shut down. GitOrigin-RevId: f9f037de7f9d6018ae755b38475c4131ca7ba1f0
This commit is contained in:
@@ -307,7 +307,7 @@ async fn application_network_loader_allows_listed_https_destination_to_connect()
|
||||
let client = config
|
||||
.http_client_factory()
|
||||
.build_client(&url, ClientRouteClass::Other)?;
|
||||
let (response, connection) = timeout(Duration::from_secs(2), async {
|
||||
let (response, connection) = timeout(Duration::from_secs(10), async {
|
||||
tokio::join!(client.get(&url).send(), async {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
// This listener proves TCP permission; it deliberately does not provide TLS.
|
||||
|
||||
@@ -635,8 +635,9 @@ trust_level = "trusted"
|
||||
} else {
|
||||
session.terminate();
|
||||
}
|
||||
let exit =
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), spawned.exit_rx).await??;
|
||||
let exit = tokio::time::timeout(Duration::from_secs(/*secs*/ 30), spawned.exit_rx)
|
||||
.await
|
||||
.context("timed out waiting for the worktree TUI to exit")??;
|
||||
// Include shutdown output: ConPTY can retain the channel after process exit.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(/*secs*/ 1), async {
|
||||
while let Some(bytes) = stdout.recv().await {
|
||||
|
||||
@@ -22,6 +22,7 @@ use codex_code_mode_protocol::grpc as proto;
|
||||
use codex_code_mode_protocol::grpc::code_mode_host_server::CodeModeHost;
|
||||
use codex_code_mode_protocol::host::LEGACY_MAX_PENDING_DELEGATE_CALLS;
|
||||
use codex_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use codex_code_mode_runtime::ToolPreload;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use futures::Stream;
|
||||
use futures::StreamExt;
|
||||
@@ -70,6 +71,7 @@ fn trace_context_from_request<T>(request: &Request<T>) -> Option<W3cTraceContext
|
||||
#[derive(Clone)]
|
||||
pub struct GrpcCodeModeHost {
|
||||
state: Arc<GrpcHostState>,
|
||||
pub(super) tool_preloads: &'static [ToolPreload],
|
||||
process_metrics: Option<Arc<crate::process_metrics::ProcessMetrics>>,
|
||||
}
|
||||
|
||||
@@ -78,10 +80,17 @@ impl GrpcCodeModeHost {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
state: Arc::new(GrpcHostState::new()),
|
||||
tool_preloads: &[],
|
||||
process_metrics: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the trusted helpers used when this host opens a session.
|
||||
pub fn with_tool_preloads(mut self, tool_preloads: &'static [ToolPreload]) -> Self {
|
||||
self.tool_preloads = tool_preloads;
|
||||
self
|
||||
}
|
||||
|
||||
/// Uses a collector whose resources were prepared before sandbox entry.
|
||||
pub fn with_process_metrics(collector: crate::CodeModeProcessMetricsCollector) -> Self {
|
||||
Self {
|
||||
@@ -126,6 +135,7 @@ impl GrpcCodeModeHost {
|
||||
..Default::default()
|
||||
},
|
||||
max_pending_delegate_calls,
|
||||
self.tool_preloads,
|
||||
)?;
|
||||
Ok(Response::new(with_heartbeats(
|
||||
events,
|
||||
|
||||
@@ -18,6 +18,7 @@ use codex_code_mode_protocol::WaitOutcome;
|
||||
use codex_code_mode_protocol::grpc as proto;
|
||||
use codex_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use codex_code_mode_runtime::InProcessCodeModeSession;
|
||||
use codex_code_mode_runtime::ToolPreload;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
@@ -113,6 +114,7 @@ impl GrpcHostState {
|
||||
self: &Arc<Self>,
|
||||
options: CodeModeSessionOptions,
|
||||
max_pending_delegate_calls: usize,
|
||||
tool_preloads: &'static [ToolPreload],
|
||||
) -> Result<GrpcStream<proto::SessionEvent>, Status> {
|
||||
let id = Uuid::new_v4();
|
||||
let (events, receiver) = mpsc::channel(OUTGOING_CHANNEL_CAPACITY);
|
||||
@@ -125,6 +127,7 @@ impl GrpcHostState {
|
||||
Arc::clone(&self.delegate_permits),
|
||||
options,
|
||||
max_pending_delegate_calls,
|
||||
tool_preloads,
|
||||
);
|
||||
events
|
||||
.try_send(Ok(proto::SessionEvent {
|
||||
@@ -227,6 +230,7 @@ impl GrpcSession {
|
||||
delegate_permits: Arc<Semaphore>,
|
||||
options: CodeModeSessionOptions,
|
||||
max_pending_delegate_calls: usize,
|
||||
tool_preloads: &'static [ToolPreload],
|
||||
) -> Arc<Self> {
|
||||
Arc::new_cyclic(|weak: &Weak<Self>| {
|
||||
let failure_session = weak.clone();
|
||||
@@ -238,9 +242,10 @@ impl GrpcSession {
|
||||
});
|
||||
Self {
|
||||
id,
|
||||
runtime: Arc::new(InProcessCodeModeSession::with_options(
|
||||
runtime: Arc::new(InProcessCodeModeSession::with_options_and_tool_preloads(
|
||||
options,
|
||||
Some(failure_handler),
|
||||
tool_preloads,
|
||||
)),
|
||||
closed,
|
||||
state: Mutex::new(SessionState::default()),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::collections::HashMap;
|
||||
use std::pin::Pin;
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
@@ -10,7 +11,9 @@ use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_code_mode_protocol::CodeModeSessionOptions;
|
||||
use codex_code_mode_protocol::CodeModeToolKind;
|
||||
use codex_code_mode_protocol::TerminateRequest;
|
||||
use codex_code_mode_protocol::ToolDefinition;
|
||||
use codex_code_mode_protocol::host::BOUNDED_OUTPUT_CAPABILITY;
|
||||
use codex_code_mode_protocol::host::Capability;
|
||||
use codex_code_mode_protocol::host::CapabilitySet;
|
||||
@@ -39,9 +42,13 @@ use codex_code_mode_protocol::host::WireResult;
|
||||
use codex_code_mode_protocol::host::WireRuntimeResponse;
|
||||
use codex_code_mode_protocol::host::WireWaitOutcome;
|
||||
use codex_code_mode_protocol::host::WireWaitRequest;
|
||||
use codex_code_mode_runtime::ToolPreload;
|
||||
use codex_protocol::ToolName;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
@@ -127,7 +134,7 @@ async fn handshake_and_multiple_session_lifecycles_are_ordered() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 4096);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let host = tokio::spawn(run(host_reader, host_writer, &[]));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
|
||||
@@ -202,6 +209,168 @@ async fn handshake_and_multiple_session_lifecycles_are_ordered() {
|
||||
host.await.expect("host task").expect("host connection");
|
||||
}
|
||||
|
||||
const PRELOAD_STDIO_CHILD: &str = "CODE_MODE_HOST_PRELOAD_STDIO_CHILD";
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "stdio subprocess for preload_errors_preserve_other_sessions_on_the_connection"]
|
||||
async fn preload_stdio_child() {
|
||||
if std::env::var_os(PRELOAD_STDIO_CHILD).is_none() {
|
||||
return;
|
||||
}
|
||||
super::run_stdio_with_tool_preloads(&[
|
||||
ToolPreload {
|
||||
tool: "first",
|
||||
tool_name: "first",
|
||||
tool_namespace: None,
|
||||
source: "const shared = 1;",
|
||||
},
|
||||
ToolPreload {
|
||||
tool: "second",
|
||||
tool_name: "second",
|
||||
tool_namespace: None,
|
||||
source: "const shared = 2;",
|
||||
},
|
||||
])
|
||||
.await
|
||||
.expect("stdio host");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preload_errors_preserve_other_sessions_on_the_connection() {
|
||||
let mut command =
|
||||
codex_utils_process::background_command(std::env::current_exe().expect("test executable"));
|
||||
command
|
||||
.args([
|
||||
"--quiet",
|
||||
"--exact",
|
||||
"tests::preload_stdio_child",
|
||||
"--ignored",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(PRELOAD_STDIO_CHILD, "1")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped());
|
||||
let mut child = tokio::process::Command::from(command)
|
||||
.kill_on_drop(/*kill_on_drop*/ true)
|
||||
.spawn()
|
||||
.expect("spawn stdio host");
|
||||
let mut stdout = BufReader::new(child.stdout.take().expect("host stdout"));
|
||||
// libtest emits its banner before entering the child; subsequent bytes must be frames.
|
||||
let mut banner = String::new();
|
||||
for _ in 0..2 {
|
||||
banner.clear();
|
||||
stdout.read_line(&mut banner).await.expect("libtest banner");
|
||||
if banner.trim() == "running 1 test" {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(banner.trim(), "running 1 test");
|
||||
let mut reader = FramedReader::new(stdout);
|
||||
let mut writer = FramedWriter::new(child.stdin.take().expect("host stdin"));
|
||||
writer
|
||||
.write(&client_hello([ProtocolVersion::V1], CapabilitySet::empty()))
|
||||
.await
|
||||
.expect("hello");
|
||||
assert!(matches!(
|
||||
reader.read::<HostToClient>().await.expect("host hello"),
|
||||
Some(HostToClient::HostHello(_))
|
||||
));
|
||||
for (id, name) in [(1, "broken"), (2, "healthy")] {
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id(id),
|
||||
request: HostRequest::OpenSession {
|
||||
session_id: session_id(name),
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("open session");
|
||||
assert!(matches!(
|
||||
next_response(&mut reader).await,
|
||||
HostToClient::Response {
|
||||
id: actual_id,
|
||||
result: WireResult::Ok { value: HostResponse::SessionReady { .. } },
|
||||
} if actual_id == request_id(id)
|
||||
));
|
||||
}
|
||||
let mut broken = execute_request("text('never runs')");
|
||||
broken.enabled_tools = ["first", "second"]
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
ToolDefinition {
|
||||
name: name.to_string(),
|
||||
tool_name: ToolName::plain(name),
|
||||
description: String::new(),
|
||||
kind: CodeModeToolKind::Function,
|
||||
input_schema: None,
|
||||
input_schema_max_bytes: None,
|
||||
output_schema: None,
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.collect();
|
||||
for (id, name, request, expected_content, expected_error) in [
|
||||
(
|
||||
3,
|
||||
"broken",
|
||||
broken,
|
||||
Vec::new(),
|
||||
Some("failed to execute tool preload #2 for `second`".to_string()),
|
||||
),
|
||||
(
|
||||
4,
|
||||
"healthy",
|
||||
execute_request("text('still alive')"),
|
||||
vec![WireContentItem::InputText {
|
||||
text: "still alive".to_string(),
|
||||
}],
|
||||
None,
|
||||
),
|
||||
] {
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: request_id(id),
|
||||
request: HostRequest::Execute {
|
||||
session_id: session_id(name),
|
||||
request,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("execute");
|
||||
assert!(matches!(
|
||||
next_response(&mut reader).await,
|
||||
HostToClient::Response {
|
||||
id: actual_id,
|
||||
result: WireResult::Ok { value: HostResponse::ExecutionStarted { .. } },
|
||||
} if actual_id == request_id(id)
|
||||
));
|
||||
let HostToClient::InitialResponse {
|
||||
id: actual_id,
|
||||
result:
|
||||
WireResult::Ok {
|
||||
value:
|
||||
WireRuntimeResponse::Result {
|
||||
content_items,
|
||||
error_text,
|
||||
..
|
||||
},
|
||||
},
|
||||
} = next_response(&mut reader).await
|
||||
else {
|
||||
panic!("expected framed cell result");
|
||||
};
|
||||
assert_eq!(actual_id, request_id(id));
|
||||
assert_eq!(
|
||||
(content_items, error_text),
|
||||
(expected_content, expected_error)
|
||||
);
|
||||
}
|
||||
drop(writer);
|
||||
assert!(child.wait().await.expect("host exit").success());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disconnect_cancels_a_backpressured_host_writer() {
|
||||
let (host_reader, client_writer) = tokio::io::duplex(/*max_buf_size*/ 4096);
|
||||
@@ -212,6 +381,7 @@ async fn disconnect_cancels_a_backpressured_host_writer() {
|
||||
blocked_tx: Some(blocked_tx),
|
||||
handshake_flushed: false,
|
||||
},
|
||||
&[],
|
||||
));
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
|
||||
@@ -305,7 +475,7 @@ async fn supported_capabilities_are_negotiated_when_optional_or_required() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 1024);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let host = tokio::spawn(run(host_reader, host_writer, &[]));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
|
||||
@@ -341,7 +511,7 @@ async fn output_selection_is_per_session() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 4096);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let host = tokio::spawn(run(host_reader, host_writer, &[]));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
writer
|
||||
@@ -494,7 +664,7 @@ async fn incompatible_or_invalid_handshake_is_rejected() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 1024);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let host = tokio::spawn(run(host_reader, host_writer, &[]));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
let version_two = ProtocolVersion::new(/*value*/ 2).expect("protocol version");
|
||||
@@ -517,7 +687,7 @@ async fn incompatible_or_invalid_handshake_is_rejected() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 1024);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let host = tokio::spawn(run(host_reader, host_writer, &[]));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
writer
|
||||
@@ -547,7 +717,7 @@ async fn unsupported_required_capability_is_rejected() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 1024);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let host = tokio::spawn(run(host_reader, host_writer, &[]));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
let capability = Capability::new("required").expect("capability");
|
||||
@@ -573,7 +743,7 @@ async fn session_id_cannot_be_reused_after_shutdown() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 2048);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(host_reader, host_writer));
|
||||
let host = tokio::spawn(run(host_reader, host_writer, &[]));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
writer
|
||||
@@ -669,6 +839,7 @@ async fn request_task_panic_disconnects_host() {
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
let state = HostState {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
tool_preloads: &[],
|
||||
limits: Arc::new(HostLimits::new()),
|
||||
seen_session_ids: Mutex::new(SeenSessionIds::default()),
|
||||
requests: Mutex::new(RequestRegistry::default()),
|
||||
@@ -697,6 +868,7 @@ async fn execute_request_id_remains_active_until_initial_response() {
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
let state = Arc::new(HostState {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
tool_preloads: &[],
|
||||
limits: Arc::new(HostLimits::new()),
|
||||
seen_session_ids: Mutex::new(SeenSessionIds::default()),
|
||||
requests: Mutex::new(RequestRegistry::default()),
|
||||
@@ -758,6 +930,7 @@ async fn active_cell_limit_rejects_execute_without_disconnecting() {
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, MAX_PENDING_DELEGATE_CALLS));
|
||||
let state = HostState {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
tool_preloads: &[],
|
||||
limits: Arc::new(HostLimits {
|
||||
request_permits: Arc::new(Semaphore::new(MAX_IN_FLIGHT_REQUESTS)),
|
||||
active_cell_permits: Arc::new(Semaphore::new(/*permits*/ 0)),
|
||||
|
||||
@@ -40,6 +40,7 @@ use codex_code_mode_protocol::host::TOOL_CATALOG_CAPABILITY;
|
||||
use codex_code_mode_protocol::host::WireWaitOutcome;
|
||||
use codex_code_mode_protocol::host::YIELD_OBSERVATION_CAPABILITY;
|
||||
use codex_code_mode_runtime::InProcessCodeModeSession;
|
||||
use codex_code_mode_runtime::ToolPreload;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
@@ -104,14 +105,26 @@ impl HostLimits {
|
||||
}
|
||||
|
||||
/// Runs the code-mode host on its configured stdio or gRPC transport.
|
||||
pub async fn run_main(listen_url: &str) -> Result<()> {
|
||||
run_main_with_tool_preloads(listen_url, &[]).await
|
||||
}
|
||||
|
||||
/// Opens each session on the configured transport with the supplied tool helpers.
|
||||
#[tracing::instrument(
|
||||
name = "code_mode_host.run_main",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(otel.name = "code_mode_host.run_main")
|
||||
)]
|
||||
pub async fn run_main(listen_url: &str) -> Result<()> {
|
||||
transport::run_transport(listen_url, GrpcCodeModeHost::new()).await
|
||||
pub async fn run_main_with_tool_preloads(
|
||||
listen_url: &str,
|
||||
tool_preloads: &'static [ToolPreload],
|
||||
) -> Result<()> {
|
||||
transport::run_transport(
|
||||
listen_url,
|
||||
GrpcCodeModeHost::new().with_tool_preloads(tool_preloads),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Runs with an optional gRPC metrics collector initialized before sandbox entry.
|
||||
@@ -129,11 +142,15 @@ pub async fn run_main_with_process_metrics(
|
||||
|
||||
/// Runs one code-mode host connection over the process standard streams.
|
||||
pub async fn run_stdio() -> Result<()> {
|
||||
run(tokio::io::stdin(), tokio::io::stdout()).await
|
||||
run_stdio_with_tool_preloads(&[]).await
|
||||
}
|
||||
|
||||
async fn run_stdio_with_tool_preloads(tool_preloads: &'static [ToolPreload]) -> Result<()> {
|
||||
run(tokio::io::stdin(), tokio::io::stdout(), tool_preloads).await
|
||||
}
|
||||
|
||||
/// Runs one code-mode host connection over an ordered input/output pair.
|
||||
async fn run<R, W>(reader: R, writer: W) -> Result<()>
|
||||
async fn run<R, W>(reader: R, writer: W, tool_preloads: &'static [ToolPreload]) -> Result<()>
|
||||
where
|
||||
R: AsyncRead + Send + Unpin + 'static,
|
||||
W: AsyncWrite + Send + Unpin + 'static,
|
||||
@@ -150,6 +167,7 @@ where
|
||||
let peer = Arc::new(HostPeer::new(outgoing_tx, max_pending_delegate_calls));
|
||||
let state = Arc::new(HostState {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
tool_preloads,
|
||||
limits: Arc::new(HostLimits::new()),
|
||||
seen_session_ids: Mutex::new(SeenSessionIds::default()),
|
||||
requests: Mutex::new(RequestRegistry::default()),
|
||||
@@ -340,6 +358,7 @@ async fn negotiate<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
|
||||
struct HostState {
|
||||
sessions: Mutex<HashMap<SessionId, Arc<InProcessCodeModeSession>>>,
|
||||
tool_preloads: &'static [ToolPreload],
|
||||
limits: Arc<HostLimits>,
|
||||
seen_session_ids: Mutex<SeenSessionIds>,
|
||||
requests: Mutex<RequestRegistry>,
|
||||
@@ -609,9 +628,10 @@ impl HostState {
|
||||
});
|
||||
sessions.insert(
|
||||
session_id,
|
||||
Arc::new(InProcessCodeModeSession::with_options(
|
||||
Arc::new(InProcessCodeModeSession::with_options_and_tool_preloads(
|
||||
options,
|
||||
Some(task_failure_handler),
|
||||
self.tool_preloads,
|
||||
)),
|
||||
);
|
||||
Ok(())
|
||||
|
||||
@@ -17,7 +17,7 @@ enum ListenTransport {
|
||||
|
||||
pub(crate) async fn run_transport(listen_url: &str, host: crate::GrpcCodeModeHost) -> Result<()> {
|
||||
match parse_listen_url(listen_url)? {
|
||||
ListenTransport::Stdio => crate::run_stdio().await,
|
||||
ListenTransport::Stdio => crate::run_stdio_with_tool_preloads(host.tool_preloads).await,
|
||||
ListenTransport::GrpcStdio => crate::grpc_stdio::run(host).await,
|
||||
ListenTransport::Grpc(bind_address) => {
|
||||
grpc_transport::run_tcp_listener(bind_address, host).await
|
||||
|
||||
@@ -135,6 +135,7 @@ fn spawn_cell_actor_harness_with_host_and_failure_handler<H: CellHost>(
|
||||
CellRequest {
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: Default::default(),
|
||||
tool_preloads: &[],
|
||||
source: "await new Promise(() => {});".to_string(),
|
||||
output_truncation: CodeModeOutputTruncation::Client,
|
||||
},
|
||||
|
||||
@@ -10,6 +10,7 @@ pub(crate) type TaskFailureHandler = std::sync::Arc<dyn Fn(String) + Send + Sync
|
||||
|
||||
pub use codex_code_mode_protocol::*;
|
||||
pub use service::InProcessCodeModeSession;
|
||||
pub use service::ToolPreload;
|
||||
pub use ui::run as run_ui_sandbox;
|
||||
pub use v8_init::V8JitMode;
|
||||
pub use v8_init::initialize_v8;
|
||||
|
||||
@@ -106,7 +106,7 @@ clearTimeout(earlyTimer); setTimeout(() => {}, 60000);
|
||||
let (event_tx, mut event_rx) = mpsc::unbounded_channel();
|
||||
let (runtime_command_tx, _runtime_command_rx) = std_mpsc::channel();
|
||||
let tool_name = ToolName::plain("echo");
|
||||
globals::install_globals(scope).expect("install globals");
|
||||
globals::install_globals(scope, &[]).expect("install globals");
|
||||
scope.set_slot(RuntimeState {
|
||||
event_tx: event_tx.into(),
|
||||
pending_tool_calls: HashMap::new(),
|
||||
|
||||
@@ -13,9 +13,15 @@ use super::callbacks::store_callback;
|
||||
use super::callbacks::text_callback;
|
||||
use super::callbacks::tool_callback;
|
||||
use super::callbacks::yield_control_callback;
|
||||
use crate::ToolPreload;
|
||||
use codex_code_mode_protocol::EnabledToolMetadata;
|
||||
|
||||
pub(super) fn install_globals(scope: &mut v8::PinScope<'_, '_>) -> Result<(), String> {
|
||||
const MAX_PRELOAD_BINDING_CHARS: usize = 96;
|
||||
|
||||
pub(super) fn install_globals(
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
tool_preloads: &[ToolPreload],
|
||||
) -> Result<(), String> {
|
||||
let global = scope.get_current_context().global(scope);
|
||||
delete_global(scope, global, "console")?;
|
||||
delete_global(scope, global, "Atomics")?;
|
||||
@@ -56,11 +62,52 @@ pub(super) fn install_globals(scope: &mut v8::PinScope<'_, '_>) -> Result<(), St
|
||||
set_global(scope, global, "exit", exit.into())?;
|
||||
|
||||
let helpers = concat!(include_str!("settled.js"), "\n", include_str!("content.js"));
|
||||
let source = v8::String::new(scope, helpers)
|
||||
.ok_or_else(|| "failed to allocate JavaScript helpers".to_string())?;
|
||||
v8::Script::compile(scope, source, /*origin*/ None)
|
||||
.and_then(|script| script.run(scope))
|
||||
.ok_or_else(|| "failed to initialize JavaScript helpers".to_string())?;
|
||||
run_helpers(scope, helpers, "built-in JavaScript helpers")?;
|
||||
for (index, preload) in tool_preloads.iter().enumerate() {
|
||||
let binding: String = preload
|
||||
.tool
|
||||
.chars()
|
||||
.take(MAX_PRELOAD_BINDING_CHARS)
|
||||
.collect();
|
||||
let label = format!("tool preload #{} for `{binding}`", index + 1);
|
||||
let enabled = {
|
||||
let state = scope
|
||||
.get_slot::<super::RuntimeState>()
|
||||
.ok_or_else(|| "code-mode catalog is unavailable".to_string())?;
|
||||
let mut matches = state
|
||||
.enabled_tools
|
||||
.iter()
|
||||
.filter(|tool| tool.global_name == preload.tool);
|
||||
let candidate = matches.next();
|
||||
if matches.next().is_some() {
|
||||
return Err(format!("ambiguous binding: {label}"));
|
||||
}
|
||||
candidate.is_some_and(|tool| {
|
||||
tool.tool_name.name == preload.tool_name
|
||||
&& tool.tool_name.namespace.as_deref() == preload.tool_namespace
|
||||
})
|
||||
};
|
||||
if enabled {
|
||||
run_helpers(scope, preload.source, &label)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_helpers(scope: &mut v8::PinScope<'_, '_>, helpers: &str, label: &str) -> Result<(), String> {
|
||||
// Uncaught V8 diagnostics go to stdout, which may carry the host protocol.
|
||||
// Keep the reported error bounded and avoid invoking a thrown value's getters.
|
||||
let tc = std::pin::pin!(v8::TryCatch::new(scope));
|
||||
let mut tc = tc.init();
|
||||
tc.set_verbose(/*value*/ false);
|
||||
tc.set_capture_message(/*value*/ false);
|
||||
let source =
|
||||
v8::String::new(&tc, helpers).ok_or_else(|| format!("failed to allocate {label}"))?;
|
||||
let script = v8::Script::compile(&tc, source, /*origin*/ None)
|
||||
.ok_or_else(|| format!("failed to compile {label}"))?;
|
||||
script
|
||||
.run(&tc)
|
||||
.ok_or_else(|| format!("failed to execute {label}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ use std::sync::mpsc as std_mpsc;
|
||||
use std::thread;
|
||||
|
||||
use crate::TaskFailureHandler;
|
||||
use crate::ToolPreload;
|
||||
use crate::session_runtime::CreateCellRequest;
|
||||
use crate::session_runtime::OutputItem;
|
||||
use crate::session_runtime::ToolCatalog;
|
||||
@@ -95,6 +96,7 @@ pub(crate) fn spawn_runtime(
|
||||
let config = RuntimeConfig {
|
||||
tool_call_id: request.tool_call_id,
|
||||
enabled_tools: request.enabled_tools,
|
||||
tool_preloads: request.tool_preloads,
|
||||
source: request.source,
|
||||
stored_values,
|
||||
};
|
||||
@@ -139,6 +141,7 @@ fn spawn_supervised_runtime_thread(
|
||||
struct RuntimeConfig {
|
||||
tool_call_id: String,
|
||||
enabled_tools: ToolCatalog,
|
||||
tool_preloads: &'static [ToolPreload],
|
||||
source: String,
|
||||
stored_values: HashMap<String, Arc<JsonValue>>,
|
||||
}
|
||||
@@ -182,11 +185,6 @@ fn run_runtime(
|
||||
let context = v8::Context::new(scope, Default::default());
|
||||
let scope = &mut v8::ContextScope::new(scope, context);
|
||||
|
||||
if let Err(error_text) = globals::install_globals(scope) {
|
||||
send_result(&event_tx, HashMap::new(), Some(error_text));
|
||||
return;
|
||||
}
|
||||
|
||||
scope.set_slot(RuntimeState {
|
||||
event_tx: event_tx.clone(),
|
||||
pending_tool_calls: HashMap::new(),
|
||||
@@ -201,6 +199,11 @@ fn run_runtime(
|
||||
exit_requested: false,
|
||||
});
|
||||
|
||||
if let Err(error_text) = globals::install_globals(scope, config.tool_preloads) {
|
||||
send_result(&event_tx, HashMap::new(), Some(error_text));
|
||||
return;
|
||||
}
|
||||
|
||||
let _ = event_tx.blocking_send(RuntimeEvent::Started);
|
||||
|
||||
let pending_promise = match module_loader::evaluate_main_module(scope, &config.source) {
|
||||
@@ -341,6 +344,7 @@ mod tests {
|
||||
CreateCellRequest {
|
||||
tool_call_id: "call_1".to_string(),
|
||||
enabled_tools: Default::default(),
|
||||
tool_preloads: &[],
|
||||
source: source.to_string(),
|
||||
output_truncation: codex_code_mode_protocol::CodeModeOutputTruncation::Client,
|
||||
}
|
||||
|
||||
@@ -38,10 +38,24 @@ use crate::session_runtime::SessionRuntime;
|
||||
const YIELD_GRACE_PERIOD: Duration = Duration::from_secs(1);
|
||||
const MIN_YIELD_TIME_FOR_GRACE: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Trusted JavaScript a session installs in cells that expose the named nested tool.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct ToolPreload {
|
||||
/// The tool's binding on the Code Mode `tools` object.
|
||||
pub tool: &'static str,
|
||||
/// The exact name dispatched by that binding.
|
||||
pub tool_name: &'static str,
|
||||
/// The exact namespace dispatched by that binding, if any.
|
||||
pub tool_namespace: Option<&'static str>,
|
||||
/// A script evaluated before the cell's module, in the same V8 context.
|
||||
pub source: &'static str,
|
||||
}
|
||||
|
||||
pub struct InProcessCodeModeSession {
|
||||
runtime: SessionRuntime,
|
||||
catalog: Mutex<(u64, runtime::ToolCatalog)>,
|
||||
options: CodeModeSessionOptions,
|
||||
tool_preloads: &'static [ToolPreload],
|
||||
}
|
||||
|
||||
impl InProcessCodeModeSession {
|
||||
@@ -64,10 +78,20 @@ impl InProcessCodeModeSession {
|
||||
pub fn with_options(
|
||||
options: CodeModeSessionOptions,
|
||||
task_failure_handler: Option<TaskFailureHandler>,
|
||||
) -> Self {
|
||||
Self::with_options_and_tool_preloads(options, task_failure_handler, &[])
|
||||
}
|
||||
|
||||
/// Creates a session with trusted host helpers selected against each cell's tool catalog.
|
||||
pub fn with_options_and_tool_preloads(
|
||||
options: CodeModeSessionOptions,
|
||||
task_failure_handler: Option<TaskFailureHandler>,
|
||||
tool_preloads: &'static [ToolPreload],
|
||||
) -> Self {
|
||||
Self {
|
||||
runtime: SessionRuntime::new_with_task_failure_handler(task_failure_handler),
|
||||
catalog: Default::default(),
|
||||
tool_preloads,
|
||||
options: CodeModeSessionOptions {
|
||||
cell_execution_limits: CodeModeSessionCellExecutionLimits {
|
||||
max_heap_size_bytes: None,
|
||||
@@ -119,6 +143,7 @@ impl InProcessCodeModeSession {
|
||||
output_truncation: self.options.output_truncation,
|
||||
tool_call_id: request.tool_call_id,
|
||||
enabled_tools: tools,
|
||||
tool_preloads: self.tool_preloads,
|
||||
source: request.source,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -146,6 +146,7 @@ async fn termination_rejects_a_waiting_store_commit_before_the_next_cell_can_loa
|
||||
output_truncation: CodeModeOutputTruncation::Client,
|
||||
tool_call_id: "reader".to_string(),
|
||||
enabled_tools: Default::default(),
|
||||
tool_preloads: &[],
|
||||
source: r#"text(String(load("candidate")));"#.to_string(),
|
||||
},
|
||||
ObserveMode::YieldAfter(Duration::from_secs(1)),
|
||||
@@ -171,6 +172,7 @@ fn execute_request(source: &str) -> CreateCellRequest {
|
||||
output_truncation: CodeModeOutputTruncation::Client,
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: Default::default(),
|
||||
tool_preloads: &[],
|
||||
source: source.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,6 +90,7 @@ pub(crate) struct CreateCellRequest {
|
||||
pub(crate) output_truncation: codex_code_mode_protocol::CodeModeOutputTruncation,
|
||||
pub(crate) tool_call_id: String,
|
||||
pub(crate) enabled_tools: ToolCatalog,
|
||||
pub(crate) tool_preloads: &'static [crate::ToolPreload],
|
||||
pub(crate) source: String,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
//! Each session selects its helpers independently and exposes them only with their tools.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_code_mode_runtime::CellId;
|
||||
use codex_code_mode_runtime::CodeModeNestedToolCall;
|
||||
use codex_code_mode_runtime::CodeModeSessionDelegate;
|
||||
use codex_code_mode_runtime::CodeModeToolKind;
|
||||
use codex_code_mode_runtime::ExecuteRequest;
|
||||
use codex_code_mode_runtime::FunctionCallOutputContentItem;
|
||||
use codex_code_mode_runtime::InProcessCodeModeSession;
|
||||
use codex_code_mode_runtime::NoopCodeModeSessionDelegate;
|
||||
use codex_code_mode_runtime::NotificationFuture;
|
||||
use codex_code_mode_runtime::RuntimeResponse;
|
||||
use codex_code_mode_runtime::ToolDefinition;
|
||||
use codex_code_mode_runtime::ToolInvocationFuture;
|
||||
use codex_code_mode_runtime::ToolPreload;
|
||||
use codex_protocol::ToolName;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
const SEND_BINDING: &str = "mcp__codex_apps__user_message_send_message";
|
||||
const SEND_NAMESPACE: &str = "mcp__codex_apps";
|
||||
|
||||
#[derive(Default)]
|
||||
struct RecordingDelegate(Mutex<Vec<ToolName>>);
|
||||
|
||||
impl CodeModeSessionDelegate for RecordingDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
invocation: CodeModeNestedToolCall,
|
||||
_cancellation_token: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.push(invocation.tool_name);
|
||||
Box::pin(async { Ok(json!({"ok": true})) })
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
_call_id: String,
|
||||
_cell_id: CellId,
|
||||
_text: String,
|
||||
_cancellation_token: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
|
||||
fn cell_closed(&self, _cell_id: &CellId) {}
|
||||
}
|
||||
|
||||
fn definition(binding: &str, tool_name: ToolName) -> ToolDefinition {
|
||||
ToolDefinition {
|
||||
name: binding.to_string(),
|
||||
tool_name,
|
||||
description: String::new(),
|
||||
kind: CodeModeToolKind::Function,
|
||||
input_schema: None,
|
||||
input_schema_max_bytes: None,
|
||||
output_schema: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute(
|
||||
session: &InProcessCodeModeSession,
|
||||
tools: Vec<ToolDefinition>,
|
||||
source: &str,
|
||||
delegate: Arc<dyn CodeModeSessionDelegate>,
|
||||
) -> Result<(CellId, RuntimeResponse), String> {
|
||||
let started = session
|
||||
.execute(
|
||||
ExecuteRequest {
|
||||
tool_call_id: "test".to_string(),
|
||||
enabled_tools: tools,
|
||||
source: source.to_string(),
|
||||
yield_time_ms: None,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
delegate,
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await?;
|
||||
let cell_id = started.cell_id.clone();
|
||||
Ok((cell_id, started.initial_response().await?))
|
||||
}
|
||||
|
||||
fn result(cell_id: CellId, outcome: Result<&str, &str>) -> RuntimeResponse {
|
||||
let (content_items, error_text) = match outcome {
|
||||
Ok(text) => (
|
||||
vec![FunctionCallOutputContentItem::InputText {
|
||||
text: text.to_string(),
|
||||
}],
|
||||
None,
|
||||
),
|
||||
Err(error) => (Vec::new(), Some(error.to_string())),
|
||||
};
|
||||
RuntimeResponse::Result {
|
||||
cell_id,
|
||||
content_items,
|
||||
error_text,
|
||||
result_buffered_for: Duration::ZERO,
|
||||
code_mode_host_duration: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preloads_follow_the_session_and_the_current_cells_tool_binding() {
|
||||
let plain = InProcessCodeModeSession::new();
|
||||
let lookup = InProcessCodeModeSession::with_options_and_tool_preloads(
|
||||
Default::default(),
|
||||
/*task_failure_handler*/ None,
|
||||
&[ToolPreload {
|
||||
tool: "lookup",
|
||||
tool_name: "lookup",
|
||||
tool_namespace: None,
|
||||
source: "globalThis.findItem = tools.lookup;",
|
||||
}],
|
||||
);
|
||||
let alternate = InProcessCodeModeSession::with_options_and_tool_preloads(
|
||||
Default::default(),
|
||||
/*task_failure_handler*/ None,
|
||||
&[ToolPreload {
|
||||
tool: "lookup",
|
||||
tool_name: "lookup",
|
||||
tool_namespace: None,
|
||||
source: "globalThis.findItem = () => 'alternate';",
|
||||
}],
|
||||
);
|
||||
for (session, name, expected) in [
|
||||
(&lookup, "lookup", "true"),
|
||||
(&plain, "lookup", "undefined"),
|
||||
(&alternate, "lookup", "false"),
|
||||
(&lookup, "lookup_other", "undefined"),
|
||||
(&lookup, "lookup", "true"),
|
||||
] {
|
||||
let started = session
|
||||
.execute(
|
||||
ExecuteRequest {
|
||||
tool_call_id: name.to_string(),
|
||||
enabled_tools: vec![ToolDefinition {
|
||||
name: name.to_string(),
|
||||
tool_name: ToolName::plain(name),
|
||||
description: String::new(),
|
||||
kind: CodeModeToolKind::Function,
|
||||
input_schema: None,
|
||||
input_schema_max_bytes: None,
|
||||
output_schema: None,
|
||||
}],
|
||||
source: "text(typeof findItem === 'function' ? findItem === tools.lookup : typeof findItem);".to_string(),
|
||||
yield_time_ms: None,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let cell_id = started.cell_id.clone();
|
||||
assert_eq!(
|
||||
started.initial_response().await.unwrap(),
|
||||
RuntimeResponse::Result {
|
||||
cell_id,
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: expected.to_string(),
|
||||
}],
|
||||
error_text: None,
|
||||
result_buffered_for: std::time::Duration::ZERO,
|
||||
code_mode_host_duration: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preload_requires_one_binding_with_the_exact_dispatch_identity() {
|
||||
let session = InProcessCodeModeSession::with_options_and_tool_preloads(
|
||||
Default::default(),
|
||||
/*task_failure_handler*/ None,
|
||||
&[ToolPreload {
|
||||
tool: SEND_BINDING,
|
||||
tool_name: SEND_BINDING,
|
||||
tool_namespace: None,
|
||||
source: "globalThis.sendMsgToUser = message => tools.mcp__codex_apps__user_message_send_message({text: message});",
|
||||
}],
|
||||
);
|
||||
let expected_name = ToolName::plain(SEND_BINDING);
|
||||
let canonical = definition(SEND_BINDING, expected_name.clone());
|
||||
let alias = definition(
|
||||
"mcp__codex_apps__user_message_send-message",
|
||||
ToolName::plain("mcp__codex_apps__user_message_send-message"),
|
||||
);
|
||||
let reassigned = definition(SEND_BINDING, ToolName::plain("unrelated"));
|
||||
let wrong_namespace = definition(
|
||||
SEND_BINDING,
|
||||
ToolName::namespaced("unrelated", SEND_BINDING),
|
||||
);
|
||||
let split_identity = definition(
|
||||
SEND_BINDING,
|
||||
ToolName::namespaced(SEND_NAMESPACE, "user_message_send_message"),
|
||||
);
|
||||
let delegate = Arc::new(RecordingDelegate::default());
|
||||
let source = "if (typeof sendMsgToUser === 'function') await sendMsgToUser('private'); text(typeof sendMsgToUser);";
|
||||
let ambiguous =
|
||||
"ambiguous binding: tool preload #1 for `mcp__codex_apps__user_message_send_message`";
|
||||
for (tools, expected) in [
|
||||
(vec![alias.clone()], Ok("undefined")),
|
||||
(vec![canonical.clone(), alias.clone()], Err(ambiguous)),
|
||||
(vec![alias, canonical.clone()], Err(ambiguous)),
|
||||
(vec![reassigned], Ok("undefined")),
|
||||
(vec![wrong_namespace], Ok("undefined")),
|
||||
(vec![split_identity.clone()], Ok("undefined")),
|
||||
] {
|
||||
let (cell_id, response) = execute(&session, tools, source, delegate.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response, result(cell_id, expected));
|
||||
assert_eq!(*delegate.0.lock().unwrap(), Vec::<ToolName>::new());
|
||||
}
|
||||
|
||||
let (cell_id, response) = execute(&session, vec![canonical], source, delegate.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response, result(cell_id, Ok("function")));
|
||||
assert_eq!(*delegate.0.lock().unwrap(), vec![expected_name]);
|
||||
|
||||
let namespaced = InProcessCodeModeSession::with_options_and_tool_preloads(
|
||||
Default::default(),
|
||||
/*task_failure_handler*/ None,
|
||||
&[ToolPreload {
|
||||
tool: SEND_BINDING,
|
||||
tool_name: "user_message_send_message",
|
||||
tool_namespace: Some(SEND_NAMESPACE),
|
||||
source: "globalThis.sendMsgToUser = message => tools.mcp__codex_apps__user_message_send_message({text: message});",
|
||||
}],
|
||||
);
|
||||
let (cell_id, response) = execute(&namespaced, vec![split_identity], source, delegate.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response, result(cell_id, Ok("function")));
|
||||
assert_eq!(
|
||||
*delegate.0.lock().unwrap(),
|
||||
vec![
|
||||
ToolName::plain(SEND_BINDING),
|
||||
ToolName::namespaced(SEND_NAMESPACE, "user_message_send_message")
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preload_compile_and_execution_failures_are_bounded_cell_errors() {
|
||||
for (preloads, expected) in [
|
||||
(
|
||||
&[ToolPreload {
|
||||
tool: "lookup",
|
||||
tool_name: "lookup",
|
||||
tool_namespace: None,
|
||||
source: "const =",
|
||||
}][..],
|
||||
"failed to compile tool preload #1 for `lookup`",
|
||||
),
|
||||
(
|
||||
&[ToolPreload {
|
||||
tool: "lookup",
|
||||
tool_name: "lookup",
|
||||
tool_namespace: None,
|
||||
source: "throw 'x'.repeat(1_000_000)",
|
||||
}][..],
|
||||
"failed to execute tool preload #1 for `lookup`",
|
||||
),
|
||||
] {
|
||||
let session = InProcessCodeModeSession::with_options_and_tool_preloads(
|
||||
Default::default(),
|
||||
/*task_failure_handler*/ None,
|
||||
preloads,
|
||||
);
|
||||
let (cell_id, response) = execute(
|
||||
&session,
|
||||
vec![definition("lookup", ToolName::plain("lookup"))],
|
||||
"text('never runs')",
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response, result(cell_id, Err(expected)));
|
||||
}
|
||||
}
|
||||
@@ -104,7 +104,7 @@ async fn stalled_handshake_unblocks_remote_executor(
|
||||
params,
|
||||
// Allow the request to reach the remote HTTP server on loaded CI
|
||||
// workers before testing cancellation of its stalled response.
|
||||
Some(Duration::from_secs(5)),
|
||||
Some(Duration::from_secs(15)),
|
||||
Box::new(|_, _| {
|
||||
async {
|
||||
Ok(ElicitationResponse {
|
||||
|
||||
@@ -324,7 +324,7 @@ pub(crate) async fn spawn_streamable_http_server() -> anyhow::Result<(Child, Str
|
||||
let address = wait_for_streamable_http_server(
|
||||
&mut child,
|
||||
&bound_addr_path,
|
||||
Duration::from_secs(/*secs*/ 5),
|
||||
Duration::from_secs(/*secs*/ 20),
|
||||
)
|
||||
.await?;
|
||||
Ok((child, format!("http://{address}")))
|
||||
|
||||
Reference in New Issue
Block a user