diff --git a/packages/codemode-rust/crates/psychoscript/src/codemode/mod.rs b/packages/codemode-rust/crates/psychoscript/src/codemode/mod.rs index 8e4a5da5a6c..05111555ec1 100644 --- a/packages/codemode-rust/crates/psychoscript/src/codemode/mod.rs +++ b/packages/codemode-rust/crates/psychoscript/src/codemode/mod.rs @@ -5,6 +5,9 @@ pub(crate) mod hooks; pub mod openapi; pub(crate) mod program; pub(crate) mod run; +pub(crate) mod runtime; pub(crate) mod schema; pub(crate) mod search; +#[cfg(feature = "test262")] +pub mod test262; pub(crate) mod tool; diff --git a/packages/codemode-rust/crates/psychoscript/src/codemode/run.rs b/packages/codemode-rust/crates/psychoscript/src/codemode/run.rs index 85f526ee5fc..9eb4956b182 100644 --- a/packages/codemode-rust/crates/psychoscript/src/codemode/run.rs +++ b/packages/codemode-rust/crates/psychoscript/src/codemode/run.rs @@ -93,31 +93,6 @@ fn failed(error: Diagnostic) -> Outcome { } } -/// A random run id, as the reference uses a random UUID. -pub fn random_run_id() -> String { - use std::sync::atomic::{AtomicU64, Ordering}; - static COUNTER: AtomicU64 = AtomicU64::new(0); - let seed = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos() as u64) - .unwrap_or(0) - ^ COUNTER.fetch_add(0x9e37_79b9_7f4a_7c15, Ordering::Relaxed); - let mix = |mut z: u64| { - z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); - z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); - z ^ (z >> 31) - }; - let (a, b) = (mix(seed), mix(seed.wrapping_add(0x9e37_79b9_7f4a_7c15))); - format!( - "{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}", - a >> 32, - (a >> 16) & 0xffff, - a & 0x0fff, - ((b >> 48) & 0x3fff) | 0x8000, - b & 0xffff_ffff_ffff - ) -} - /// Compiles a program and sets up its run, or the outcome when it does not compile. pub fn start<'a>( rt: &'a Runtime, diff --git a/packages/codemode-rust/crates/psychoscript/src/codemode/runtime.rs b/packages/codemode-rust/crates/psychoscript/src/codemode/runtime.rs new file mode 100644 index 00000000000..5226fdf0b12 --- /dev/null +++ b/packages/codemode-rust/crates/psychoscript/src/codemode/runtime.rs @@ -0,0 +1,308 @@ +//! The runtime a host makes, the counterpart of the reference's `CodeMode.make`: its tools, extensions, hooks and +//! limits, and the outcome of a run. + +use crate::{ + ConfigError, Diagnostic, Extension, Hooks, Interrupted, Json, Limits, Program, Schema, + Snapshot, SnapshotError, Tool, ToolDescription, ToolError, from_bytes, host, run, search, tool, +}; + +/// A host tool: plain data in, plain data out. A failure is thrown into the program as an error. +pub type ToolFn = Box Result + Send + Sync>; + +#[derive(Clone, Debug)] +pub struct ToolCall { + pub path: String, + pub input: Json, +} + +#[derive(Clone, Debug)] +pub struct Outcome { + /// `Ok(value)` is JSON-safe; `undefined` becomes `null`. + pub result: Result, + /// Non-fatal diagnostics. + pub warnings: Vec, + pub logs: Vec, + /// Whether `max_output_bytes` cut the retained result or logs. + pub truncated: bool, + pub tool_calls: Vec, +} + +/// Options for one run of a runtime's program: [`Runtime::execute_with`], [`Runtime::program_with`] and +/// [`Runtime::resume_with`], the reference's `RunOptions`. +#[derive(Clone, Debug, Default)] +pub struct RunOptions { + extensions: Option>, +} + +impl RunOptions { + pub fn new() -> Self { + Self::default() + } + + /// Which of the runtime's extensions this run gets as globals, by name; all of them by default. Each must be one + /// the runtime was made with. They apply in the order the runtime has them, so the same extensions picked in any + /// order give the same globals, and resume alike. A resumed run needs the ones it started with. + pub fn extensions>(mut self, names: impl IntoIterator) -> Self { + self.extensions = Some(names.into_iter().map(Into::into).collect()); + self + } +} + +/// What a runtime shares with every run it starts. +pub(crate) struct Setup { + pub registry: tool::Registry, + pub hooks: Hooks, + pub extensions: Vec, + pub limits: Limits, +} + +impl Setup { + /// The extensions a run gets: those `options` picks, in the runtime's order, or all of them. + /// + /// # Panics + /// + /// When `options` picks an extension the runtime wasn't made with, as the reference throws a `TypeError`. + pub(crate) fn pick(&self, options: &RunOptions) -> std::rc::Rc<[&Extension]> { + self.check(options); + match &options.extensions { + None => self.extensions.iter().collect(), + Some(names) => self + .extensions + .iter() + .filter(|e| names.iter().any(|n| n == e.name())) + .collect(), + } + } + + /// Panics, as [`Setup::pick`] does, when `options` picks an extension the runtime wasn't made with. + pub(crate) fn check(&self, options: &RunOptions) { + let unknown = options + .extensions + .iter() + .flatten() + .find(|n| !self.extensions.iter().any(|e| e.name() == n.as_str())); + if let Some(name) = unknown { + panic!("Extension \"{name}\" isn't one this runtime was made with."); + } + } +} + +/// Reusable runtime: tools, extensions, hooks and limits are fixed, each `execute` is an independent run. +pub struct Runtime { + setup: Setup, +} + +impl Runtime { + pub fn new() -> Self { + Self { + setup: Setup { + registry: tool::Registry::default(), + hooks: Hooks::default(), + extensions: Vec::new(), + limits: Limits::default(), + }, + } + } + + /// Registers a tool at a dotted path, callable as `tools.(input)`; `"git.status"` is `tools.git.status`. + /// Its schemas accept anything, so its signature is `(unknown): Promise`. + /// + /// # Panics + /// + /// When the path has an empty segment. + pub fn tool( + self, + path: &str, + f: impl Fn(&Json) -> Result + Send + Sync + 'static, + ) -> Self { + self.with_tool( + path, + Tool::new("", move |input, _| f(&input).map_err(ToolError::from)) + .output(Schema::render_only(Json::Object(Default::default()))), + ) + } + + /// Registers a schema-described tool at a dotted path. A later tool at the same canonical path replaces it. + /// + /// # Panics + /// + /// When the path has an empty segment, as the reference throws from `CodeMode.make`. + pub fn with_tool(self, path: &str, tool: Tool) -> Self { + self.try_with_tool(path, tool) + .unwrap_or_else(|e| panic!("{e}")) + } + + pub fn try_with_tool(mut self, path: &str, tool: Tool) -> Result { + tool::check_path(path)?; + self.setup.registry.insert(path, tool); + Ok(self) + } + + /// Describes the namespace at a dotted path, like the reference's `Namespace.make`. The description is + /// model-visible through search: it matches every tool under the namespace. + /// + /// # Panics + /// + /// When the path has an empty segment. + pub fn namespace(mut self, path: &str, description: &str) -> Self { + if let Err(e) = tool::check_path(path) { + panic!("{e}"); + } + self.setup.registry.namespace(path, description); + self + } + + /// Adds host globals. See [`Extension`]. + /// + /// # Panics + /// + /// When a global shadows a built-in or another extension's global. + pub fn extension(self, extension: Extension) -> Self { + self.try_extension(extension) + .unwrap_or_else(|e| panic!("{e}")) + } + + pub fn try_extension(mut self, extension: Extension) -> Result { + for (name, _) in extension.globals() { + let taken = host::BUILTIN_GLOBALS.contains(&name.as_str()) + || self + .setup + .extensions + .iter() + .any(|e| e.globals().iter().any(|(n, _)| n == name)); + if taken { + return Err(ConfigError(format!( + "Extension \"{}\" global \"{name}\" is already defined.", + extension.name() + ))); + } + } + self.setup.extensions.push(extension); + Ok(self) + } + + pub fn hooks(mut self, hooks: Hooks) -> Self { + self.setup.hooks = hooks; + self + } + + /// # Panics + /// + /// When `timeout_ms` is `Some(0)`, which the reference refuses with a `RangeError`. + pub fn limits(mut self, limits: Limits) -> Self { + assert!( + limits.timeout_ms != Some(0), + "timeoutMs must be a safe integer greater than or equal to 1." + ); + self.setup.limits = limits; + self + } + + /// Every tool with its exact path, description and generated TypeScript signature, sorted by path. + pub fn catalog(&self) -> Vec { + self.setup + .registry + .entries() + .iter() + .map(tool::Entry::describe) + .collect() + } + + /// Parses, compiles and runs `code` on the calling thread, blocking on asynchronous host work. `bindings` become + /// top-level constants. An interrupted run ends with an `ExecutionFailure` saying so; [`Program::run`] tells the + /// two apart. + pub fn execute(&self, code: &str, bindings: &serde_json::Map) -> Outcome { + run::execute(self, code, bindings, &RunOptions::default()) + } + + /// [`Runtime::execute`] with [`RunOptions`], such as only some of the runtime's extensions. + /// + /// # Panics + /// + /// When `options` picks an extension this runtime wasn't made with. + pub fn execute_with( + &self, + code: &str, + bindings: &serde_json::Map, + options: &RunOptions, + ) -> Outcome { + run::execute(self, code, bindings, options) + } + + /// Runs `code` as a future on any executor. Dropping it interrupts the run and every host call in flight; a tool + /// can interrupt it too, and then it ends with [`Interrupted`]. + pub async fn execute_async( + &self, + code: &str, + bindings: &serde_json::Map, + ) -> Result { + self.program(code, bindings, None).run_async().await + } + + /// A program ready to run once; nothing runs until [`Program::run`] or [`Program::run_async`]. Host calls get the keys `:`; a random run id by default. + pub fn program<'a>( + &'a self, + code: &'a str, + bindings: &serde_json::Map, + run_id: Option<&str>, + ) -> Program<'a> { + Program::new(self, code, bindings, run_id, &RunOptions::default()) + } + + /// [`Runtime::program`] with [`RunOptions`], such as only some of the runtime's extensions. + /// + /// # Panics + /// + /// When `options` picks an extension this runtime wasn't made with. + pub fn program_with<'a>( + &'a self, + code: &'a str, + bindings: &serde_json::Map, + run_id: Option<&str>, + options: &RunOptions, + ) -> Program<'a> { + Program::new(self, code, bindings, run_id, options) + } + + /// A program continuing a suspended run, from its state or from [`to_bytes`]. It keeps the limits it was saved + /// with. Fails with a [`SnapshotError`] when the state was saved by another build, with other extensions, from a + /// source that no longer compiles the same, or is malformed. + pub fn resume(&self, state: &Snapshot) -> Result, SnapshotError> { + Program::resume(self, state, &RunOptions::default()) + } + + /// [`Runtime::resume`] with [`RunOptions`]. A run started with only some of the runtime's extensions resumes only + /// with the same ones, picked in any order. + /// + /// # Panics + /// + /// When `options` picks an extension this runtime wasn't made with. + pub fn resume_with( + &self, + state: &Snapshot, + options: &RunOptions, + ) -> Result, SnapshotError> { + Program::resume(self, state, options) + } + + /// [`Runtime::resume`] from bytes. + pub fn resume_bytes(&self, bytes: &[u8]) -> Result, SnapshotError> { + let state = from_bytes(bytes)?; + Program::resume(self, &state, &RunOptions::default()) + } + + pub(crate) fn setup(&self) -> &Setup { + &self.setup + } +} + +impl Default for Runtime { + fn default() -> Self { + Self::new() + } +} + +/// The exact callable signature of the built-in `search(...)`, for host-owned instructions. +pub fn search_signature() -> String { + search::search_signature() +} diff --git a/packages/codemode-rust/crates/psychoscript/src/language/test262.rs b/packages/codemode-rust/crates/psychoscript/src/codemode/test262.rs similarity index 100% rename from packages/codemode-rust/crates/psychoscript/src/language/test262.rs rename to packages/codemode-rust/crates/psychoscript/src/codemode/test262.rs diff --git a/packages/codemode-rust/crates/psychoscript/src/codemode/tool.rs b/packages/codemode-rust/crates/psychoscript/src/codemode/tool.rs index 529c0412228..e7b3c091d1d 100644 --- a/packages/codemode-rust/crates/psychoscript/src/codemode/tool.rs +++ b/packages/codemode-rust/crates/psychoscript/src/codemode/tool.rs @@ -3,14 +3,13 @@ use std::collections::BTreeMap; use std::fmt; use std::future::Future; -use std::pin::Pin; use std::sync::{Arc, OnceLock}; use crate::Json; use crate::schema::{self, Schema}; -/// A boxed future a host hands the runtime. `Send`, so a run can move between threads. -pub type BoxFuture<'a, T> = Pin + Send + 'a>>; +pub use crate::exec::BoxFuture; +use crate::host::RunId; /// What a tool call knows about itself: its stable idempotency key, `:`. #[derive(Clone, Debug)] @@ -19,9 +18,6 @@ pub struct ToolContext { pub(crate) call: u64, } -/// A run's id, shared by its calls and made the first time a key is read, when the host gave none. -pub(crate) type RunId = Arc>; - impl ToolContext { pub(crate) fn new(run_id: RunId, call: u64) -> Self { Self { run_id, call } @@ -29,11 +25,7 @@ impl ToolContext { /// `:`, the same at every hook. pub fn key(&self) -> String { - format!( - "{}:{}", - self.run_id.get_or_init(crate::run::random_run_id), - self.call - ) + crate::host::call_key(&self.run_id, self.call) } } diff --git a/packages/codemode-rust/crates/psychoscript/src/language/diagnostic.rs b/packages/codemode-rust/crates/psychoscript/src/language/diagnostic.rs new file mode 100644 index 00000000000..8db9e006ef4 --- /dev/null +++ b/packages/codemode-rust/crates/psychoscript/src/language/diagnostic.rs @@ -0,0 +1,53 @@ +//! What a run ends with besides its value: diagnostics and their kinds, and the limits it runs under. + +#[derive(Clone, Copy, Debug, Default)] +pub struct Limits { + pub timeout_ms: Option, + pub max_tool_calls: Option, + pub max_output_bytes: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DiagnosticKind { + ParseError, + UnsupportedSyntax, + UnknownTool, + InvalidToolInput, + InvalidToolOutput, + InvalidDataValue, + ToolCallLimitExceeded, + TimeoutExceeded, + ToolFailure, + ExecutionFailure, + /// Warning only: additional warnings were omitted by `max_output_bytes`. + Truncated, +} + +impl DiagnosticKind { + /// The reference's name for the kind, such as `"UnknownTool"`. + pub fn name(self) -> &'static str { + match self { + DiagnosticKind::ParseError => "ParseError", + DiagnosticKind::UnsupportedSyntax => "UnsupportedSyntax", + DiagnosticKind::UnknownTool => "UnknownTool", + DiagnosticKind::InvalidToolInput => "InvalidToolInput", + DiagnosticKind::InvalidToolOutput => "InvalidToolOutput", + DiagnosticKind::InvalidDataValue => "InvalidDataValue", + DiagnosticKind::ToolCallLimitExceeded => "ToolCallLimitExceeded", + DiagnosticKind::TimeoutExceeded => "TimeoutExceeded", + DiagnosticKind::ToolFailure => "ToolFailure", + DiagnosticKind::ExecutionFailure => "ExecutionFailure", + DiagnosticKind::Truncated => "Truncated", + } + } +} + +#[derive(Clone, Debug)] +pub struct Diagnostic { + pub kind: DiagnosticKind, + pub message: String, + /// 1-based line and column in the program source, when known. + pub location: Option<(u32, u32)>, + /// What the model could do about it, such as `"Use search to find available tools."`. + pub suggestions: Vec, +} diff --git a/packages/codemode-rust/crates/psychoscript/src/language/exec.rs b/packages/codemode-rust/crates/psychoscript/src/language/exec.rs index 0387809258d..37db77f4dbe 100644 --- a/packages/codemode-rust/crates/psychoscript/src/language/exec.rs +++ b/packages/codemode-rust/crates/psychoscript/src/language/exec.rs @@ -8,7 +8,8 @@ use std::sync::{Arc, Condvar, Mutex, OnceLock}; use std::task::{Context, Poll, Wake, Waker}; use std::time::Instant; -use crate::tool::BoxFuture; +/// A boxed future a host hands the runtime. `Send`, so a run can move between threads. +pub type BoxFuture<'a, T> = std::pin::Pin + Send + 'a>>; // ---------- block_on ---------- diff --git a/packages/codemode-rust/crates/psychoscript/src/language/extension.rs b/packages/codemode-rust/crates/psychoscript/src/language/extension.rs index 9fdda652be0..9dc157c6e5b 100644 --- a/packages/codemode-rust/crates/psychoscript/src/language/extension.rs +++ b/packages/codemode-rust/crates/psychoscript/src/language/extension.rs @@ -8,7 +8,7 @@ use std::fmt; use std::future::Future; use std::sync::Arc; -use crate::tool::BoxFuture; +use crate::exec::BoxFuture; /// A value on the host's side of the boundary. #[derive(Clone, Debug, Default)] diff --git a/packages/codemode-rust/crates/psychoscript/src/language/host.rs b/packages/codemode-rust/crates/psychoscript/src/language/host.rs index 083a7696f3c..ba1fa1a863d 100644 --- a/packages/codemode-rust/crates/psychoscript/src/language/host.rs +++ b/packages/codemode-rust/crates/psychoscript/src/language/host.rs @@ -174,13 +174,46 @@ pub struct ResultRoot { pub functions: std::ops::Range, } +/// A run's id, shared by its calls and made the first time a key is read, when the host gave none. +pub(crate) type RunId = Arc>; + +/// The key of a run's host call, `:`, the same at every hook. +pub(crate) fn call_key(run_id: &RunId, call: u64) -> String { + format!("{}:{}", run_id.get_or_init(random_run_id), call) +} + +/// A random run id, as the reference uses a random UUID. +pub fn random_run_id() -> String { + use std::sync::atomic::{AtomicU64, Ordering}; + static COUNTER: AtomicU64 = AtomicU64::new(0); + let seed = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos() as u64) + .unwrap_or(0) + ^ COUNTER.fetch_add(0x9e37_79b9_7f4a_7c15, Ordering::Relaxed); + let mix = |mut z: u64| { + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) + }; + let (a, b) = (mix(seed), mix(seed.wrapping_add(0x9e37_79b9_7f4a_7c15))); + format!( + "{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}", + a >> 32, + (a >> 16) & 0xffff, + a & 0x0fff, + ((b >> 48) & 0x3fff) | 0x8000, + b & 0xffff_ffff_ffff + ) +} + /// The host state of one run. pub struct RunHost<'rt> { pub setup: &'rt Setup, /// The runtime's extensions this run gets, in the runtime's order. pub extensions: std::rc::Rc<[&'rt crate::Extension]>, /// Names the run's host calls; made on first use when the host gave none. - pub(crate) run_id: crate::tool::RunId, + pub(crate) run_id: RunId, pub(crate) next_call: u64, /// The context handed to synchronous tools, its call id set for each call. ctx: Option, @@ -278,7 +311,7 @@ impl<'rt> RunHost<'rt> { id } - pub fn run_id(&mut self) -> crate::tool::RunId { + pub fn run_id(&mut self) -> RunId { self.run_id.clone() } diff --git a/packages/codemode-rust/crates/psychoscript/src/language/mod.rs b/packages/codemode-rust/crates/psychoscript/src/language/mod.rs index 2406082fa88..9f29e662ef1 100644 --- a/packages/codemode-rust/crates/psychoscript/src/language/mod.rs +++ b/packages/codemode-rust/crates/psychoscript/src/language/mod.rs @@ -8,6 +8,7 @@ pub(crate) mod compiler; pub(crate) mod conversion; pub(crate) mod convert; pub(crate) mod cross; +pub(crate) mod diagnostic; pub(crate) mod exec; pub(crate) mod extension; pub(crate) mod host; @@ -20,7 +21,5 @@ pub(crate) mod reach; pub(crate) mod snapshot; pub(crate) mod streaming; pub(crate) mod strings; -#[cfg(feature = "test262")] -pub mod test262; pub(crate) mod value; pub(crate) mod vm; diff --git a/packages/codemode-rust/crates/psychoscript/src/lib.rs b/packages/codemode-rust/crates/psychoscript/src/lib.rs index 1a8be0f11c0..4a564db7c5e 100644 --- a/packages/codemode-rust/crates/psychoscript/src/lib.rs +++ b/packages/codemode-rust/crates/psychoscript/src/lib.rs @@ -19,9 +19,12 @@ use language::{ }; pub use codemode::openapi; +pub(crate) use codemode::runtime::Setup; +pub use codemode::runtime::{Outcome, RunOptions, Runtime, ToolCall, ToolFn, search_signature}; #[cfg(feature = "test262")] #[doc(hidden)] -pub use language::test262; +pub use codemode::test262; +pub use language::diagnostic::{Diagnostic, DiagnosticKind, Limits}; pub use extension::{Extension, HostError, HostFunction, HostValue, SnapshotHooks}; pub use hooks::{CallResult, ExtensionInvocation, Hooks, ToolInvocation}; @@ -34,356 +37,3 @@ pub use tool::{ BoxFuture, ConfigError, Execute, Interrupted, Tool, ToolContext, ToolDescription, ToolError, tool_expression, }; - -/// A host tool: plain data in, plain data out. A failure is thrown into the program as an error. -pub type ToolFn = Box Result + Send + Sync>; - -#[derive(Clone, Copy, Debug, Default)] -pub struct Limits { - pub timeout_ms: Option, - pub max_tool_calls: Option, - pub max_output_bytes: Option, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum DiagnosticKind { - ParseError, - UnsupportedSyntax, - UnknownTool, - InvalidToolInput, - InvalidToolOutput, - InvalidDataValue, - ToolCallLimitExceeded, - TimeoutExceeded, - ToolFailure, - ExecutionFailure, - /// Warning only: additional warnings were omitted by `max_output_bytes`. - Truncated, -} - -impl DiagnosticKind { - /// The reference's name for the kind, such as `"UnknownTool"`. - pub fn name(self) -> &'static str { - match self { - DiagnosticKind::ParseError => "ParseError", - DiagnosticKind::UnsupportedSyntax => "UnsupportedSyntax", - DiagnosticKind::UnknownTool => "UnknownTool", - DiagnosticKind::InvalidToolInput => "InvalidToolInput", - DiagnosticKind::InvalidToolOutput => "InvalidToolOutput", - DiagnosticKind::InvalidDataValue => "InvalidDataValue", - DiagnosticKind::ToolCallLimitExceeded => "ToolCallLimitExceeded", - DiagnosticKind::TimeoutExceeded => "TimeoutExceeded", - DiagnosticKind::ToolFailure => "ToolFailure", - DiagnosticKind::ExecutionFailure => "ExecutionFailure", - DiagnosticKind::Truncated => "Truncated", - } - } -} - -#[derive(Clone, Debug)] -pub struct Diagnostic { - pub kind: DiagnosticKind, - pub message: String, - /// 1-based line and column in the program source, when known. - pub location: Option<(u32, u32)>, - /// What the model could do about it, such as `"Use search to find available tools."`. - pub suggestions: Vec, -} - -#[derive(Clone, Debug)] -pub struct ToolCall { - pub path: String, - pub input: Json, -} - -#[derive(Clone, Debug)] -pub struct Outcome { - /// `Ok(value)` is JSON-safe; `undefined` becomes `null`. - pub result: Result, - /// Non-fatal diagnostics. - pub warnings: Vec, - pub logs: Vec, - /// Whether `max_output_bytes` cut the retained result or logs. - pub truncated: bool, - pub tool_calls: Vec, -} - -/// Options for one run of a runtime's program: [`Runtime::execute_with`], [`Runtime::program_with`] and -/// [`Runtime::resume_with`], the reference's `RunOptions`. -#[derive(Clone, Debug, Default)] -pub struct RunOptions { - extensions: Option>, -} - -impl RunOptions { - pub fn new() -> Self { - Self::default() - } - - /// Which of the runtime's extensions this run gets as globals, by name; all of them by default. Each must be one - /// the runtime was made with. They apply in the order the runtime has them, so the same extensions picked in any - /// order give the same globals, and resume alike. A resumed run needs the ones it started with. - pub fn extensions>(mut self, names: impl IntoIterator) -> Self { - self.extensions = Some(names.into_iter().map(Into::into).collect()); - self - } -} - -/// What a runtime shares with every run it starts. -pub(crate) struct Setup { - pub registry: tool::Registry, - pub hooks: Hooks, - pub extensions: Vec, - pub limits: Limits, -} - -impl Setup { - /// The extensions a run gets: those `options` picks, in the runtime's order, or all of them. - /// - /// # Panics - /// - /// When `options` picks an extension the runtime wasn't made with, as the reference throws a `TypeError`. - pub(crate) fn pick(&self, options: &RunOptions) -> std::rc::Rc<[&Extension]> { - self.check(options); - match &options.extensions { - None => self.extensions.iter().collect(), - Some(names) => self - .extensions - .iter() - .filter(|e| names.iter().any(|n| n == e.name())) - .collect(), - } - } - - /// Panics, as [`Setup::pick`] does, when `options` picks an extension the runtime wasn't made with. - pub(crate) fn check(&self, options: &RunOptions) { - let unknown = options - .extensions - .iter() - .flatten() - .find(|n| !self.extensions.iter().any(|e| e.name() == n.as_str())); - if let Some(name) = unknown { - panic!("Extension \"{name}\" isn't one this runtime was made with."); - } - } -} - -/// Reusable runtime: tools, extensions, hooks and limits are fixed, each `execute` is an independent run. -pub struct Runtime { - setup: Setup, -} - -impl Runtime { - pub fn new() -> Self { - Self { - setup: Setup { - registry: tool::Registry::default(), - hooks: Hooks::default(), - extensions: Vec::new(), - limits: Limits::default(), - }, - } - } - - /// Registers a tool at a dotted path, callable as `tools.(input)`; `"git.status"` is `tools.git.status`. - /// Its schemas accept anything, so its signature is `(unknown): Promise`. - /// - /// # Panics - /// - /// When the path has an empty segment. - pub fn tool( - self, - path: &str, - f: impl Fn(&Json) -> Result + Send + Sync + 'static, - ) -> Self { - self.with_tool( - path, - Tool::new("", move |input, _| f(&input).map_err(ToolError::from)) - .output(Schema::render_only(Json::Object(Default::default()))), - ) - } - - /// Registers a schema-described tool at a dotted path. A later tool at the same canonical path replaces it. - /// - /// # Panics - /// - /// When the path has an empty segment, as the reference throws from `CodeMode.make`. - pub fn with_tool(self, path: &str, tool: Tool) -> Self { - self.try_with_tool(path, tool) - .unwrap_or_else(|e| panic!("{e}")) - } - - pub fn try_with_tool(mut self, path: &str, tool: Tool) -> Result { - tool::check_path(path)?; - self.setup.registry.insert(path, tool); - Ok(self) - } - - /// Describes the namespace at a dotted path, like the reference's `Namespace.make`. The description is - /// model-visible through search: it matches every tool under the namespace. - /// - /// # Panics - /// - /// When the path has an empty segment. - pub fn namespace(mut self, path: &str, description: &str) -> Self { - if let Err(e) = tool::check_path(path) { - panic!("{e}"); - } - self.setup.registry.namespace(path, description); - self - } - - /// Adds host globals. See [`Extension`]. - /// - /// # Panics - /// - /// When a global shadows a built-in or another extension's global. - pub fn extension(self, extension: Extension) -> Self { - self.try_extension(extension) - .unwrap_or_else(|e| panic!("{e}")) - } - - pub fn try_extension(mut self, extension: Extension) -> Result { - for (name, _) in extension.globals() { - let taken = host::BUILTIN_GLOBALS.contains(&name.as_str()) - || self - .setup - .extensions - .iter() - .any(|e| e.globals().iter().any(|(n, _)| n == name)); - if taken { - return Err(ConfigError(format!( - "Extension \"{}\" global \"{name}\" is already defined.", - extension.name() - ))); - } - } - self.setup.extensions.push(extension); - Ok(self) - } - - pub fn hooks(mut self, hooks: Hooks) -> Self { - self.setup.hooks = hooks; - self - } - - /// # Panics - /// - /// When `timeout_ms` is `Some(0)`, which the reference refuses with a `RangeError`. - pub fn limits(mut self, limits: Limits) -> Self { - assert!( - limits.timeout_ms != Some(0), - "timeoutMs must be a safe integer greater than or equal to 1." - ); - self.setup.limits = limits; - self - } - - /// Every tool with its exact path, description and generated TypeScript signature, sorted by path. - pub fn catalog(&self) -> Vec { - self.setup - .registry - .entries() - .iter() - .map(tool::Entry::describe) - .collect() - } - - /// Parses, compiles and runs `code` on the calling thread, blocking on asynchronous host work. `bindings` become - /// top-level constants. An interrupted run ends with an `ExecutionFailure` saying so; [`Program::run`] tells the - /// two apart. - pub fn execute(&self, code: &str, bindings: &serde_json::Map) -> Outcome { - run::execute(self, code, bindings, &RunOptions::default()) - } - - /// [`Runtime::execute`] with [`RunOptions`], such as only some of the runtime's extensions. - /// - /// # Panics - /// - /// When `options` picks an extension this runtime wasn't made with. - pub fn execute_with( - &self, - code: &str, - bindings: &serde_json::Map, - options: &RunOptions, - ) -> Outcome { - run::execute(self, code, bindings, options) - } - - /// Runs `code` as a future on any executor. Dropping it interrupts the run and every host call in flight; a tool - /// can interrupt it too, and then it ends with [`Interrupted`]. - pub async fn execute_async( - &self, - code: &str, - bindings: &serde_json::Map, - ) -> Result { - self.program(code, bindings, None).run_async().await - } - - /// A program ready to run once; nothing runs until [`Program::run`] or [`Program::run_async`]. Host calls get the keys `:`; a random run id by default. - pub fn program<'a>( - &'a self, - code: &'a str, - bindings: &serde_json::Map, - run_id: Option<&str>, - ) -> Program<'a> { - Program::new(self, code, bindings, run_id, &RunOptions::default()) - } - - /// [`Runtime::program`] with [`RunOptions`], such as only some of the runtime's extensions. - /// - /// # Panics - /// - /// When `options` picks an extension this runtime wasn't made with. - pub fn program_with<'a>( - &'a self, - code: &'a str, - bindings: &serde_json::Map, - run_id: Option<&str>, - options: &RunOptions, - ) -> Program<'a> { - Program::new(self, code, bindings, run_id, options) - } - - /// A program continuing a suspended run, from its state or from [`to_bytes`]. It keeps the limits it was saved - /// with. Fails with a [`SnapshotError`] when the state was saved by another build, with other extensions, from a - /// source that no longer compiles the same, or is malformed. - pub fn resume(&self, state: &Snapshot) -> Result, SnapshotError> { - Program::resume(self, state, &RunOptions::default()) - } - - /// [`Runtime::resume`] with [`RunOptions`]. A run started with only some of the runtime's extensions resumes only - /// with the same ones, picked in any order. - /// - /// # Panics - /// - /// When `options` picks an extension this runtime wasn't made with. - pub fn resume_with( - &self, - state: &Snapshot, - options: &RunOptions, - ) -> Result, SnapshotError> { - Program::resume(self, state, options) - } - - /// [`Runtime::resume`] from bytes. - pub fn resume_bytes(&self, bytes: &[u8]) -> Result, SnapshotError> { - let state = from_bytes(bytes)?; - Program::resume(self, &state, &RunOptions::default()) - } - - pub(crate) fn setup(&self) -> &Setup { - &self.setup - } -} - -impl Default for Runtime { - fn default() -> Self { - Self::new() - } -} - -/// The exact callable signature of the built-in `search(...)`, for host-owned instructions. -pub fn search_signature() -> String { - search::search_signature() -}