//! One confined psychoscript activation on the UI thread, driven as one never-returning run by an inbox pump. //! //! Linked ES modules (`opencode:entry`, `opencode:plugin`, `opencode:host`, and the plugin's files) compile once //! into a shared [`Compiled`] program off the UI thread. Each [`Activation`] starts one `'static` run with //! `Runtime::offload(false)` so every compute stretch runs directly on the UI thread under `Clock::ThreadCpu`, a //! reachable-heap cap, and crossing value bounds. use std::collections::VecDeque; use std::future::Future; use std::pin::Pin; use std::sync::{Arc, Mutex, MutexGuard}; use std::task::{Context, Poll, Waker}; use std::time::Duration; use psychoscript::{ Clock, Diagnostic, DiagnosticKind, HostFunction, HostResult, HostString, HostValue, Interrupted, Limits, Module, ProgramOptions, Run, RunOutcome, Runtime, Source, Sources, }; use super::value; /// The heap a script activation may hold, in psychoscript's reachable-bytes size model. pub const MEMORY: usize = 32 << 20; #[cfg(test)] thread_local! { static MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; } #[cfg(test)] pub(crate) fn made() -> usize { MADE.with(std::cell::Cell::get) } const OUTPUT: usize = 64 << 10; // Carrier 1 MiB source cap plus headroom for synthetic `opencode:entry`. const MAX_SOURCE_BYTES: usize = crate::source::SOURCES as usize + 4096; // Slightly above `value::MAX_DEPTH` so the pump's call envelope fits alongside a 128-level value. const VALUE_DEPTH: usize = value::MAX_DEPTH + 2; // Matches `MEMORY` so large errors/logs cross to be cut by the host while shared string DAGs stop before host OOM. const VALUE_STRING_BYTES: usize = MEMORY; // Slack so `done(token, value)` does not eat into the contract value's parts budget. const VALUE_NODES_SLACK: usize = 16; const ENTRY_MODULE: &str = "opencode:entry"; const HOST_MODULE: &str = "opencode:host"; const PLUGIN_MODULE: &str = "opencode:plugin"; const HOST_GLOBAL: &str = "__opencode_host"; fn modules(prelude: &str) -> [(&'static str, Module); 2] { [(HOST_MODULE, Module::global(HOST_GLOBAL).internal()), (PLUGIN_MODULE, Module::host_source(prelude))] } #[derive(Clone)] pub(crate) struct Compiled { id: String, files: Arc>, compiled: psychoscript::Compiled, } impl Compiled { /// Links and compiles all `.ts` (excluding `.d.ts`) and `.js` files in `sources` against `prelude`. pub(crate) fn new(sources: &crate::source::Sources, id: &str, entry: &str, prelude: &str) -> Result { let _ = sources.text(entry)?; let mut list = Vec::new(); let mut files = Vec::new(); for (path, _) in sources.files() { if !path.ends_with(".js") && !(path.ends_with(".ts") && !path.ends_with(".d.ts")) { continue; } let text = sources.text(path)?; list.push(Source::new(path, text)); files.push((path.to_owned(), text.to_owned())); } list.push(Source::host(ENTRY_MODULE, entry_source(entry))); let rt = Runtime::make() .limits(Limits { max_source_bytes: Some(MAX_SOURCE_BYTES), ..Limits::default() }) .modules(modules(prelude)); let compiled = rt.compile(&Sources::new(ENTRY_MODULE, list)).map_err(|d| format_diagnostic(id, &d, 0, MEMORY))?; Ok(Self { id: id.to_owned(), files: Arc::new(files), compiled }) } pub(crate) fn id(&self) -> &str { &self.id } } fn entry_source(entry: &str) -> String { let specifier = serde_json::to_string(&format!("./{entry}")).unwrap_or_else(|_| format!("{entry:?}")); let fallback_loc = serde_json::to_string(&format!(" ({entry}:1:1)")).unwrap_or_else(|_| format!("{entry:?}")); format!( r#"import entry from {specifier} import {{ fail, next, rawLocate, ready }} from "{HOST_MODULE}" import {{ dispatch, tasked }} from "{PLUGIN_MODULE}" const run = entry && typeof entry.setup === "function" ? entry.setup : entry const setupStack = entry && typeof entry.stack === "string" ? entry.stack : "" if (typeof run !== "function") {{ throw new TypeError("plugin entry must export default define((setup) => {{ ... }})") }} const result = run(tasked()) if (result && typeof result.then === "function") {{ const loc = rawLocate(Function.prototype.toString.call(run)) const name = run.name || "" const frame = loc ? " at " + name + " (" + loc + ")" : "" const fallback = setupStack || " at " + name + {fallback_loc} const stack = frame ? (setupStack ? frame + "\n" + setupStack : frame) : fallback fail(0, "TypeError", "plugin setup cannot wait", stack) throw new TypeError("plugin setup cannot wait") }} ready() for (;;) {{ dispatch(await next()) }} "# ) } #[derive(Debug)] pub(crate) enum CallOutcome { Done(HostValue), Waiting, } #[derive(Default)] pub(crate) struct HostBindings { pub(crate) globals: Vec<(String, HostValue)>, pub(crate) internal: Vec<(String, HostValue)>, } /// Latches an uncatchable refusal and returns `HostValue::Interrupt` to stop the activation immediately. #[derive(Clone)] pub(crate) struct Refusal(Arc>); impl Refusal { pub(crate) fn refuse(&self, reason: impl Into) -> HostValue { lock(&self.0).refused.get_or_insert_with(|| reason.into()); HostValue::Interrupt } } enum Answer { Done(HostValue), Fail(String), } #[derive(Default)] struct Shared { inbox: VecDeque, waker: Option, idle: bool, ready: bool, next_token: u64, current_token: Option, answer: Option, unhandled: Option, refused: Option, } impl Shared { fn push(&mut self, handler: u32, args: Vec) -> u64 { self.next_token += 1; let token = self.next_token; let mut message = Vec::with_capacity(args.len() + 2); message.push(Some(HostValue::Number(token as f64))); message.push(Some(HostValue::Number(f64::from(handler)))); message.extend(args.into_iter().map(Some)); self.inbox.push_back(HostValue::Array(message)); self.idle = false; if let Some(waker) = self.waker.take() { waker.wake(); } token } } struct Next(Arc>); impl Future for Next { type Output = HostResult; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let mut shared = lock(&self.0); match shared.inbox.pop_front() { Some(value) => Poll::Ready(Ok(value)), None => { shared.idle = true; shared.waker = Some(cx.waker().clone()); Poll::Pending } } } } type RunFuture = Pin> + 'static>>; pub(crate) struct Activation { id: String, slice_ms: u64, memory: usize, shared: Arc>, run_handle: Arc>>, run: Option, } impl Activation { /// Starts a new activation, running module top-levels and `setup` synchronously up to the first `await next()`. pub(crate) fn start( compiled: &Compiled, prelude: &str, limit: Duration, memory: usize, build_bindings: impl FnOnce(Refusal) -> HostBindings, ) -> Result { #[cfg(test)] MADE.with(|made| made.set(made.get() + 1)); let slice_ms = limit.as_millis().clamp(1, u128::from(u64::MAX)) as u64; let limits = Limits { timeout_ms: None, slice_ms: Some(slice_ms), clock: Clock::ThreadCpu, max_heap_bytes: Some((memory as u64).max(1)), max_output_bytes: Some(OUTPUT), max_value_depth: Some(VALUE_DEPTH), max_value_nodes: Some(value::parts_limit().saturating_add(VALUE_NODES_SLACK).max(1)), max_value_string_bytes: Some(VALUE_STRING_BYTES), max_source_bytes: Some(MAX_SOURCE_BYTES), // psychoscript's default for a run with a time limit: a regular expression's pattern of at most 64 KiB. max_regex_pattern_length: None, }; let shared = Arc::new(Mutex::new(Shared::default())); let run_handle: Arc>> = Arc::new(Mutex::new(None)); let bindings = build_bindings(Refusal(shared.clone())); let public_globals = Arc::new(bindings.globals); let extra_internal = Arc::new(bindings.internal); let id = compiled.id.clone(); let id_fail = id.clone(); let files = compiled.files.clone(); let state = shared.clone(); let run_slot = run_handle.clone(); let runtime = Runtime::make() .offload(false) .limits(limits) .modules(modules(prelude)) .globals(move |_| (*public_globals).clone()) .internal_globals(move |run| { *lock(&run_slot) = Some(run.clone()); let next_fn = HostFunction::new_async({ let s = state.clone(); move |_, _| Next(s.clone()) }) .idempotent(); let ready_fn = HostFunction::new({ let s = state.clone(); move |_, _| { lock(&s).ready = true; HostValue::Undefined } }); let done_fn = HostFunction::new({ let s = state.clone(); move |args, _| { let mut iter = args.into_iter(); let token = iter.next().and_then(|v| v.as_f64()).map(|n| n as u64).unwrap_or(0); let value = iter.next().unwrap_or(HostValue::Undefined); let mut st = lock(&s); if token != 0 && st.current_token == Some(token) { st.answer = Some(Answer::Done(value)); } HostValue::Undefined } }); let fail_fn = HostFunction::new({ let (s, id) = (state.clone(), id_fail.clone()); move |args, _| { let mut iter = args.into_iter(); let token = iter.next().and_then(|v| v.as_f64()).map(|n| n as u64).unwrap_or(0); let name = iter.next().map(lossy_string).unwrap_or_default(); let message = iter.next().map(lossy_string).unwrap_or_default(); let stack = iter.next().map(lossy_string).unwrap_or_default(); let formatted = format_js_error(&id, &name, &message, &stack); let mut st = lock(&s); if token != 0 && st.current_token == Some(token) { st.answer = Some(Answer::Fail(formatted)); } else { st.unhandled.get_or_insert(formatted); } HostValue::Undefined } }); let locate_fn = HostFunction::new({ let files = files.clone(); move |args, _| { let snippet = args.first().and_then(HostValue::as_str).unwrap_or(""); locate_unique(&files, snippet).map_or(HostValue::Undefined, HostValue::from) } }); let mut host_fields: Vec<(HostString, HostValue)> = Vec::with_capacity(5 + extra_internal.len()); host_fields.extend([ ("next".into(), HostValue::from(next_fn)), ("ready".into(), HostValue::from(ready_fn)), ("done".into(), HostValue::from(done_fn)), ("fail".into(), HostValue::from(fail_fn)), ("rawLocate".into(), HostValue::from(locate_fn)), ]); host_fields.extend(extra_internal.iter().map(|(k, v)| (k.as_str().into(), v.clone()))); [(HOST_GLOBAL.to_owned(), HostValue::Object(host_fields))] }); let program = runtime.program(&compiled.compiled, &ProgramOptions::default()); let mut activation = Self { id, slice_ms, memory, shared, run_handle, run: Some(Box::pin(program.run_resumable_async())) }; let polled = activation.poll_until_idle(); if let Some(err) = lock(&activation.shared).unhandled.take() { activation.run = None; return Err(err); } polled?; if !lock(&activation.shared).ready { activation.run = None; return Err(format!("{}: plugin setup did not finish", activation.id)); } Ok(activation) } pub(crate) fn call(&mut self, handler: u32, args: Vec) -> Result { { let mut shared = lock(&self.shared); let token = shared.push(handler, args); shared.current_token = Some(token); shared.answer = None; shared.unhandled = None; } let polled = self.poll_until_idle(); let mut shared = lock(&self.shared); shared.current_token = None; let answer = shared.answer.take(); let unhandled = shared.unhandled.take(); drop(shared); polled?; if let Some(err) = unhandled { self.run = None; return Err(err); } match answer { Some(Answer::Done(value)) => Ok(CallOutcome::Done(value)), Some(Answer::Fail(report)) => { self.run = None; Err(report) } None => Ok(CallOutcome::Waiting), } } pub(crate) fn call_sync(&mut self, handler: u32, args: Vec, kind: &str) -> Result { match self.call(handler, args)? { CallOutcome::Done(value) => Ok(value), CallOutcome::Waiting => { self.run = None; Err(format!("{}: a {kind} cannot wait", self.id)) } } } /// Polls the run until idle after settling a pending host future (such as a `client` call). pub(crate) fn poll_idle(&mut self) -> Result<(), String> { { let mut shared = lock(&self.shared); shared.current_token = None; shared.answer = None; shared.unhandled = None; } let polled = self.poll_until_idle(); let unhandled = lock(&self.shared).unhandled.take(); polled?; if let Some(err) = unhandled { self.run = None; return Err(err); } Ok(()) } pub(crate) fn heap_bytes(&self) -> Option { lock(&self.run_handle).as_ref().and_then(Run::heap_bytes) } fn poll_until_idle(&mut self) -> Result<(), String> { let Some(run) = self.run.as_mut() else { return Err(format!("{}: the script plugin has ended", self.id)); }; let mut cx = Context::from_waker(Waker::noop()); // With `offload(false)` and `next()` as the only async host function, one poll drives the entire stretch and // its promise microtasks on this thread until `next()` waits on an empty inbox. match run.as_mut().poll(&mut cx) { Poll::Pending => { let mut shared = lock(&self.shared); if let Some(reason) = shared.refused.take() { self.run = None; return Err(crate::report::format(&self.id, &reason, [])); } if shared.idle { return Ok(()); } self.run = None; Err(format!("{}: the script plugin waited on an unknown async call", self.id)) } Poll::Ready(ended) => { self.run = None; if let Some(reason) = lock(&self.shared).refused.take() { return Err(crate::report::format(&self.id, &reason, [])); } Err(match ended { Ok(RunOutcome::Done(outcome)) => match outcome.result { Err(diag) => format_diagnostic(&self.id, &diag, self.slice_ms, self.memory), Ok(_) => format!("{}: the script plugin exited unexpectedly", self.id), }, Ok(RunOutcome::Suspended(_)) => format!("{}: the script plugin suspended unexpectedly", self.id), Err(Interrupted) => format!("{}: the script plugin was interrupted", self.id), }) } } } } pub(crate) fn format_diagnostic(id: &str, diag: &Diagnostic, slice_ms: u64, memory: usize) -> String { let raw = diag.message_lossy(); let body = match &diag.kind { DiagnosticKind::SliceExceeded => format!("used over {slice_ms} ms of CPU: stopped by the script budget"), DiagnosticKind::MemoryLimitExceeded => { let cap = if memory >= (1 << 20) && memory.is_multiple_of(1 << 20) { format!("{} MiB", memory >> 20) } else { format!("{memory} bytes") }; format!("out of memory: an allocation went past its {cap} script heap cap") } _ => strip_location_suffix(&raw, diag.module.as_deref(), diag.location).to_owned(), }; let frames = diag.stack_lossy().map(|s| parse_stack_frames(&s)).unwrap_or_default(); let loc = diag .location .map(|(line, col)| { match diag.module.as_deref().filter(|m| !matches!(*m, ENTRY_MODULE | PLUGIN_MODULE | HOST_MODULE)) { Some(module) => format!("{module}:{line}:{col}"), None => format!("{line}:{col}"), } }) .or_else(|| frames.first().map(|(loc, _)| loc.clone())); let message = match loc { Some(loc) => format!("{loc}: {body}"), None => body, }; crate::report::format(id, &message, frames.iter().map(|(_, f)| f.as_str())) } pub(crate) fn format_js_error(id: &str, name: &str, message: &str, stack: &str) -> String { let frames = parse_stack_frames(stack); let headline = match (name.is_empty(), message.is_empty()) { (true, _) => message.to_owned(), (false, true) => name.to_owned(), (false, false) => format!("{name}: {message}"), }; let header = match frames.first() { Some((loc, _)) => format!("{loc}: {headline}"), None => headline, }; crate::report::format(id, &header, frames.iter().map(|(_, f)| f.as_str())) } fn parse_stack_frames(stack: &str) -> Vec<(String, String)> { let mut out = Vec::new(); for line in stack.lines() { let Some(rest) = line.trim().strip_prefix("at ") else { continue }; let (func, loc) = match rest.strip_suffix(')').and_then(|s| s.rsplit_once(" (")) { Some((func, loc)) => (Some(func), loc), None => (None, rest), }; if is_host_location(loc) { continue; } let formatted = match func { Some(func) if !func.is_empty() => format!("{loc}: in function '{func}'"), _ => loc.to_owned(), }; out.push((loc.to_owned(), formatted)); } out } fn is_host_location(loc: &str) -> bool { [ENTRY_MODULE, PLUGIN_MODULE, HOST_MODULE] .iter() .any(|m| loc == *m || loc.strip_prefix(m).is_some_and(|rest| rest.starts_with(':'))) } fn strip_location_suffix<'a>(msg: &'a str, module: Option<&str>, location: Option<(u32, u32)>) -> &'a str { let Some((line, col)) = location else { return msg }; if let Some(module) = module && let Some(stripped) = msg.strip_suffix(&format!(" ({module}:{line}:{col})")) { return stripped; } msg.strip_suffix(&format!(" (line {line}, col {col})")).unwrap_or(msg) } /// Returns `"::"` when `snippet` appears exactly once across `files`. fn locate_unique(files: &[(String, String)], snippet: &str) -> Option { if snippet.is_empty() { return None; } let mut found: Option<(&str, &str, usize)> = None; for (path, text) in files { let mut matches = text.match_indices(snippet); if let Some((offset, _)) = matches.next() { if found.is_some() || matches.next().is_some() { return None; } found = Some((path.as_str(), text.as_str(), offset)); } } let (path, text, offset) = found?; let prefix = &text[..offset]; let line = prefix.bytes().filter(|&b| b == b'\n').count() + 1; let line_start = prefix.rfind('\n').map_or(0, |i| i + 1); let col = prefix[line_start..].encode_utf16().count() + 1; Some(format!("{path}:{line}:{col}")) } fn lossy_string(value: HostValue) -> String { match value { HostValue::String(s) => s.to_string_lossy().into_owned(), HostValue::Undefined | HostValue::Null => String::new(), other => other.to_json().map(|j| j.to_string()).unwrap_or_default(), } } fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { mutex.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) }