Skip to main content

yk_lua/
host.rs

1//! The capabilities a `Lua` extension can reach.
2//!
3//! Deliberately tiny, and defined here as a trait rather than assembled from
4//! `reqwest` inside `yk-lua`. `yk-lua` knows about no HTTP, and
5//! a trait is how that stays true: the binary implements [`Host`] with its
6//! existing client, and `yk-lua` stays testable with a fake.
7//!
8//! Every member of this trait is a capability the agent already has through its
9//! built-in tools. That is the bar: a capability that gives an extension reach
10//! the built-in tools do not already have is a different conversation.
11
12use std::collections::BTreeMap;
13use std::path::{Path, PathBuf};
14
15use yk_core::Result;
16
17/// What an HTTP POST came back with.
18///
19/// A status and the body, deliberately not a parsed body: `host.json` is the
20/// parser, and a host that guessed at a shape would be wrong for every service
21/// that is not the one it was written for.
22#[derive(Clone, Debug, Eq, PartialEq)]
23pub struct HttpResponse {
24    /// The HTTP status code. Not an error at this layer, because the difference
25    /// between "the model answered no" and "the vendor rate-limited you" is the
26    /// caller's to make, not the transport's.
27    pub status: u16,
28    /// The response body, as text.
29    pub body: String,
30}
31
32#[async_trait::async_trait]
33
34/// What an extension can ask the host to do.
35#[async_trait::async_trait]
36pub trait Host: Send + Sync {
37    /// Read a file, already resolved and checked against the working directory.
38    ///
39    /// # Errors
40    ///
41    /// [`yk_core::Error::Read`] when the file cannot be read.
42    async fn read_file(&self, path: &Path) -> Result<String>;
43
44    /// Fetch a URL as text.
45    ///
46    /// # Errors
47    ///
48    /// [`yk_core::Error::Provider`] when the request fails.
49    async fn http_get(&self, url: &str) -> Result<String>;
50
51    /// POST a JSON document and read the reply.
52    ///
53    /// The first write reach an extension has, and the reason it is here:
54    /// `http_get` can read a URL and nothing else, which is enough for a
55    /// document and not enough for any hosted API, because they authenticate
56    /// with a request header and answer on POST.
57    ///
58    /// `headers` are the caller's, so the caller chooses the credentials and
59    /// the body chooses the rest. The host sets `Content-Type: application/json`
60    /// first and lets `headers` override it, because the name promises JSON and
61    /// a caller talking to something else should be able to say so.
62    ///
63    /// # Errors
64    ///
65    /// [`yk_core::Error::Provider`] when the request fails or a header is one
66    /// the HTTP client refuses. A response with a non-2xx status is not an
67    /// error here.
68    async fn http_post_json(
69        &self,
70        url: &str,
71        headers: &BTreeMap<String, String>,
72        body: &str,
73    ) -> Result<HttpResponse>;
74
75    /// Read one environment variable by name, or `None` when it is unset.
76    ///
77    /// `os.getenv` does not exist in this VM, so without this an extension
78    /// cannot read a key at all, which puts every hosted API out of reach for a
79    /// script that has no filesystem and no process to inherit one from.
80    ///
81    /// One name at a time rather than the whole table. A script that can dump
82    /// the environment in one call is a much better exfiltration story than one
83    /// that has to ask for each value it wants.
84    fn env(&self, name: &str) -> Option<String>;
85}
86
87/// A host that refuses everything, for tests and for running with no network.
88///
89/// Useful beyond tests: it is what a caller gets if it does not supply one, so
90/// forgetting to wire the real host fails closed rather than open.
91#[derive(Clone, Copy, Debug, Default)]
92pub struct DenyHost;
93
94#[async_trait::async_trait]
95impl Host for DenyHost {
96    async fn read_file(&self, path: &Path) -> Result<String> {
97        Err(yk_core::Error::Tool {
98            tool: "host.read_file".to_owned(),
99            reason: format!(
100                "no host is configured, so `{}` was not read",
101                path.display()
102            ),
103        })
104    }
105
106    async fn http_get(&self, url: &str) -> Result<String> {
107        Err(yk_core::Error::Tool {
108            tool: "host.http_get".to_owned(),
109            reason: format!("no host is configured, so `{url}` was not fetched"),
110        })
111    }
112
113    async fn http_post_json(
114        &self,
115        url: &str,
116        _headers: &BTreeMap<String, String>,
117        _body: &str,
118    ) -> Result<HttpResponse> {
119        Err(yk_core::Error::Tool {
120            tool: "host.http_post_json".to_owned(),
121            reason: format!("no host is configured, so nothing was posted to `{url}`"),
122        })
123    }
124
125    fn env(&self, name: &str) -> Option<String> {
126        let _ = name;
127        None
128    }
129}
130
131/// Where extensions are loaded from, and whether they may run.
132///
133/// The two directories are split deliberately. The user's own directory is
134/// always loaded because the user put it there. A repository's directory is
135/// not, and checking out a repository must never run code.
136#[derive(Clone, Debug, Default)]
137pub struct ExtensionSources {
138    /// `~/.config/yk/lua`, always loaded.
139    pub user: Option<PathBuf>,
140    /// `<repo>/.yk/lua`, loaded only when `trust_repo` is set.
141    pub repo: Option<PathBuf>,
142    /// Whether the repository's scripts may run this session.
143    pub trust_repo: bool,
144}
145
146impl ExtensionSources {
147    /// The directories that will actually be read, in load order.
148    ///
149    /// User first so a user's own script can be overridden by a deliberate
150    /// project-local one, rather than the other way round.
151    #[must_use]
152    pub fn active(&self) -> Vec<PathBuf> {
153        let mut dirs: Vec<PathBuf> = self.user.iter().cloned().collect();
154        if self.trust_repo
155            && let Some(repo) = &self.repo
156        {
157            dirs.push(repo.clone());
158        }
159        dirs
160    }
161
162    /// The directories that were skipped, and why, for the startup message.
163    #[must_use]
164    pub fn skipped(&self) -> Vec<PathBuf> {
165        if self.trust_repo {
166            Vec::new()
167        } else {
168            self.repo.iter().cloned().collect()
169        }
170    }
171}
172
173/// The conventional user directory for extensions.
174#[must_use]
175pub fn user_dir() -> PathBuf {
176    let base = std::env::var_os("XDG_CONFIG_HOME").map_or_else(
177        || {
178            std::env::var_os("HOME")
179                .map_or_else(|| PathBuf::from("."), PathBuf::from)
180                .join(".config")
181        },
182        PathBuf::from,
183    );
184
185    base.join("yk").join("lua")
186}
187
188/// Where extensions the model wrote live, inside a project.
189///
190/// Session-scoped: loaded for the current run, never promoted
191/// without `yk promote`.
192#[must_use]
193pub fn session_dir(project_root: &Path) -> PathBuf {
194    project_root.join(".yk").join("extensions")
195}
196
197/// The default `extension_sources` for a run in `project_root`.
198///
199/// # Errors
200///
201/// None today. It returns a value because a future trust check has somewhere to
202/// report from.
203#[must_use]
204pub fn extension_sources(project_root: &Path, trust_repo: bool) -> ExtensionSources {
205    ExtensionSources {
206        user: Some(user_dir()),
207        repo: Some(project_root.join(".yk").join("lua")),
208        trust_repo,
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    #![allow(
215        clippy::unwrap_used,
216        clippy::expect_used,
217        clippy::indexing_slicing,
218        clippy::as_conversions,
219        clippy::arithmetic_side_effects
220    )]
221
222    use std::collections::BTreeMap;
223    use std::path::{Path, PathBuf};
224
225    use yk_core::Result;
226
227    use super::{DenyHost, Host, HttpResponse, extension_sources, session_dir, user_dir};
228
229    #[tokio::test]
230    async fn a_denying_host_refuses_rather_than_pretending() {
231        let host = DenyHost;
232        let error = host
233            .read_file(Path::new("a.txt"))
234            .await
235            .expect_err("must fail");
236        assert!(
237            error.to_string().contains("no host is configured"),
238            "{error}"
239        );
240
241        let error = host
242            .http_get("https://example.com")
243            .await
244            .expect_err("must fail");
245        assert!(error.to_string().contains("no host"), "{error}");
246
247        let error = host
248            .http_post_json("https://example.com", &BTreeMap::new(), "{}")
249            .await
250            .expect_err("must fail");
251        assert!(error.to_string().contains("nothing was posted"), "{error}");
252    }
253
254    #[test]
255    fn a_denying_host_reports_no_environment_rather_than_an_empty_one() {
256        // `None` and `Some("")` are different answers, and a caller that cannot
257        // tell them apart treats "no key configured" as "the key is empty".
258        assert_eq!(DenyHost.env("PATH"), None);
259    }
260
261    #[test]
262    fn the_user_directory_is_always_active() {
263        let found = extension_sources(Path::new("/project"), false);
264        assert!(found.active().contains(&user_dir()));
265    }
266
267    #[test]
268    fn a_repository_is_not_loaded_without_trust() {
269        // The regression this whole split exists for: `git clone` must not run code.
270        let found = extension_sources(Path::new("/project"), false);
271
272        assert!(
273            !found.active().iter().any(|dir| dir.starts_with("/project")),
274            "project scripts loaded without trust: {:?}",
275            found.active()
276        );
277        assert_eq!(found.skipped().len(), 1);
278    }
279
280    #[test]
281    fn a_trusted_repository_is_loaded() {
282        let found = extension_sources(Path::new("/project"), true);
283
284        assert_eq!(found.active().len(), 2);
285        assert!(found.skipped().is_empty());
286    }
287
288    #[test]
289    fn the_user_directory_loads_before_the_project_one() {
290        // So a project can deliberately override a user-wide script.
291        let found = extension_sources(Path::new("/project"), true);
292        let active = found.active();
293
294        assert_eq!(active.first(), Some(&user_dir()));
295    }
296
297    #[test]
298    fn model_written_extensions_live_under_dot_yk_extensions() {
299        let dir = session_dir(Path::new("/project"));
300        assert_eq!(dir, PathBuf::from("/project/.yk/extensions"));
301    }
302
303    #[test]
304    fn a_trusted_repository_still_reports_nothing_skipped() {
305        let found = extension_sources(Path::new("/project"), true);
306        assert!(found.skipped().is_empty());
307    }
308
309    // A host that answers, to prove the trait is implementable from outside.
310    struct Fixed(String);
311
312    #[async_trait::async_trait]
313    impl Host for Fixed {
314        async fn read_file(&self, _path: &Path) -> Result<String> {
315            Ok(self.0.clone())
316        }
317
318        async fn http_get(&self, _url: &str) -> Result<String> {
319            Ok(self.0.clone())
320        }
321
322        async fn http_post_json(
323            &self,
324            _url: &str,
325            headers: &BTreeMap<String, String>,
326            body: &str,
327        ) -> Result<HttpResponse> {
328            // Header count in the hundreds and body length in the units, so a
329            // test can tell "the headers did not arrive" from "the body did
330            // not arrive" rather than seeing one number either way.
331            let encoded = headers.len().saturating_mul(100).saturating_add(body.len());
332            Ok(HttpResponse {
333                status: 200,
334                body: encoded.to_string(),
335            })
336        }
337
338        fn env(&self, name: &str) -> Option<String> {
339            (name == "SET").then(|| "value".to_owned())
340        }
341    }
342
343    #[tokio::test]
344    async fn a_host_can_be_implemented_outside_this_crate() {
345        let host = Fixed("content".to_owned());
346        assert_eq!(
347            host.read_file(Path::new("a")).await.expect("reads"),
348            "content"
349        );
350        assert_eq!(host.http_get("x").await.expect("fetches"), "content");
351
352        let mut headers = BTreeMap::new();
353        headers.insert("Authorization".to_owned(), "Bearer k".to_owned());
354        let reply = host
355            .http_post_json("x", &headers, "{}")
356            .await
357            .expect("posts");
358        assert_eq!(reply.status, 200);
359        // One header plus a two byte body, which is the only thing the fake
360        // reports and enough to show both arguments arrive.
361        assert_eq!(reply.body, "102");
362
363        assert_eq!(host.env("SET").as_deref(), Some("value"));
364        assert_eq!(host.env("UNSET"), None);
365    }
366}