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:
Henry Levy
2026-11-19 04:48:49 +00:00
committed by copyberry
parent b5d9f7116e
commit d64451b049
18 changed files with 613 additions and 31 deletions
@@ -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,
},
+1
View File
@@ -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,
}
+25
View File
@@ -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,
}