1use byob_types::process::NoWindow as _;
13use std::collections::BTreeMap;
14use std::ffi::OsString;
15use std::fs;
16use std::path::{Path, PathBuf};
17use std::process::Command;
18use std::sync::Arc;
19use std::time::{Duration, SystemTime};
20
21use byob_sandbox::{Limits, Policy, RunOptions, Sandbox, TempDir};
22use byob_tools::{Access, FileChange, Tool, ToolContext, ToolOutput, ToolSpec};
23use serde_json::Value;
24
25use crate::PluginRef;
26use crate::discover::Plugin;
27use crate::manifest::{ManifestTool, ToolKind, path_inside};
28use crate::names::{ToolNames, namespaced};
29use crate::pyenv::PluginPython;
30
31pub const SCRIPT_TIMEOUT: Duration = Duration::from_secs(60);
33pub const MAX_SCRIPT_OUTPUT: usize = 256 * 1024;
35const MAX_SCANNED_FILES: usize = 5000;
37
38pub fn default_python() -> Vec<OsString> {
40 vec![OsString::from(if cfg!(windows) { "python" } else { "python3" })]
41}
42
43#[derive(Debug, Clone)]
45pub struct ScriptRun {
46 pub program: Vec<OsString>,
48 pub script: PathBuf,
49 pub args: Vec<OsString>,
51 pub cwd: PathBuf,
52 pub stdin: Vec<u8>,
53 pub env: BTreeMap<String, String>,
55 pub timeout: Duration,
56 pub max_output: usize,
58}
59
60#[derive(Debug, Clone, Default, PartialEq, Eq)]
61pub struct ScriptOutcome {
62 pub stdout: String,
63 pub stderr: String,
64 pub exit_code: Option<i32>,
66 pub timed_out: bool,
67 pub stopped: bool,
68 pub truncated: bool,
70}
71
72impl ScriptOutcome {
73 pub fn success(&self) -> bool {
74 self.exit_code == Some(0) && !self.timed_out && !self.stopped
75 }
76}
77
78pub fn run_script_unsandboxed(run: &ScriptRun, cancelled: &dyn Fn() -> bool) -> Result<ScriptOutcome, String> {
81 let Some((program, lead)) = run.program.split_first() else { return Err("no interpreter configured".into()) };
82 let mut cmd = Command::new(program);
83 cmd.no_window();
84 cmd.args(lead).arg(&run.script).args(&run.args).current_dir(&run.cwd).envs(&run.env);
85 execute(cmd, run, cancelled)
86}
87
88pub fn run_script_sandboxed(
92 run: &ScriptRun,
93 sandbox: &Sandbox,
94 plugin_dir: &Path,
95 network: bool,
96 cancelled: &dyn Fn() -> bool,
97) -> Result<ScriptOutcome, String> {
98 run_script_sandboxed_reading(run, sandbox, &[plugin_dir.to_path_buf()], network, cancelled)
99}
100
101pub fn run_script_sandboxed_reading(
104 run: &ScriptRun,
105 sandbox: &Sandbox,
106 read: &[PathBuf],
107 network: bool,
108 cancelled: &dyn Fn() -> bool,
109) -> Result<ScriptOutcome, String> {
110 let Some((program, lead)) = run.program.split_first() else { return Err("no interpreter configured".into()) };
111 let cwd = run.cwd.canonicalize().map_err(|e| format!("{}: {e}", run.cwd.display()))?;
112 let tmp = TempDir::new("byob-plugin-")?;
113 let mut policy = Policy::for_workspace(&cwd, tmp.path())
114 .network(network)
115 .limits(Limits::for_timeout(run.timeout.as_secs()))
116 .allow_path_dirs(std::env::var_os("PATH").as_deref())
117 .allow_unsandboxed(true);
119 for p in read {
120 policy = policy.allow_read(p);
121 }
122 for p in byob_sandbox::interpreter_read_paths(program) {
123 policy = policy.allow_read(p);
124 }
125 let mut args: Vec<OsString> = lead.to_vec();
126 args.push(run.script.clone().into_os_string());
127 args.extend(run.args.iter().cloned());
128 let mut cmd = sandbox.command(&policy, program, &args);
129 cmd.current_dir(&cwd);
130 byob_sandbox::clean_env(&mut cmd, tmp.path());
131 cmd.envs(&run.env);
132 let out = execute(cmd, run, cancelled)?;
133 drop(tmp);
134 Ok(out)
135}
136
137fn execute(cmd: Command, run: &ScriptRun, cancelled: &dyn Fn() -> bool) -> Result<ScriptOutcome, String> {
138 let opts = RunOptions { stdin: run.stdin.clone(), timeout: run.timeout, max_output: run.max_output };
139 let o = byob_sandbox::run(cmd, &opts, cancelled)?;
140 if let Some(e) = o.sandbox_error() {
141 return Err(format!("the sandbox couldn't start: {e}"));
142 }
143 Ok(ScriptOutcome {
144 stdout: String::from_utf8_lossy(&o.stdout.bytes()).into_owned(),
145 stderr: String::from_utf8_lossy(&o.stderr.bytes()).into_owned(),
146 exit_code: o.exit_code,
147 timed_out: o.timed_out,
148 stopped: o.cancelled,
149 truncated: o.stdout.truncated() || o.stderr.truncated(),
150 })
151}
152
153pub fn fill_title(template: &str, args: &Value) -> String {
155 let mut out = String::new();
156 let mut rest = template;
157 while let Some(open) = rest.find('{') {
158 out.push_str(&rest[..open]);
159 let after = &rest[open + 1..];
160 let key_len = after.find(|c: char| !(c.is_alphanumeric() || c == '_')).unwrap_or(after.len());
161 if key_len > 0 && after[key_len..].starts_with('}') {
162 let key = &after[..key_len];
163 match args.get(key) {
164 Some(Value::String(s)) => out.push_str(s),
165 Some(v) => out.push_str(&v.to_string()),
166 None => out.push_str(&rest[open..open + key_len + 2]),
167 }
168 rest = &after[key_len + 1..];
169 } else {
170 out.push('{');
171 rest = after;
172 }
173 }
174 out.push_str(rest);
175 out.chars().take(120).collect()
176}
177
178fn snapshot(dir: &Path) -> BTreeMap<PathBuf, Option<SystemTime>> {
180 let mut m = BTreeMap::new();
181 let mut stack = vec![(dir.to_path_buf(), 0u8)];
182 while let Some((d, depth)) = stack.pop() {
183 let Ok(rd) = fs::read_dir(&d) else { continue };
184 for e in rd.flatten() {
185 if m.len() >= MAX_SCANNED_FILES {
186 return m;
187 }
188 if e.file_name().to_string_lossy().starts_with('.') {
189 continue;
190 }
191 let Ok(meta) = e.metadata() else { continue };
192 if meta.is_dir() {
193 if depth < 2 {
194 stack.push((e.path(), depth + 1));
195 }
196 } else {
197 m.insert(e.path(), meta.modified().ok());
198 }
199 }
200 }
201 m
202}
203
204pub struct PythonTool {
206 name: String,
207 plugin: PluginRef,
208 decl: ManifestTool,
209 script: String,
210 interpreter: Vec<OsString>,
211 python: Option<PluginPython>,
213 sandbox: Option<Sandbox>,
214 timeout: Duration,
215}
216
217impl PythonTool {
218 pub fn new(name: String, plugin: PluginRef, decl: ManifestTool, interpreter: Vec<OsString>) -> Option<Self> {
220 let ToolKind::Script(script) = &decl.kind else { return None };
221 let script = script.clone();
222 Some(Self { name, plugin, decl, script, interpreter, python: None, sandbox: None, timeout: SCRIPT_TIMEOUT })
223 }
224
225 pub fn with_python(mut self, python: Option<PluginPython>) -> Self {
227 self.python = python;
228 self
229 }
230
231 pub fn with_sandbox(mut self, sandbox: Option<Sandbox>) -> Self {
233 self.sandbox = sandbox;
234 self
235 }
236
237 pub fn with_timeout(mut self, timeout: Duration) -> Self {
238 self.timeout = timeout;
239 self
240 }
241
242 pub fn plugin(&self) -> &PluginRef {
243 &self.plugin
244 }
245
246 pub fn declared(&self) -> &ManifestTool {
249 &self.decl
250 }
251
252 fn finish(&self, r: &ScriptOutcome, workspace: &Path, before: &BTreeMap<PathBuf, Option<SystemTime>>) -> ToolOutput {
253 let name = &self.plugin.name;
254 if r.stopped {
255 return ToolOutput::err("Stopped by the user.");
256 }
257 if r.timed_out {
258 return ToolOutput::err(format!("{name} took longer than {} seconds and was stopped.", self.timeout.as_secs()));
259 }
260 if r.exit_code != Some(0) {
261 let output = [r.stdout.trim(), r.stderr.trim()].iter().filter(|s| !s.is_empty()).copied().collect::<Vec<_>>().join("\n");
262 return ToolOutput::err(format!("{name} ran into a problem:\n{output}"));
263 }
264 let out = r.stdout.trim();
265 let mut text = out.to_string();
266 let mut listed: Vec<PathBuf> = Vec::new();
267 if out.starts_with('{')
268 && let Ok(Value::Object(j)) = serde_json::from_str::<Value>(out)
269 {
270 if let Some(t) = j.get("text").and_then(Value::as_str) {
271 text = t.to_string();
272 }
273 if let Some(files) = j.get("files").and_then(Value::as_array) {
274 listed = files.iter().filter_map(Value::as_str).filter(|f| path_inside(f)).map(|f| workspace.join(f)).filter(|p| p.is_file()).collect();
275 }
276 }
277 if r.truncated {
278 text.push_str("\n…(output cut: it was too long)");
279 }
280 let after = snapshot(workspace);
281 let mut changes: Vec<FileChange> = after
282 .iter()
283 .filter(|(f, m)| before.get(*f) != Some(*m))
284 .map(|(f, _)| if before.contains_key(f) { FileChange::Modified(f.clone()) } else { FileChange::Created(f.clone()) })
285 .collect();
286 for f in listed {
287 if !changes.iter().any(|c| matches!(c, FileChange::Created(p) | FileChange::Modified(p) if *p == f)) {
288 changes.push(FileChange::Modified(f));
289 }
290 }
291 if text.is_empty() {
292 text = "(no result)".into();
293 }
294 ToolOutput { text, failed: false, changes, images: Vec::new() }
295 }
296}
297
298impl Tool for PythonTool {
299 fn spec(&self) -> ToolSpec {
300 ToolSpec { name: self.name.clone(), description: self.decl.description.clone(), parameters: self.decl.params.clone() }
301 }
302
303 fn title(&self, args: &Value) -> String {
304 match &self.decl.title {
305 Some(t) => fill_title(t, args),
306 None => format!("Used {}: {}", self.plugin.name, self.decl.name),
307 }
308 }
309
310 fn pending_title(&self, args: &Value) -> String {
313 match &self.decl.title {
314 Some(t) => fill_title(t, args),
315 None => format!("Use {}: {}", self.plugin.name, self.decl.name),
316 }
317 }
318
319 fn access(&self, _args: &Value) -> Access {
320 self.decl.access.unwrap_or(Access::Execute)
321 }
322
323 fn always_ask(&self, args: &Value) -> Option<String> {
324 self.decl.confirm.as_ref()?.applies(args)
325 }
326
327 fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput {
328 if ctx.cancelled() {
329 return ToolOutput::err("Stopped by the user.");
330 }
331 let script = self.plugin.dir.join(&self.script);
332 if !path_inside(&self.script) || !script.is_file() {
333 return ToolOutput::err(format!("{}: {} is missing", self.plugin.name, self.script));
334 }
335 let args = if args.is_object() { args.clone() } else { Value::Object(serde_json::Map::new()) };
336 let chat = ctx.workspace.to_string_lossy().into_owned();
337 let dir = self.plugin.dir.to_string_lossy().into_owned();
338 let mut env = self.plugin.env.clone();
339 for (k, v) in [("HOB_CHAT_DIR", &chat), ("BYOB_CHAT_DIR", &chat), ("HOB_PLUGIN_DIR", &dir), ("BYOB_PLUGIN_DIR", &dir)] {
340 env.insert(k.into(), v.clone());
341 }
342 let mut read = vec![self.plugin.dir.clone()];
343 let program = match &self.python {
344 None => self.interpreter.clone(),
345 Some(p) => match p.python_until(&|| ctx.cancelled()) {
347 Ok(py) => {
348 read.extend(py.read);
349 env.extend(py.env);
350 py.program
351 }
352 Err(_) if ctx.cancelled() => return ToolOutput::err("Stopped by the user."),
353 Err(e) => return ToolOutput::err(format!("{} couldn't run: {e}", self.plugin.name)),
354 },
355 };
356 let run = ScriptRun {
357 program,
358 script,
359 args: Vec::new(),
360 cwd: ctx.workspace.to_path_buf(),
361 stdin: serde_json::to_vec(&args).unwrap_or_else(|_| b"{}".to_vec()),
362 env,
363 timeout: self.timeout,
364 max_output: MAX_SCRIPT_OUTPUT,
365 };
366 let before = snapshot(ctx.workspace);
367 let result = match &self.sandbox {
368 Some(sb) => run_script_sandboxed_reading(&run, sb, &read, self.plugin.network, &|| ctx.cancelled()),
369 None => run_script_unsandboxed(&run, &|| ctx.cancelled()),
370 };
371 match result {
372 Ok(r) => self.finish(&r, ctx.workspace, &before),
373 Err(e) => ToolOutput::err(format!("{} couldn't run: {e}", self.plugin.name)),
374 }
375 }
376}
377
378pub fn python_tools(plugin: &Plugin, settings: &BTreeMap<String, String>, interpreter: &[OsString], names: &mut ToolNames) -> Vec<Arc<PythonTool>> {
382 python_tools_in(plugin, settings, interpreter, names, None)
383}
384
385pub fn python_tools_in(
387 plugin: &Plugin,
388 settings: &BTreeMap<String, String>,
389 interpreter: &[OsString],
390 names: &mut ToolNames,
391 sandbox: Option<&Sandbox>,
392) -> Vec<Arc<PythonTool>> {
393 python_tools_with(plugin, settings, interpreter, names, sandbox, None)
394}
395
396pub fn python_tools_with(
398 plugin: &Plugin,
399 settings: &BTreeMap<String, String>,
400 interpreter: &[OsString],
401 names: &mut ToolNames,
402 sandbox: Option<&Sandbox>,
403 python: Option<&PluginPython>,
404) -> Vec<Arc<PythonTool>> {
405 let r = PluginRef::new(plugin, settings);
406 plugin
407 .manifest
408 .tools
409 .iter()
410 .filter(|t| matches!(&t.kind, ToolKind::Script(s) if plugin.dir.join(s).is_file()))
411 .filter_map(|t| {
412 let name = names.claim(&t.name, &namespaced(plugin.id(), &t.name));
413 PythonTool::new(name, r.clone(), t.clone(), interpreter.to_vec()).map(|t| Arc::new(t.with_sandbox(sandbox.cloned()).with_python(python.cloned())))
414 })
415 .collect()
416}
417
418#[cfg(test)]
419mod tests {
420 use super::*;
421 use serde_json::json;
422
423 #[test]
424 fn titles() {
425 let a = json!({"amount": 5, "from": "EUR", "x": null});
426 assert_eq!(fill_title("Converted {amount} {from} {to} {x}", &a), "Converted 5 EUR {to} null");
427 assert_eq!(fill_title("{ not a key } {", &a), "{ not a key } {");
428 assert_eq!(fill_title(&"é".repeat(200), &a).chars().count(), 120);
429 }
430
431 #[test]
432 fn missing_interpreter_is_an_error() {
433 let run = ScriptRun {
434 program: vec![OsString::from("/definitely/not/an/interpreter")],
435 script: PathBuf::from("x"),
436 args: vec![],
437 cwd: std::env::temp_dir(),
438 stdin: vec![],
439 env: BTreeMap::new(),
440 timeout: SCRIPT_TIMEOUT,
441 max_output: 10,
442 };
443 assert!(run_script_unsandboxed(&run, &|| false).unwrap_err().starts_with("couldn't start"));
444 let empty = ScriptRun { program: vec![], ..run };
445 assert!(run_script_unsandboxed(&empty, &|| false).is_err());
446 }
447}