use std::path::PathBuf;
use std::sync::atomic::Ordering;
use std::time::Duration;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use crate::prompt::BlockOrigin;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
pub struct ScriptBinding {
pub path: PathBuf,
pub point: String,
pub entry: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timeout_ms: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub calls_per_turn: Option<u32>,
}
#[derive(Debug, Clone)]
pub struct ScriptSource {
pub id: String,
pub origin: BlockOrigin,
pub code: String,
}
#[derive(Debug, Clone, Copy)]
pub struct ScriptLimits {
pub timeout: Duration,
pub calls_per_turn: u32,
}
impl Default for ScriptLimits {
fn default() -> Self {
Self {
timeout: Duration::from_millis(100),
calls_per_turn: 1_000,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScriptError {
NoEngine,
TimedOut { after: Duration },
QuotaExhausted { calls_per_turn: u32 },
Failed(String),
}
impl std::fmt::Display for ScriptError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NoEngine => f.write_str(
"no script engine is available in this build; a host supplies one through \
`script_host`",
),
Self::TimedOut { after } => write!(f, "script exceeded its {after:?} budget"),
Self::QuotaExhausted { calls_per_turn } => {
write!(f, "script already ran {calls_per_turn} times this turn")
}
Self::Failed(e) => write!(f, "script failed: {e}"),
}
}
}
#[async_trait]
pub trait ScriptEngine: Send + Sync {
async fn eval(
&self,
script: &ScriptSource,
entry: &str,
input: serde_json::Value,
limits: &ScriptLimits,
) -> Result<serde_json::Value, ScriptError>;
fn eval_blocking(
&self,
_script: &ScriptSource,
_entry: &str,
_input: serde_json::Value,
_limits: &ScriptLimits,
) -> Result<serde_json::Value, ScriptError> {
Err(ScriptError::Failed(
"this script engine cannot be called from a synchronous hook point".into(),
))
}
}
pub struct RefusingEngine;
#[async_trait]
impl ScriptEngine for RefusingEngine {
async fn eval(
&self,
_script: &ScriptSource,
_entry: &str,
_input: serde_json::Value,
_limits: &ScriptLimits,
) -> Result<serde_json::Value, ScriptError> {
Err(ScriptError::NoEngine)
}
}
pub struct FnScriptEngine<F>(pub F);
#[async_trait]
impl<F, Fut> ScriptEngine for FnScriptEngine<F>
where
F: Fn(&ScriptSource, &str, serde_json::Value) -> Fut + Send + Sync,
Fut: std::future::Future<Output = Result<serde_json::Value, ScriptError>> + Send,
{
async fn eval(
&self,
script: &ScriptSource,
entry: &str,
input: serde_json::Value,
_limits: &ScriptLimits,
) -> Result<serde_json::Value, ScriptError> {
(self.0)(script, entry, input).await
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScriptOutcome {
Applied,
NoChange { detail: Option<String> },
Failed { error: ScriptError },
Refused { detail: String },
}
#[derive(Debug, Clone)]
pub struct ScriptRecord {
pub point: String,
pub script: String,
pub entry: String,
pub turn: u32,
pub outcome: ScriptOutcome,
}
pub struct ScriptLedger {
entries: std::sync::Mutex<std::collections::VecDeque<ScriptRecord>>,
dropped: std::sync::atomic::AtomicUsize,
capacity: usize,
}
impl Default for ScriptLedger {
fn default() -> Self {
Self::with_capacity(4096)
}
}
impl ScriptLedger {
pub fn new() -> Self {
Self::default()
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
entries: std::sync::Mutex::new(std::collections::VecDeque::new()),
dropped: std::sync::atomic::AtomicUsize::new(0),
capacity: capacity.max(1),
}
}
pub fn append(&self, record: ScriptRecord) {
let mut entries = match self.entries.lock() {
Ok(e) => e,
Err(poisoned) => poisoned.into_inner(),
};
while entries.len() >= self.capacity {
entries.pop_front();
self.dropped.fetch_add(1, Ordering::Relaxed);
}
entries.push_back(record);
}
pub fn records(&self) -> Vec<ScriptRecord> {
match self.entries.lock() {
Ok(e) => e.iter().cloned().collect(),
Err(poisoned) => poisoned.into_inner().iter().cloned().collect(),
}
}
pub fn dropped(&self) -> usize {
self.dropped.load(Ordering::Relaxed)
}
}
const RESERVED_WORDS: &str = "arguments async await break case catch class const continue \
debugger default delete do else enum eval export extends false finally for function if \
implements import in instanceof interface let new null package private protected public \
return static super switch this throw true try typeof undefined var void while with yield";
const CARRIER_GLOBALS: &str = "agent args callTool console exports fetch fs log messages \
module notify process require stopRequested tools";
const STANDARD_GLOBALS: &str = "atob btoa constructor escape eval performance undefined unescape";
pub fn check_global_name(name: &str) -> Result<(), &'static str> {
let listed = |words: &str| words.split_whitespace().any(|w| w == name);
if !name.starts_with(|c: char| c.is_ascii_lowercase()) {
Err("it must start with a lowercase ASCII letter")
} else if !name
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
{
Err("only lowercase ASCII letters and digits are allowed")
} else if listed(RESERVED_WORDS) {
Err("it is a JavaScript reserved word")
} else if listed(CARRIER_GLOBALS) || listed(STANDARD_GLOBALS) {
Err("a script already has a global of that name")
} else {
Ok(())
}
}