| 1 | use std::collections::HashSet; |
| 2 | use std::io::Read; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::process::{Command, Stdio}; |
| 5 | use std::sync::{Arc, Mutex}; |
| 6 | use std::time::Duration; |
| 7 | |
| 8 | use codewhale_plugins::host_services::{AgentPosture, PluginApprover}; |
| 9 | use serde_json::{Value, json}; |
| 10 | use tempfile::TempDir; |
| 11 | use wait_timeout::ChildExt; |
| 12 | use wiremock::matchers::{method, path}; |
| 13 | use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate}; |
| 14 | |
| 15 | const TEST_MODEL: &str = "acceptance-model"; |
| 16 | |
| 17 | fn discover_node_binary() -> PathBuf { |
| 18 | for var in ["NODE_BINARY", "CODEWHALE_NODE_BINARY"] { |
| 19 | if let Some(value) = std::env::var_os(var) { |
| 20 | let candidate = PathBuf::from(value); |
| 21 | if candidate.is_file() { |
| 22 | return candidate; |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | let names: &[&str] = if cfg!(windows) { |
| 27 | &["node.exe", "node.cmd", "node"] |
| 28 | } else { |
| 29 | &["node"] |
| 30 | }; |
| 31 | if let Some(path_var) = std::env::var_os("PATH") { |
| 32 | for dir in std::env::split_paths(&path_var) { |
| 33 | for name in names { |
| 34 | let candidate = dir.join(name); |
| 35 | if candidate.is_file() { |
| 36 | return candidate; |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | for candidate in [ |
| 42 | Path::new("/opt/homebrew/bin/node"), |
| 43 | Path::new("/usr/local/bin/node"), |
| 44 | Path::new("/usr/bin/node"), |
| 45 | Path::new(r"C:\Program Files\nodejs\node.exe"), |
| 46 | ] { |
| 47 | if candidate.is_file() { |
| 48 | return candidate.to_path_buf(); |
| 49 | } |
| 50 | } |
| 51 | panic!("node binary required for creator_exec tests"); |
| 52 | } |
| 53 | |
| 54 | fn tool_package_json() -> String { |
| 55 | json!({ |
| 56 | "name": "@local/my-plugin", |
| 57 | "version": "1.0.0", |
| 58 | "private": true, |
| 59 | "type": "module", |
| 60 | "exports": { ".": "./index.js" }, |
| 61 | "dsh": { "bundle": { "patch": "./cordis.patch.yml" } } |
| 62 | }) |
| 63 | .to_string() |
| 64 | } |
| 65 | |
| 66 | fn tool_cordis_patch() -> &'static str { |
| 67 | "- insert:\n - id: my-plugin\n name: '@local/my-plugin'\n config: {}\n" |
| 68 | } |
| 69 | |
| 70 | fn tool_index_js(reply: &str) -> String { |
| 71 | format!( |
| 72 | "export const inject = ['tools', 'storage']\n\ |
| 73 | export function apply(ctx) {{\n \ |
| 74 | ctx.tools.register({{\n \ |
| 75 | name: 'loop_echo',\n \ |
| 76 | description: 'Echo from creator exec fixture.',\n \ |
| 77 | parameters: {{\n \ |
| 78 | type: 'object',\n \ |
| 79 | properties: {{ note: {{ type: 'string' }} }},\n \ |
| 80 | additionalProperties: false,\n }},\n \ |
| 81 | execute: async (input) => {{\n \ |
| 82 | if (input && typeof input.note === 'string') {{\n \ |
| 83 | await ctx.storage.set('saved_note', input.note)\n \ |
| 84 | }}\n \ |
| 85 | return {{ reply: {reply:?}, saved: (await ctx.storage.get('saved_note')) ?? null }}\n \ |
| 86 | }},\n }})\n\ |
| 87 | }}\n" |
| 88 | ) |
| 89 | } |
| 90 | |
| 91 | fn sse_chunk(value: Value) -> String { |
| 92 | format!( |
| 93 | "data: {}\n\n", |
| 94 | serde_json::to_string(&value).expect("SSE JSON") |
| 95 | ) |
| 96 | } |
| 97 | |
| 98 | fn tool_call_sse(id: &str, tool_name: &str, arguments: &str) -> String { |
| 99 | [ |
| 100 | sse_chunk(json!({ |
| 101 | "id": "chatcmpl-tool", |
| 102 | "object": "chat.completion.chunk", |
| 103 | "model": TEST_MODEL, |
| 104 | "choices": [{ |
| 105 | "index": 0, |
| 106 | "delta": { |
| 107 | "tool_calls": [{ |
| 108 | "index": 0, |
| 109 | "id": id, |
| 110 | "type": "function", |
| 111 | "function": { |
| 112 | "name": tool_name, |
| 113 | "arguments": arguments |
| 114 | } |
| 115 | }] |
| 116 | }, |
| 117 | "finish_reason": null |
| 118 | }] |
| 119 | })), |
| 120 | sse_chunk(json!({ |
| 121 | "id": "chatcmpl-tool", |
| 122 | "object": "chat.completion.chunk", |
| 123 | "model": TEST_MODEL, |
| 124 | "choices": [{ |
| 125 | "index": 0, |
| 126 | "delta": {}, |
| 127 | "finish_reason": "tool_calls" |
| 128 | }], |
| 129 | "usage": { |
| 130 | "prompt_tokens": 10, |
| 131 | "completion_tokens": 2, |
| 132 | "total_tokens": 12 |
| 133 | } |
| 134 | })), |
| 135 | "data: [DONE]\n\n".to_string(), |
| 136 | ] |
| 137 | .join("") |
| 138 | } |
| 139 | |
| 140 | fn final_answer_sse(answer: &str) -> String { |
| 141 | [ |
| 142 | sse_chunk(json!({ |
| 143 | "id": "chatcmpl-final", |
| 144 | "object": "chat.completion.chunk", |
| 145 | "model": TEST_MODEL, |
| 146 | "choices": [{ |
| 147 | "index": 0, |
| 148 | "delta": { "content": answer }, |
| 149 | "finish_reason": null |
| 150 | }] |
| 151 | })), |
| 152 | sse_chunk(json!({ |
| 153 | "id": "chatcmpl-final", |
| 154 | "object": "chat.completion.chunk", |
| 155 | "model": TEST_MODEL, |
| 156 | "choices": [{ |
| 157 | "index": 0, |
| 158 | "delta": {}, |
| 159 | "finish_reason": "stop" |
| 160 | }], |
| 161 | "usage": { |
| 162 | "prompt_tokens": 20, |
| 163 | "completion_tokens": 8, |
| 164 | "total_tokens": 28 |
| 165 | } |
| 166 | })), |
| 167 | "data: [DONE]\n\n".to_string(), |
| 168 | ] |
| 169 | .join("") |
| 170 | } |
| 171 | |
| 172 | fn sse_response(body: &str) -> ResponseTemplate { |
| 173 | ResponseTemplate::new(200) |
| 174 | .insert_header("content-type", "text/event-stream") |
| 175 | .insert_header("cache-control", "no-cache") |
| 176 | .set_body_string(body.to_string()) |
| 177 | } |
| 178 | |
| 179 | fn tool_messages(body: &Value) -> Vec<String> { |
| 180 | body.get("messages") |
| 181 | .and_then(Value::as_array) |
| 182 | .map(|msgs| { |
| 183 | msgs.iter() |
| 184 | .filter(|msg| msg.get("role").and_then(Value::as_str) == Some("tool")) |
| 185 | .filter_map(|msg| { |
| 186 | msg.get("content") |
| 187 | .and_then(Value::as_str) |
| 188 | .map(str::to_string) |
| 189 | }) |
| 190 | .collect() |
| 191 | }) |
| 192 | .unwrap_or_default() |
| 193 | } |
| 194 | |
| 195 | fn extract_skill_base_dir(text: &str) -> PathBuf { |
| 196 | let marker = "Base directory for this skill: `"; |
| 197 | let start = text |
| 198 | .find(marker) |
| 199 | .unwrap_or_else(|| panic!("missing base dir marker in:\n{text}")) |
| 200 | + marker.len(); |
| 201 | let rest = &text[start..]; |
| 202 | let end = rest |
| 203 | .find('`') |
| 204 | .unwrap_or_else(|| panic!("unclosed base dir backtick in:\n{text}")); |
| 205 | PathBuf::from(&rest[..end]) |
| 206 | } |
| 207 | |
| 208 | struct FullAccessResponder { |
| 209 | pkg_dir: PathBuf, |
| 210 | captured: Arc<Mutex<Vec<Value>>>, |
| 211 | } |
| 212 | |
| 213 | impl Respond for FullAccessResponder { |
| 214 | fn respond(&self, request: &Request) -> ResponseTemplate { |
| 215 | let body: Value = request.body_json().expect("request JSON"); |
| 216 | self.captured |
| 217 | .lock() |
| 218 | .expect("captured lock") |
| 219 | .push(body.clone()); |
| 220 | let results = tool_messages(&body); |
| 221 | let sse = match results.len() { |
| 222 | 0 => tool_call_sse( |
| 223 | "call_1", |
| 224 | "load_skill", |
| 225 | r#"{"name":"cordis-plugin-development"}"#, |
| 226 | ), |
| 227 | 1 => { |
| 228 | let base_dir = extract_skill_base_dir(&results[0]); |
| 229 | assert!(base_dir.ends_with("cordis-plugin-development")); |
| 230 | tool_call_sse( |
| 231 | "call_2", |
| 232 | "read", |
| 233 | &json!({ "path": base_dir.join("templates/decoration/package.json") }) |
| 234 | .to_string(), |
| 235 | ) |
| 236 | } |
| 237 | 2 => { |
| 238 | assert!(results[1].contains("dsh"), "{}", results[1]); |
| 239 | tool_call_sse( |
| 240 | "call_3", |
| 241 | "write", |
| 242 | &json!({ |
| 243 | "path": self.pkg_dir.join("package.json"), |
| 244 | "content": tool_package_json(), |
| 245 | }) |
| 246 | .to_string(), |
| 247 | ) |
| 248 | } |
| 249 | 3 => tool_call_sse( |
| 250 | "call_4", |
| 251 | "write", |
| 252 | &json!({ |
| 253 | "path": self.pkg_dir.join("cordis.patch.yml"), |
| 254 | "content": tool_cordis_patch(), |
| 255 | }) |
| 256 | .to_string(), |
| 257 | ), |
| 258 | 4 => tool_call_sse( |
| 259 | "call_5", |
| 260 | "write", |
| 261 | &json!({ |
| 262 | "path": self.pkg_dir.join("index.js"), |
| 263 | "content": tool_index_js("exec-v1"), |
| 264 | }) |
| 265 | .to_string(), |
| 266 | ), |
| 267 | 5 => tool_call_sse( |
| 268 | "call_6", |
| 269 | "plugin_manager", |
| 270 | &json!({ |
| 271 | "action": "install_bundle", |
| 272 | "target": self.pkg_dir, |
| 273 | }) |
| 274 | .to_string(), |
| 275 | ), |
| 276 | 6 => tool_call_sse("call_7", "loop_echo", r#"{"note":"from-exec"}"#), |
| 277 | _ => final_answer_sse("creator exec ok"), |
| 278 | }; |
| 279 | sse_response(&sse) |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | struct AskDenyResponder { |
| 284 | pkg_dir: PathBuf, |
| 285 | captured: Arc<Mutex<Vec<Value>>>, |
| 286 | } |
| 287 | |
| 288 | impl Respond for AskDenyResponder { |
| 289 | fn respond(&self, request: &Request) -> ResponseTemplate { |
| 290 | let body: Value = request.body_json().expect("request JSON"); |
| 291 | self.captured |
| 292 | .lock() |
| 293 | .expect("captured lock") |
| 294 | .push(body.clone()); |
| 295 | let results = tool_messages(&body); |
| 296 | let sse = if results.is_empty() { |
| 297 | tool_call_sse( |
| 298 | "call_deny", |
| 299 | "plugin_manager", |
| 300 | &json!({ |
| 301 | "action": "install_bundle", |
| 302 | "target": self.pkg_dir, |
| 303 | }) |
| 304 | .to_string(), |
| 305 | ) |
| 306 | } else { |
| 307 | final_answer_sse("denied as expected") |
| 308 | }; |
| 309 | sse_response(&sse) |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | fn prepare_hermetic_home(home: &Path, workspace: &Path, node: &Path) { |
| 314 | let codewhale_dir = home.join(".codewhale"); |
| 315 | std::fs::create_dir_all(&codewhale_dir).expect("create .codewhale"); |
| 316 | std::fs::create_dir_all(home.join(".deepseek")).expect("create .deepseek"); |
| 317 | let node_toml = toml::Value::String(node.to_string_lossy().into_owned()).to_string(); |
| 318 | codewhale_engine::test_support::install_project_cordis_skill_fixture(workspace); |
| 319 | let project = toml::Value::String( |
| 320 | workspace |
| 321 | .canonicalize() |
| 322 | .unwrap() |
| 323 | .to_string_lossy() |
| 324 | .into_owned(), |
| 325 | ) |
| 326 | .to_string(); |
| 327 | let config_toml = format!( |
| 328 | "[features]\nextension_host = true\nplugin_creator = true\n\n[extension_host]\nruntime = \"node\"\nnode = {node_toml}\n\n[projects.{project}]\ntrust_level = \"trusted\"\n" |
| 329 | ); |
| 330 | std::fs::write(codewhale_dir.join("config.toml"), config_toml).expect("write config.toml"); |
| 331 | } |
| 332 | |
| 333 | fn run_exec_binary( |
| 334 | workspace: &Path, |
| 335 | home: &Path, |
| 336 | node: &Path, |
| 337 | server_uri: &str, |
| 338 | permission_mode: Option<&str>, |
| 339 | exec_args: &[&str], |
| 340 | ) -> std::process::Output { |
| 341 | let mut command = Command::new(crate::binary::codewhale()); |
| 342 | command.env_clear(); |
| 343 | for key in [ |
| 344 | "PATHEXT", |
| 345 | "SystemRoot", |
| 346 | "SystemDrive", |
| 347 | "WINDIR", |
| 348 | "LOCALAPPDATA", |
| 349 | "APPDATA", |
| 350 | "PROGRAMDATA", |
| 351 | "COMSPEC", |
| 352 | "TEMP", |
| 353 | "TMP", |
| 354 | "TMPDIR", |
| 355 | "TERM", |
| 356 | "COLORTERM", |
| 357 | "LANG", |
| 358 | "LC_ALL", |
| 359 | ] { |
| 360 | if let Some(value) = std::env::var_os(key) { |
| 361 | command.env(key, value); |
| 362 | } |
| 363 | } |
| 364 | let mut path_entries = Vec::new(); |
| 365 | if let Some(parent) = node.parent() { |
| 366 | path_entries.push(parent.to_path_buf()); |
| 367 | } |
| 368 | if let Some(existing) = std::env::var_os("PATH") { |
| 369 | let mut seen: HashSet<PathBuf> = path_entries.iter().cloned().collect(); |
| 370 | for dir in std::env::split_paths(&existing) { |
| 371 | if seen.insert(dir.clone()) { |
| 372 | path_entries.push(dir); |
| 373 | } |
| 374 | } |
| 375 | } |
| 376 | let joined_path = std::env::join_paths(path_entries).expect("join PATH"); |
| 377 | |
| 378 | command |
| 379 | .current_dir(workspace) |
| 380 | .arg("--workspace") |
| 381 | .arg(workspace) |
| 382 | .arg("--no-project-config"); |
| 383 | if let Some(mode) = permission_mode { |
| 384 | command.arg("--permission-mode").arg(mode); |
| 385 | } |
| 386 | command |
| 387 | .arg("exec") |
| 388 | .arg("--conversation-mode") |
| 389 | .arg("creator") |
| 390 | .args(exec_args) |
| 391 | .arg("--model") |
| 392 | .arg(TEST_MODEL) |
| 393 | .arg("--output-format") |
| 394 | .arg("stream-json") |
| 395 | .arg("create and call loop_echo") |
| 396 | .env("PATH", joined_path) |
| 397 | .env("HOME", home) |
| 398 | .env("USERPROFILE", home) |
| 399 | .env("XDG_CONFIG_HOME", home.join(".config")) |
| 400 | .env("XDG_DATA_HOME", home.join(".local").join("share")) |
| 401 | .env("XDG_CACHE_HOME", home.join(".cache")) |
| 402 | .env("CODEWHALE_HOME", home.join(".codewhale")) |
| 403 | .env( |
| 404 | "CODEWHALE_CONFIG_PATH", |
| 405 | home.join(".codewhale").join("config.toml"), |
| 406 | ) |
| 407 | .env( |
| 408 | "DEEPSEEK_CONFIG_PATH", |
| 409 | home.join(".deepseek").join("config.toml"), |
| 410 | ) |
| 411 | .env("DEEPSEEK_API_KEY", "ci-test-key-not-real") |
| 412 | .env("DEEPSEEK_BASE_URL", server_uri) |
| 413 | .env("CODEWHALE_BASE_URL", server_uri) |
| 414 | .env("DEEPSEEK_MODEL", TEST_MODEL) |
| 415 | .env("CODEWHALE_MODEL", TEST_MODEL) |
| 416 | .env("CODEWHALE_DISABLE_MODELS_DEV_FETCH", "1") |
| 417 | .env("CODEWHALE_NO_UPDATE_CHECK", "1") |
| 418 | .env("CODEWHALE_DISABLE_LOCAL_OLLAMA_PROBE", "1") |
| 419 | .env("RUST_LOG", "warn") |
| 420 | .stdin(Stdio::null()) |
| 421 | .stdout(Stdio::piped()) |
| 422 | .stderr(Stdio::piped()); |
| 423 | |
| 424 | let mut child = command.spawn().expect("spawn codewhale exec"); |
| 425 | let mut stdout_pipe = child.stdout.take().expect("stdout pipe"); |
| 426 | let mut stderr_pipe = child.stderr.take().expect("stderr pipe"); |
| 427 | let stdout_reader = std::thread::spawn(move || { |
| 428 | let mut buf = Vec::new(); |
| 429 | stdout_pipe.read_to_end(&mut buf).map(|_| buf) |
| 430 | }); |
| 431 | let stderr_reader = std::thread::spawn(move || { |
| 432 | let mut buf = Vec::new(); |
| 433 | stderr_pipe.read_to_end(&mut buf).map(|_| buf) |
| 434 | }); |
| 435 | |
| 436 | let status = match child |
| 437 | .wait_timeout(Duration::from_secs(90)) |
| 438 | .expect("wait codewhale exec") |
| 439 | { |
| 440 | Some(status) => status, |
| 441 | None => { |
| 442 | let _ = child.kill(); |
| 443 | let _ = child.wait(); |
| 444 | let out = stdout_reader |
| 445 | .join() |
| 446 | .expect("stdout join") |
| 447 | .unwrap_or_default(); |
| 448 | let err = stderr_reader |
| 449 | .join() |
| 450 | .expect("stderr join") |
| 451 | .unwrap_or_default(); |
| 452 | panic!( |
| 453 | "codewhale exec timed out\nstdout:\n{}\nstderr:\n{}", |
| 454 | String::from_utf8_lossy(&out), |
| 455 | String::from_utf8_lossy(&err) |
| 456 | ); |
| 457 | } |
| 458 | }; |
| 459 | let stdout = stdout_reader |
| 460 | .join() |
| 461 | .expect("stdout join") |
| 462 | .expect("read stdout"); |
| 463 | let stderr = stderr_reader |
| 464 | .join() |
| 465 | .expect("stderr join") |
| 466 | .expect("read stderr"); |
| 467 | std::process::Output { |
| 468 | status, |
| 469 | stdout, |
| 470 | stderr, |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | fn stream_events(stdout: &[u8]) -> Vec<Value> { |
| 475 | String::from_utf8_lossy(stdout) |
| 476 | .lines() |
| 477 | .filter(|line| !line.trim().is_empty()) |
| 478 | .map(|line| serde_json::from_str(line).unwrap_or_else(|e| panic!("bad JSONL {e}: {line}"))) |
| 479 | .collect() |
| 480 | } |
| 481 | |
| 482 | #[tokio::test(flavor = "multi_thread", worker_threads = 2)] |
| 483 | async fn creator_exec_full_access_installs_and_calls_its_tool() { |
| 484 | let node = discover_node_binary(); |
| 485 | let home = TempDir::new().expect("home tempdir"); |
| 486 | let workspace = TempDir::new().expect("workspace tempdir"); |
| 487 | prepare_hermetic_home(home.path(), workspace.path(), &node); |
| 488 | let pkg_dir = workspace.path().join("my-plugin"); |
| 489 | |
| 490 | let server = MockServer::start().await; |
| 491 | Mock::given(method("GET")) |
| 492 | .and(path("/v1/models")) |
| 493 | .respond_with( |
| 494 | ResponseTemplate::new(200) |
| 495 | .insert_header("content-type", "application/json") |
| 496 | .set_body_json(json!({ |
| 497 | "object": "list", |
| 498 | "data": [{ "id": TEST_MODEL, "object": "model" }] |
| 499 | })), |
| 500 | ) |
| 501 | .mount(&server) |
| 502 | .await; |
| 503 | |
| 504 | let captured = Arc::new(Mutex::new(Vec::new())); |
| 505 | Mock::given(method("POST")) |
| 506 | .and(path("/v1/chat/completions")) |
| 507 | .respond_with(FullAccessResponder { |
| 508 | pkg_dir: pkg_dir.clone(), |
| 509 | captured: Arc::clone(&captured), |
| 510 | }) |
| 511 | .mount(&server) |
| 512 | .await; |
| 513 | |
| 514 | let uri = server.uri(); |
| 515 | let ws_path = workspace.path().to_path_buf(); |
| 516 | let home_path = home.path().to_path_buf(); |
| 517 | let output = tokio::task::spawn_blocking(move || { |
| 518 | run_exec_binary(&ws_path, &home_path, &node, &uri, None, &["--auto"]) |
| 519 | }) |
| 520 | .await |
| 521 | .expect("spawn_blocking join"); |
| 522 | |
| 523 | let stdout_str = String::from_utf8_lossy(&output.stdout); |
| 524 | let stderr_str = String::from_utf8_lossy(&output.stderr); |
| 525 | assert!( |
| 526 | output.status.success(), |
| 527 | "codewhale exec failed ({:?})\nstdout:\n{stdout_str}\nstderr:\n{stderr_str}", |
| 528 | output.status.code() |
| 529 | ); |
| 530 | |
| 531 | let starter_dir = home.path().join(".codewhale/skills/.system"); |
| 532 | assert!(starter_dir.join("plugin-creator/SKILL.md").is_file()); |
| 533 | |
| 534 | let requests = captured.lock().expect("captured lock"); |
| 535 | assert!(!requests.is_empty()); |
| 536 | let first_tools = requests[0]["tools"] |
| 537 | .as_array() |
| 538 | .expect("tools on first request"); |
| 539 | assert!( |
| 540 | first_tools |
| 541 | .iter() |
| 542 | .any(|t| t["function"]["name"] == "plugin_manager" || t["name"] == "plugin_manager"), |
| 543 | "expected plugin_manager in first request: {}", |
| 544 | requests[0] |
| 545 | ); |
| 546 | assert!( |
| 547 | requests.iter().all(|req| { |
| 548 | !req["messages"] |
| 549 | .to_string() |
| 550 | .contains("\"name\":\"tool_search\"") |
| 551 | }), |
| 552 | "model must not call tool_search in creator full access" |
| 553 | ); |
| 554 | drop(requests); |
| 555 | |
| 556 | let events = stream_events(&output.stdout); |
| 557 | let loop_echo_result = events |
| 558 | .iter() |
| 559 | .find(|ev| { |
| 560 | ev.get("type").and_then(Value::as_str) == Some("tool_result") |
| 561 | && ev.get("name").and_then(Value::as_str) == Some("loop_echo") |
| 562 | }) |
| 563 | .unwrap_or_else(|| panic!("missing loop_echo tool_result in:\n{stdout_str}")); |
| 564 | assert_eq!(loop_echo_result["status"], json!("success")); |
| 565 | let echo_output = loop_echo_result["output"].as_str().expect("output string"); |
| 566 | assert!(echo_output.contains("exec-v1"), "{echo_output}"); |
| 567 | assert!(echo_output.contains("from-exec"), "{echo_output}"); |
| 568 | |
| 569 | let state_raw = std::fs::read_to_string(home.path().join(".codewhale/plugins/state.json")) |
| 570 | .expect("read plugin state.json"); |
| 571 | let state: Value = serde_json::from_str(&state_raw).expect("parse state.json"); |
| 572 | let plugins = state["plugins"].as_object().expect("plugins object"); |
| 573 | let (_, entry) = plugins |
| 574 | .iter() |
| 575 | .find(|(id, _)| id.ends_with("my-plugin")) |
| 576 | .expect("my-plugin state entry"); |
| 577 | assert_eq!(entry["enabled"], json!(true)); |
| 578 | let approver: PluginApprover = |
| 579 | serde_json::from_value(entry["trust"]["approved_by"].clone()).expect("approved_by"); |
| 580 | match approver { |
| 581 | PluginApprover::Agent(agent) => { |
| 582 | assert_eq!(agent.posture, AgentPosture::FullAccess); |
| 583 | } |
| 584 | other => panic!("expected Agent FullAccess approval, got {other:?}"), |
| 585 | } |
| 586 | |
| 587 | drop(server); |
| 588 | } |
| 589 | |
| 590 | #[tokio::test(flavor = "multi_thread", worker_threads = 2)] |
| 591 | async fn creator_exec_ask_is_denied_and_installs_nothing() { |
| 592 | let node = discover_node_binary(); |
| 593 | let home = TempDir::new().expect("home tempdir"); |
| 594 | let workspace = TempDir::new().expect("workspace tempdir"); |
| 595 | prepare_hermetic_home(home.path(), workspace.path(), &node); |
| 596 | let pkg_dir = workspace.path().join("my-plugin"); |
| 597 | std::fs::create_dir_all(&pkg_dir).expect("mkdir pkg"); |
| 598 | std::fs::write(pkg_dir.join("package.json"), tool_package_json()).expect("write pkg"); |
| 599 | std::fs::write(pkg_dir.join("cordis.patch.yml"), tool_cordis_patch()).expect("write patch"); |
| 600 | std::fs::write(pkg_dir.join("index.js"), tool_index_js("never")).expect("write index"); |
| 601 | |
| 602 | let server = MockServer::start().await; |
| 603 | Mock::given(method("GET")) |
| 604 | .and(path("/v1/models")) |
| 605 | .respond_with( |
| 606 | ResponseTemplate::new(200) |
| 607 | .insert_header("content-type", "application/json") |
| 608 | .set_body_json(json!({ |
| 609 | "object": "list", |
| 610 | "data": [{ "id": TEST_MODEL, "object": "model" }] |
| 611 | })), |
| 612 | ) |
| 613 | .mount(&server) |
| 614 | .await; |
| 615 | |
| 616 | let captured = Arc::new(Mutex::new(Vec::new())); |
| 617 | Mock::given(method("POST")) |
| 618 | .and(path("/v1/chat/completions")) |
| 619 | .respond_with(AskDenyResponder { |
| 620 | pkg_dir: pkg_dir.clone(), |
| 621 | captured: Arc::clone(&captured), |
| 622 | }) |
| 623 | .mount(&server) |
| 624 | .await; |
| 625 | |
| 626 | let uri = server.uri(); |
| 627 | let ws_path = workspace.path().to_path_buf(); |
| 628 | let home_path = home.path().to_path_buf(); |
| 629 | let output = tokio::task::spawn_blocking(move || { |
| 630 | run_exec_binary(&ws_path, &home_path, &node, &uri, Some("ask"), &[]) |
| 631 | }) |
| 632 | .await |
| 633 | .expect("spawn_blocking join"); |
| 634 | |
| 635 | let stdout_str = String::from_utf8_lossy(&output.stdout); |
| 636 | let stderr_str = String::from_utf8_lossy(&output.stderr); |
| 637 | let events = stream_events(&output.stdout); |
| 638 | |
| 639 | let pm_result = events |
| 640 | .iter() |
| 641 | .find(|ev| { |
| 642 | ev.get("type").and_then(Value::as_str) == Some("tool_result") |
| 643 | && ev.get("name").and_then(Value::as_str) == Some("plugin_manager") |
| 644 | }) |
| 645 | .unwrap_or_else(|| { |
| 646 | panic!("missing plugin_manager tool_result:\n{stdout_str}\n{stderr_str}") |
| 647 | }); |
| 648 | assert_eq!(pm_result["status"], json!("error"), "{pm_result}"); |
| 649 | assert_eq!( |
| 650 | pm_result["error_category"], |
| 651 | json!("permission_denied"), |
| 652 | "{pm_result}" |
| 653 | ); |
| 654 | let pm_output = pm_result["output"] |
| 655 | .as_str() |
| 656 | .expect("plugin_manager error output"); |
| 657 | assert!( |
| 658 | pm_output.contains("denied by user") |
| 659 | && pm_output.contains("the call was not approved") |
| 660 | && pm_output.contains("approval"), |
| 661 | "expected permission_denied approval message in tool_result\nstdout:\n{stdout_str}\nstderr:\n{stderr_str}" |
| 662 | ); |
| 663 | let meta_event = events |
| 664 | .iter() |
| 665 | .find(|ev| ev.get("type").and_then(Value::as_str) == Some("metadata")) |
| 666 | .unwrap_or_else(|| panic!("missing metadata receipt:\n{stdout_str}\n{stderr_str}")); |
| 667 | assert_eq!( |
| 668 | meta_event["meta"]["approval_posture"], |
| 669 | json!("ask"), |
| 670 | "{meta_event}" |
| 671 | ); |
| 672 | assert!(!home.path().join(".codewhale/plugins/state.json").exists()); |
| 673 | |
| 674 | drop(server); |
| 675 | } |
| 676 |