Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,63 @@
//! Measures tool-generated PCM WAV clips using the audio bytes actually present.
//! Unknown formats retain the existing audio output behavior.
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use akode_protocol::models::MAX_PROMPT_AUDIO_INPUT_BYTES;
pub(super) fn wav_duration_seconds(audio_url: &str) -> Option<f64> {
let (metadata, payload) = audio_url.split_once(',')?;
if !metadata
.split(';')
.skip(1)
.any(|part| part.eq_ignore_ascii_case("base64"))
|| payload.len() > MAX_PROMPT_AUDIO_INPUT_BYTES.div_ceil(3) * 4
{
return None;
}
let bytes = BASE64_STANDARD.decode(payload).ok()?;
if bytes.get(..4)? != b"RIFF" || bytes.get(8..12)? != b"WAVE" {
return None;
}
let mut chunks = bytes.get(12..)?;
let mut format = None;
while chunks.len() >= 8 {
let chunk_id = &chunks[..4];
let size = u32::from_le_bytes(chunks[4..8].try_into().ok()?) as usize;
let remaining = &chunks[8..];
// Streaming WAV headers can declare more data than the file contains.
let chunk = &remaining[..size.min(remaining.len())];
match chunk_id {
b"fmt " => {
let mut encoding = u16::from_le_bytes(chunk.get(..2)?.try_into().ok()?);
if encoding == 0xfffe {
// WAVE_FORMAT_EXTENSIBLE stores the encoding in a subtype GUID.
if chunk.get(26..40)?
!= [0, 0, 0, 0, 0x10, 0, 0x80, 0, 0, 0xaa, 0, 0x38, 0x9b, 0x71]
{
return None;
}
encoding = u16::from_le_bytes(chunk.get(24..26)?.try_into().ok()?);
}
if !matches!(encoding, 1 | 3) {
return None;
}
let sample_rate = u32::from_le_bytes(chunk.get(4..8)?.try_into().ok()?);
let block_align = u16::from_le_bytes(chunk.get(12..14)?.try_into().ok()?);
if sample_rate == 0 || block_align == 0 {
return None;
}
format = Some((sample_rate, block_align));
}
b"data" => {
let (sample_rate, block_align) = format?;
let frames = chunk.len() / usize::from(block_align);
return Some(frames as f64 / f64::from(sample_rate));
}
_ => {}
}
chunks = remaining.get(size.checked_add(size % 2)?..)?;
}
None
}

View File

@@ -0,0 +1,375 @@
use crate::session_runtime::OutputItem;
use std::sync::Arc;
use super::RuntimeEvent;
use super::RuntimeState;
use super::timers;
use super::value::json_to_v8;
use super::value::normalize_output_audio;
use super::value::normalize_output_image;
use super::value::serialize_output_text;
use super::value::throw_type_error;
use super::value::v8_value_to_json;
pub(super) fn tool_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let tool_index = match args.data().to_rust_string_lossy(scope).parse::<usize>() {
Ok(tool_index) => tool_index,
Err(_) => {
throw_type_error(scope, "invalid tool callback data");
return;
}
};
let input = if args.length() == 0 {
Ok(None)
} else {
v8_value_to_json(scope, args.get(0))
};
let input = match input {
Ok(input) => input,
Err(error_text) => {
throw_type_error(scope, &error_text);
return;
}
};
let (tool_name, tool_kind) = {
let Some(state) = scope.get_slot::<RuntimeState>() else {
throw_type_error(scope, "runtime state unavailable");
return;
};
// Input serialization can call exit() from a getter or toJSON.
if state.exit_requested {
return;
}
let Some(tool) = state.enabled_tools.get(tool_index) else {
throw_type_error(scope, "tool callback data is out of range");
return;
};
(tool.tool_name.clone(), tool.kind)
};
let Some(resolver) = v8::PromiseResolver::new(scope) else {
throw_type_error(scope, "failed to create tool promise");
return;
};
let promise = resolver.get_promise(scope);
let resolver = v8::Global::new(scope, resolver);
let Some(state) = scope.get_slot_mut::<RuntimeState>() else {
throw_type_error(scope, "runtime state unavailable");
return;
};
let id = format!("tool-{}", state.next_tool_call_id);
state.next_tool_call_id = state.next_tool_call_id.saturating_add(1);
let event_tx = state.event_tx.clone();
state.pending_tool_calls.insert(id.clone(), resolver);
let _ = event_tx.blocking_send(RuntimeEvent::ToolCall {
id,
name: tool_name,
kind: tool_kind,
input,
});
retval.set(promise.into());
}
pub(super) fn text_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let value = if args.length() == 0 {
v8::undefined(scope).into()
} else {
args.get(0)
};
let text = match serialize_output_text(scope, value) {
Ok(text) => text,
Err(error_text) => {
throw_type_error(scope, &error_text);
return;
}
};
if let Some(state) = scope.get_slot::<RuntimeState>()
&& !state.exit_requested
{
let _ = state
.event_tx
.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputText { text }));
}
retval.set(v8::undefined(scope).into());
}
pub(super) fn audio_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let value = if args.length() == 0 {
v8::undefined(scope).into()
} else {
args.get(0)
};
let audio_item = match normalize_output_audio(scope, value) {
Ok(audio_item) => audio_item,
Err(()) => return,
};
if let Some(state) = scope.get_slot::<RuntimeState>()
&& !state.exit_requested
{
let _ = state
.event_tx
.blocking_send(RuntimeEvent::ContentItem(audio_item));
}
retval.set(v8::undefined(scope).into());
}
pub(super) fn image_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let value = if args.length() == 0 {
v8::undefined(scope).into()
} else {
args.get(0)
};
let detail_override = if args.length() < 2 {
None
} else {
let detail = args.get(1);
if detail.is_string() {
Some(detail.to_rust_string_lossy(scope))
} else if detail.is_null() || detail.is_undefined() {
None
} else {
throw_type_error(scope, "image detail must be a string when provided");
return;
}
};
let image_item = match normalize_output_image(scope, value, detail_override) {
Ok(image_item) => image_item,
Err(()) => return,
};
if let Some(state) = scope.get_slot::<RuntimeState>()
&& !state.exit_requested
{
let _ = state
.event_tx
.blocking_send(RuntimeEvent::ContentItem(image_item));
}
retval.set(v8::undefined(scope).into());
}
pub(super) fn generated_image_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let value = if args.length() == 0 {
v8::undefined(scope).into()
} else {
args.get(0)
};
let output_hint = match generated_image_output_hint(scope, value) {
Ok(output_hint) => output_hint,
Err(error_text) => {
throw_type_error(scope, &error_text);
return;
}
};
let image_item = match normalize_output_image(scope, value, /*detail_override*/ None) {
Ok(image_item) => image_item,
Err(()) => return,
};
if let Some(state) = scope.get_slot::<RuntimeState>()
&& !state.exit_requested
{
let _ = state
.event_tx
.blocking_send(RuntimeEvent::ContentItem(image_item));
if let Some(text) = output_hint {
let _ = state
.event_tx
.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputText { text }));
}
}
retval.set(v8::undefined(scope).into());
}
fn generated_image_output_hint(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> Result<Option<String>, String> {
let object = v8::Local::<v8::Object>::try_from(value)
.map_err(|_| "generatedImage expects an image generation result object".to_string())?;
let key = v8::String::new(scope, "output_hint")
.ok_or_else(|| "failed to allocate generatedImage helper keys".to_string())?;
let output_hint = object
.get(scope, key.into())
.ok_or_else(|| "failed to read generatedImage output_hint".to_string())?;
if output_hint.is_undefined() {
return Ok(None);
}
if !output_hint.is_string() {
return Err("generatedImage output_hint must be a string when provided".to_string());
}
Ok(Some(output_hint.to_rust_string_lossy(scope)))
}
pub(super) fn store_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
_retval: v8::ReturnValue<v8::Value>,
) {
let key = match args.get(0).to_string(scope) {
Some(key) => key.to_rust_string_lossy(scope),
None => {
throw_type_error(scope, "store key must be a string");
return;
}
};
let value = args.get(1);
let serialized = match v8_value_to_json(scope, value) {
Ok(Some(value)) => value,
Ok(None) => {
throw_type_error(
scope,
&format!("Unable to store {key:?}. Only plain serializable objects can be stored."),
);
return;
}
Err(error_text) => {
throw_type_error(scope, &error_text);
return;
}
};
if let Some(state) = scope.get_slot_mut::<RuntimeState>()
&& !state.exit_requested
{
let serialized = Arc::new(serialized);
state
.stored_values
.insert(key.clone(), Arc::clone(&serialized));
state.stored_value_writes.insert(key, serialized);
}
}
pub(super) fn load_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let key = match args.get(0).to_string(scope) {
Some(key) => key.to_rust_string_lossy(scope),
None => {
throw_type_error(scope, "load key must be a string");
return;
}
};
let value = scope
.get_slot::<RuntimeState>()
.and_then(|state| state.stored_values.get(&key))
.cloned();
let Some(value) = value else {
retval.set(v8::undefined(scope).into());
return;
};
let Some(value) = json_to_v8(scope, &value) else {
throw_type_error(scope, "failed to load stored value");
return;
};
retval.set(value);
}
pub(super) fn notify_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let value = if args.length() == 0 {
v8::undefined(scope).into()
} else {
args.get(0)
};
let text = match serialize_output_text(scope, value) {
Ok(text) => text,
Err(error_text) => {
throw_type_error(scope, &error_text);
return;
}
};
if text.trim().is_empty() {
throw_type_error(scope, "notify expects non-empty text");
return;
}
if let Some(state) = scope.get_slot::<RuntimeState>()
&& !state.exit_requested
{
let _ = state.event_tx.blocking_send(RuntimeEvent::Notify {
call_id: state.tool_call_id.clone(),
text,
});
}
retval.set(v8::undefined(scope).into());
}
pub(super) fn set_timeout_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
let timeout_id = match timers::schedule_timeout(scope, args) {
Ok(Some(timeout_id)) => timeout_id,
Ok(None) => return,
Err(error_text) => {
throw_type_error(scope, &error_text);
return;
}
};
retval.set(v8::Number::new(scope, timeout_id as f64).into());
}
pub(super) fn clear_timeout_callback(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
if let Err(error_text) = timers::clear_timeout(scope, args) {
throw_type_error(scope, &error_text);
return;
}
retval.set(v8::undefined(scope).into());
}
pub(super) fn yield_control_callback(
scope: &mut v8::PinScope<'_, '_>,
_args: v8::FunctionCallbackArguments,
_retval: v8::ReturnValue<v8::Value>,
) {
if let Some(state) = scope.get_slot::<RuntimeState>()
&& !state.exit_requested
{
let _ = state.event_tx.blocking_send(RuntimeEvent::YieldRequested);
}
}
pub(super) fn exit_callback(
scope: &mut v8::PinScope<'_, '_>,
_args: v8::FunctionCallbackArguments,
_retval: v8::ReturnValue<v8::Value>,
) {
if let Some(state) = scope.get_slot_mut::<RuntimeState>() {
state.exit_requested = true;
}
scope.terminate_execution();
}
#[cfg(test)]
#[path = "callbacks_tests.rs"]
mod tests;

View File

@@ -0,0 +1,194 @@
//! Exercises the host guard separately from V8's interrupt mechanism. Simulate
//! V8 continuing to execute after exit was requested, including during getters.
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::mpsc as std_mpsc;
use akode_code_mode_protocol::CodeModeToolKind;
use akode_code_mode_protocol::EnabledToolMetadata;
use akode_protocol::ToolName;
use pretty_assertions::assert_eq;
use serde_json::json;
use tokio::sync::mpsc;
use super::super::RuntimeEvent;
use super::super::RuntimeState;
use super::super::ToolCallbackMetadata;
use super::super::globals;
use crate::session_runtime::OutputItem;
use crate::v8_init::ensure_v8_initialized;
// Deliberately leave JS running: the test must verify host-side admission even
// when V8 has not processed its interrupt. Returning a value exercises coercion.
fn mark_exit_requested(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
mut retval: v8::ReturnValue<v8::Value>,
) {
scope
.get_slot_mut::<RuntimeState>()
.expect("runtime state")
.exit_requested = true;
retval.set(args.get(0));
}
#[tokio::test]
async fn host_callbacks_admit_no_new_effects_after_exit_is_requested() {
for (label, source) in [
(
"ordinary calls",
r#"
markExit();
text("still working");
image("data:image/png;base64,AAA");
audio("data:audio/mpeg;base64,YXVkaW8=");
generatedImage({image_url: "data:image/png;base64,AAA", output_hint: "late"});
notify("late"); store("phase", "late");
tools.echo("late"); yield_control();
clearTimeout(earlyTimer); setTimeout(() => {}, 60000);
"#,
),
(
"text conversion",
r#"text({toJSON() { return markExit("late"); }});"#,
),
(
"notify conversion",
r#"notify({toJSON() { return markExit("late"); }});"#,
),
(
"store conversion",
r#"store("phase", {toJSON() { return markExit("late"); }});"#,
),
(
"store key",
r#"store({toString() { return markExit("phase"); }}, "late");"#,
),
(
"tool conversion",
r#"tools.echo({toJSON() { return markExit("late"); }});"#,
),
(
"image getter",
r#"image({get image_url() { return markExit("data:image/png;base64,AAA"); }});"#,
),
(
"audio getter",
r#"audio({get audio_url() { return markExit("data:audio/mpeg;base64,YXVkaW8="); }});"#,
),
(
"generated image hint",
r#"generatedImage({image_url: "data:image/png;base64,AAA", get output_hint() {return markExit("late"); }});"#,
),
(
"timer delay",
r#"setTimeout(() => {}, {valueOf() {return markExit(60000); }});"#,
),
(
"clear timer id",
r#"clearTimeout({valueOf() {return markExit(earlyTimer); }});"#,
),
] {
ensure_v8_initialized().expect("initialize V8");
let isolate = &mut v8::Isolate::new(v8::CreateParams::default());
v8::scope!(let scope, isolate);
let context = v8::Context::new(scope, Default::default());
let scope = &mut v8::ContextScope::new(scope, context);
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,
&[EnabledToolMetadata {
global_name: "echo".to_string(),
tool_name: tool_name.clone(),
description: String::new(),
kind: CodeModeToolKind::Function,
}],
)
.expect("install globals");
scope.set_slot(RuntimeState {
event_tx: event_tx.into(),
pending_tool_calls: HashMap::new(),
pending_timeouts: HashMap::new(),
stored_values: HashMap::new(),
stored_value_writes: HashMap::new(),
enabled_tools: vec![ToolCallbackMetadata {
tool_name,
kind: CodeModeToolKind::Function,
}],
next_tool_call_id: 1,
next_timeout_id: 1,
tool_call_id: "cell".to_string(),
runtime_command_tx,
exit_requested: false,
});
let marker = v8::Function::new(scope, mark_exit_requested).expect("exit marker");
let key = v8::String::new(scope, "markExit").expect("marker name");
context.global(scope).set(scope, key.into(), marker.into());
let program = v8::String::new(
scope,
&format!(
r#"
text("before"); store("phase", "before"); notify("before");
tools.echo("before");
const earlyTimer = setTimeout(() => text("early timer"), 60000);
{source}
"#
),
)
.expect("test program");
let tc = std::pin::pin!(v8::TryCatch::new(scope));
let tc = tc.init();
let result =
v8::Script::compile(&tc, program, /*origin*/ None).and_then(|script| script.run(&tc));
assert!(
result.is_some(),
"{label}: {:?}",
tc.exception().map(|e| e.to_rust_string_lossy(&tc))
);
assert!(
matches!(event_rx.try_recv(), Ok(RuntimeEvent::ContentItem(
OutputItem::InputText { text }
)) if text == "before"),
"{label}: pre-exit output"
);
assert!(
matches!(event_rx.try_recv(), Ok(RuntimeEvent::Notify { text, .. }) if text == "before"),
"{label}: pre-exit notification"
);
assert!(
matches!(event_rx.try_recv(), Ok(RuntimeEvent::ToolCall { id, input, .. })
if id == "tool-1" && input == Some(json!("before"))),
"{label}: pre-exit tool"
);
assert!(
matches!(event_rx.try_recv(), Err(mpsc::error::TryRecvError::Empty)),
"{label}: emitted an effect after exit"
);
let state = tc.get_slot::<RuntimeState>().expect("runtime state");
assert_eq!(
state.stored_value_writes,
HashMap::from([("phase".to_string(), Arc::new(json!("before")))]),
"{label}: stored writes"
);
assert_eq!(
state.stored_values, state.stored_value_writes,
"{label}: cell storage"
);
assert_eq!(state.next_tool_call_id, 2, "{label}: allocated tool ID");
assert_eq!(state.next_timeout_id, 2, "{label}: allocated timeout ID");
assert!(
state.pending_tool_calls.contains_key("tool-1"),
"{label}: lost prior tool"
);
assert!(
state.pending_timeouts.contains_key(&1),
"{label}: lost prior timer"
);
}
}

View File

@@ -0,0 +1,77 @@
//! Ordered runtime event transport with backpressure for bounded collectors.
use tokio::sync::mpsc;
use super::RuntimeEvent;
use akode_code_mode_protocol::CodeModeOutputTruncation;
// Amortize small-write handoffs while keeping the backlog of raw payloads
// ahead of the bounded collector small.
const EVENT_CAPACITY: usize = 4;
#[derive(Clone)]
pub(crate) enum RuntimeEventSender {
Legacy(mpsc::UnboundedSender<RuntimeEvent>),
Bounded(mpsc::Sender<RuntimeEvent>),
}
pub(crate) enum RuntimeEventReceiver {
Legacy(mpsc::UnboundedReceiver<RuntimeEvent>),
Bounded(mpsc::Receiver<RuntimeEvent>),
}
pub(crate) fn runtime_event_channel(
mode: CodeModeOutputTruncation,
) -> (RuntimeEventSender, RuntimeEventReceiver) {
match mode {
CodeModeOutputTruncation::Client => {
let (tx, rx) = mpsc::unbounded_channel();
(
RuntimeEventSender::Legacy(tx),
RuntimeEventReceiver::Legacy(rx),
)
}
CodeModeOutputTruncation::Server => {
let (tx, rx) = mpsc::channel(EVENT_CAPACITY);
(
RuntimeEventSender::Bounded(tx),
RuntimeEventReceiver::Bounded(rx),
)
}
}
}
impl From<mpsc::UnboundedSender<RuntimeEvent>> for RuntimeEventSender {
fn from(value: mpsc::UnboundedSender<RuntimeEvent>) -> Self {
Self::Legacy(value)
}
}
impl RuntimeEventReceiver {
pub(crate) async fn recv(&mut self) -> Option<RuntimeEvent> {
match self {
Self::Legacy(rx) => rx.recv().await,
Self::Bounded(rx) => rx.recv().await,
}
}
}
impl RuntimeEventSender {
/// Bounded sends run only on the dedicated V8 thread, preserving event order
/// without making synchronous JavaScript output helpers return promises.
/// Capacity limits the backlog between V8 and the cell actor.
///
/// # Panics
///
/// In server mode, panics if called from an async execution context.
pub(crate) fn blocking_send(&self, event: RuntimeEvent) -> Result<(), ()> {
match self {
Self::Legacy(tx) => tx.send(event).map_err(|_| ()),
Self::Bounded(tx) => tx.blocking_send(event).map_err(|_| ()),
}
}
}
#[cfg(test)]
#[path = "event_channel_tests.rs"]
mod tests;

View File

@@ -0,0 +1,133 @@
//! Raw emissions and control events share one bounded FIFO before collection.
use pretty_assertions::assert_eq;
use tokio::sync::oneshot;
use super::*;
use crate::session_runtime::OutputItem;
use akode_code_mode_protocol::host::BOUNDED_OUTPUT_MAX_BYTES as MAX_OUTPUT_BYTES;
#[tokio::test]
async fn a_blocked_send_uses_the_released_slot_before_the_receiver_takes_the_item() {
let (tx, mut rx) = runtime_event_channel(CodeModeOutputTruncation::Server);
let RuntimeEventSender::Bounded(raw) = tx.clone() else {
panic!("expected bounded sender");
};
let mut permits = raw.reserve_many(EVENT_CAPACITY).await.unwrap();
let (done_tx, mut done_rx) = oneshot::channel();
let text = "😀".repeat(MAX_OUTPUT_BYTES);
let producer_text = text.clone();
let producer = std::thread::spawn(move || {
let result = tx.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputText {
text: producer_text,
}));
let _ = done_tx.send(result);
});
// Queue a competing waiter before releasing the slot. A blocking producer can
// win the slot in FIFO order; a try_send can never find an unreserved slot.
let sent = tokio::time::timeout(std::time::Duration::from_secs(5), async {
let mut slot = permits.next().unwrap();
loop {
let mut next = std::pin::pin!(raw.reserve());
assert!(futures::poll!(next.as_mut()).is_pending());
drop(slot);
tokio::select! {
result = &mut done_rx => break result.unwrap(),
permit = &mut next => slot = permit.unwrap(),
}
tokio::task::yield_now().await;
}
})
.await
.expect("the producer must eventually acquire the released slot");
assert_eq!(sent, Ok(()));
// Close the test's sender so a missing event fails the receive immediately.
drop(permits);
drop(raw);
let event = rx.recv().await.unwrap();
let RuntimeEvent::ContentItem(item) = event else {
panic!("expected raw content");
};
assert_eq!(item, OutputItem::InputText { text });
producer.join().unwrap();
}
#[tokio::test]
async fn content_and_control_are_received_in_send_order() {
let (tx, mut rx) = runtime_event_channel(CodeModeOutputTruncation::Server);
let producer = std::thread::spawn(move || {
tx.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputImage {
image_url: "image".to_owned(),
detail: None,
}))
.unwrap();
tx.blocking_send(RuntimeEvent::YieldRequested).unwrap();
tx.blocking_send(RuntimeEvent::ContentItem(OutputItem::InputText {
text: "after yield".to_owned(),
}))
.unwrap();
});
assert!(matches!(
rx.recv().await,
Some(RuntimeEvent::ContentItem(OutputItem::InputImage { .. }))
));
assert!(matches!(
rx.recv().await,
Some(RuntimeEvent::YieldRequested)
));
assert!(matches!(
rx.recv().await,
Some(RuntimeEvent::ContentItem(OutputItem::InputText { text }))
if text == "after yield"
));
producer.join().unwrap();
}
#[tokio::test]
async fn full_channel_blocks_the_producer_and_receiver_drop_releases_it() {
let (tx, rx) = runtime_event_channel(CodeModeOutputTruncation::Server);
let RuntimeEventSender::Bounded(tx) = tx else {
panic!("expected bounded sender");
};
for _ in 0..EVENT_CAPACITY {
tx.try_send(RuntimeEvent::Started).unwrap();
}
let (ready_tx, ready_rx) = oneshot::channel();
let producer = tokio::spawn(async move {
// Tokio's blocking_send runs this same send future. Polling it first
// proves the full channel has registered this producer as a waiter.
let mut send = std::pin::pin!(tx.send(RuntimeEvent::YieldRequested));
assert!(futures::poll!(send.as_mut()).is_pending());
ready_tx.send(()).unwrap();
send.await
});
// This current-thread runtime cannot resume us until the producer yields.
// Closing must wake that already-waiting task, not just reject a new send.
ready_rx.await.unwrap();
drop(rx);
let result = tokio::time::timeout(std::time::Duration::from_secs(1), producer)
.await
.expect("receiver drop must wake the blocked producer")
.expect("producer task");
assert!(matches!(
result,
Err(mpsc::error::SendError(RuntimeEvent::YieldRequested))
));
}
#[tokio::test]
async fn sending_after_receiver_drop_rejects_content() {
let (tx, rx) = runtime_event_channel(CodeModeOutputTruncation::Server);
drop(rx);
assert_eq!(
std::thread::spawn(move || tx.blocking_send(RuntimeEvent::ContentItem(
OutputItem::InputAudio {
audio_url: "large audio".repeat(MAX_OUTPUT_BYTES)
}
)))
.join()
.unwrap(),
Err(())
);
}

View File

@@ -0,0 +1,166 @@
use super::callbacks::audio_callback;
use super::callbacks::clear_timeout_callback;
use super::callbacks::exit_callback;
use super::callbacks::generated_image_callback;
use super::callbacks::image_callback;
use super::callbacks::load_callback;
use super::callbacks::notify_callback;
use super::callbacks::set_timeout_callback;
use super::callbacks::store_callback;
use super::callbacks::text_callback;
use super::callbacks::tool_callback;
use super::callbacks::yield_control_callback;
use akode_code_mode_protocol::EnabledToolMetadata;
pub(super) fn install_globals(
scope: &mut v8::PinScope<'_, '_>,
enabled_tools: &[EnabledToolMetadata],
) -> Result<(), String> {
let global = scope.get_current_context().global(scope);
delete_global(scope, global, "console")?;
delete_global(scope, global, "Atomics")?;
delete_global(scope, global, "SharedArrayBuffer")?;
delete_global(scope, global, "WebAssembly")?;
let tools = build_tools_object(scope, enabled_tools)?;
let all_tools = build_all_tools_value(scope, enabled_tools)?;
let clear_timeout = helper_function(scope, "clearTimeout", clear_timeout_callback)?;
let set_timeout = helper_function(scope, "setTimeout", set_timeout_callback)?;
let text = helper_function(scope, "text", text_callback)?;
let image = helper_function(scope, "image", image_callback)?;
let audio = helper_function(scope, "audio", audio_callback)?;
let generated_image = helper_function(scope, "generatedImage", generated_image_callback)?;
let store = helper_function(scope, "store", store_callback)?;
let load = helper_function(scope, "load", load_callback)?;
let notify = helper_function(scope, "notify", notify_callback)?;
let yield_control = helper_function(scope, "yield_control", yield_control_callback)?;
let exit = helper_function(scope, "exit", exit_callback)?;
set_global(scope, global, "tools", tools.into())?;
set_global(scope, global, "ALL_TOOLS", all_tools)?;
set_global(scope, global, "clearTimeout", clear_timeout.into())?;
set_global(scope, global, "setTimeout", set_timeout.into())?;
set_global(scope, global, "text", text.into())?;
set_global(scope, global, "image", image.into())?;
set_global(scope, global, "audio", audio.into())?;
set_global(scope, global, "generatedImage", generated_image.into())?;
set_global(scope, global, "store", store.into())?;
set_global(scope, global, "load", load.into())?;
set_global(scope, global, "notify", notify.into())?;
set_global(scope, global, "yield_control", yield_control.into())?;
set_global(scope, global, "exit", exit.into())?;
let source = v8::String::new(scope, include_str!("settled.js"))
.ok_or_else(|| "failed to allocate settlement helpers".to_string())?;
v8::Script::compile(scope, source, /*origin*/ None)
.and_then(|script| script.run(scope))
.ok_or_else(|| "failed to initialize settlement helpers".to_string())?;
Ok(())
}
fn build_tools_object<'s>(
scope: &mut v8::PinScope<'s, '_>,
enabled_tools: &[EnabledToolMetadata],
) -> Result<v8::Local<'s, v8::Object>, String> {
let tools = v8::Object::new(scope);
for (tool_index, tool) in enabled_tools.iter().enumerate() {
let name = v8::String::new(scope, &tool.global_name)
.ok_or_else(|| "failed to allocate tool name".to_string())?;
let function = tool_function(scope, tool_index)?;
tools.set(scope, name.into(), function.into());
}
Ok(tools)
}
fn build_all_tools_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
enabled_tools: &[EnabledToolMetadata],
) -> Result<v8::Local<'s, v8::Value>, String> {
let array = v8::Array::new(scope, enabled_tools.len() as i32);
let name_key = v8::String::new(scope, "name")
.ok_or_else(|| "failed to allocate ALL_TOOLS name key".to_string())?;
let description_key = v8::String::new(scope, "description")
.ok_or_else(|| "failed to allocate ALL_TOOLS description key".to_string())?;
for (index, tool) in enabled_tools.iter().enumerate() {
let item = v8::Object::new(scope);
let name = v8::String::new(scope, &tool.global_name)
.ok_or_else(|| "failed to allocate ALL_TOOLS name".to_string())?;
let description = v8::String::new(scope, &tool.description)
.ok_or_else(|| "failed to allocate ALL_TOOLS description".to_string())?;
if item.set(scope, name_key.into(), name.into()) != Some(true) {
return Err("failed to set ALL_TOOLS name".to_string());
}
if item.set(scope, description_key.into(), description.into()) != Some(true) {
return Err("failed to set ALL_TOOLS description".to_string());
}
if array.set_index(scope, index as u32, item.into()) != Some(true) {
return Err("failed to append ALL_TOOLS metadata".to_string());
}
}
Ok(array.into())
}
fn helper_function<'s, F>(
scope: &mut v8::PinScope<'s, '_>,
name: &str,
callback: F,
) -> Result<v8::Local<'s, v8::Function>, String>
where
F: v8::MapFnTo<v8::FunctionCallback>,
{
let name =
v8::String::new(scope, name).ok_or_else(|| "failed to allocate helper name".to_string())?;
let template = v8::FunctionTemplate::builder(callback)
.data(name.into())
.build(scope);
template
.get_function(scope)
.ok_or_else(|| "failed to create helper function".to_string())
}
fn tool_function<'s>(
scope: &mut v8::PinScope<'s, '_>,
tool_index: usize,
) -> Result<v8::Local<'s, v8::Function>, String> {
let data = v8::String::new(scope, &tool_index.to_string())
.ok_or_else(|| "failed to allocate tool callback data".to_string())?;
let template = v8::FunctionTemplate::builder(tool_callback)
.data(data.into())
.build(scope);
template
.get_function(scope)
.ok_or_else(|| "failed to create tool function".to_string())
}
fn set_global<'s>(
scope: &mut v8::PinScope<'s, '_>,
global: v8::Local<'s, v8::Object>,
name: &str,
value: v8::Local<'s, v8::Value>,
) -> Result<(), String> {
let key = v8::String::new(scope, name)
.ok_or_else(|| format!("failed to allocate global `{name}`"))?;
if global.set(scope, key.into(), value) == Some(true) {
Ok(())
} else {
Err(format!("failed to set global `{name}`"))
}
}
fn delete_global<'s>(
scope: &mut v8::PinScope<'s, '_>,
global: v8::Local<'s, v8::Object>,
name: &str,
) -> Result<(), String> {
let key = v8::String::new(scope, name)
.ok_or_else(|| format!("failed to allocate global `{name}`"))?;
if global.delete(scope, key.into()) == Some(true) {
Ok(())
} else {
Err(format!("failed to remove global `{name}`"))
}
}

View File

@@ -0,0 +1,619 @@
mod audio;
mod callbacks;
mod event_channel;
mod globals;
mod module_loader;
mod timers;
mod value;
use std::collections::HashMap;
use std::panic::AssertUnwindSafe;
use std::panic::catch_unwind;
use std::sync::Arc;
use std::sync::mpsc as std_mpsc;
use std::thread;
use crate::TaskFailureHandler;
use crate::session_runtime::OutputItem;
use crate::v8_init::ensure_v8_initialized;
use akode_code_mode_protocol::CodeModeToolKind;
use akode_code_mode_protocol::EnabledToolMetadata;
use akode_code_mode_protocol::ExecuteRequest;
use akode_code_mode_protocol::normalize_code_mode_identifier;
use akode_protocol::ToolName;
pub(crate) use event_channel::RuntimeEventReceiver;
pub(crate) use event_channel::RuntimeEventSender;
pub(crate) use event_channel::runtime_event_channel;
use serde_json::Value as JsonValue;
#[derive(Debug)]
pub(crate) enum RuntimeCommand {
ToolResponse { id: String, result: JsonValue },
ToolError { id: String, error_text: String },
TimeoutFired { id: u64 },
ObservePendingFrontier,
Terminate,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum PendingRuntimeMode {
#[cfg(test)]
Continue,
PauseUntilResumed,
}
#[derive(Debug)]
pub(crate) enum RuntimeControlCommand {
Continue,
Resume,
Terminate,
}
#[derive(Debug)]
pub(crate) enum RuntimeEvent {
Started,
Pending,
ContentItem(OutputItem),
YieldRequested,
ToolCall {
id: String,
name: ToolName,
kind: CodeModeToolKind,
input: Option<JsonValue>,
},
Notify {
call_id: String,
text: String,
},
Result {
stored_value_writes: HashMap<String, Arc<JsonValue>>,
error_text: Option<String>,
},
ThreadPanicked,
}
pub(crate) fn spawn_runtime(
stored_values: HashMap<String, Arc<JsonValue>>,
request: ExecuteRequest,
event_tx: impl Into<RuntimeEventSender>,
pending_mode: PendingRuntimeMode,
task_failure_handler: Option<TaskFailureHandler>,
) -> Result<
(
std_mpsc::Sender<RuntimeCommand>,
std_mpsc::Sender<RuntimeControlCommand>,
v8::IsolateHandle,
),
String,
> {
let event_tx = event_tx.into();
ensure_v8_initialized()?;
let (command_tx, command_rx) = std_mpsc::channel();
let (control_tx, control_rx) = std_mpsc::channel();
let runtime_command_tx = command_tx.clone();
let (isolate_handle_tx, isolate_handle_rx) = std_mpsc::sync_channel(1);
let enabled_tools = request
.enabled_tools
.into_iter()
.map(|definition| EnabledToolMetadata {
global_name: normalize_code_mode_identifier(&definition.name),
tool_name: definition.tool_name,
description: definition.description,
kind: definition.kind,
})
.collect::<Vec<_>>();
let config = RuntimeConfig {
tool_call_id: request.tool_call_id,
enabled_tools,
source: request.source,
stored_values,
};
let runtime_handle = tokio::runtime::Handle::current();
spawn_supervised_runtime_thread(event_tx.clone(), task_failure_handler, move || {
let _runtime_guard = runtime_handle.enter();
run_runtime(
config,
event_tx,
command_rx,
control_rx,
pending_mode,
isolate_handle_tx,
runtime_command_tx,
);
});
let isolate_handle = isolate_handle_rx
.recv()
.map_err(|_| "failed to initialize code mode runtime".to_string())?;
Ok((command_tx, control_tx, isolate_handle))
}
fn spawn_supervised_runtime_thread(
event_tx: impl Into<RuntimeEventSender>,
task_failure_handler: Option<TaskFailureHandler>,
runtime: impl FnOnce() + Send + 'static,
) {
let event_tx = event_tx.into();
thread::spawn(move || {
if catch_unwind(AssertUnwindSafe(runtime)).is_err() {
if let Some(task_failure_handler) = task_failure_handler {
task_failure_handler("code-mode V8 runtime thread panicked".to_string());
}
let _ = event_tx.blocking_send(RuntimeEvent::ThreadPanicked);
}
});
}
#[derive(Clone)]
struct RuntimeConfig {
tool_call_id: String,
enabled_tools: Vec<EnabledToolMetadata>,
source: String,
stored_values: HashMap<String, Arc<JsonValue>>,
}
// Callback indices refer to this cell's original catalog for its entire lifetime.
struct ToolCallbackMetadata {
tool_name: ToolName,
kind: CodeModeToolKind,
}
pub(super) struct RuntimeState {
event_tx: RuntimeEventSender,
pending_tool_calls: HashMap<String, v8::Global<v8::PromiseResolver>>,
pending_timeouts: HashMap<u64, timers::ScheduledTimeout>,
stored_values: HashMap<String, Arc<JsonValue>>,
stored_value_writes: HashMap<String, Arc<JsonValue>>,
enabled_tools: Vec<ToolCallbackMetadata>,
next_tool_call_id: u64,
next_timeout_id: u64,
tool_call_id: String,
runtime_command_tx: std_mpsc::Sender<RuntimeCommand>,
exit_requested: bool,
}
pub(super) enum CompletionState {
Pending,
Completed { error_text: Option<String> },
}
fn run_runtime(
config: RuntimeConfig,
event_tx: RuntimeEventSender,
command_rx: std_mpsc::Receiver<RuntimeCommand>,
control_rx: std_mpsc::Receiver<RuntimeControlCommand>,
pending_mode: PendingRuntimeMode,
isolate_handle_tx: std_mpsc::SyncSender<v8::IsolateHandle>,
runtime_command_tx: std_mpsc::Sender<RuntimeCommand>,
) {
let isolate = &mut v8::Isolate::new(v8::CreateParams::default());
let isolate_handle = isolate.thread_safe_handle();
if isolate_handle_tx.send(isolate_handle).is_err() {
return;
}
isolate.set_host_import_module_dynamically_callback(module_loader::dynamic_import_callback);
v8::scope!(let scope, isolate);
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, &config.enabled_tools) {
send_result(&event_tx, HashMap::new(), Some(error_text));
return;
}
scope.set_slot(RuntimeState {
event_tx: event_tx.clone(),
pending_tool_calls: HashMap::new(),
pending_timeouts: HashMap::new(),
stored_values: config.stored_values,
stored_value_writes: HashMap::new(),
enabled_tools: config
.enabled_tools
.into_iter()
.map(|tool| ToolCallbackMetadata {
tool_name: tool.tool_name,
kind: tool.kind,
})
.collect(),
next_tool_call_id: 1,
next_timeout_id: 1,
tool_call_id: config.tool_call_id,
runtime_command_tx,
exit_requested: false,
});
let _ = event_tx.blocking_send(RuntimeEvent::Started);
let pending_promise = match module_loader::evaluate_main_module(scope, &config.source) {
Ok(pending_promise) => pending_promise,
Err(error_text) => {
send_scope_result(scope, &event_tx, Some(error_text));
return;
}
};
match module_loader::completion_state(scope, pending_promise.as_ref()) {
CompletionState::Completed { error_text } => {
send_scope_result(scope, &event_tx, error_text);
return;
}
CompletionState::Pending => {}
}
let mut pending_promise = pending_promise;
while let Some(command) =
next_runtime_command(&event_tx, &command_rx, &control_rx, pending_mode)
{
match command {
RuntimeCommand::Terminate => break,
RuntimeCommand::ToolResponse { id, result } => {
if let Err(error_text) =
module_loader::resolve_tool_response(scope, &id, Ok(result))
{
send_scope_result(scope, &event_tx, Some(error_text));
return;
}
}
RuntimeCommand::ToolError { id, error_text } => {
if let Err(runtime_error) =
module_loader::resolve_tool_response(scope, &id, Err(error_text))
{
send_scope_result(scope, &event_tx, Some(runtime_error));
return;
}
}
RuntimeCommand::TimeoutFired { id } => {
if let Err(runtime_error) = timers::invoke_timeout_callback(scope, id) {
send_scope_result(scope, &event_tx, Some(runtime_error));
return;
}
}
RuntimeCommand::ObservePendingFrontier => {}
}
scope.perform_microtask_checkpoint();
match module_loader::completion_state(scope, pending_promise.as_ref()) {
CompletionState::Completed { error_text } => {
send_scope_result(scope, &event_tx, error_text);
return;
}
CompletionState::Pending => {}
}
if let Some(promise) = pending_promise.as_ref() {
let promise = v8::Local::new(scope, promise);
if promise.state() != v8::PromiseState::Pending {
pending_promise = None;
}
}
}
}
fn next_runtime_command(
event_tx: &RuntimeEventSender,
command_rx: &std_mpsc::Receiver<RuntimeCommand>,
control_rx: &std_mpsc::Receiver<RuntimeControlCommand>,
pending_mode: PendingRuntimeMode,
) -> Option<RuntimeCommand> {
loop {
match command_rx.try_recv() {
Ok(command) => return Some(command),
Err(std_mpsc::TryRecvError::Disconnected) => return None,
Err(std_mpsc::TryRecvError::Empty) => {}
}
let _ = event_tx.blocking_send(RuntimeEvent::Pending);
match pending_mode {
#[cfg(test)]
PendingRuntimeMode::Continue => return command_rx.recv().ok(),
PendingRuntimeMode::PauseUntilResumed => match control_rx.recv().ok()? {
RuntimeControlCommand::Continue => return command_rx.recv().ok(),
RuntimeControlCommand::Resume => continue,
RuntimeControlCommand::Terminate => return Some(RuntimeCommand::Terminate),
},
}
}
}
fn send_scope_result(
scope: &mut v8::PinScope<'_, '_>,
event_tx: &RuntimeEventSender,
error_text: Option<String>,
) {
// Error rendering can itself run JS getters, including exit(). Capture
// the result only after every call into the exiting isolate has returned.
let state = scope.get_slot::<RuntimeState>();
let stored_value_writes = state
.map(|state| state.stored_value_writes.clone())
.unwrap_or_default();
let error_text = error_text.filter(|_| !state.is_some_and(|state| state.exit_requested));
send_result(event_tx, stored_value_writes, error_text);
}
fn send_result(
event_tx: &RuntimeEventSender,
stored_value_writes: HashMap<String, Arc<JsonValue>>,
error_text: Option<String>,
) {
let _ = event_tx.blocking_send(RuntimeEvent::Result {
stored_value_writes,
error_text,
});
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::time::Duration;
use pretty_assertions::assert_eq;
use tokio::sync::mpsc;
use super::ExecuteRequest;
use super::PendingRuntimeMode;
use super::RuntimeCommand;
use super::RuntimeControlCommand;
use super::RuntimeEvent;
use super::spawn_runtime;
use super::spawn_supervised_runtime_thread;
use crate::session_runtime::OutputItem;
fn execute_request(source: &str) -> ExecuteRequest {
ExecuteRequest {
tool_call_id: "call_1".to_string(),
enabled_tools: Vec::new(),
source: source.to_string(),
yield_time_ms: Some(1),
max_output_tokens: None,
}
}
#[test]
fn linked_v8_has_sandbox_enabled() {
unsafe extern "C" {
fn v8__V8__IsSandboxEnabled() -> bool;
}
// `rusty_v8` exposes this symbol for verifying linked sandbox support.
assert!(
unsafe { v8__V8__IsSandboxEnabled() },
"code mode must link against sandbox-enabled V8"
);
}
#[tokio::test]
async fn runtime_thread_panic_before_initialization_is_reported_directly() {
let (event_tx, event_rx) = mpsc::unbounded_channel();
drop(event_rx);
let (failure_tx, mut failure_rx) = mpsc::unbounded_channel();
spawn_supervised_runtime_thread(
event_tx,
Some(std::sync::Arc::new(move |reason| {
let _ = failure_tx.send(reason);
})),
|| panic!("runtime thread panic probe"),
);
assert_eq!(
tokio::time::timeout(Duration::from_secs(1), failure_rx.recv())
.await
.expect("runtime failure timeout")
.expect("runtime failure"),
"code-mode V8 runtime thread panicked"
);
}
#[tokio::test]
async fn runtime_thread_panic_is_forwarded_without_owner_supervision() {
let (event_tx, mut event_rx) = mpsc::unbounded_channel();
spawn_supervised_runtime_thread(
event_tx,
/*task_failure_handler*/ None,
|| panic!("runtime thread panic probe"),
);
assert!(matches!(
tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.expect("runtime panic event timeout"),
Some(RuntimeEvent::ThreadPanicked)
));
}
#[tokio::test]
async fn terminate_execution_stops_javascript() {
for source in [
r#"notify("started"); while (true) {}"#,
// The failed first read enters JSON fallback, whose TryCatch must preserve termination.
r#"
let reads = 0;
const value = {
get image_url() {
if (++reads === 1) throw new Error("enter fallback");
notify("started");
while (true) {}
}
};
try { image(value); } catch {}
text("continued after cancellation");
"#,
] {
let (event_tx, mut event_rx) = mpsc::unbounded_channel();
let (_runtime_tx, _runtime_control_tx, runtime_terminate_handle) = spawn_runtime(
HashMap::new(),
execute_request(source),
event_tx,
PendingRuntimeMode::Continue,
/*task_failure_handler*/ None,
)
.unwrap();
let started_event = tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.unwrap();
assert!(matches!(started_event, RuntimeEvent::Started));
// Started precedes evaluation; the notification proves the workload is running.
assert!(matches!(
tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap(),
Some(RuntimeEvent::Notify { .. })
));
assert!(runtime_terminate_handle.terminate_execution());
let result_event = tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.unwrap();
let RuntimeEvent::Result { error_text, .. } = result_event else {
panic!("expected runtime result after termination");
};
assert!(error_text.is_some());
assert!(
tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.is_none()
);
}
}
#[tokio::test]
async fn pending_mode_freezes_runtime_commands_until_resume() {
let (event_tx, mut event_rx) = mpsc::unbounded_channel();
let (runtime_tx, runtime_control_tx, _runtime_terminate_handle) = spawn_runtime(
HashMap::new(),
execute_request(
r#"
await new Promise((resolve) => setTimeout(resolve, 60_000));
text("after");
await new Promise(() => {});
"#,
),
event_tx,
PendingRuntimeMode::PauseUntilResumed,
/*task_failure_handler*/ None,
)
.unwrap();
assert!(matches!(
tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.unwrap(),
RuntimeEvent::Started
));
assert!(matches!(
tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.unwrap(),
RuntimeEvent::Pending
));
runtime_tx
.send(RuntimeCommand::TimeoutFired { id: 1 })
.unwrap();
assert!(
tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.is_err()
);
runtime_control_tx
.send(RuntimeControlCommand::Resume)
.unwrap();
let content_event = tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.unwrap();
let RuntimeEvent::ContentItem(OutputItem::InputText { text }) = content_event else {
panic!("expected resumed runtime output");
};
assert_eq!(text, "after");
assert!(matches!(
tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
.unwrap(),
RuntimeEvent::Pending
));
runtime_control_tx
.send(RuntimeControlCommand::Terminate)
.unwrap();
}
#[tokio::test]
async fn timers_release_tasks_when_cleared_or_the_cell_finishes() {
let (event_tx, mut event_rx) = mpsc::unbounded_channel();
let (_runtime_tx, _runtime_control_tx, _runtime_terminate_handle) = spawn_runtime(
HashMap::new(),
execute_request(
r#"
clearTimeout(setTimeout(() => text("cancelled"), 3_600_000));
await new Promise((resolve) => setTimeout(resolve, 3_600_000));
text("done");
setTimeout(() => text("late"), 3_600_000);
"#,
),
event_tx,
PendingRuntimeMode::Continue,
/*task_failure_handler*/ None,
)
.unwrap();
loop {
match tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.unwrap()
{
Some(RuntimeEvent::Pending) => break,
Some(_) => {}
None => panic!("runtime closed before the timer was pending"),
}
}
tokio::task::yield_now().await;
assert_eq!(
tokio::runtime::Handle::current()
.metrics()
.num_alive_tasks(),
1
);
tokio::time::pause();
tokio::time::advance(Duration::from_secs(3_600)).await;
tokio::time::resume();
let mut output = Vec::new();
while let Some(event) = tokio::time::timeout(Duration::from_secs(1), event_rx.recv())
.await
.expect("timer runtime should finish")
{
match event {
RuntimeEvent::ContentItem(item) => output.push(item),
RuntimeEvent::Result { error_text, .. } => assert_eq!(error_text, None),
_ => {}
}
}
assert_eq!(
output,
vec![OutputItem::InputText {
text: "done".to_string()
}]
);
tokio::task::yield_now().await;
assert_eq!(
tokio::runtime::Handle::current()
.metrics()
.num_alive_tasks(),
0
);
}
}

View File

@@ -0,0 +1,217 @@
use serde_json::Value as JsonValue;
use super::CompletionState;
use super::RuntimeState;
use super::value::json_to_v8;
use super::value::value_to_error_text;
pub(super) fn evaluate_main_module(
scope: &mut v8::PinScope<'_, '_>,
source_text: &str,
) -> Result<Option<v8::Global<v8::Promise>>, String> {
let tc = std::pin::pin!(v8::TryCatch::new(scope));
let mut tc = tc.init();
let source = v8::String::new(&tc, source_text)
.ok_or_else(|| "failed to allocate exec source".to_string())?;
let origin = script_origin(&mut tc, "exec_main.mjs")?;
let mut source = v8::script_compiler::Source::new(source, Some(&origin));
let module = v8::script_compiler::compile_module(&tc, &mut source).ok_or_else(|| {
tc.exception()
.map(|exception| value_to_error_text(&mut tc, exception))
.unwrap_or_else(|| "unknown code mode exception".to_string())
})?;
module
.instantiate_module(&tc, resolve_module_callback)
.ok_or_else(|| {
tc.exception()
.map(|exception| value_to_error_text(&mut tc, exception))
.unwrap_or_else(|| "unknown code mode exception".to_string())
})?;
let result = match module.evaluate(&tc) {
Some(result) => result,
None => {
if let Some(exception) = tc.exception() {
return Err(value_to_error_text(&mut tc, exception));
}
return Err("unknown code mode exception".to_string());
}
};
tc.perform_microtask_checkpoint();
if result.is_promise() {
let promise = v8::Local::<v8::Promise>::try_from(result)
.map_err(|_| "failed to read exec promise".to_string())?;
return Ok(Some(v8::Global::new(&tc, promise)));
}
Ok(None)
}
pub(super) fn resolve_tool_response(
scope: &mut v8::PinScope<'_, '_>,
id: &str,
response: Result<JsonValue, String>,
) -> Result<(), String> {
let resolver = {
let state = scope
.get_slot_mut::<RuntimeState>()
.ok_or_else(|| "runtime state unavailable".to_string())?;
state.pending_tool_calls.remove(id)
}
.ok_or_else(|| format!("unknown tool call `{id}`"))?;
// Release delivery handles before the cell ends; live promises retain their results.
v8::scope!(let scope, scope);
let tc = std::pin::pin!(v8::TryCatch::new(scope));
let mut tc = tc.init();
let resolver = v8::Local::new(&tc, &resolver);
match response {
Ok(result) => {
let value = json_to_v8(&mut tc, &result)
.ok_or_else(|| "failed to serialize tool response".to_string())?;
resolver.resolve(&tc, value);
}
Err(error_text) => {
let value = v8::String::new(&tc, &error_text)
.ok_or_else(|| "failed to allocate tool error".to_string())?;
resolver.reject(&tc, value.into());
}
}
if tc.has_caught() {
return Err(tc
.exception()
.map(|exception| value_to_error_text(&mut tc, exception))
.unwrap_or_else(|| "unknown code mode exception".to_string()));
}
Ok(())
}
pub(super) fn completion_state(
scope: &mut v8::PinScope<'_, '_>,
pending_promise: Option<&v8::Global<v8::Promise>>,
) -> CompletionState {
// Termination during a microtask can leave the module promise pending.
// This isolate belongs to the exiting cell; never pump or await it again.
if scope
.get_slot::<RuntimeState>()
.is_some_and(|state| state.exit_requested)
{
return CompletionState::Completed { error_text: None };
}
let Some(pending_promise) = pending_promise else {
return CompletionState::Completed { error_text: None };
};
let promise = v8::Local::new(scope, pending_promise);
match promise.state() {
v8::PromiseState::Pending => CompletionState::Pending,
v8::PromiseState::Fulfilled => CompletionState::Completed { error_text: None },
v8::PromiseState::Rejected => {
let result = promise.result(scope);
CompletionState::Completed {
error_text: Some(value_to_error_text(scope, result)),
}
}
}
}
fn script_origin<'s>(
scope: &mut v8::PinScope<'s, '_>,
resource_name_: &str,
) -> Result<v8::ScriptOrigin<'s>, String> {
let resource_name = v8::String::new(scope, resource_name_)
.ok_or_else(|| "failed to allocate script origin".to_string())?;
let source_map_url = v8::String::new(scope, resource_name_)
.ok_or_else(|| "failed to allocate source map url".to_string())?;
Ok(v8::ScriptOrigin::new(
scope,
resource_name.into(),
0,
0,
true,
0,
Some(source_map_url.into()),
true,
false,
true,
None,
))
}
fn resolve_module_callback<'s>(
context: v8::Local<'s, v8::Context>,
specifier: v8::Local<'s, v8::String>,
_import_attributes: v8::Local<'s, v8::FixedArray>,
_referrer: v8::Local<'s, v8::Module>,
) -> Option<v8::Local<'s, v8::Module>> {
v8::callback_scope!(unsafe scope, context);
let specifier = specifier.to_rust_string_lossy(scope);
resolve_module(scope, &specifier)
}
pub(super) fn dynamic_import_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
_host_defined_options: v8::Local<'s, v8::Data>,
_resource_name: v8::Local<'s, v8::Value>,
specifier: v8::Local<'s, v8::String>,
_import_attributes: v8::Local<'s, v8::FixedArray>,
) -> Option<v8::Local<'s, v8::Promise>> {
let specifier = specifier.to_rust_string_lossy(scope);
let resolver = v8::PromiseResolver::new(scope)?;
match resolve_module(scope, &specifier) {
Some(module) => {
if module.get_status() == v8::ModuleStatus::Uninstantiated
&& module
.instantiate_module(scope, resolve_module_callback)
.is_none()
{
let error = v8::String::new(scope, "failed to instantiate module")
.map(Into::into)
.unwrap_or_else(|| v8::undefined(scope).into());
resolver.reject(scope, error);
return Some(resolver.get_promise(scope));
}
if matches!(
module.get_status(),
v8::ModuleStatus::Instantiated | v8::ModuleStatus::Evaluated
) && module.evaluate(scope).is_none()
{
let error = v8::String::new(scope, "failed to evaluate module")
.map(Into::into)
.unwrap_or_else(|| v8::undefined(scope).into());
resolver.reject(scope, error);
return Some(resolver.get_promise(scope));
}
let namespace = module.get_module_namespace();
resolver.resolve(scope, namespace);
Some(resolver.get_promise(scope))
}
None => {
let error = v8::String::new(scope, "unsupported import in exec")
.map(Into::into)
.unwrap_or_else(|| v8::undefined(scope).into());
resolver.reject(scope, error);
Some(resolver.get_promise(scope))
}
}
}
fn resolve_module<'s>(
scope: &mut v8::PinScope<'s, '_>,
specifier: &str,
) -> Option<v8::Local<'s, v8::Module>> {
if let Some(message) =
v8::String::new(scope, &format!("Unsupported import in exec: {specifier}"))
{
scope.throw_exception(message.into());
} else {
scope.throw_exception(v8::undefined(scope).into());
}
None
}
#[cfg(test)]
#[path = "module_loader_tests.rs"]
mod tests;

View File

@@ -0,0 +1,67 @@
//! Checks that tool response delivery preserves live results without rooting discarded values.
use std::collections::HashMap;
use std::sync::mpsc as std_mpsc;
use pretty_assertions::assert_eq;
use serde_json::json;
use tokio::sync::mpsc;
use super::super::RuntimeState;
use super::super::value::v8_value_to_json;
use super::resolve_tool_response;
use crate::v8_init::ensure_v8_initialized;
#[test]
fn discarded_tool_response_is_collectible_before_cell_ends() {
ensure_v8_initialized().expect("initialize V8");
let isolate = &mut v8::Isolate::new(v8::CreateParams::default());
v8::scope!(let scope, isolate);
let context = v8::Context::new(scope, Default::default());
let scope = &mut v8::ContextScope::new(scope, context);
let (event_tx, _event_rx) = mpsc::unbounded_channel();
let (runtime_command_tx, _runtime_command_rx) = std_mpsc::channel();
scope.set_slot(RuntimeState {
event_tx: event_tx.into(),
pending_tool_calls: HashMap::new(),
pending_timeouts: HashMap::new(),
stored_values: HashMap::new(),
stored_value_writes: HashMap::new(),
enabled_tools: Vec::new(),
next_tool_call_id: 1,
next_timeout_id: 1,
tool_call_id: "cell".to_string(),
runtime_command_tx,
exit_requested: false,
});
let promise = {
v8::scope!(let scope, scope);
let resolver = v8::PromiseResolver::new(scope).expect("create tool promise");
let promise = resolver.get_promise(scope);
let resolver = v8::Global::new(scope, resolver);
scope
.get_slot_mut::<RuntimeState>()
.expect("runtime state")
.pending_tool_calls
.insert("tool".to_string(), resolver);
v8::Global::new(scope, promise)
};
let response = json!({"content": [{"type": "text", "text": "tool result"}]});
resolve_tool_response(scope, "tool", Ok(response.clone())).expect("resolve tool promise");
scope.perform_microtask_checkpoint();
scope.low_memory_notification();
let weak_result = {
v8::scope!(let scope, scope);
let promise = v8::Local::new(scope, &promise);
assert_eq!(promise.state(), v8::PromiseState::Fulfilled);
let result = promise.result(scope);
assert_eq!(v8_value_to_json(scope, result), Ok(Some(response)));
v8::Weak::new(scope, result)
};
drop(promise);
scope.low_memory_notification();
assert!(weak_result.is_empty(), "discarded response is still rooted");
}

View File

@@ -0,0 +1,67 @@
// Runtime-owned promise combinators; all state stays in the cell's V8 heap.
// Observe each input once and queue settlements while the consumer is busy.
// Repeated races can lose that order and attach extra reactions to pending inputs.
(() => {
function as_settled(promises) {
let ready = [];
let pending = 0;
let wake;
let closed = false;
function settle(result) {
pending--;
if (closed) return;
ready.push(result);
if (wake) {
const resolve = wake;
wake = undefined;
resolve();
}
}
const keyed = promises instanceof Map;
let position = 0;
try {
for (const entry of promises) {
const [index, promise] = keyed ? entry : [position++, entry];
pending++;
Promise.resolve(promise).then(
(value) => settle({ index, status: "fulfilled", value }),
(reason) => settle({ index, status: "rejected", reason }),
);
}
} catch (error) {
closed = true;
throw error;
}
return (async function* () {
try {
while (pending > 0 || ready.length > 0) {
if (ready.length === 0) {
await new Promise((resolve) => {
wake = resolve;
});
}
const batch = ready;
ready = [];
yield* batch;
}
} finally {
closed = true;
ready = [];
}
})();
}
async function stream_settled(promises, emit) {
if (typeof emit !== "function") {
throw new TypeError("stream_settled requires a callback");
}
for await (const result of as_settled(promises)) {
await emit(result);
}
}
Object.assign(globalThis, { as_settled, stream_settled });
})();

View File

@@ -0,0 +1,128 @@
use std::time::Duration;
use tokio_util::task::AbortOnDropHandle;
use super::RuntimeCommand;
use super::RuntimeState;
use super::value::value_to_error_text;
pub(super) struct ScheduledTimeout {
callback: v8::Global<v8::Function>,
// Clearing the timeout or dropping the isolate also cancels its sleep.
_task: AbortOnDropHandle<()>,
}
pub(super) fn schedule_timeout(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
) -> Result<Option<u64>, String> {
let callback = args.get(0);
if !callback.is_function() {
return Err("setTimeout expects a function callback".to_string());
}
let callback = v8::Local::<v8::Function>::try_from(callback)
.map_err(|_| "setTimeout expects a function callback".to_string())?;
let delay_ms = args
.get(1)
.number_value(scope)
.map(normalize_delay_ms)
.unwrap_or(0);
let callback = v8::Global::new(scope, callback);
let state = scope
.get_slot_mut::<RuntimeState>()
.ok_or_else(|| "runtime state unavailable".to_string())?;
// Converting the delay can execute JavaScript that calls exit().
if state.exit_requested {
return Ok(None);
}
let timeout_id = state.next_timeout_id;
state.next_timeout_id = state.next_timeout_id.saturating_add(1);
let runtime_command_tx = state.runtime_command_tx.clone();
let sleep = tokio::time::sleep(Duration::from_millis(delay_ms));
let task = tokio::spawn(async move {
sleep.await;
let _ = runtime_command_tx.send(RuntimeCommand::TimeoutFired { id: timeout_id });
});
state.pending_timeouts.insert(
timeout_id,
ScheduledTimeout {
callback,
_task: AbortOnDropHandle::new(task),
},
);
Ok(Some(timeout_id))
}
pub(super) fn clear_timeout(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
) -> Result<(), String> {
let Some(timeout_id) = timeout_id_from_args(scope, args)? else {
return Ok(());
};
let Some(state) = scope.get_slot_mut::<RuntimeState>() else {
return Err("runtime state unavailable".to_string());
};
if !state.exit_requested {
state.pending_timeouts.remove(&timeout_id);
}
Ok(())
}
pub(super) fn invoke_timeout_callback(
scope: &mut v8::PinScope<'_, '_>,
timeout_id: u64,
) -> Result<(), String> {
let callback = {
let state = scope
.get_slot_mut::<RuntimeState>()
.ok_or_else(|| "runtime state unavailable".to_string())?;
state.pending_timeouts.remove(&timeout_id)
};
let Some(callback) = callback else {
return Ok(());
};
let tc = std::pin::pin!(v8::TryCatch::new(scope));
let mut tc = tc.init();
let callback = v8::Local::new(&tc, &callback.callback);
let receiver = v8::undefined(&tc).into();
let _ = callback.call(&tc, receiver, &[]);
if tc.has_caught() {
return Err(tc
.exception()
.map(|exception| value_to_error_text(&mut tc, exception))
.unwrap_or_else(|| "unknown code mode exception".to_string()));
}
Ok(())
}
fn timeout_id_from_args(
scope: &mut v8::PinScope<'_, '_>,
args: v8::FunctionCallbackArguments,
) -> Result<Option<u64>, String> {
if args.length() == 0 || args.get(0).is_null_or_undefined() {
return Ok(None);
}
let Some(timeout_id) = args.get(0).number_value(scope) else {
return Err("clearTimeout expects a numeric timeout id".to_string());
};
if !timeout_id.is_finite() || timeout_id <= 0.0 {
return Ok(None);
}
Ok(Some(timeout_id.trunc().min(u64::MAX as f64) as u64))
}
fn normalize_delay_ms(delay_ms: f64) -> u64 {
if !delay_ms.is_finite() || delay_ms <= 0.0 {
0
} else {
delay_ms.trunc().min(u64::MAX as f64) as u64
}
}

View File

@@ -0,0 +1,386 @@
use serde_json::Value as JsonValue;
use crate::session_runtime::OutputItem;
use akode_code_mode_protocol::DEFAULT_IMAGE_DETAIL;
use akode_code_mode_protocol::ImageDetail;
use super::RuntimeState;
use super::audio::wav_duration_seconds;
const IMAGE_HELPER_EXPECTS_MESSAGE: &str = "image expects a non-empty image URL string, an object with image_url and optional detail, or a raw MCP image block";
const AUDIO_HELPER_EXPECTS_MESSAGE: &str = "audio expects a non-empty audio URL string, an object with audio_url, or a raw MCP audio block";
const REMOTE_IMAGE_URL_ERROR: &str = "Tool call failed: remote image URLs are not supported in tool outputs. Pass a base64 data URI instead";
const INVALID_IMAGE_URL_ERROR: &str =
"Tool call failed: invalid image output. Pass a base64 data URI instead";
const INVALID_AUDIO_URL_ERROR: &str =
"Tool call failed: invalid audio output. Pass a base64 data URI instead";
const AKODE_IMAGE_DETAIL_META_KEY: &str = "codex/imageDetail";
pub(super) fn serialize_output_text(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> Result<String, String> {
if value.is_undefined()
|| value.is_null()
|| value.is_boolean()
|| value.is_number()
|| value.is_big_int()
|| value.is_string()
{
return Ok(value.to_rust_string_lossy(scope));
}
let tc = std::pin::pin!(v8::TryCatch::new(scope));
let mut tc = tc.init();
if let Some(stringified) = v8::json::stringify(&tc, value) {
return Ok(stringified.to_rust_string_lossy(&tc));
}
if tc.has_caught() {
return Err(tc
.exception()
.map(|exception| value_to_error_text(&mut tc, exception))
.unwrap_or_else(|| "unknown code mode exception".to_string()));
}
Ok(value.to_rust_string_lossy(&tc))
}
pub(super) fn normalize_output_image(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
detail_override: Option<String>,
) -> Result<OutputItem, ()> {
let result = (|| -> Result<OutputItem, String> {
let (image_url, detail) = if value.is_string() {
(value.to_rust_string_lossy(scope), None)
} else if value.is_object() && !value.is_array() {
let object = v8::Local::<v8::Object>::try_from(value)
.map_err(|_| IMAGE_HELPER_EXPECTS_MESSAGE.to_string())?;
if let Some(image) = parse_non_mcp_output_image(scope, object)? {
image
} else {
parse_mcp_output_image(scope, value)?
}
} else {
return Err(IMAGE_HELPER_EXPECTS_MESSAGE.to_string());
};
if image_url.is_empty() {
return Err(IMAGE_HELPER_EXPECTS_MESSAGE.to_string());
}
let Some((scheme, _)) = image_url.split_once(':') else {
return Err(INVALID_IMAGE_URL_ERROR.to_string());
};
if scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") {
return Err(REMOTE_IMAGE_URL_ERROR.to_string());
}
if !scheme.eq_ignore_ascii_case("data") {
return Err(INVALID_IMAGE_URL_ERROR.to_string());
}
let detail = detail_override.or(detail);
let detail = match detail {
Some(detail) => {
let normalized = detail.to_ascii_lowercase();
Some(match normalized.as_str() {
"auto" => ImageDetail::Auto,
"low" => ImageDetail::Low,
"high" => ImageDetail::High,
"original" => ImageDetail::Original,
_ => {
return Err(
"image detail must be one of: auto, low, high, original".to_string()
);
}
})
}
None => Some(DEFAULT_IMAGE_DETAIL),
};
Ok(OutputItem::InputImage { image_url, detail })
})();
match result {
Ok(item) => Ok(item),
Err(error_text) => {
throw_type_error(scope, &error_text);
Err(())
}
}
}
fn parse_non_mcp_output_image(
scope: &mut v8::PinScope<'_, '_>,
object: v8::Local<'_, v8::Object>,
) -> Result<Option<(String, Option<String>)>, String> {
let image_url_key = v8::String::new(scope, "image_url")
.ok_or_else(|| "failed to allocate image helper keys".to_string())?;
let Some(image_url) = object.get(scope, image_url_key.into()) else {
return Ok(None);
};
if image_url.is_undefined() {
return Ok(None);
}
if !image_url.is_string() {
return Err(IMAGE_HELPER_EXPECTS_MESSAGE.to_string());
}
let detail_key = v8::String::new(scope, "detail")
.ok_or_else(|| "failed to allocate image helper keys".to_string())?;
let detail = parse_image_detail_value(scope, object.get(scope, detail_key.into()))?;
Ok(Some((image_url.to_rust_string_lossy(scope), detail)))
}
fn parse_mcp_output_image(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> Result<(String, Option<String>), String> {
let Some(result) = v8_value_to_json(scope, value)? else {
return Err(IMAGE_HELPER_EXPECTS_MESSAGE.to_string());
};
let JsonValue::Object(result) = result else {
return Err(IMAGE_HELPER_EXPECTS_MESSAGE.to_string());
};
let Some(item_type) = result.get("type").and_then(JsonValue::as_str) else {
return Err(IMAGE_HELPER_EXPECTS_MESSAGE.to_string());
};
if item_type != "image" {
return Err(format!(
"image only accepts MCP image blocks, got \"{item_type}\""
));
}
let data = result
.get("data")
.and_then(JsonValue::as_str)
.ok_or_else(|| "image expected MCP image data".to_string())?;
if data.is_empty() {
return Err("image expected MCP image data".to_string());
}
let image_url = if data.to_ascii_lowercase().starts_with("data:") {
data.to_string()
} else {
let mime_type = result
.get("mimeType")
.or_else(|| result.get("mime_type"))
.and_then(JsonValue::as_str)
.filter(|mime_type| !mime_type.is_empty())
.unwrap_or("application/octet-stream");
format!("data:{mime_type};base64,{data}")
};
let detail = result
.get("_meta")
.and_then(JsonValue::as_object)
.and_then(|meta| meta.get(AKODE_IMAGE_DETAIL_META_KEY))
.and_then(JsonValue::as_str)
.filter(|detail| matches!(*detail, "auto" | "low" | "high" | "original"))
.map(str::to_string);
Ok((image_url, detail))
}
fn parse_image_detail_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
value: Option<v8::Local<'s, v8::Value>>,
) -> Result<Option<String>, String> {
match value {
Some(value) if value.is_string() => Ok(Some(value.to_rust_string_lossy(scope))),
Some(value) if value.is_null() || value.is_undefined() => Ok(None),
Some(_) => Err("image detail must be a string when provided".to_string()),
None => Ok(None),
}
}
pub(super) fn normalize_output_audio(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> Result<OutputItem, ()> {
let result = (|| -> Result<OutputItem, String> {
let audio_url = if value.is_string() {
value.to_rust_string_lossy(scope)
} else if value.is_object() && !value.is_array() {
let object = v8::Local::<v8::Object>::try_from(value)
.map_err(|_| AUDIO_HELPER_EXPECTS_MESSAGE.to_string())?;
if let Some(audio_url) = parse_non_mcp_output_audio(scope, object)? {
audio_url
} else {
parse_mcp_output_audio(scope, value)?
}
} else {
return Err(AUDIO_HELPER_EXPECTS_MESSAGE.to_string());
};
if audio_url.is_empty() {
return Err(AUDIO_HELPER_EXPECTS_MESSAGE.to_string());
}
let Some((scheme, _)) = audio_url.split_once(':') else {
return Err(INVALID_AUDIO_URL_ERROR.to_string());
};
if !scheme.eq_ignore_ascii_case("data") {
return Err(INVALID_AUDIO_URL_ERROR.to_string());
}
// Tiny tool-generated clips cannot be encoded reliably by audio models.
if wav_duration_seconds(&audio_url).is_some_and(|duration| duration < 0.025) {
return Ok(OutputItem::InputText {
text: "Audio output omitted because the clip is shorter than 25 ms; use a longer clip."
.to_string(),
});
}
Ok(OutputItem::InputAudio { audio_url })
})();
match result {
Ok(item) => Ok(item),
Err(error_text) => {
throw_type_error(scope, &error_text);
Err(())
}
}
}
fn parse_non_mcp_output_audio(
scope: &mut v8::PinScope<'_, '_>,
object: v8::Local<'_, v8::Object>,
) -> Result<Option<String>, String> {
let audio_url_key = v8::String::new(scope, "audio_url")
.ok_or_else(|| "failed to allocate audio helper keys".to_string())?;
let Some(audio_url) = object.get(scope, audio_url_key.into()) else {
return Ok(None);
};
if audio_url.is_undefined() {
return Ok(None);
}
if !audio_url.is_string() {
return Err(AUDIO_HELPER_EXPECTS_MESSAGE.to_string());
}
Ok(Some(audio_url.to_rust_string_lossy(scope)))
}
fn parse_mcp_output_audio(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> Result<String, String> {
let Some(result) = v8_value_to_json(scope, value)? else {
return Err(AUDIO_HELPER_EXPECTS_MESSAGE.to_string());
};
let JsonValue::Object(result) = result else {
return Err(AUDIO_HELPER_EXPECTS_MESSAGE.to_string());
};
let Some(item_type) = result.get("type").and_then(JsonValue::as_str) else {
return Err(AUDIO_HELPER_EXPECTS_MESSAGE.to_string());
};
if item_type != "audio" {
return Err(format!(
"audio only accepts MCP audio blocks, got \"{item_type}\""
));
}
let data = result
.get("data")
.and_then(JsonValue::as_str)
.ok_or_else(|| "audio expected MCP audio data".to_string())?;
if data.is_empty() {
return Err("audio expected MCP audio data".to_string());
}
if data.to_ascii_lowercase().starts_with("data:") {
Ok(data.to_string())
} else {
let mime_type = result
.get("mimeType")
.or_else(|| result.get("mime_type"))
.and_then(JsonValue::as_str)
.filter(|mime_type| !mime_type.is_empty())
.unwrap_or("application/octet-stream");
Ok(format!("data:{mime_type};base64,{data}"))
}
}
pub(super) fn v8_value_to_json(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> Result<Option<JsonValue>, String> {
// Reentering V8 during termination can replace it with a catchable exception.
if scope.is_execution_terminating() {
return Err("JavaScript execution terminated".to_string());
}
// V8 stringifies undefined as the non-JSON text "undefined".
if value.is_undefined() {
return Ok(None);
}
let tc = std::pin::pin!(v8::TryCatch::new(scope));
let mut tc = tc.init();
let Some(stringified) = v8::json::stringify(&tc, value) else {
if tc.has_caught() {
return Err(tc
.exception()
.map(|exception| value_to_error_text(&mut tc, exception))
.unwrap_or_else(|| "unknown code mode exception".to_string()));
}
return Ok(None);
};
let json = stringified.to_rust_string_lossy(&tc);
// V8 emits compact JSON with these ASCII key names unescaped. The object/comma
// prefix and colon distinguish keys from string contents. Reject these before
// Serde can reinterpret them as values and bypass its normal recursion limit.
// TODO(cconger): Remove this guard once our resolved serde_json dependency
// includes the upstream private-key provenance fix. Retain regression coverage
// for literal keys, depth limits, and session recovery.
// https://github.com/cconger/json/commit/63f6f14053ef3a173013d7e5ee5ac74140736929
if [
r#"{"$serde_json::private::RawValue":"#,
r#","$serde_json::private::RawValue":"#,
r#"{"$serde_json::private::Number":"#,
r#","$serde_json::private::Number":"#,
]
.into_iter()
.any(|key| json.contains(key))
{
return Err("failed to serialize JavaScript value: reserved JSON object key".to_string());
}
serde_json::from_str(&json)
.map(Some)
.map_err(|err| format!("failed to serialize JavaScript value: {err}"))
}
pub(super) fn json_to_v8<'s>(
scope: &mut v8::PinScope<'s, '_>,
value: &JsonValue,
) -> Option<v8::Local<'s, v8::Value>> {
let json = serde_json::to_string(value).ok()?;
let json = v8::String::new(scope, &json)?;
v8::json::parse(scope, json)
}
pub(super) fn value_to_error_text(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> String {
if value.is_object()
&& let Ok(object) = v8::Local::<v8::Object>::try_from(value)
&& let Some(key) = v8::String::new(scope, "stack")
&& let Some(stack) = object.get(scope, key.into())
&& stack.is_string()
{
return stack.to_rust_string_lossy(scope);
}
// The stack getter can call exit() and V8 can clear its termination before
// returning here. Never enter a user-defined toString() after that.
if scope
.get_slot::<RuntimeState>()
.is_some_and(|state| state.exit_requested)
{
// send_scope_result reports this as successful exit and preserves prior stores.
return String::new();
}
value.to_rust_string_lossy(scope)
}
pub(super) fn throw_type_error(scope: &mut v8::PinScope<'_, '_>, message: &str) {
// Preserve V8's uncatchable termination instead of replacing it with a JS error.
if scope.is_execution_terminating() {
return;
}
if let Some(message) = v8::String::new(scope, message) {
scope.throw_exception(message.into());
}
}