返回 CodeWhale
plugin.rs
根目录 / crates / engine / src / tools / plugin.rs
1 //! Plugin tool system — scripts and commands as first-class tools.
2 //!
3 //! Users can drop self-describing scripts in `~/.codewhale/tools/` and they
4 //! are auto-discovered, parsed for frontmatter, and registered as model-visible
5 //! tools alongside built-in implementations.
6 //!
7 //! # Script frontmatter format
8 //!
9 //! Every plugin script must have a frontmatter header in its first 20 lines:
10 //!
11 //! ```sh
12 //! # name: my-tool
13 //! # description: Does something useful
14 //! # schema: {"type":"object","properties":{"input":{"type":"string"}}}
15 //! # approval: required
16 //! ```
17 //!
18 //! The script receives the tool's JSON input on **stdin** and must return
19 //! a JSON `ToolResult` (`{"content": "...", "success": true}`) on **stdout**.
20 //! Non-JSON output is wrapped in a `ToolResult` with `success: false`.
21 //!
22 //! # What a script tool cannot do (D4, CURRENT_DECISIONS §26)
23 //!
24 //! - **Approve itself.** `# approval:` accepts `suggest` (the default) and
25 //! `required`. `auto` is no longer honoured: the tool gets the default a
26 //! script without the line gets, and [`PluginMetadata::auto_approval_ignored`]
27 //! lets each loader say so (runtime log, `/plugin tools`) instead of
28 //! downgrading silently.
29 //! - **Replace a built-in.** A drop-in script whose name is already registered
30 //! is refused by `ToolRegistry::load_plugins`, and a `[tools.overrides]`
31 //! `script` / `command` entry keyed by a built-in is refused by
32 //! `ToolRegistry::apply_overrides_with_executor`; `disabled` still turns a built-in off.
33 //!
34 //! Known limitation: an unrecognised `# approval:` value (a typo such as
35 //! `requried`) still falls back to the default without a diagnostic.
36
37 use std::path::{Path, PathBuf};
38 use std::sync::Arc;
39 use std::time::Duration;
40
41 use async_trait::async_trait;
42 use serde_json::Value;
43
44 use super::spec::{
45 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
46 };
47
48 use codewhale_runtime::config::ToolOverride;
49
50 /// Timeout for plugin script execution (120 seconds).
51 const PLUGIN_EXECUTION_TIMEOUT: Duration = Duration::from_secs(120);
52
53 /// Captured at catalogue preparation. Enabled host errors never select Legacy.
54 #[derive(Clone)]
55 pub enum PluginExecutor {
56 Legacy,
57 Host(Arc<crate::extension_host::ExtensionHostManager>),
58 }
59 impl PluginExecutor {
60 pub fn for_engine() -> Self {
61 if codewhale_plugins::activation::extension_host_policy_enabled() {
62 let manager = crate::extension_host::manager();
63 if let Ok(handle) = tokio::runtime::Handle::try_current() {
64 manager.bind_engine_handle(handle);
65 }
66 Self::Host(manager)
67 } else {
68 Self::Legacy
69 }
70 }
71 async fn run(
72 &self,
73 program: &str,
74 args: Vec<String>,
75 label: &str,
76 input: Value,
77 context: &ToolContext,
78 ) -> Result<ToolResult, ToolError> {
79 match self {
80 Self::Legacy if !codewhale_plugins::activation::extension_host_policy_enabled() => {
81 let mut command = crate::tools::shell::sandboxed_runner_command(
82 context,
83 program,
84 args,
85 &context.workspace,
86 PLUGIN_EXECUTION_TIMEOUT,
87 )?;
88 run_plugin_child_raw(&mut command, label, input).await
89 }
90 Self::Legacy => Err(ToolError::not_available(
91 "script catalogue predates enabled execution; prepare tools again",
92 )),
93 Self::Host(manager) => {
94 let mut command = tokio::process::Command::new(program);
95 codewhale_util::utils::suppress_tokio_console_window(&mut command);
96 command.args(args);
97 manager.execute_script(command, input, context).await
98 }
99 }
100 }
101 }
102
103 /// Metadata extracted from a plugin script's frontmatter header.
104 #[derive(Debug, Clone)]
105 pub struct PluginMetadata {
106 /// Tool name (from `# name:`).
107 pub name: String,
108 /// Human-readable description (from `# description:`).
109 pub description: String,
110 /// JSON Schema for the tool's input (from `# schema:`).
111 /// Defaults to a permissive `{"type": "object"}` when absent.
112 pub input_schema: Value,
113 /// Approval requirement (from `# approval:`).
114 /// Defaults to `Suggest`; never `Auto` (see the module docs).
115 pub approval: ApprovalRequirement,
116 /// The frontmatter asked for `approval: auto`, which script tools may no
117 /// longer use; `approval` holds the default instead. Loaders report it
118 /// with `AUTO_APPROVAL_UNSUPPORTED`.
119 pub auto_approval_ignored: bool,
120 }
121
122 /// Why a script's `approval: auto` was ignored. Shared by the load warning and
123 /// the `/plugin tools` diagnostic so the two surfaces say the same thing.
124 pub const AUTO_APPROVAL_UNSUPPORTED: &str = "`approval: auto` is no longer supported for script tools; \
125 the tool follows the session's approval setting like a script with no `approval:` line";
126
127 /// Log the D4 downgrade for a script tool registered as `tool_name`.
128 fn warn_auto_approval_ignored(tool_name: &str) {
129 tracing::warn!(
130 "Script tool '{}': {AUTO_APPROVAL_UNSUPPORTED}",
131 codewhale_runtime::safe_label::SafeLabel::identifier(tool_name)
132 );
133 }
134
135 /// A tool backed by an external script or executable dropped into the
136 /// plugins directory. The script receives JSON input on stdin and writes
137 /// a JSON `ToolResult` to stdout.
138 struct ScriptPluginTool {
139 executor: PluginExecutor,
140 metadata: PluginMetadata,
141 /// Absolute path to the script.
142 script_path: PathBuf,
143 /// Optional static arguments passed before the JSON input.
144 args: Vec<String>,
145 }
146
147 impl std::fmt::Debug for ScriptPluginTool {
148 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149 f.debug_struct("ScriptPluginTool")
150 .field("name", &self.metadata.name)
151 .field("script_path", &self.script_path)
152 .finish()
153 }
154 }
155
156 #[async_trait]
157 impl ToolSpec for ScriptPluginTool {
158 fn name(&self) -> &str {
159 &self.metadata.name
160 }
161
162 fn registration_origin(&self) -> std::borrow::Cow<'_, str> {
163 use codewhale_runtime::safe_label::SafeLabel;
164 let filename = self
165 .script_path
166 .file_name()
167 .unwrap_or_default()
168 .to_string_lossy();
169 format!(
170 "plugin script {} ({})",
171 SafeLabel::identifier(&filename),
172 SafeLabel::identifier(&self.script_path.to_string_lossy())
173 )
174 .into()
175 }
176
177 fn description(&self) -> &str {
178 &self.metadata.description
179 }
180
181 fn input_schema(&self) -> Value {
182 self.metadata.input_schema.clone()
183 }
184
185 fn capabilities(&self) -> Vec<ToolCapability> {
186 // Unknown plugin — conservative: mark as requiring execution + approval.
187 vec![
188 ToolCapability::ExecutesCode,
189 ToolCapability::RequiresApproval,
190 ]
191 }
192
193 fn approval_requirement(&self) -> ApprovalRequirement {
194 self.metadata.approval
195 }
196
197 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
198 let (interpreter, script_args) = script_command_parts(&self.script_path, &self.args);
199 self.executor
200 .run(
201 &interpreter,
202 script_args,
203 &self.script_path.display().to_string(),
204 input,
205 context,
206 )
207 .await
208 }
209 }
210
211 /// A tool backed by an arbitrary shell command from config.toml overrides.
212 /// Behaves like `ScriptPluginTool` but uses the user-specified command string.
213 struct CommandPluginTool {
214 executor: PluginExecutor,
215 name: String,
216 description: String,
217 input_schema: Value,
218 command: String,
219 args: Vec<String>,
220 approval: ApprovalRequirement,
221 }
222
223 impl std::fmt::Debug for CommandPluginTool {
224 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
225 f.debug_struct("CommandPluginTool")
226 .field("name", &self.name)
227 .field("command", &self.command)
228 .finish()
229 }
230 }
231
232 #[async_trait]
233 impl ToolSpec for CommandPluginTool {
234 fn name(&self) -> &str {
235 &self.name
236 }
237
238 fn registration_origin(&self) -> std::borrow::Cow<'_, str> {
239 format!(
240 "config [tools.overrides.{}]",
241 codewhale_runtime::safe_label::SafeLabel::identifier(&self.name)
242 )
243 .into()
244 }
245
246 fn description(&self) -> &str {
247 &self.description
248 }
249
250 fn input_schema(&self) -> Value {
251 self.input_schema.clone()
252 }
253
254 fn capabilities(&self) -> Vec<ToolCapability> {
255 vec![
256 ToolCapability::ExecutesCode,
257 ToolCapability::RequiresApproval,
258 ]
259 }
260
261 fn approval_requirement(&self) -> ApprovalRequirement {
262 self.approval
263 }
264
265 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
266 // On Windows, if the command doesn't have an extension, try wrapping
267 // in `cmd /c` or use `powershell` for `.ps1` files. For portability
268 // we let tokio::process::Command resolve via PATH.
269 let (program, mut args) = if cfg!(windows) && !self.command.contains('.') {
270 (
271 "cmd".to_string(),
272 vec!["/c".to_string(), self.command.clone()],
273 )
274 } else {
275 (self.command.clone(), Vec::new())
276 };
277 args.extend(self.args.iter().cloned());
278 let label = format!("command '{}'", self.command);
279 self.executor
280 .run(&program, args, &label, input, context)
281 .await
282 }
283 }
284
285 // ---------------------------------------------------------------------------
286 // Script interpreter resolution
287 // ---------------------------------------------------------------------------
288
289 /// Parse a shebang line (`#!/usr/bin/env node`) to extract the interpreter.
290 fn parse_shebang(path: &Path) -> Option<(String, Vec<String>)> {
291 let mut file = std::fs::File::open(path).ok()?;
292 let content = read_prefix_to_string(&mut file, 256)?;
293 let first_line = content.lines().next()?;
294 let rest = first_line.strip_prefix("#!")?;
295 let parts: Vec<&str> = rest.split_whitespace().collect();
296 if parts.is_empty() {
297 return None;
298 }
299 let interpreter = parts[0].to_string();
300 let args: Vec<String> = parts[1..].iter().map(|s| s.to_string()).collect();
301 Some((interpreter, args))
302 }
303
304 /// Resolve the interpreter binary and pre-args for a script file.
305 ///
306 /// Priority:
307 /// 1. Shebang line from the script itself (`#!/usr/bin/env node`)
308 /// 2. Extension-based fallback for known script types
309 /// 3. Direct execution (assumes the OS knows how to run it)
310 fn resolve_interpreter(path: &Path) -> (String, Vec<String>) {
311 // 1. Try shebang
312 if let Some((interp, shebang_args)) = parse_shebang(path) {
313 let bin_name = interp.rsplit('/').next().unwrap_or(&interp);
314 // `env` is a special case: `#!/usr/bin/env node` → `node`
315 // On Windows, `env` is not available, so extract the intended binary.
316 if bin_name == "env" {
317 let env_args = match shebang_args.first().map(String::as_str) {
318 Some("-S" | "--split-string") => &shebang_args[1..],
319 _ => &shebang_args[..],
320 };
321 if let Some((program, args)) = env_args.split_first() {
322 return (program.clone(), args.to_vec());
323 }
324 }
325 if cfg!(windows) {
326 return (bin_name.to_string(), shebang_args);
327 }
328 return (interp, shebang_args);
329 }
330
331 // 2. Extension-based fallback for common script types
332 let ext = path
333 .extension()
334 .and_then(|e| e.to_str())
335 .unwrap_or("")
336 .to_lowercase();
337 match ext.as_str() {
338 "ps1" => ("powershell".into(), vec!["-File".into()]),
339 "py" => ("python".into(), vec![]),
340 "js" | "mjs" => ("node".into(), vec![]),
341 "ts" => ("npx".into(), vec!["tsx".into()]),
342 "rb" => ("ruby".into(), vec![]),
343 "sh" | "bash" | "zsh" => {
344 // On Windows, route shell scripts through sh if available
345 if cfg!(windows) {
346 ("sh".into(), vec![])
347 } else {
348 (path.to_string_lossy().into(), vec![])
349 }
350 }
351 _ => (path.to_string_lossy().into(), vec![]),
352 }
353 }
354
355 fn script_command_parts(script_path: &Path, args: &[String]) -> (String, Vec<String>) {
356 let (interpreter, mut script_args) = resolve_interpreter(script_path);
357 let script_path_arg = script_path.to_string_lossy().to_string();
358 if interpreter != script_path_arg {
359 script_args.push(script_path_arg);
360 }
361 script_args.extend(args.iter().cloned());
362 (interpreter, script_args)
363 }
364
365 fn read_prefix_to_string(reader: impl std::io::Read, max_bytes: u64) -> Option<String> {
366 use std::io::Read;
367
368 let mut buf = Vec::new();
369 reader.take(max_bytes).read_to_end(&mut buf).ok()?;
370 Some(String::from_utf8_lossy(&buf).into_owned())
371 }
372
373 // ---------------------------------------------------------------------------
374 // Shared child process helpers
375 // ---------------------------------------------------------------------------
376
377 /// Run a pre-configured tokio Command, pipe JSON input, collect ToolResult.
378 async fn run_plugin_child_raw(
379 cmd: &mut tokio::process::Command,
380 label: &str,
381 input: Value,
382 ) -> Result<ToolResult, ToolError> {
383 let input_bytes = serde_json::to_vec(&input)
384 .map_err(|e| ToolError::invalid_input(format!("failed to serialize input: {e}")))?;
385
386 // Contained: a timed-out or cancelled plugin takes everything it started
387 // down with it, not just the interpreter that `kill_on_drop` would reach.
388 let output = tokio::time::timeout(
389 PLUGIN_EXECUTION_TIMEOUT,
390 codewhale_runtime::process_tree::contained_output_with_input(cmd, input_bytes),
391 )
392 .await
393 .map_err(|_| ToolError::Timeout {
394 seconds: PLUGIN_EXECUTION_TIMEOUT.as_secs(),
395 })?
396 .map_err(|e| ToolError::execution_failed(format!("failed to run {label}: {e}")))?;
397
398 if output.status.success() {
399 let stdout = String::from_utf8_lossy(&output.stdout).to_string();
400 if let Ok(parsed) = serde_json::from_str::<ToolResult>(&stdout) {
401 Ok(parsed)
402 } else {
403 Ok(ToolResult::success(stdout))
404 }
405 } else {
406 let stderr = String::from_utf8_lossy(&output.stderr).to_string();
407 let stdout = String::from_utf8_lossy(&output.stdout).to_string();
408 let combined = if stderr.is_empty() {
409 stdout
410 } else if stdout.is_empty() {
411 stderr
412 } else {
413 format!("{stdout}\n{stderr}")
414 };
415 Err(ToolError::execution_failed(combined))
416 }
417 }
418
419 // ---------------------------------------------------------------------------
420 // Frontmatter parsing
421 // ---------------------------------------------------------------------------
422
423 /// Parse frontmatter header from the first `max_lines` lines of a text file.
424 ///
425 /// Expected format (one `# key: value` per line):
426 /// ```text
427 /// # name: my-tool
428 /// # description: Does something
429 /// # schema: {"type":"object"}
430 /// # approval: required
431 /// ```
432 ///
433 /// Also supports `// ` prefix for JavaScript/TypeScript scripts and `-- ` for Lua.
434 pub fn parse_frontmatter(content: &str) -> PluginMetadata {
435 let mut name = String::new();
436 let mut description = String::new();
437 let mut schema_str = String::new();
438 let mut approval_str = String::new();
439
440 for line in content.lines().take(20) {
441 let line = line.trim();
442 // Strip leading comment markers: `#`, `//`, `--`.
443 let rest = line
444 .strip_prefix('#')
445 .or_else(|| line.strip_prefix("//"))
446 .or_else(|| line.strip_prefix("--"));
447 let Some(rest) = rest else { continue };
448 if let Some((key, value)) = rest.trim_start().split_once(':') {
449 let key = key.trim().to_lowercase();
450 let value = value.trim();
451 match key.as_str() {
452 "name" => name = value.to_string(),
453 "description" => description = value.to_string(),
454 "schema" => schema_str = value.to_string(),
455 "approval" => approval_str = value.to_string(),
456 _ => {}
457 }
458 }
459 }
460
461 let input_schema = if schema_str.is_empty() {
462 // Default: accept any object payload
463 serde_json::json!({"type": "object"})
464 } else {
465 serde_json::from_str(&schema_str).unwrap_or_else(|_| serde_json::json!({"type": "object"}))
466 };
467
468 // A script cannot approve itself (D4): `auto` gets the default, flagged so
469 // the loaders can report it.
470 let (approval, auto_approval_ignored) = match approval_str.to_lowercase().as_str() {
471 "required" => (ApprovalRequirement::Required, false),
472 "auto" => (ApprovalRequirement::Suggest, true),
473 _ => (ApprovalRequirement::Suggest, false),
474 };
475
476 PluginMetadata {
477 name: if name.is_empty() {
478 "unnamed-plugin".to_string()
479 } else {
480 name
481 },
482 description: if description.is_empty() {
483 "User-provided plugin tool".to_string()
484 } else {
485 description
486 },
487 input_schema,
488 approval,
489 auto_approval_ignored,
490 }
491 }
492
493 /// Read the first 4 KB of a file and parse its frontmatter.
494 fn read_script_metadata(path: &Path) -> Option<PluginMetadata> {
495 let mut file = std::fs::File::open(path).ok()?;
496 let content = read_prefix_to_string(&mut file, 4096)?;
497 let meta = parse_frontmatter(&content);
498 // Require at least the `name` field to consider it a valid plugin.
499 if meta.name == "unnamed-plugin" {
500 return None;
501 }
502 Some(meta)
503 }
504
505 // ---------------------------------------------------------------------------
506 // Directory scanning
507 // ---------------------------------------------------------------------------
508
509 /// Scan a directory for plugin script files with frontmatter headers.
510 ///
511 /// Files are considered eligible when:
512 /// - They are regular files (not directories, not symlinks)
513 /// - They don't start with `.` (hidden files)
514 /// - They are not `README.md`
515 /// - Their first 20 lines contain `# name:` frontmatter
516 pub fn scan_plugin_dir(dir: &Path) -> Vec<(PathBuf, PluginMetadata)> {
517 let mut results = Vec::new();
518
519 let entries = match std::fs::read_dir(dir) {
520 Ok(entries) => entries,
521 Err(e) => {
522 tracing::warn!("Failed to read plugin directory {}: {e}", dir.display());
523 return results;
524 }
525 };
526
527 let mut entries: Vec<_> = entries.flatten().collect();
528 entries.sort_by_key(|entry| entry.file_name());
529
530 for entry in entries {
531 let path = entry.path();
532
533 // Skip directories and hidden files
534 if path.is_dir() {
535 continue;
536 }
537 if let Some(name) = path.file_name().and_then(|n| n.to_str())
538 && (name.starts_with('.') || name == "README.md")
539 {
540 continue;
541 }
542
543 // Try to parse frontmatter
544 if let Some(meta) = read_script_metadata(&path) {
545 results.push((path, meta));
546 }
547 }
548
549 results
550 }
551
552 /// Load all plugin tools from a directory. Each eligible script becomes
553 /// a registered `ScriptPluginTool`.
554 #[cfg(any(test, feature = "test-support"))]
555 pub fn load_plugin_tools(plugin_dir: &Path) -> Vec<Arc<dyn ToolSpec>> {
556 load_plugin_tools_with_executor(plugin_dir, PluginExecutor::for_engine())
557 }
558 pub fn load_plugin_tools_with_executor(
559 plugin_dir: &Path,
560 executor: PluginExecutor,
561 ) -> Vec<Arc<dyn ToolSpec>> {
562 let discovered = scan_plugin_dir(plugin_dir);
563 let mut tools: Vec<Arc<dyn ToolSpec>> = Vec::with_capacity(discovered.len());
564
565 for (path, meta) in discovered {
566 tracing::info!(
567 "Discovered plugin tool '{}' at {}",
568 meta.name,
569 path.display()
570 );
571 if meta.auto_approval_ignored {
572 warn_auto_approval_ignored(&meta.name);
573 }
574 tools.push(Arc::new(ScriptPluginTool {
575 executor: executor.clone(),
576 metadata: meta,
577 script_path: path,
578 args: Vec::new(),
579 }));
580 }
581
582 tools
583 }
584
585 /// Create a single tool from a `ToolOverride` config entry.
586 ///
587 /// Returns `None` for `Disabled` (the caller handles removal separately).
588 /// This builds the tool only; `ToolRegistry::apply_overrides_with_executor` decides whether
589 /// the name may be taken, and refuses one owned by a built-in.
590 #[cfg(any(test, feature = "test-support"))]
591 pub fn tool_from_override(
592 tool_name: &str,
593 override_cfg: &ToolOverride,
594 plugin_dir: &Path,
595 ) -> Option<Arc<dyn ToolSpec>> {
596 tool_from_override_with_executor(
597 tool_name,
598 override_cfg,
599 plugin_dir,
600 PluginExecutor::for_engine(),
601 )
602 }
603 pub fn tool_from_override_with_executor(
604 tool_name: &str,
605 override_cfg: &ToolOverride,
606 plugin_dir: &Path,
607 executor: PluginExecutor,
608 ) -> Option<Arc<dyn ToolSpec>> {
609 match override_cfg {
610 ToolOverride::Disabled => None,
611 ToolOverride::Script { path, args } => {
612 let script_path = if Path::new(path).is_absolute() {
613 PathBuf::from(path)
614 } else {
615 // Relative paths resolve relative to the plugin directory.
616 plugin_dir.join(path)
617 };
618
619 if !script_path.exists() {
620 tracing::warn!(
621 "Override script for '{}' not found at {}",
622 tool_name,
623 script_path.display()
624 );
625 return None;
626 }
627
628 // Read the script's own frontmatter for metadata, or provide
629 // defaults if it has none.
630 let mut meta = read_script_metadata(&script_path).unwrap_or_else(|| PluginMetadata {
631 name: tool_name.to_string(),
632 description: format!("Script tool '{tool_name}' from [tools.overrides]"),
633 input_schema: serde_json::json!({"type": "object"}),
634 approval: ApprovalRequirement::Suggest,
635 auto_approval_ignored: false,
636 });
637
638 // The config key owns the replacement target; frontmatter supplies metadata only.
639 meta.name = tool_name.to_string();
640 if meta.auto_approval_ignored {
641 warn_auto_approval_ignored(tool_name);
642 }
643
644 Some(Arc::new(ScriptPluginTool {
645 executor,
646 metadata: meta,
647 script_path,
648 args: args.clone().unwrap_or_default(),
649 }) as Arc<dyn ToolSpec>)
650 }
651 ToolOverride::Command { command, args } => {
652 // Build a description that includes the command.
653 let description = format!("Override for '{tool_name}' — runs: {command}");
654 let cmd_args = args.clone().unwrap_or_default();
655
656 Some(Arc::new(CommandPluginTool {
657 executor,
658 name: tool_name.to_string(),
659 description,
660 input_schema: serde_json::json!({"type": "object"}),
661 command: command.clone(),
662 args: cmd_args,
663 approval: ApprovalRequirement::Suggest,
664 }) as Arc<dyn ToolSpec>)
665 }
666 }
667 }
668
669 // ---------------------------------------------------------------------------
670 // Tests
671 // ---------------------------------------------------------------------------
672
673 #[cfg(test)]
674 mod tests {
675 use super::*;
676 use tempfile::TempDir;
677
678 const DEADLOCK_CHILD_ENV: &str = "CODEWHALE_PLUGIN_DEADLOCK_CHILD";
679
680 #[test]
681 fn test_parse_frontmatter_full() {
682 let content = "\
683 #!/usr/bin/env sh
684 # name: my-tool
685 # description: A useful custom tool
686 # schema: {\"type\":\"object\",\"properties\":{\"input\":{\"type\":\"string\"}}}
687 # approval: required
688 echo hello
689 ";
690 let meta = parse_frontmatter(content);
691 assert_eq!(meta.name, "my-tool");
692 assert_eq!(meta.description, "A useful custom tool");
693 assert_eq!(meta.approval, ApprovalRequirement::Required);
694 assert_eq!(
695 meta.input_schema,
696 serde_json::json!({"type":"object","properties":{"input":{"type":"string"}}})
697 );
698 }
699
700 #[test]
701 fn test_parse_frontmatter_accepts_compact_and_spaced_markers() {
702 let content = "\
703 #!/usr/bin/env node
704 #name:compact-name
705 // description: spaced description
706 -- schema : {\"type\":\"object\",\"properties\":{\"ok\":{\"type\":\"boolean\"}}}
707 # approval: auto
708 ";
709
710 let meta = parse_frontmatter(content);
711
712 assert_eq!(meta.name, "compact-name");
713 assert_eq!(meta.description, "spaced description");
714 assert_eq!(meta.approval, ApprovalRequirement::Suggest);
715 assert!(meta.auto_approval_ignored);
716 assert_eq!(
717 meta.input_schema,
718 serde_json::json!({"type":"object","properties":{"ok":{"type":"boolean"}}})
719 );
720 }
721
722 #[test]
723 fn test_parse_frontmatter_minimal() {
724 let content = "# name: mini";
725 let meta = parse_frontmatter(content);
726 assert_eq!(meta.name, "mini");
727 assert_eq!(meta.description, "User-provided plugin tool");
728 assert_eq!(meta.approval, ApprovalRequirement::Suggest);
729 }
730
731 #[test]
732 fn test_parse_frontmatter_missing_name() {
733 let content = "# description: no name here";
734 let meta = parse_frontmatter(content);
735 assert_eq!(meta.name, "unnamed-plugin");
736 // read_script_metadata would return None for this.
737 }
738
739 #[test]
740 fn test_read_prefix_collects_multiple_short_reads() {
741 struct OneByteReader {
742 bytes: Vec<u8>,
743 pos: usize,
744 }
745
746 impl std::io::Read for OneByteReader {
747 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
748 if self.pos >= self.bytes.len() {
749 return Ok(0);
750 }
751 buf[0] = self.bytes[self.pos];
752 self.pos += 1;
753 Ok(1)
754 }
755 }
756
757 let reader = OneByteReader {
758 bytes: b"# name: short-read\n# description: ok\n".to_vec(),
759 pos: 0,
760 };
761
762 assert_eq!(
763 read_prefix_to_string(reader, 4096).as_deref(),
764 Some("# name: short-read\n# description: ok\n")
765 );
766 }
767
768 #[test]
769 fn test_resolve_interpreter_handles_absolute_shebang_by_platform() {
770 let dir = TempDir::new().unwrap();
771 let script = dir.path().join("tool");
772 std::fs::write(
773 &script,
774 "#!/opt/custom/bin/tool-runner --safe\n# name: tool\n",
775 )
776 .unwrap();
777
778 let (interpreter, args) = resolve_interpreter(&script);
779
780 if cfg!(windows) {
781 assert_eq!(interpreter, "tool-runner");
782 } else {
783 assert_eq!(interpreter, "/opt/custom/bin/tool-runner");
784 }
785 assert_eq!(args, vec!["--safe"]);
786 }
787
788 #[test]
789 fn resolve_interpreter_skips_env_split_string_flag() {
790 let dir = TempDir::new().unwrap();
791 let script = dir.path().join("tool");
792 std::fs::write(&script, "#!/usr/bin/env -S python3 -u\n# name: tool\n").unwrap();
793
794 assert_eq!(
795 resolve_interpreter(&script),
796 ("python3".to_string(), vec!["-u".to_string()])
797 );
798 }
799
800 #[test]
801 fn test_script_command_parts_does_not_pass_direct_script_as_own_arg() {
802 let dir = TempDir::new().unwrap();
803 let script = dir.path().join("direct-tool");
804 std::fs::write(&script, "# name: direct\n").unwrap();
805
806 let (interpreter, args) =
807 script_command_parts(&script, &["--flag".to_string(), "value".to_string()]);
808
809 assert_eq!(interpreter, script.to_string_lossy());
810 assert_eq!(args, vec!["--flag", "value"]);
811 }
812
813 #[test]
814 fn test_script_command_parts_passes_script_to_external_interpreter() {
815 let dir = TempDir::new().unwrap();
816 let script = dir.path().join("script.py");
817 std::fs::write(&script, "# name: py\n").unwrap();
818
819 let (interpreter, args) = script_command_parts(&script, &["--flag".to_string()]);
820
821 assert_eq!(interpreter, "python");
822 assert_eq!(
823 args,
824 vec![script.to_string_lossy().to_string(), "--flag".to_string()]
825 );
826 }
827
828 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
829 async fn test_run_plugin_child_drains_stdout_while_writing_large_stdin() {
830 let mut cmd = tokio::process::Command::new(std::env::current_exe().unwrap());
831 cmd.arg("plugin_deadlock_child_process")
832 .arg("--nocapture")
833 .env(DEADLOCK_CHILD_ENV, "1");
834
835 let input = serde_json::json!({ "payload": "y".repeat(1024 * 1024) });
836 let result = tokio::time::timeout(
837 Duration::from_secs(10),
838 run_plugin_child_raw(&mut cmd, "deadlock child", input),
839 )
840 .await
841 .expect("plugin execution should not deadlock")
842 .expect("plugin child should succeed");
843
844 assert!(result.success);
845 assert!(result.content.len() > 64 * 1024);
846 }
847
848 /// A cancelled (or timed-out) plugin call kills what the plugin started,
849 /// not just the interpreter.
850 #[cfg(unix)]
851 #[tokio::test]
852 async fn dropped_plugin_call_kills_the_plugin_process_tree() {
853 let tmp = TempDir::new().unwrap();
854 let pid_file = tmp.path().join("grandchild.pid");
855 let mut cmd = tokio::process::Command::new("/bin/sh");
856 cmd.arg("-c")
857 .arg("sleep 300 & echo $! > grandchild.pid; wait")
858 .current_dir(tmp.path());
859 let run = run_plugin_child_raw(&mut cmd, "hanging plugin", serde_json::json!({}));
860 let grandchild =
861 codewhale_runtime::process_tree::drop_once_pid_written(run, &pid_file).await;
862 assert!(
863 codewhale_runtime::process_tree::wait_for_pid_exit(grandchild, Duration::from_secs(5)),
864 "a process started by the cancelled plugin is still running"
865 );
866 }
867
868 #[test]
869 fn plugin_deadlock_child_process() {
870 if std::env::var_os(DEADLOCK_CHILD_ENV).is_none() {
871 return;
872 }
873
874 use std::io::{Read, Write};
875
876 let mut stdout = std::io::stdout();
877 stdout.write_all(&vec![b'x'; 1024 * 1024]).unwrap();
878 stdout.flush().unwrap();
879
880 let mut stdin = Vec::new();
881 std::io::stdin().read_to_end(&mut stdin).unwrap();
882 writeln!(
883 stdout,
884 "{{\"content\":\"read {} bytes\",\"success\":true}}",
885 stdin.len()
886 )
887 .unwrap();
888 std::process::exit(0);
889 }
890
891 #[test]
892 fn test_scan_plugin_dir_finds_scripts() {
893 let dir = TempDir::new().unwrap();
894
895 // Valid plugin
896 std::fs::write(
897 dir.path().join("my-plugin.sh"),
898 "# name: my-plugin\n# description: test\n",
899 )
900 .unwrap();
901
902 // Hidden file — should be skipped
903 std::fs::write(
904 dir.path().join(".hidden.sh"),
905 "# name: hidden\n# description: should skip\n",
906 )
907 .unwrap();
908
909 // README — should be skipped
910 std::fs::write(dir.path().join("README.md"), "# Tools\n").unwrap();
911
912 // No frontmatter — should be skipped
913 std::fs::write(dir.path().join("random.sh"), "echo hi\n").unwrap();
914
915 let discovered = scan_plugin_dir(dir.path());
916 assert_eq!(discovered.len(), 1);
917 assert_eq!(discovered[0].1.name, "my-plugin");
918 }
919
920 #[test]
921 fn test_scan_plugin_dir_returns_files_sorted_by_name() {
922 let dir = TempDir::new().unwrap();
923 std::fs::write(
924 dir.path().join("z-plugin.sh"),
925 "# name: z-plugin\n# description: z\n",
926 )
927 .unwrap();
928 std::fs::write(
929 dir.path().join("a-plugin.sh"),
930 "# name: a-plugin\n# description: a\n",
931 )
932 .unwrap();
933
934 let discovered = scan_plugin_dir(dir.path());
935
936 let names: Vec<_> = discovered
937 .iter()
938 .map(|(_, meta)| meta.name.as_str())
939 .collect();
940 assert_eq!(names, vec!["a-plugin", "z-plugin"]);
941 }
942
943 #[test]
944 fn test_load_plugin_tools_creates_tools() {
945 let dir = TempDir::new().unwrap();
946 std::fs::write(
947 dir.path().join("greet.sh"),
948 "# name: greet\n# description: Say hello\n# schema: {\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"}},\"required\":[\"name\"]}\n",
949 )
950 .unwrap();
951
952 let tools = load_plugin_tools(dir.path());
953 assert_eq!(tools.len(), 1);
954 assert_eq!(tools[0].name(), "greet");
955 assert_eq!(tools[0].description(), "Say hello");
956 }
957
958 #[test]
959 fn runtime_surface_hardening_override_uses_configured_name() {
960 let dir = TempDir::new().unwrap();
961 std::fs::write(
962 dir.path().join("wrapper.sh"),
963 "# name: custom-shell\n# description: Audit wrapper for exec_shell\n",
964 )
965 .unwrap();
966
967 let override_cfg = ToolOverride::Script {
968 path: "wrapper.sh".to_string(),
969 args: None,
970 };
971
972 let tool = tool_from_override("exec_shell", &override_cfg, dir.path());
973 assert!(tool.is_some());
974 assert_eq!(tool.unwrap().name(), "exec_shell");
975 }
976
977 #[test]
978 fn test_tool_from_override_disabled() {
979 let dir = TempDir::new().unwrap();
980 let override_cfg = ToolOverride::Disabled;
981 let tool = tool_from_override("code_execution", &override_cfg, dir.path());
982 assert!(tool.is_none());
983 }
984
985 #[test]
986 fn test_tool_from_override_command() {
987 let dir = TempDir::new().unwrap();
988 let override_cfg = ToolOverride::Command {
989 command: "my-custom-reader".to_string(),
990 args: Some(vec!["--format".to_string(), "json".to_string()]),
991 };
992 let tool = tool_from_override("read_file", &override_cfg, dir.path());
993 assert!(tool.is_some());
994 assert_eq!(tool.unwrap().name(), "read_file");
995 }
996
997 #[test]
998 fn test_tool_from_override_script_absolute_path() {
999 let dir = TempDir::new().unwrap();
1000 let script_path = dir.path().join("audit.sh");
1001 std::fs::write(&script_path, "# name: exec_shell\n# description: Audit\n").unwrap();
1002
1003 let override_cfg = ToolOverride::Script {
1004 path: script_path.to_str().unwrap().to_string(),
1005 args: None,
1006 };
1007
1008 let tool = tool_from_override("exec_shell", &override_cfg, dir.path());
1009 assert!(tool.is_some());
1010 }
1011
1012 #[test]
1013 fn test_approval_variants() {
1014 let check = |content: &str, expected: ApprovalRequirement| {
1015 assert_eq!(parse_frontmatter(content).approval, expected);
1016 };
1017
1018 // D4: a script cannot approve itself; `auto` gets the default.
1019 check("# name: x\n# approval: auto", ApprovalRequirement::Suggest);
1020 check("# name: x\n# approval: AUTO", ApprovalRequirement::Suggest);
1021 check(
1022 "# name: x\n# approval: required",
1023 ApprovalRequirement::Required,
1024 );
1025 check(
1026 "# name: x\n# approval: suggest",
1027 ApprovalRequirement::Suggest,
1028 );
1029 check(
1030 "# name: x\n# approval: unknown",
1031 ApprovalRequirement::Suggest,
1032 );
1033 check("# name: x", ApprovalRequirement::Suggest);
1034 }
1035 }
1036
1036 lines RUST