//! Binds psychoscript setup, reads, effects, waits, `client` namespace, `console`, and `view.memo` to the linked SDK. //! //! Host functions in psychoscript must be `Send + Sync + 'static`, while the host's per-call borrows (`Read`, `Host`, //! `Setup`, `View`) live only for the active call on the UI thread, reached via thread-local slots (`CURRENT` and //! `SETTING_UP`) entered for each call and restored on drop. use std::cell::RefCell; use std::collections::{BTreeSet, HashMap}; use std::future::Future; use std::pin::Pin; use std::rc::Rc; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, mpsc}; use std::task::{Context, Poll, Waker}; use std::time::Duration; use opencode_plugin_abi::interact::{self, Handled}; use opencode_plugin_abi::{self as abi, v2}; use psychoscript::{HostError, HostFunction, HostResult, HostString, HostValue, Namespace, Resolved, Returned}; use serde::Serialize; use serde::de::DeserializeOwned; use super::value; use super::vm::{Activation, CallOutcome, Compiled, HostBindings, Refusal}; use crate::client; use crate::current::{ChangedSlot, Current, Enter, EnterChanged, Slot}; /// The host-provided `opencode:plugin` module source. pub(crate) const PRELUDE: &str = include_str!("prelude.ts"); /// The most of one `console.*` line the log keeps, in bytes of the plugin's text. pub(crate) const PRINT: usize = 4 << 10; /// The most tasks a script plugin may have parked at once across fetches, foreground runs, dialogs, timers, `all`, and /// `client` calls. const PARKED: usize = 256; /// The most JSON values freed synchronously on the UI thread; larger replies drop off-thread. const DROP_HERE: usize = 64; thread_local! { static CURRENT: Slot = const { Slot::new() }; static CURRENT_CHANGED: ChangedSlot = const { ChangedSlot::new() }; static SETTING_UP: RefCell>> = const { RefCell::new(None) }; } struct SetupGuard(Option>); impl SetupGuard { fn new(plugin: &Rc) -> Self { Self(SETTING_UP.with(|slot| slot.replace(Some(plugin.clone())))) } } impl Drop for SetupGuard { fn drop(&mut self) { SETTING_UP.with(|slot| slot.replace(self.0.take())); } } #[derive(serde::Deserialize)] struct Placement { path: String, #[serde(default = "append")] kind: abi::SlotKind, } fn append() -> abi::SlotKind { abi::SlotKind::Append } #[derive(serde::Deserialize)] struct SurfaceSpec { name: String, place: abi::SurfacePlace, #[serde(default)] layers: Vec, #[serde(default)] mounts: bool, #[serde(default)] palette: bool, } #[derive(Default)] struct TaskState { parked: usize, can_wait: bool, waits: HashMap, } enum ReplyKind { Value, Void, Client(client::Reply), } struct PendingWait { slot: Arc>, reply: ReplyKind, owner: u64, } #[derive(Default)] struct WaitSlot { result: Option, waker: Option, } struct WaitFuture(Arc>); impl Future for WaitFuture { type Output = HostResult; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let mut slot = lock(&self.0); match slot.result.take() { Some(result) => Poll::Ready(result), None => { slot.waker = Some(cx.waker().clone()); Poll::Pending } } } } /// A live script plugin activation held by its registered host callbacks. pub(crate) struct Plugin { pub(crate) vm: RefCell>, } impl Plugin { fn run(&self, current: Current, f: impl FnOnce(&mut Activation) -> Result) -> R { let called = CURRENT.with(|slot| { let _enter = Enter::new(slot, current); let result = match self.vm.try_borrow_mut() { Ok(mut guard) => match guard.as_mut() { Some(vm) => f(vm), None => Err("the plugin has ended".to_owned()), }, Err(_) => Err("re-entrant call into a running script plugin".to_owned()), }; if let Ok(host) = current.host() { host.set_owner(None); } result }); called.unwrap_or_else(|error| self.fail(error)) } fn fail(&self, error: String) -> ! { self.vm.borrow_mut().take(); std::panic::resume_unwind(Box::new(error)) } } /// Starts a script plugin activation for `compiled`, runs its `setup` against `setup`, and returns the `Plugin` held /// by the registered callbacks. pub(crate) fn setup( compiled: &Compiled, setup: &mut abi::Setup<'_>, limit: Duration, memory: usize, options: Option<&str>, ) -> Result, String> { let options_val = match options { Some(text) => { let parsed: serde_json::Value = serde_json::from_str(text).map_err(|error| format!("the plugin's options: {error}"))?; value::to_host(&parsed).map_err(|error| format!("the plugin's options: {error}"))? } None => HostValue::Undefined, }; let setup_id = setup.id().to_owned(); let tasks = Arc::new(Mutex::new(TaskState::default())); let plugin = Rc::new(Plugin { vm: RefCell::new(None) }); let _setup_guard = SetupGuard::new(&plugin); let activation = CURRENT.with(|slot| { let _enter = Enter::new(slot, Current::setting_up(setup)); Activation::start(compiled, PRELUDE, limit, memory, |refusal| { build_bindings(compiled.id(), &setup_id, options_val, refusal, tasks.clone()) }) })?; *plugin.vm.borrow_mut() = Some(activation); lock(&tasks).can_wait = true; register_wait_callbacks(setup, &plugin, &tasks); Ok(plugin) } fn build_bindings( plugin_id: &str, setup_id: &str, setup_options: HostValue, refusal: Refusal, tasks: Arc>, ) -> HostBindings { let reads: Vec<(HostString, HostValue)> = READS .iter() .map(|&(name, f)| { let refusal = refusal.clone(); let func = HostFunction::new(move |args, _| -> HostResult { f(CURRENT.with(Slot::get).read().map_err(located)?, &args, &refusal) }); (HostString::from(name), HostValue::from(func)) }) .collect(); let mut host_entries = reads.clone(); for &(name, f) in EFFECTS { let refusal = refusal.clone(); let func = HostFunction::new(move |args, _| -> HostResult { f(CURRENT.with(Slot::get).host().map_err(located)?, &args, &refusal) }); host_entries.push((HostString::from(name), HostValue::from(func))); } host_entries.push(( "fetch".into(), HostValue::from(HostFunction::new({ let (tasks, refusal) = (tasks.clone(), refusal.clone()); move |args, _| -> Returned { start_wait(&tasks, "host.fetch", |host| { Ok(host.try_fetch(decode(arg(&args, 0), &refusal)?).map(|id| (id, ReplyKind::Value))) }) } })), )); host_entries.push(( "foreground".into(), HostValue::from(HostFunction::new({ let (tasks, refusal) = (tasks.clone(), refusal.clone()); move |args, _| -> Returned { start_wait(&tasks, "host.foreground", |host| { Ok(host.try_foreground(decode(arg(&args, 0), &refusal)?).map(|id| (id, ReplyKind::Value))) }) } })), )); let sleep_fn = HostFunction::new({ let (tasks, refusal) = (tasks.clone(), refusal.clone()); move |args, _| -> Returned { start_wait(&tasks, "sleep", |host| { let ms: f64 = decode(arg(&args, 0), &refusal)?; let delay = match ms { ms if ms.is_nan() || ms <= 0.0 => Duration::ZERO, ms => Duration::try_from_secs_f64(ms / 1000.0).unwrap_or(Duration::MAX), }; Ok(host.try_timer(delay).map(|id| (id, ReplyKind::Void))) }) } }); let memo_same_fn = HostFunction::new({ let refusal = refusal.clone(); move |args, _| -> HostResult { let key = decode_str(&args, 0, &refusal)?; let val: serde_json::Value = decode(arg(&args, 1), &refusal)?; let view = CURRENT.with(Slot::get).view().ok_or_else(|| located("view.memo runs only in a view"))?; Ok(HostValue::Bool(view.memo_same(&key, &val))) } }); let raw_owner_fn = HostFunction::new(move |_, _| -> HostResult { Ok(HostValue::Number(CURRENT.with(Slot::get).host().map_err(located)?.owner() as f64)) }); let raw_set_owner_fn = HostFunction::new({ let refusal = refusal.clone(); move |args, _| -> HostResult { let owner: Option = decode_optional(arg(&args, 0), &refusal)?; CURRENT.with(Slot::get).host().map_err(located)?.set_owner(owner); Ok(HostValue::Undefined) } }); let set_can_wait_fn = HostFunction::new({ let tasks = tasks.clone(); move |args, _| { let mut state = lock(&tasks); let prev = state.can_wait; state.can_wait = matches!(arg(&args, 0), HostValue::Bool(true)); HostValue::Bool(prev) } }); let park_try_fn = HostFunction::new({ let (tasks, refusal) = (tasks.clone(), refusal.clone()); move |args, _| -> HostResult { let name = decode_str(&args, 0, &refusal)?; let park = !matches!(arg(&args, 1), HostValue::Bool(false)); check_can_wait(&tasks, &name, park)?; if park { lock(&tasks).parked += 1; } Ok(HostValue::Undefined) } }); let park_done_fn = HostFunction::new({ let tasks = tasks.clone(); move |_, _| { let mut state = lock(&tasks); state.parked = state.parked.saturating_sub(1); HostValue::Undefined } }); let task_ended_fn = HostFunction::new({ let id = plugin_id.to_owned(); move |args, _| { let name = arg(&args, 0).as_str().unwrap_or("Error"); let msg = match arg(&args, 1) { HostValue::String(s) => s.to_string_lossy().into_owned(), _ => String::new(), }; log::warn!("plugin {id}: task ended with {name}: {msg}"); HostValue::Undefined } }); let raw_changed_fn = HostFunction::new(move |args, _| -> HostResult { CURRENT_CHANGED.with(|slot| { let Some(changed) = slot.get() else { return Ok(HostValue::Undefined); }; match arg(&args, 0).as_f64().map(|n| n as u32) { Some(0) => out(&changed.sessions), Some(1) => out(&changed.lists), Some(2) => out(&changed.messages), Some(3) => out(&changed.locations), _ => Ok(HostValue::Undefined), } }) }); let mut internal = vec![ ("setupId".to_owned(), HostValue::from(setup_id)), ("setupOptions".to_owned(), setup_options), ("rawRead".to_owned(), HostValue::Object(reads)), ("rawHost".to_owned(), HostValue::Object(host_entries)), ("rawSleep".to_owned(), HostValue::from(sleep_fn)), ("rawClient".to_owned(), HostValue::from(client_namespace(tasks, refusal.clone()))), ("memoSame".to_owned(), HostValue::from(memo_same_fn)), ("rawOwner".to_owned(), HostValue::from(raw_owner_fn)), ("rawSetOwner".to_owned(), HostValue::from(raw_set_owner_fn)), ("setCanWait".to_owned(), HostValue::from(set_can_wait_fn)), ("parkTry".to_owned(), HostValue::from(park_try_fn)), ("parkDone".to_owned(), HostValue::from(park_done_fn)), ("taskEnded".to_owned(), HostValue::from(task_ended_fn)), ("rawChanged".to_owned(), HostValue::from(raw_changed_fn)), ]; for &(export, name, f) in REGISTRATIONS { let refusal = refusal.clone(); let func = HostFunction::new(move |args, _| -> HostResult { let plugin = SETTING_UP .with(|slot| slot.borrow().clone()) .ok_or_else(|| located(format!("setup.{name} registers only while setup runs")))?; let current = CURRENT.with(Slot::get); let setup = current.setup().ok_or_else(|| located(format!("setup.{name} registers only while setup runs")))?; f(&args, &refusal, &plugin, setup)?; Ok(HostValue::Undefined) }); internal.push((export.to_owned(), HostValue::from(func))); } HostBindings { globals: vec![("console".to_owned(), console_object(plugin_id))], internal } } // --- Conversion and error helpers --- fn located(message: impl Into) -> HostValue { HostError::located("Error", message) } fn named_error(kind: &str, message: impl Into) -> HostValue { HostValue::Error(Box::new(HostError::new(message).with_field("name", kind))) } fn out(value: &T) -> HostResult { value::to_host(value).map_err(|error| located(error.to_string())) } fn arg(args: &[HostValue], index: usize) -> &HostValue { static UNDEF: HostValue = HostValue::Undefined; args.get(index).unwrap_or(&UNDEF) } fn decode(value: &HostValue, refusal: &Refusal) -> Result { match value::from_host(value) { Ok(decoded) => Ok(decoded), Err(value::Error::Limit(reason)) => Err(refusal.refuse(reason)), Err(value::Error::Message(reason)) => Err(located(reason)), } } fn decode_optional(value: &HostValue, refusal: &Refusal) -> Result, HostValue> { match value { HostValue::Undefined | HostValue::Null => Ok(None), other => decode(other, refusal).map(Some), } } fn decode_str(args: &[HostValue], index: usize, refusal: &Refusal) -> Result { decode::(arg(args, index), refusal) } fn decode_opt_str(args: &[HostValue], index: usize, refusal: &Refusal) -> Result, HostValue> { decode_optional::(arg(args, index), refusal) } fn handler_id(args: &[HostValue], index: usize) -> u32 { arg(args, index).as_f64().unwrap_or(0.0) as u32 } fn decode_callback_opt(value: &HostValue) -> Result, String> { match value { HostValue::Undefined | HostValue::Null => Ok(None), other => value::from_host(other).map(Some).map_err(|error| error.to_string()), } } fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { mutex.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Drops large JSON replies on a background thread so freeing thousands of small allocations stays off the UI thread. fn drop_later(value: serde_json::Value) { static DROPS: OnceLock>> = OnceLock::new(); let mut left = DROP_HERE; if !larger(&value, &mut left) { return; } let drops = DROPS.get_or_init(|| { let (send, receive) = mpsc::channel::(); std::thread::Builder::new() .name("plugin-drop".to_owned()) .spawn(move || receive.into_iter().for_each(drop)) .ok() .map(|_| send) }); if let Some(drops) = drops { drop(drops.send(value)); } } fn larger(value: &serde_json::Value, left: &mut usize) -> bool { let Some(rest) = left.checked_sub(1) else { return true }; *left = rest; match value { serde_json::Value::Array(items) => items.iter().any(|item| larger(item, left)), serde_json::Value::Object(fields) => fields.values().any(|field| larger(field, left)), _ => false, } } // --- Unified waits and client Namespace --- fn check_can_wait(tasks: &Mutex, name: &str, check_limit: bool) -> Result<(), HostValue> { let state = lock(tasks); if !state.can_wait { return Err(located(format!( "{name} waits, and only a task can: a command's, an event's, a mount's, a layer's or a surface's handler, or spawn" ))); } if check_limit && state.parked >= PARKED { return Err(located(format!("{name}: more than {PARKED} tasks of the plugin wait"))); } Ok(()) } fn start_wait( tasks: &Arc>, name: &str, start: impl FnOnce(&dyn abi::Host) -> Result, HostValue>, ) -> Returned { if let Err(err) = check_can_wait(tasks, name, true) { return Returned::Now(Err(err)); } let host = match CURRENT.with(Slot::get).host() { Ok(host) => host, Err(err) => return Returned::Now(Err(located(err))), }; let (id, reply) = match start(host) { Ok(Ok(started)) => started, Ok(Err(why)) => return Returned::Pending(Box::pin(std::future::ready(Err(named_error("HostError", why))))), Err(err) => return Returned::Now(Err(err)), }; let owner = host.owner(); let slot = Arc::new(Mutex::new(WaitSlot::default())); let mut state = lock(tasks); state.parked += 1; state.waits.insert(id, PendingWait { slot: slot.clone(), reply, owner }); Returned::Pending(Box::pin(WaitFuture(slot))) } fn register_wait_callbacks(setup: &mut abi::Setup<'_>, plugin: &Rc, tasks: &Arc>) { let (reply_tasks, reply_plugin) = (tasks.clone(), plugin.clone()); setup.on_reply(move |host, id, result| { let Some(pending) = take_wait(&reply_tasks, id) else { if let Ok(value) = result { drop_later(value); } return; }; let outcome = match &result { Ok(body) => match pending.reply { ReplyKind::Void | ReplyKind::Client(client::Reply::Empty) => Ok(HostValue::Undefined), ReplyKind::Client(client::Reply::Data) => match body.as_object() { Some(obj) => match obj.get("data") { Some(data) => value::to_host(data).map_err(|e| named_error("HostError", e.to_string())), None => Ok(HostValue::Undefined), }, None => Err(named_error("HostError", "the reply is not an object with data")), }, ReplyKind::Value | ReplyKind::Client(_) => { value::to_host(body).map_err(|e| named_error("HostError", e.to_string())) } }, Err(err) => Err(named_error("HostError", err.as_str())), }; if let Ok(value) = result { drop_later(value); } finish_wait(&reply_plugin, host, pending, outcome); }); let (cancel_tasks, cancel_plugin) = (tasks.clone(), plugin.clone()); setup.on_cancelled(move |host, id| { let Some(pending) = take_wait(&cancel_tasks, id) else { return }; finish_wait(&cancel_plugin, host, pending, Err(named_error("AbortError", "cancelled"))); }); } fn take_wait(tasks: &Mutex, id: abi::RequestId) -> Option { let mut state = lock(tasks); let pending = state.waits.remove(&id)?; state.parked = state.parked.saturating_sub(1); Some(pending) } fn finish_wait(plugin: &Plugin, host: &dyn abi::Host, pending: PendingWait, outcome: HostResult) { { let mut slot = lock(&pending.slot); slot.result = Some(outcome); if let Some(waker) = slot.waker.take() { waker.wake(); } } host.set_owner(Some(pending.owner)); plugin.run(Current::acting(host), |vm| vm.poll_idle()); } fn client_namespace(tasks: Arc>, refusal: Refusal) -> Namespace { Namespace::new( |path| { let prefix = if path.is_empty() { String::new() } else { let joined: Vec = path.iter().map(|s| s.to_string_lossy().into_owned()).collect(); format!("{}.", joined.join(".")) }; let mut children = BTreeSet::new(); for op in client::names() { if let Some(rest) = op.strip_prefix(&prefix) && let Some(seg) = rest.split('.').next() { children.insert(seg.to_owned()); } } Ok(children.into_iter().map(HostString::from).collect()) }, move |path| { let op_name = path.iter().map(|s| s.to_string_lossy().into_owned()).collect::>().join("."); let (tasks, refusal) = (tasks.clone(), refusal.clone()); Resolved::Function(HostFunction::new(move |args, _| -> Returned { start_wait(&tasks, &format!("client.{op_name}"), |host| { let input = match arg(&args, 0) { HostValue::Undefined | HostValue::Null => serde_json::Value::Object(serde_json::Map::new()), other => decode::(other, &refusal)?, }; let (fetch, reply) = match client::request(&op_name, &input) { Ok(built) => built, Err(why) => return Ok(Err(why)), }; Ok(host.try_fetch(fetch).map(|id| (id, ReplyKind::Client(reply)))) }) })) }, ) } // --- Registrations --- type RegFn = fn(&[HostValue], &Refusal, &Rc, &mut abi::Setup<'static>) -> Result<(), HostValue>; fn call_render( vm: &mut Activation, handler: u32, mut args: Vec, changed: &abi::Changed, ) -> Result { let flags = u32::from(changed.all) | (u32::from(changed.local) << 1) | (u32::from(changed.size) << 2) | (u32::from(changed.woken) << 3) | (u32::from(!changed.sessions.is_empty()) << 4) | (u32::from(!changed.lists.is_empty()) << 5) | (u32::from(!changed.messages.is_empty()) << 6) | (u32::from(!changed.locations.is_empty()) << 7); args.push(HostValue::Number(f64::from(flags))); let val = CURRENT_CHANGED.with(|slot| { let _guard = EnterChanged::new(slot, changed); vm.call_sync(handler, args, "render") })?; Ok(decode_callback_opt::(&val)?.unwrap_or(abi::Render::Hide)) } fn handle_event(plugin: &Rc, handler: u32, host: &dyn abi::Host, event: &interact::Event) -> Handled { plugin.run(Current::acting(host), |vm| { let event_val = value::to_host(event).map_err(|error| error.to_string())?; match vm.call(handler, vec![event_val])? { CallOutcome::Done(val) => Ok(decode_callback_opt::(&val)?.unwrap_or(Handled::Pass)), CallOutcome::Waiting => Ok(Handled::Consume), } }) } const REGISTRATIONS: &[(&str, &str, RegFn)] = &[ ("regStorageKey", "storageKey", |args, rf, _, setup| { setup.storage_key(&decode_str(args, 0, rf)?); Ok(()) }), ("regCommand", "command", |args, rf, plugin, setup| { let serde_json::Value::Object(given) = decode::(arg(args, 0), rf)? else { return Err(located("setup.command spec must be an object")); }; let mut whole = serde_json::to_value(abi::Command::default()).map_err(|e| located(e.to_string()))?; if let Some(whole) = whole.as_object_mut() { whole.extend(given); } let command: abi::Command = serde_json::from_value(whole).map_err(|e| located(e.to_string()))?; let handler = handler_id(args, 1); let plugin = plugin.clone(); setup.command(command, move |host, input| { plugin.run(Current::acting(host), |vm| { let arg = input.map(HostValue::from).unwrap_or(HostValue::Undefined); match vm.call(handler, vec![arg])? { CallOutcome::Done(val) => Ok(decode_callback_opt::(&val)?.unwrap_or(Handled::Consume)), CallOutcome::Waiting => Ok(Handled::Consume), } }) }); Ok(()) }), ("regSlot", "slot", |args, rf, plugin, setup| { let at: Placement = decode(arg(args, 0), rf)?; let handler = handler_id(args, 1); let plugin = plugin.clone(); setup.slot(abi::Placement::new(at.kind, at.path), move |read, slot, changed| { plugin.run(Current::reading(read), |vm| { let slot_val = value::to_host(slot).map_err(|e| e.to_string())?; call_render(vm, handler, vec![slot_val], changed) }) }); Ok(()) }), ("regOnMount", "onMount", |args, rf, plugin, setup| { let at: Placement = decode(arg(args, 0), rf)?; let handler = handler_id(args, 1); let plugin = plugin.clone(); setup.on_mount(abi::Placement::new(at.kind, at.path), move |host, slot, mounted| { plugin.run(Current::acting(host), |vm| { let slot_val = value::to_host(slot).map_err(|e| e.to_string())?; vm.call(handler, vec![slot_val, HostValue::Bool(mounted)]).map(drop) }); }); Ok(()) }), ("regRoute", "route", |args, rf, plugin, setup| { let name = decode_str(args, 0, rf)?; let handler = handler_id(args, 1); let plugin = plugin.clone(); setup.route(&name, move |read, changed| { plugin.run(Current::reading(read), |vm| call_render(vm, handler, Vec::new(), changed)) }); Ok(()) }), ("regOnRouteMount", "onRouteMount", |args, rf, plugin, setup| { let name = decode_str(args, 0, rf)?; let handler = handler_id(args, 1); let plugin = plugin.clone(); setup.on_route_mount(&name, move |host, mounted| { plugin.run(Current::acting(host), |vm| vm.call(handler, vec![HostValue::Bool(mounted)]).map(drop)); }); Ok(()) }), ("regCodeBlock", "codeBlock", |args, rf, plugin, setup| { let language = decode_str(args, 0, rf)?; let handler = handler_id(args, 1); let plugin = plugin.clone(); setup.code_block(&language, move |read, fence| { plugin.run(Current::reading(read), |vm| { let fence_val = value::to_host(fence).map_err(|e| e.to_string())?; let val = vm.call_sync(handler, vec![fence_val], "codeBlock")?; Ok(decode_callback_opt::(&val)?.unwrap_or(abi::Fenced::Code)) }) }); Ok(()) }), ("regOnEvent", "onEvent", |args, rf, plugin, setup| { let types: Vec = decode(arg(args, 0), rf)?; let handler = handler_id(args, 1); let plugin = plugin.clone(); let refs: Vec<&str> = types.iter().map(String::as_str).collect(); setup.on_event(&refs, move |host, event| { plugin.run(Current::acting(host), |vm| { let event_val = value::to_host(event).map_err(|e| e.to_string())?; vm.call(handler, vec![event_val]).map(drop) }); }); Ok(()) }), ("regOnDispose", "onDispose", |args, _, plugin, setup| { let handler = handler_id(args, 0); let plugin = plugin.clone(); setup.on_dispose(move |host| { plugin.run(Current::acting(host), |vm| vm.call_sync(handler, vec![], "onDispose").map(drop)); }); Ok(()) }), ("regLayer", "layer", |args, rf, plugin, setup| { let layer: interact::Layer = decode(arg(args, 0), rf)?; let handler = handler_id(args, 1); let plugin = plugin.clone(); setup.layer(layer, move |host, event| handle_event(&plugin, handler, host, event)); Ok(()) }), ("regSurface", "surface", |args, rf, plugin, setup| { let spec: SurfaceSpec = decode(arg(args, 0), rf)?; let view_handler = handler_id(args, 1); let event_handler = match arg(args, 2) { HostValue::Undefined | HostValue::Null => None, _ => Some(handler_id(args, 2)), }; let viewing = plugin.clone(); let mut surface = v2::Surface::new(spec.name, (&spec.place).into(), move |surface| { let surface_input = surface.input; let raw = viewing.run(Current::viewing(surface), |vm| { let input_val = value::to_host(surface_input).map_err(|e| e.to_string())?; vm.call_sync(view_handler, vec![input_val], "view") }); let decoded = if has_memo(&raw, 0) { decode_memo_node(surface, &raw, 0) } else { value::from_host(&raw) }; decoded.unwrap_or_else(|error| viewing.fail(error.to_string())) }) .layers(spec.layers); if spec.mounts { surface = surface.mounts(); } if spec.palette { surface = surface.palette(); } if let Some(handler) = event_handler { let acting = plugin.clone(); surface = surface.on(move |host, event| handle_event(&acting, handler, host, event)); } setup.surface(surface); Ok(()) }), ]; // --- View memo replay --- fn has_memo(value: &HostValue, depth: usize) -> bool { if depth > value::MAX_DEPTH { return false; } let HostValue::Object(_) = value else { return false }; if value.get("type").and_then(HostValue::as_str) == Some("memo") { return true; } if let Some(HostValue::Array(list)) = value.get("children") && list.iter().flatten().any(|child| has_memo(child, depth + 1)) { return true; } if let Some(HostValue::Array(list)) = value.get("items") { return list.iter().flatten().any(|item| item.get("node").is_some_and(|node| has_memo(node, depth + 1))); } false } fn with_field(fields: &[(HostString, HostValue)], name: &str, replacement: HostValue) -> HostValue { HostValue::Object( fields .iter() .map(|(k, v)| if k == name { (k.clone(), replacement.clone()) } else { (k.clone(), v.clone()) }) .collect(), ) } fn decode_memo_node(surface: &mut v2::View<'_>, raw: &HostValue, depth: usize) -> Result { if depth > value::MAX_DEPTH { return Err(value::Error::Limit(format!( "the plugin's value is refused: nested deeper than {} levels", value::MAX_DEPTH ))); } let HostValue::Object(fields) = raw else { return value::from_host(raw); }; let kind = raw.get("type").and_then(HostValue::as_str); if kind == Some("memo") { let key: String = value::from_host(raw.get("key").unwrap_or(&HostValue::Undefined))?; let val: serde_json::Value = value::from_host(raw.get("value").unwrap_or(&HostValue::Undefined))?; let inner_node = raw.get("node"); let mut failed: Option = None; let node = surface.memo(key, val, |inner| match inner_node { Some(node_val) => decode_memo_node(inner, node_val, depth + 1).unwrap_or_else(|error| { failed = Some(error); v2::Node::column(Vec::new()) }), None => { failed = Some(value::Error::Message("memo placeholder is missing its built node".to_owned())); v2::Node::column(Vec::new()) } }); return match failed { Some(error) => Err(error), None => Ok(node), }; } if matches!(kind, Some("box" | "scroll")) && let Some(HostValue::Array(raw_children)) = raw.get("children") && raw_children.iter().flatten().any(|child| has_memo(child, depth + 1)) { let mut decoded_children = Vec::with_capacity(raw_children.len()); for child in raw_children { decoded_children.push(decode_memo_node( surface, child.as_ref().unwrap_or(&HostValue::Undefined), depth + 1, )?); } let mut parent: v2::Node = value::from_host(&with_field(fields, "children", HostValue::Array(Vec::new())))?; if let v2::Node::Box { children, .. } | v2::Node::Scroll { children, .. } = &mut parent { *children = decoded_children; } return Ok(parent); } if kind == Some("list") && let Some(HostValue::Array(raw_items)) = raw.get("items") && raw_items.iter().flatten().any(|item| item.get("node").is_some_and(|node| has_memo(node, depth + 1))) { let placeholder = HostValue::object([("type", HostValue::from("keep")), ("key", HostValue::from(""))]); let mut decoded_nodes = Vec::with_capacity(raw_items.len()); let mut shell_items = Vec::with_capacity(raw_items.len()); for item in raw_items { let item_val = item.as_ref().unwrap_or(&HostValue::Undefined); let HostValue::Object(item_fields) = item_val else { return value::from_host(raw); }; decoded_nodes.push(decode_memo_node( surface, item_val.get("node").unwrap_or(&HostValue::Undefined), depth + 1, )?); shell_items.push(Some(with_field(item_fields, "node", placeholder.clone()))); } let mut list: v2::Node = value::from_host(&with_field(fields, "items", HostValue::Array(shell_items)))?; if let v2::Node::List { items, .. } = &mut list { for (item, node) in items.iter_mut().zip(decoded_nodes) { item.node = node; } } return Ok(list); } value::from_host(raw) } // --- 34 reads & 27 sync effects --- type ReadFn = fn(&dyn abi::Read, &[HostValue], &Refusal) -> HostResult; type EffectFn = fn(&dyn abi::Host, &[HostValue], &Refusal) -> HostResult; const READS: &[(&str, ReadFn)] = &[ ("themeMode", |r, _, _| { out(match r.theme_mode() { abi::ThemeMode::Dark => "dark", abi::ThemeMode::Light => "light", }) }), ("color", |r, a, rf| out(&r.color(&decode_str(a, 0, rf)?))), ("storageGet", |r, a, rf| out(&r.storage_get(&decode_str(a, 0, rf)?))), ("session", |r, a, rf| out(&r.session(&decode_str(a, 0, rf)?))), ("sessions", |r, _, _| out(&r.sessions())), ("family", |r, a, rf| out(&r.family(&decode_str(a, 0, rf)?))), ("messages", |r, a, rf| { let id = decode_str(a, 0, rf)?; let mut result = Ok(HostValue::Null); r.messages(&id, &mut |messages| result = out(messages)); result }), ("pending", |r, a, rf| out(&r.pending(&decode_str(a, 0, rf)?))), ("models", |r, a, rf| out(&r.models(decode_optional::(arg(a, 0), rf)?.as_ref()).as_deref())), ("providers", |r, a, rf| { out(&r.providers(decode_optional::(arg(a, 0), rf)?.as_ref()).as_deref()) }), ("limits", |r, _, _| out(&r.limits())), ("model", |r, _, _| out(&r.model())), ("info", |r, _, _| out(&r.info())), ("route", |r, _, _| out(&r.route())), ("interactive", |r, _, _| out(&r.interactive())), ("shortcut", |r, a, rf| out(&r.shortcut(&decode_str(a, 0, rf)?))), ("dialogOpen", |r, a, rf| out(&r.dialog_open(&decode_str(a, 0, rf)?))), ("keymapPending", |r, _, _| out(&r.keymap_pending())), ("composer", |r, _, _| out(&r.composer())), ("tabs", |r, _, _| out(&r.tabs())), ("tabsEnabled", |r, _, _| out(&r.tabs_enabled())), ("theme", |r, _, _| out(&r.theme())), ("themes", |r, _, _| out(&r.themes())), ("selection", |r, _, _| out(&r.selection())), ("rect", |r, a, rf| out(&r.rect(&decode_str(a, 0, rf)?))), ("focused", |r, _, _| out(&r.focused())), ("mode", |r, _, _| out(&r.mode())), ("mount", |r, _, _| out(&r.mount())), ("setting", |r, a, rf| out(&r.setting(&decode_str(a, 0, rf)?))), ("plugins", |r, _, _| out(&r.plugins())), ("abi", |r, _, _| { let abi = r.abi(); out(&serde_json::json!({ "major": abi.major, "minor": abi.minor, "features": abi.features })) }), ("hasFeature", |r, a, rf| out(&r.abi().has_feature(&decode_str(a, 0, rf)?))), ("utcOffset", |r, a, rf| out(&r.utc_offset(decode::(arg(a, 0), rf)? as i64))), ("measure", |r, a, rf| out(&r.measure(&decode_str(a, 0, rf)?))), ]; macro_rules! void_effect { ($name:literal, |$h:ident, $a:pat_param, $rf:pat_param| $body:expr) => { ($name, |$h, $a, $rf| { $body; Ok(HostValue::Undefined) }) }; } const EFFECTS: &[(&str, EffectFn)] = &[ void_effect!("storageSet", |h, a, rf| h.storage_set(&decode_str(a, 0, rf)?, decode(arg(a, 1), rf)?)), void_effect!("storageMerge", |h, a, rf| h.storage_merge(&decode_str(a, 0, rf)?, decode(arg(a, 1), rf)?)), void_effect!("dispatch", |h, a, rf| h.dispatch(&decode_str(a, 0, rf)?, decode_opt_str(a, 1, rf)?.as_deref())), void_effect!("setEnabled", |h, a, rf| h.set_enabled(&decode_str(a, 0, rf)?, decode(arg(a, 1), rf)?)), void_effect!("toast", |h, a, rf| h.toast(decode(arg(a, 0), rf)?)), void_effect!("attention", |h, a, rf| h.attention(decode(arg(a, 0), rf)?)), void_effect!("openRoute", |h, a, rf| h.open_route(&decode_str(a, 0, rf)?)), void_effect!("navigate", |h, a, rf| h.navigate(decode(arg(a, 0), rf)?)), void_effect!("dialog", |h, a, rf| h.dialog(decode(arg(a, 0), rf)?)), void_effect!("copy", |h, a, rf| h.copy(&decode_str(a, 0, rf)?, decode_optional(arg(a, 1), rf)?)), void_effect!("editComposer", |h, a, rf| h.edit_composer(decode(arg(a, 0), rf)?)), void_effect!("setTitle", |h, a, rf| h.set_title(&decode_str(a, 0, rf)?)), ("setVariant", |h, a, rf| Ok(HostValue::Bool(h.set_variant(decode_opt_str(a, 0, rf)?.as_deref())))), void_effect!("setModel", |h, a, rf| h.set_model(&decode_str(a, 0, rf)?, &decode_str(a, 1, rf)?)), ("editTab", |h, a, rf| Ok(HostValue::Bool(h.edit_tab(decode(arg(a, 0), rf)?)))), void_effect!("clearSelection", |h, _, _| h.clear_selection()), ("setTheme", |h, a, rf| Ok(HostValue::Bool(h.set_theme(&decode_str(a, 0, rf)?)))), void_effect!("setSetting", |h, a, rf| h.set_setting(&decode_str(a, 0, rf)?, decode(arg(a, 1), rf)?)), void_effect!("scroll", |h, a, rf| h.scroll(decode(arg(a, 0), rf)?, decode(arg(a, 1), rf)?)), void_effect!("openPanel", |h, a, rf| h.open_panel(decode(arg(a, 0), rf)?)), void_effect!("closePanel", |h, a, rf| h.close_panel(&decode_str(a, 0, rf)?)), void_effect!("overlay", |h, a, rf| h.overlay(decode(arg(a, 0), rf)?)), void_effect!("closeOverlay", |h, a, rf| h.close_overlay(&decode_str(a, 0, rf)?)), void_effect!("focus", |h, a, rf| h.focus(&decode_str(a, 0, rf)?)), void_effect!("blur", |h, _, _| h.blur()), void_effect!("setMode", |h, a, rf| h.set_mode(decode_opt_str(a, 0, rf)?.as_deref())), void_effect!("releaseKeys", |h, _, _| h.release_keys()), ]; // --- console --- fn console_object(id: &str) -> HostValue { HostValue::Object( ["log", "info", "warn", "error", "debug"] .into_iter() .map(|method| { let id = id.to_owned(); let func = HostFunction::new(move |args, _| { log_console(&id, &args); HostValue::Undefined }); (HostString::from(method), HostValue::from(func)) }) .collect(), ) } fn log_console(id: &str, args: &[HostValue]) { let (mut kept, mut total) = (Vec::new(), 0usize); let mut keep = |part: &[u8]| { kept.extend_from_slice(&part[..part.len().min(PRINT - kept.len())]); total += part.len(); }; for (index, value) in args.iter().enumerate() { if index > 0 { keep(b" "); } match value { HostValue::String(text) => keep(text.to_string_lossy().as_bytes()), HostValue::Undefined => keep(b"undefined"), HostValue::Null => keep(b"null"), HostValue::Bool(b) => keep(if *b { b"true" } else { b"false" }), HostValue::Number(n) => keep(n.to_string().as_bytes()), other => { let formatted = other.to_json().map(|j| j.to_string()).unwrap_or_else(|| format!("{other:?}")); keep(formatted.as_bytes()); } } } let line: String = String::from_utf8_lossy(&kept) .chars() .flat_map(|ch| if ch.is_control() { ch.escape_default().collect::>() } else { vec![ch] }) .collect(); if total > PRINT { log::info!("plugin {id} printed: {line}... ({total} bytes, cut at {PRINT})"); return; } log::info!("plugin {id} printed: {line}"); } #[cfg(test)] mod tests { use std::collections::BTreeSet; use super::*; const WAITS: &[&str] = &["fetch", "foreground", "select", "prompt", "confirm", "alert"]; #[test] fn script_stub_matches_bindings() { let stub = include_str!("opencode-plugin.d.ts"); let reads = ts_interface_methods(stub, "export interface Read {"); let host = ts_interface_methods(stub, "export interface Host extends Read {"); let expected_reads: BTreeSet<&str> = READS.iter().map(|&(name, _)| name).collect(); let expected_host: BTreeSet<&str> = EFFECTS.iter().map(|&(name, _)| name).chain(WAITS.iter().copied()).collect(); assert_eq!(expected_reads.len(), READS.len(), "duplicate name in READS"); assert_eq!(expected_host.len(), EFFECTS.len() + WAITS.len(), "duplicate name in EFFECTS + WAITS"); assert_eq!(reads, expected_reads, "Read interface in opencode-plugin.d.ts drifted from READS"); assert_eq!(host, expected_host, "Host interface in opencode-plugin.d.ts drifted from EFFECTS + WAITS"); } fn ts_interface_methods<'a>(stub: &'a str, header: &str) -> BTreeSet<&'a str> { let mut lines = stub.lines(); assert!(lines.any(|line| line.trim() == header), "missing `{header}` in opencode-plugin.d.ts"); let mut names = BTreeSet::new(); for line in lines { if line == " }" { break; } if let Some(rest) = line.strip_prefix(" ") && let Some((name, _)) = rest.split_once('(') && !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { assert!(names.insert(name), "duplicate method `{name}` in `{header}`"); } } names } }