Skip to main content

base/interface/
host_js.rs

1//! `HostJsLib` — a JavaScript library the host gives plugin code: a namespace
2//! of async functions, JSON in and JSON out, that becomes a global in the
3//! runtime of every plugin command and function whose package `uses` it
4//! (`docs/agix-sdk.md` §10「宿主 JS 库」). The host never sees the
5//! script engine: the engine writes the stubs, and each call reaches the host
6//! through [`HostFn`] with who made it and a cancellation signal.
7
8use std::future::Future;
9use std::path::PathBuf;
10use std::sync::Arc;
11
12use futures::future::BoxFuture;
13use serde_json::Value;
14use tokio_util::sync::CancellationToken;
15
16pub use crate::command::PackageSource;
17
18use crate::command::HostLibrary;
19
20/// One function of a host library. Any
21/// `Fn(HostCallContext, Value) -> impl Future<Output = Result<Value, HostJsError>>`
22/// is one.
23pub trait HostFn: Send + Sync {
24    fn call(
25        &self,
26        cx: HostCallContext,
27        input: Value,
28    ) -> BoxFuture<'static, Result<Value, HostJsError>>;
29}
30
31impl<F, Fut> HostFn for F
32where
33    F: Fn(HostCallContext, Value) -> Fut + Send + Sync,
34    Fut: Future<Output = Result<Value, HostJsError>> + Send + 'static,
35{
36    fn call(
37        &self,
38        cx: HostCallContext,
39        input: Value,
40    ) -> BoxFuture<'static, Result<Value, HostJsError>> {
41        Box::pin(self(cx, input))
42    }
43}
44
45/// Who calls a host function, from where; the host decides on it whether
46/// the call goes ahead.
47#[derive(Debug, Clone)]
48pub struct HostCallContext {
49    /// The name the package gives itself: any installed package can take
50    /// one, so `source` is what tells the host's own package from it.
51    pub plugin: String,
52    pub plugin_version: String,
53    pub source: PackageSource,
54    /// The command's name, or the function's.
55    pub entry: String,
56    pub session_id: Option<String>,
57    pub project_root: Option<PathBuf>,
58    pub cwd: PathBuf,
59    /// Who ran the plugin code: `model`, `user` (a `/name` command),
60    /// `skill`, `RunCode` or `host`.
61    pub via: String,
62    pub agent_depth: u32,
63    /// Fires when the script is stopped; the script's promise is rejected
64    /// whatever the function does after.
65    pub cancel: CancellationToken,
66}
67
68/// A host function's failure, as the script's rejected `Error` carries it.
69#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
70#[error("{code}: {message}")]
71pub struct HostJsError {
72    pub code: String,
73    pub message: String,
74}
75
76impl HostJsError {
77    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
78        Self {
79            code: code.into(),
80            message: message.into(),
81        }
82    }
83}
84
85#[derive(Clone)]
86pub struct HostJsLib {
87    namespace: String,
88    functions: Vec<(String, Arc<dyn HostFn>)>,
89    prelude: Option<String>,
90    description: Option<String>,
91}
92
93impl std::fmt::Debug for HostJsLib {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        f.debug_struct("HostJsLib")
96            .field("namespace", &self.namespace)
97            .field("functions", &self.paths().collect::<Vec<_>>())
98            .field("prelude", &self.prelude.as_ref().map(String::len))
99            .field("description", &self.description)
100            .finish()
101    }
102}
103
104impl HostJsLib {
105    pub fn new(namespace: &str) -> Self {
106        Self {
107            namespace: namespace.to_string(),
108            functions: Vec::new(),
109            prelude: None,
110            description: None,
111        }
112    }
113
114    /// `path` is dot-separated JavaScript identifiers under the namespace:
115    /// `flow.start` is `codix.flow.start(input)` in a script.
116    pub fn function<F, Fut>(mut self, path: &str, f: F) -> Self
117    where
118        F: Fn(HostCallContext, Value) -> Fut + Send + Sync + 'static,
119        Fut: Future<Output = Result<Value, HostJsError>> + Send + 'static,
120    {
121        self.functions.push((path.to_string(), Arc::new(f)));
122        self
123    }
124
125    /// Plain JavaScript evaluated after the stubs and before the plugin's
126    /// code, while the namespace can still be added to; frozen after.
127    pub fn prelude(mut self, js: impl Into<String>) -> Self {
128        self.prelude = Some(js.into());
129        self
130    }
131
132    /// What install disclosures say the library is.
133    pub fn description(mut self, text: impl Into<String>) -> Self {
134        self.description = Some(text.into());
135        self
136    }
137
138    pub fn namespace(&self) -> &str {
139        &self.namespace
140    }
141
142    pub fn paths(&self) -> impl Iterator<Item = &str> {
143        self.functions.iter().map(|(path, _)| path.as_str())
144    }
145
146    pub fn function_at(&self, path: &str) -> Option<&Arc<dyn HostFn>> {
147        self.functions
148            .iter()
149            .find(|(p, _)| p == path)
150            .map(|(_, f)| f)
151    }
152
153    pub fn prelude_source(&self) -> Option<&str> {
154        self.prelude.as_deref()
155    }
156
157    /// The library as a package's `uses` is checked against.
158    pub fn library(&self) -> HostLibrary {
159        HostLibrary {
160            name: self.namespace.clone(),
161            description: self.description.clone(),
162        }
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[tokio::test]
171    async fn a_closure_is_a_host_function() {
172        let lib = HostJsLib::new("codix")
173            .function("echo", |cx: HostCallContext, input| async move {
174                Ok(serde_json::json!({ "via": cx.via, "input": input }))
175            })
176            .description("Codix flows");
177        let cx = HostCallContext {
178            plugin: "p".into(),
179            plugin_version: "1".into(),
180            source: PackageSource::Installed,
181            entry: "cmd".into(),
182            session_id: None,
183            project_root: None,
184            cwd: PathBuf::from("/"),
185            via: "user".into(),
186            agent_depth: 0,
187            cancel: CancellationToken::new(),
188        };
189        let out = lib.function_at("echo").unwrap().call(cx, 1.into()).await;
190        assert_eq!(out, Ok(serde_json::json!({ "via": "user", "input": 1 })));
191        assert_eq!(
192            lib.library(),
193            HostLibrary {
194                name: "codix".into(),
195                description: Some("Codix flows".into())
196            }
197        );
198    }
199}