Skip to main content

base/interface/
script.rs

1//! `ScriptEngine` — the cheap tier of extension backend.
2//!
3//! A hook point today can be answered three ways: a Rust implementation
4//! compiled in, a command hook that pays for a subprocess, or a prompt hook
5//! that pays for a model call. There is nothing between "recompile the engine"
6//! and "spawn a process", so doing something small at a hook point — rewrite
7//! one line of a prompt, tag a tool result, decide whether to retry — costs
8//! either a release or several milliseconds and a PID.
9//!
10//! This is the missing tier: run a piece of the operator's own code, in this
11//! process, in microseconds.
12//!
13//! # The engine is a separate crate, behind a feature
14//!
15//! This module is the contract and the governance around it, never an
16//! interpreter: `base` has no internal dependencies and linking a JavaScript
17//! runtime into it would put one in every build of everything. `script-host`
18//! is the carrier crate — the `ScriptCarrier` that enforces the budget, the
19//! adapters for the bindable points and QuickJS behind this trait — and it is
20//! an optional dependency of `daemon` under the `scripts` feature.
21//!
22//! [`RefusingEngine`] is what runs when a host wired nothing, and
23//! [`FnScriptEngine`] gives a host the governance around logic written in
24//! Rust.
25//!
26//! # Governance is outside the engine
27//!
28//! The timeout and the call quota are enforced by `script_host::carrier::ScriptCarrier`,
29//! on this side of the trait, because an engine that enforced its own limits would be
30//! an engine that could choose not to. What the carrier *cannot* do from here
31//! is stop a script that never yields: `tokio::time::timeout` abandons a
32//! future, it does not interrupt a busy loop. An engine implementation must
33//! provide its own interruption — every serious one has a fuel or watchdog
34//! mechanism — and the carrier's timeout is the second line, not the first.
35
36use std::path::PathBuf;
37use std::sync::atomic::Ordering;
38use std::time::Duration;
39
40use async_trait::async_trait;
41use serde::{Deserialize, Serialize};
42
43use crate::prompt::BlockOrigin;
44
45/// One script, bound to one extension point.
46///
47/// ```jsonc
48/// "scripts": [
49///   { "path": ".agix/scripts/prompt.js", "point": "prompt.assemble", "entry": "onAssemble" }
50/// ]
51/// ```
52///
53/// The point is a catalog id — see `base::interface::catalog` and
54/// `docs/extension_points.md`. A binding naming a point the engine does not
55/// have, or one scripts may not use, is refused at startup with a message
56/// saying which; it is not silently ignored, because a script that quietly
57/// never runs is worse than one that fails to load.
58///
59/// Authority follows the file's location, not the configuration: a script
60/// inside the project is the operator's own and may rewrite anything, while
61/// one that arrived with a plugin may add. Nothing in this struct can change
62/// that, which is deliberate — it would otherwise be a field a plugin could
63/// set for itself.
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
65pub struct ScriptBinding {
66    /// Path to the script, relative to the project root or absolute.
67    pub path: PathBuf,
68    /// Which extension point, by its catalog id.
69    pub point: String,
70    /// The function the script exports.
71    pub entry: String,
72    /// Wall clock for one call. Defaults to the carrier's own budget.
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub timeout_ms: Option<u64>,
75    /// How many times it may run in a turn. Defaults to the carrier's.
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub calls_per_turn: Option<u32>,
78}
79
80/// A piece of code to run, and whose it is.
81#[derive(Debug, Clone)]
82pub struct ScriptSource {
83    /// What to call this in errors and logs — usually its path.
84    pub id: String,
85    /// Whose code this is. Decides what it is allowed to do at a hook point;
86    /// see [`crate::interface::prompt_assembly::Authority`].
87    pub origin: BlockOrigin,
88    pub code: String,
89}
90
91/// What a script may spend.
92#[derive(Debug, Clone, Copy)]
93pub struct ScriptLimits {
94    /// Wall clock for one call.
95    pub timeout: Duration,
96    /// How many times it may run in a turn. Bounds a hook that is called per
97    /// tool result from turning a pathological turn into a pathological bill.
98    pub calls_per_turn: u32,
99}
100
101impl Default for ScriptLimits {
102    fn default() -> Self {
103        Self {
104            // Generous for the work this tier is for — a string rewrite, a
105            // decision — and short enough that a stuck script is a hiccup
106            // rather than an outage.
107            timeout: Duration::from_millis(100),
108            calls_per_turn: 1_000,
109        }
110    }
111}
112
113#[derive(Debug, Clone, PartialEq, Eq)]
114#[non_exhaustive]
115pub enum ScriptError {
116    /// No engine is available to run it.
117    NoEngine,
118    /// It ran too long and was abandoned.
119    TimedOut { after: Duration },
120    /// It has already run as often as it may this turn.
121    QuotaExhausted { calls_per_turn: u32 },
122    /// The engine refused or the script failed.
123    Failed(String),
124}
125
126impl std::fmt::Display for ScriptError {
127    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128        match self {
129            Self::NoEngine => f.write_str(
130                "no script engine is available in this build; a host supplies one through \
131                 `script_host`",
132            ),
133            Self::TimedOut { after } => write!(f, "script exceeded its {after:?} budget"),
134            Self::QuotaExhausted { calls_per_turn } => {
135                write!(f, "script already ran {calls_per_turn} times this turn")
136            }
137            Self::Failed(e) => write!(f, "script failed: {e}"),
138        }
139    }
140}
141
142/// Runs a script.
143///
144/// One call, one entry point, JSON in and JSON out — the same shape a command
145/// hook already speaks, so a hook point does not need a second input contract
146/// to gain a second backend.
147#[async_trait]
148pub trait ScriptEngine: Send + Sync {
149    /// Call `entry` in `script` with `input`.
150    ///
151    /// Implementations must be able to interrupt a script that does not
152    /// return — see the module docs. `limits` is passed for that reason, not
153    /// so the engine can decide whether to honor it; the carrier enforces the
154    /// same budget from outside regardless.
155    async fn eval(
156        &self,
157        script: &ScriptSource,
158        entry: &str,
159        input: serde_json::Value,
160        limits: &ScriptLimits,
161    ) -> Result<serde_json::Value, ScriptError>;
162
163    /// The same call, from somewhere that cannot await.
164    ///
165    /// Most hook points are synchronous by contract and always will be: a
166    /// prompt variable provider is a plain `Fn`, a tool-result transformer
167    /// takes `&self` and returns nothing. The calling thread waits for the
168    /// script, so an engine must not let it wait much past `limits.timeout`,
169    /// whatever the script is doing. An engine
170    /// whose work is genuinely asynchronous should not implement this; the
171    /// default refuses rather than blocking a runtime from inside itself.
172    fn eval_blocking(
173        &self,
174        _script: &ScriptSource,
175        _entry: &str,
176        _input: serde_json::Value,
177        _limits: &ScriptLimits,
178    ) -> Result<serde_json::Value, ScriptError> {
179        Err(ScriptError::Failed(
180            "this script engine cannot be called from a synchronous hook point".into(),
181        ))
182    }
183}
184
185/// The engine when there is none.
186///
187/// Every call fails, with a message that says what is missing rather than
188/// what went wrong. A hook point wired to scripts in a build with no engine
189/// should be inert and legible, not mysterious.
190pub struct RefusingEngine;
191
192#[async_trait]
193impl ScriptEngine for RefusingEngine {
194    async fn eval(
195        &self,
196        _script: &ScriptSource,
197        _entry: &str,
198        _input: serde_json::Value,
199        _limits: &ScriptLimits,
200    ) -> Result<serde_json::Value, ScriptError> {
201        Err(ScriptError::NoEngine)
202    }
203}
204
205/// An "engine" that is a Rust closure.
206///
207/// The second implementation the contract needs, and not only for tests: a
208/// host that wants the hook-point plumbing — the quota, the budget, the
209/// origin-based authority — without an interpreter can express its logic
210/// natively and get all of it.
211pub struct FnScriptEngine<F>(pub F);
212
213#[async_trait]
214impl<F, Fut> ScriptEngine for FnScriptEngine<F>
215where
216    F: Fn(&ScriptSource, &str, serde_json::Value) -> Fut + Send + Sync,
217    Fut: std::future::Future<Output = Result<serde_json::Value, ScriptError>> + Send,
218{
219    async fn eval(
220        &self,
221        script: &ScriptSource,
222        entry: &str,
223        input: serde_json::Value,
224        _limits: &ScriptLimits,
225    ) -> Result<serde_json::Value, ScriptError> {
226        (self.0)(script, entry, input).await
227    }
228}
229
230/// What one script call did, once the point it was bound to had its say.
231///
232/// The distinction the outcomes exist to draw: a script that ran and asked for
233/// nothing, a script that never ran, and a script that asked for something it
234/// may not do all leave the engine in the same state. Only a record can tell
235/// them apart, and "the extension is inert" versus "the extension is being
236/// held back" is exactly the question an operator asks.
237#[derive(Debug, Clone, PartialEq, Eq)]
238pub enum ScriptOutcome {
239    /// The script ran and the point took its answer.
240    ///
241    /// Taken, not necessarily different: a script that answers with the value
242    /// a field already holds still gets this. What a point can honestly report
243    /// is whether it acted on what it was told, and an observer script that
244    /// deliberately changes nothing should still read as having run.
245    Applied,
246    /// The script ran and the point is as it was — because the script asked
247    /// for no change, or because it answered in a shape this point cannot act
248    /// on. Those two are one outcome on purpose: most points define them to
249    /// mean the same thing, and `detail` says which it was where the point
250    /// can tell.
251    NoChange { detail: Option<String> },
252    /// The call itself did not complete.
253    Failed { error: ScriptError },
254    /// The script asked for something its origin does not permit. One record
255    /// per refused edit, so a pass that was half permitted reads as one.
256    Refused { detail: String },
257}
258
259/// One line of the ledger.
260#[derive(Debug, Clone)]
261pub struct ScriptRecord {
262    pub point: String,
263    /// The script's id — its path, normally.
264    pub script: String,
265    pub entry: String,
266    /// Which user turn this call belongs to. Zero is before the first turn
267    /// began, which is when the registering points make their identity calls.
268    pub turn: u32,
269    pub outcome: ScriptOutcome,
270}
271
272/// Every script call, in the order the points made them.
273///
274/// A script cannot keep a record of its own: each call gets a fresh runtime
275/// with no filesystem and nothing carried over, so the only thing it can say
276/// is its return value at its own point. Whether it ran at all — and if it did
277/// not, why — is only answerable from out here.
278///
279/// Bounded, because a long session at a per-tool-call point would otherwise
280/// grow one forever, and the count of what was dropped is kept: a record that
281/// fell off the end and a call that never happened must not read the same.
282pub struct ScriptLedger {
283    entries: std::sync::Mutex<std::collections::VecDeque<ScriptRecord>>,
284    dropped: std::sync::atomic::AtomicUsize,
285    capacity: usize,
286}
287
288impl Default for ScriptLedger {
289    fn default() -> Self {
290        Self::with_capacity(4096)
291    }
292}
293
294impl ScriptLedger {
295    pub fn new() -> Self {
296        Self::default()
297    }
298
299    pub fn with_capacity(capacity: usize) -> Self {
300        Self {
301            entries: std::sync::Mutex::new(std::collections::VecDeque::new()),
302            dropped: std::sync::atomic::AtomicUsize::new(0),
303            capacity: capacity.max(1),
304        }
305    }
306
307    pub fn append(&self, record: ScriptRecord) {
308        let mut entries = match self.entries.lock() {
309            Ok(e) => e,
310            Err(poisoned) => poisoned.into_inner(),
311        };
312        while entries.len() >= self.capacity {
313            entries.pop_front();
314            self.dropped.fetch_add(1, Ordering::Relaxed);
315        }
316        entries.push_back(record);
317    }
318
319    pub fn records(&self) -> Vec<ScriptRecord> {
320        match self.entries.lock() {
321            Ok(e) => e.iter().cloned().collect(),
322            Err(poisoned) => poisoned.into_inner().iter().cloned().collect(),
323        }
324    }
325
326    /// How many records fell off the front. Non-zero means [`records`] is a
327    /// tail, not the whole story.
328    ///
329    /// [`records`]: Self::records
330    pub fn dropped(&self) -> usize {
331        self.dropped.load(Ordering::Relaxed)
332    }
333}
334
335const RESERVED_WORDS: &str = "arguments async await break case catch class const continue \
336    debugger default delete do else enum eval export extends false finally for function if \
337    implements import in instanceof interface let new null package private protected public \
338    return static super switch this throw true try typeof undefined var void while with yield";
339
340/// What the carriers put on `globalThis` themselves, `RunCode`'s and
341/// `RunExt`'s stand-ins for missing Node APIs included.
342const CARRIER_GLOBALS: &str = "agent args callTool console exports fetch fs log messages \
343    module notify process require stopRequested tools";
344
345/// The lowercase names a fresh QuickJS context resolves on `globalThis`, its
346/// prototype chain included; `js-lib`'s tests hold this to the interpreter.
347const STANDARD_GLOBALS: &str = "atob btoa constructor escape eval performance undefined unescape";
348
349/// Why `name` cannot be a global the engine adds to every script — the base
350/// library's, or a host library's: it is `[a-z][a-z0-9]*`, no reserved
351/// word, and no name a script already has from its carrier or the language.
352pub fn check_global_name(name: &str) -> Result<(), &'static str> {
353    let listed = |words: &str| words.split_whitespace().any(|w| w == name);
354    if !name.starts_with(|c: char| c.is_ascii_lowercase()) {
355        Err("it must start with a lowercase ASCII letter")
356    } else if !name
357        .bytes()
358        .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
359    {
360        Err("only lowercase ASCII letters and digits are allowed")
361    } else if listed(RESERVED_WORDS) {
362        Err("it is a JavaScript reserved word")
363    } else if listed(CARRIER_GLOBALS) || listed(STANDARD_GLOBALS) {
364        Err("a script already has a global of that name")
365    } else {
366        Ok(())
367    }
368}