| 1 | //! DSH import through the pinned upstream nonexecuting reviewer. All product |
| 2 | //! preview/install callers share this preparation and existing atomic installer. |
| 3 | //! Portable Rust MCP/skills remain core-owned. Closed relative Native modules |
| 4 | //! mount through the one host Loader. Bare exports come only from exact |
| 5 | //! admitted package manifests; mixed missing/unbridged rows refuse explicitly, |
| 6 | //! never a partial compatibility claim. Native install still lands disabled/untrusted and requires review. |
| 7 | |
| 8 | use std::collections::{BTreeMap, BTreeSet}; |
| 9 | use std::fs; |
| 10 | use std::io::Read as _; |
| 11 | use std::path::{Component, Path, PathBuf}; |
| 12 | |
| 13 | use anyhow::Result; |
| 14 | use regex::Regex; |
| 15 | use serde::Serialize; |
| 16 | use serde_json::{Value as Json, json}; |
| 17 | |
| 18 | pub mod presets; |
| 19 | |
| 20 | pub const CONVERTER_VERSION: &str = "0.10.1"; |
| 21 | const MAX_FILES: usize = 16_384; |
| 22 | const MAX_BYTES: usize = 256 * 1024 * 1024; |
| 23 | const MAX_DOCUMENT: usize = 1024 * 1024; |
| 24 | const MAX_PATCH_FILES: usize = 64; |
| 25 | const MAX_DEPTH: usize = 32; |
| 26 | const MAX_SERVERS: usize = 64; |
| 27 | const DSH_MCP_CLIENT: &str = "@deepseek-ai/dsh-mcp-client"; |
| 28 | const DSH_SKILL_FILESYSTEM: &str = "@deepseek-ai/dsh-skill-filesystem"; |
| 29 | |
| 30 | fn refuse<T>(message: impl Into<String>) -> Result<T> { |
| 31 | Err(anyhow::Error::msg(message.into())) |
| 32 | } |
| 33 | |
| 34 | fn require(condition: bool, message: &str) -> Result<()> { |
| 35 | if condition { Ok(()) } else { refuse(message) } |
| 36 | } |
| 37 | |
| 38 | /// A refusal names at most this many rows and counts the rest. |
| 39 | const MAX_REFUSAL_ROWS: usize = 5; |
| 40 | /// Longest package-authored fragment quoted in a refusal, in characters. |
| 41 | pub const MAX_REFUSAL_TEXT: usize = 120; |
| 42 | |
| 43 | /// Package-authored text for a one-line refusal: bounded, with control and |
| 44 | /// bidirectional-format characters shown as escapes. A refusal is plain text |
| 45 | /// (error line, Runtime API), so this is not the review's Markdown escape. |
| 46 | pub fn refusal_text(text: &str) -> String { |
| 47 | let mut shown = String::new(); |
| 48 | for ch in text.chars().take(MAX_REFUSAL_TEXT) { |
| 49 | match ch { |
| 50 | '\'' | '"' => shown.push(ch), |
| 51 | _ => shown.extend(ch.escape_debug()), |
| 52 | } |
| 53 | } |
| 54 | if text.chars().nth(MAX_REFUSAL_TEXT).is_some() { |
| 55 | shown.push('…'); |
| 56 | } |
| 57 | shown |
| 58 | } |
| 59 | |
| 60 | /// The first rows of a refusal, then how many more were left out. |
| 61 | pub fn refusal_list(mut rows: impl Iterator<Item = String>) -> String { |
| 62 | let mut shown: Vec<String> = rows.by_ref().take(MAX_REFUSAL_ROWS).collect(); |
| 63 | let more = rows.count(); |
| 64 | if more > 0 { |
| 65 | shown.push(format!("and {more} more")); |
| 66 | } |
| 67 | shown.join("; ") |
| 68 | } |
| 69 | |
| 70 | fn pattern(source: &str) -> Regex { |
| 71 | Regex::new(source).expect("static pattern") |
| 72 | } |
| 73 | |
| 74 | // ───────────────────────────────────────────────────────────────────────────── |
| 75 | // Closed data model |
| 76 | // ───────────────────────────────────────────────────────────────────────────── |
| 77 | |
| 78 | /// Parsed configuration data. `Js` is an unevaluated `!!js` scalar; it is |
| 79 | /// never executed. Maps keep source order. |
| 80 | #[derive(Debug, Clone, PartialEq)] |
| 81 | pub enum Value { |
| 82 | Null, |
| 83 | Bool(bool), |
| 84 | Int(i64), |
| 85 | Float(f64), |
| 86 | Str(String), |
| 87 | Js(String), |
| 88 | Seq(Vec<Value>), |
| 89 | Map(Vec<(String, Value)>), |
| 90 | } |
| 91 | |
| 92 | impl Value { |
| 93 | pub fn get(&self, key: &str) -> Option<&Value> { |
| 94 | match self { |
| 95 | Value::Map(entries) => entries.iter().find(|(k, _)| k == key).map(|(_, v)| v), |
| 96 | _ => None, |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | #[cfg(any(test, feature = "test-support"))] |
| 101 | pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> { |
| 102 | match self { |
| 103 | Value::Map(entries) => entries.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v), |
| 104 | _ => None, |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | fn set(&mut self, key: &str, value: Value) { |
| 109 | if let Value::Map(entries) = self { |
| 110 | match entries.iter_mut().find(|(k, _)| k == key) { |
| 111 | Some(slot) => slot.1 = value, |
| 112 | None => entries.push((key.to_string(), value)), |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | pub(super) fn str(&self) -> Option<&str> { |
| 118 | match self { |
| 119 | Value::Str(text) => Some(text), |
| 120 | _ => None, |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | fn keys(&self) -> Vec<&str> { |
| 125 | match self { |
| 126 | Value::Map(entries) => entries.iter().map(|(k, _)| k.as_str()).collect(), |
| 127 | _ => Vec::new(), |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | pub(super) fn is_true(&self) -> bool { |
| 132 | matches!(self, Value::Bool(true)) |
| 133 | } |
| 134 | |
| 135 | fn free_of_js(&self) -> bool { |
| 136 | match self { |
| 137 | Value::Js(_) => false, |
| 138 | Value::Seq(items) => items.iter().all(Value::free_of_js), |
| 139 | Value::Map(entries) => entries.iter().all(|(_, v)| v.free_of_js()), |
| 140 | _ => true, |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | fn to_json(&self) -> Json { |
| 145 | match self { |
| 146 | Value::Null | Value::Js(_) => Json::Null, |
| 147 | Value::Bool(value) => Json::Bool(*value), |
| 148 | Value::Int(value) => json!(value), |
| 149 | Value::Float(value) => { |
| 150 | serde_json::Number::from_f64(*value).map_or(Json::Null, Json::Number) |
| 151 | } |
| 152 | Value::Str(value) => Json::String(value.clone()), |
| 153 | Value::Seq(items) => Json::Array(items.iter().map(Value::to_json).collect()), |
| 154 | Value::Map(entries) => Json::Object( |
| 155 | entries |
| 156 | .iter() |
| 157 | .map(|(k, v)| (k.clone(), v.to_json())) |
| 158 | .collect(), |
| 159 | ), |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | /// Keys must be strings, unique, and limited to `allowed` when given. |
| 165 | fn mapping<'a>(value: &'a Value, allowed: Option<&[&str]>) -> Result<&'a [(String, Value)]> { |
| 166 | let Value::Map(entries) = value else { |
| 167 | return refuse("Expected a configuration object."); |
| 168 | }; |
| 169 | if let Some(allowed) = allowed { |
| 170 | require( |
| 171 | entries |
| 172 | .iter() |
| 173 | .all(|(key, _)| allowed.contains(&key.as_str())), |
| 174 | "Unsupported fields; select only documented portable declarations.", |
| 175 | )?; |
| 176 | } |
| 177 | Ok(entries) |
| 178 | } |
| 179 | |
| 180 | const PARSE_REFUSAL: &str = |
| 181 | "Cannot parse portable data; use plain YAML or JSON for DSH bundle files."; |
| 182 | |
| 183 | /// Closed YAML parsing: no aliases, no explicit tags except `!!js` on |
| 184 | /// scalars (when allowed), no duplicate or non-string keys, at most one |
| 185 | /// document and 32 levels. Parser errors are not echoed: they can contain |
| 186 | /// source lines and credentials. |
| 187 | pub fn parse_yaml(text: &str, allow_js: bool) -> Result<Value> { |
| 188 | use yaml_rust2::parser::{Event, Parser}; |
| 189 | use yaml_rust2::scanner::TScalarStyle; |
| 190 | |
| 191 | enum Frame { |
| 192 | Seq(Vec<Value>), |
| 193 | Map(Vec<(String, Value)>, Option<String>), |
| 194 | } |
| 195 | |
| 196 | fn place(stack: &mut [Frame], root: &mut Option<Value>, value: Value) -> Result<()> { |
| 197 | match stack.last_mut() { |
| 198 | None => { |
| 199 | *root = Some(value); |
| 200 | Ok(()) |
| 201 | } |
| 202 | Some(Frame::Seq(items)) => { |
| 203 | items.push(value); |
| 204 | Ok(()) |
| 205 | } |
| 206 | Some(Frame::Map(entries, pending)) => match pending.take() { |
| 207 | None => { |
| 208 | let Value::Str(key) = value else { |
| 209 | return refuse("Object keys must be strings."); |
| 210 | }; |
| 211 | require( |
| 212 | !entries.iter().any(|(existing, _)| *existing == key), |
| 213 | "Duplicate or non-string object key.", |
| 214 | )?; |
| 215 | require( |
| 216 | key != "__jsExpr", |
| 217 | "DSH executable expressions require a manual port.", |
| 218 | )?; |
| 219 | *pending = Some(key); |
| 220 | Ok(()) |
| 221 | } |
| 222 | Some(key) => { |
| 223 | entries.push((key, value)); |
| 224 | Ok(()) |
| 225 | } |
| 226 | }, |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | fn plain_scalar(text: &str) -> Value { |
| 231 | match text { |
| 232 | "" | "~" | "null" | "Null" | "NULL" => return Value::Null, |
| 233 | "true" | "True" | "TRUE" => return Value::Bool(true), |
| 234 | "false" | "False" | "FALSE" => return Value::Bool(false), |
| 235 | ".inf" | ".Inf" | ".INF" | "+.inf" | "+.Inf" | "+.INF" => { |
| 236 | return Value::Float(f64::INFINITY); |
| 237 | } |
| 238 | "-.inf" | "-.Inf" | "-.INF" => return Value::Float(f64::NEG_INFINITY), |
| 239 | ".nan" | ".NaN" | ".NAN" => return Value::Float(f64::NAN), |
| 240 | _ => {} |
| 241 | } |
| 242 | let integer = |digits: &str, radix| i64::from_str_radix(digits, radix).ok(); |
| 243 | if let Some(value) = text |
| 244 | .strip_prefix("0x") |
| 245 | .and_then(|digits| integer(digits, 16)) |
| 246 | .or_else(|| { |
| 247 | text.strip_prefix("0o") |
| 248 | .and_then(|digits| integer(digits, 8)) |
| 249 | }) |
| 250 | { |
| 251 | return Value::Int(value); |
| 252 | } |
| 253 | let bytes = text.strip_prefix(['-', '+']).unwrap_or(text); |
| 254 | if !bytes.is_empty() |
| 255 | && bytes.bytes().all(|b| b.is_ascii_digit()) |
| 256 | && let Ok(value) = text.parse::<i64>() |
| 257 | { |
| 258 | return Value::Int(value); |
| 259 | } |
| 260 | let float = pattern(r"^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$"); |
| 261 | if float.is_match(text) |
| 262 | && let Ok(value) = text.parse::<f64>() |
| 263 | { |
| 264 | return Value::Float(value); |
| 265 | } |
| 266 | Value::Str(text.to_string()) |
| 267 | } |
| 268 | |
| 269 | let is_js_tag = |tag: &yaml_rust2::parser::Tag| { |
| 270 | tag.suffix == "js" && (tag.handle == "!!" || tag.handle == "tag:yaml.org,2002:") |
| 271 | }; |
| 272 | |
| 273 | let mut parser = Parser::new_from_str(text); |
| 274 | let mut stack: Vec<Frame> = Vec::new(); |
| 275 | let mut root: Option<Value> = None; |
| 276 | let mut documents = 0usize; |
| 277 | loop { |
| 278 | let (event, _) = parser |
| 279 | .next_token() |
| 280 | .map_err(|_| anyhow::Error::msg(PARSE_REFUSAL))?; |
| 281 | match event { |
| 282 | Event::StreamEnd => break, |
| 283 | Event::StreamStart | Event::Nothing | Event::DocumentEnd => {} |
| 284 | Event::DocumentStart => { |
| 285 | documents += 1; |
| 286 | require(documents <= 1, PARSE_REFUSAL)?; |
| 287 | } |
| 288 | Event::Alias(_) => return refuse("YAML aliases are unsupported."), |
| 289 | Event::Scalar(text, style, _anchor, tag) => { |
| 290 | let value = match tag { |
| 291 | Some(tag) if allow_js && is_js_tag(&tag) => Value::Js(text), |
| 292 | Some(_) => { |
| 293 | return refuse( |
| 294 | "YAML aliases and explicit tags (including !!js) are unsupported.", |
| 295 | ); |
| 296 | } |
| 297 | None if matches!(style, TScalarStyle::Plain) => plain_scalar(&text), |
| 298 | None => Value::Str(text), |
| 299 | }; |
| 300 | place(&mut stack, &mut root, value)?; |
| 301 | } |
| 302 | Event::SequenceStart(_, tag) | Event::MappingStart(_, tag) if tag.is_some() => { |
| 303 | return refuse("YAML aliases and explicit tags (including !!js) are unsupported."); |
| 304 | } |
| 305 | Event::SequenceStart(..) => { |
| 306 | require( |
| 307 | stack.len() < MAX_DEPTH, |
| 308 | "Configuration nesting exceeds 32 levels.", |
| 309 | )?; |
| 310 | stack.push(Frame::Seq(Vec::new())); |
| 311 | } |
| 312 | Event::MappingStart(..) => { |
| 313 | require( |
| 314 | stack.len() < MAX_DEPTH, |
| 315 | "Configuration nesting exceeds 32 levels.", |
| 316 | )?; |
| 317 | stack.push(Frame::Map(Vec::new(), None)); |
| 318 | } |
| 319 | Event::SequenceEnd => { |
| 320 | let Some(Frame::Seq(items)) = stack.pop() else { |
| 321 | return refuse(PARSE_REFUSAL); |
| 322 | }; |
| 323 | place(&mut stack, &mut root, Value::Seq(items))?; |
| 324 | } |
| 325 | Event::MappingEnd => { |
| 326 | let Some(Frame::Map(entries, None)) = stack.pop() else { |
| 327 | return refuse(PARSE_REFUSAL); |
| 328 | }; |
| 329 | place(&mut stack, &mut root, Value::Map(entries))?; |
| 330 | } |
| 331 | } |
| 332 | } |
| 333 | Ok(root.unwrap_or(Value::Null)) |
| 334 | } |
| 335 | |
| 336 | /// Strict JSON (no duplicate keys, finite numbers) through the same closed |
| 337 | /// model as the YAML layers. |
| 338 | pub fn parse_json(text: &str) -> Result<Value> { |
| 339 | serde_json::from_str::<serde::de::IgnoredAny>(text) |
| 340 | .map_err(|_| anyhow::Error::msg(PARSE_REFUSAL))?; |
| 341 | parse_yaml(text, false) |
| 342 | } |
| 343 | |
| 344 | pub fn parse_package_json(text: &str) -> Result<Value> { |
| 345 | let raw: serde_json::Value = |
| 346 | serde_json::from_str(text).map_err(|_| anyhow::Error::msg(PARSE_REFUSAL))?; |
| 347 | json_value_to_yaml_value(&raw, 0) |
| 348 | } |
| 349 | |
| 350 | fn json_value_to_yaml_value(value: &serde_json::Value, depth: usize) -> Result<Value> { |
| 351 | require(depth <= MAX_DEPTH, PARSE_REFUSAL)?; |
| 352 | match value { |
| 353 | serde_json::Value::Null => Ok(Value::Null), |
| 354 | serde_json::Value::Bool(b) => Ok(Value::Bool(*b)), |
| 355 | serde_json::Value::Number(n) => { |
| 356 | if let Some(i) = n.as_i64() { |
| 357 | Ok(Value::Int(i)) |
| 358 | } else if let Some(u) = n.as_u64() { |
| 359 | match i64::try_from(u) { |
| 360 | Ok(i) => Ok(Value::Int(i)), |
| 361 | Err(_) => { |
| 362 | let f = n.as_f64().unwrap_or(f64::NAN); |
| 363 | require(f.is_finite(), PARSE_REFUSAL)?; |
| 364 | Ok(Value::Float(f)) |
| 365 | } |
| 366 | } |
| 367 | } else { |
| 368 | let f = n.as_f64().unwrap_or(f64::NAN); |
| 369 | require(f.is_finite(), PARSE_REFUSAL)?; |
| 370 | Ok(Value::Float(f)) |
| 371 | } |
| 372 | } |
| 373 | serde_json::Value::String(s) => Ok(Value::Str(s.clone())), |
| 374 | serde_json::Value::Array(items) => { |
| 375 | let mut out = Vec::with_capacity(items.len()); |
| 376 | for item in items { |
| 377 | out.push(json_value_to_yaml_value(item, depth + 1)?); |
| 378 | } |
| 379 | Ok(Value::Seq(out)) |
| 380 | } |
| 381 | serde_json::Value::Object(map) => { |
| 382 | let mut out = Vec::with_capacity(map.len()); |
| 383 | for (k, v) in map { |
| 384 | out.push((k.clone(), json_value_to_yaml_value(v, depth + 1)?)); |
| 385 | } |
| 386 | Ok(Value::Map(out)) |
| 387 | } |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | // ───────────────────────────────────────────────────────────────────────────── |
| 392 | // Contained reads |
| 393 | // ───────────────────────────────────────────────────────────────────────────── |
| 394 | |
| 395 | /// A package directory, canonicalized once; every path below it is walked |
| 396 | /// component by component so a link anywhere inside the package refuses. |
| 397 | pub struct Package { |
| 398 | root: PathBuf, |
| 399 | } |
| 400 | |
| 401 | impl Package { |
| 402 | pub fn open(path: &Path) -> Result<Self> { |
| 403 | let root = path.canonicalize().map_err(|_| { |
| 404 | anyhow::Error::msg( |
| 405 | "Select a DSH bundle package directory (a directory containing package.json).", |
| 406 | ) |
| 407 | })?; |
| 408 | require( |
| 409 | root.is_dir(), |
| 410 | "Select a DSH bundle package directory (a directory containing package.json).", |
| 411 | )?; |
| 412 | Ok(Self { root }) |
| 413 | } |
| 414 | |
| 415 | /// Join a contained relative path, refusing escapes and links. |
| 416 | fn contained(&self, relative: &Path) -> Result<PathBuf> { |
| 417 | let mut current = self.root.clone(); |
| 418 | for component in relative.components() { |
| 419 | match component { |
| 420 | Component::CurDir => continue, |
| 421 | Component::Normal(part) => current.push(part), |
| 422 | _ => return refuse("Paths must stay inside the selected package."), |
| 423 | } |
| 424 | if let Ok(metadata) = fs::symlink_metadata(¤t) { |
| 425 | require( |
| 426 | !codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata), |
| 427 | "Source paths must not contain links or reparse points.", |
| 428 | )?; |
| 429 | } |
| 430 | } |
| 431 | Ok(current) |
| 432 | } |
| 433 | |
| 434 | fn relative_of<'a>(&self, path: &'a Path) -> &'a Path { |
| 435 | path.strip_prefix(&self.root).unwrap_or(path) |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | /// Read a regular, singly linked file no larger than `limit`. |
| 440 | fn read_file(path: &Path, limit: usize) -> Result<Vec<u8>> { |
| 441 | let metadata = fs::symlink_metadata(path).map_err(|_| { |
| 442 | anyhow::Error::msg("File operation failed; source files must be accessible regular paths.") |
| 443 | })?; |
| 444 | require( |
| 445 | metadata.is_file() |
| 446 | && !codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata), |
| 447 | "Only regular, non-linked source files are supported.", |
| 448 | )?; |
| 449 | #[cfg(unix)] |
| 450 | { |
| 451 | use std::os::unix::fs::MetadataExt as _; |
| 452 | require( |
| 453 | metadata.nlink() == 1, |
| 454 | "Only regular, non-linked source files are supported.", |
| 455 | )?; |
| 456 | } |
| 457 | require( |
| 458 | usize::try_from(metadata.len()).is_ok_and(|len| len <= limit), |
| 459 | "Source file exceeds the conversion size limit.", |
| 460 | )?; |
| 461 | let mut file = codewhale_util::bundle_file::open_bundle_file(path).map_err(|_| { |
| 462 | anyhow::Error::msg("File operation failed; source files must be accessible regular paths.") |
| 463 | })?; |
| 464 | #[cfg(unix)] |
| 465 | { |
| 466 | use std::os::unix::fs::MetadataExt as _; |
| 467 | let opened = file.metadata()?; |
| 468 | require( |
| 469 | (opened.dev(), opened.ino()) == (metadata.dev(), metadata.ino()) && opened.nlink() == 1, |
| 470 | "Source changed during conversion.", |
| 471 | )?; |
| 472 | } |
| 473 | let mut content = Vec::new(); |
| 474 | file.by_ref() |
| 475 | .take(u64::try_from(limit).unwrap_or(u64::MAX).saturating_add(1)) |
| 476 | .read_to_end(&mut content)?; |
| 477 | require( |
| 478 | content.len() <= limit, |
| 479 | "Source file exceeds the conversion size limit.", |
| 480 | )?; |
| 481 | Ok(content) |
| 482 | } |
| 483 | |
| 484 | fn utf8(content: Vec<u8>) -> Result<String> { |
| 485 | String::from_utf8(content) |
| 486 | .map_err(|_| anyhow::Error::msg("Configuration and skill entrypoints must be UTF-8.")) |
| 487 | } |
| 488 | |
| 489 | use codewhale_skill_install::install::sha256_hex; |
| 490 | |
| 491 | /// Relative path spellings a package may use for its own files. |
| 492 | fn plain_relative(text: &str) -> bool { |
| 493 | !text.is_empty() |
| 494 | // A rooted path without a drive (`/tmp/a.yml`) is not `is_absolute` on |
| 495 | // Windows, but it is not relative to the bundle either. |
| 496 | && !text.starts_with('/') |
| 497 | && !Path::new(text).is_absolute() |
| 498 | && !Path::new(text) |
| 499 | .components() |
| 500 | .any(|c| matches!(c, Component::ParentDir)) |
| 501 | && !text |
| 502 | .chars() |
| 503 | .any(|c| c == '\\' || c == ':' || (c as u32) < 0x20) |
| 504 | } |
| 505 | |
| 506 | // ───────────────────────────────────────────────────────────────────────────── |
| 507 | // Receipts |
| 508 | // ───────────────────────────────────────────────────────────────────────────── |
| 509 | |
| 510 | /// One structured per-row or per-patch outcome. |
| 511 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 512 | pub struct DshOutcome { |
| 513 | pub row: Option<String>, |
| 514 | pub package: Option<String>, |
| 515 | pub kind: String, |
| 516 | pub outcome: String, |
| 517 | pub reason: String, |
| 518 | #[serde(skip_serializing_if = "Option::is_none")] |
| 519 | pub layer: Option<String>, |
| 520 | #[serde(skip_serializing_if = "Option::is_none")] |
| 521 | pub patch: Option<usize>, |
| 522 | } |
| 523 | |
| 524 | impl DshOutcome { |
| 525 | /// A skipped row or operation is a manual port the reviewer must see. |
| 526 | pub fn needs_manual_port(&self) -> bool { |
| 527 | self.outcome == "skipped" |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 532 | pub struct DshLayer { |
| 533 | pub path: String, |
| 534 | pub sha256: String, |
| 535 | pub bytes: usize, |
| 536 | } |
| 537 | |
| 538 | /// What a conversion produced, for preview and install receipts. |
| 539 | #[derive(Debug, Clone, Serialize)] |
| 540 | pub struct DshConversion { |
| 541 | pub plugin_name: String, |
| 542 | pub source_package: Option<String>, |
| 543 | pub source_version: Option<String>, |
| 544 | pub manifest_sha256: String, |
| 545 | pub layers: Vec<DshLayer>, |
| 546 | pub outcomes: Vec<DshOutcome>, |
| 547 | pub diagnostics: Vec<String>, |
| 548 | pub skills: Vec<String>, |
| 549 | pub commands: Vec<String>, |
| 550 | pub agents: Vec<String>, |
| 551 | pub hooks: Vec<String>, |
| 552 | pub remote_servers: Vec<String>, |
| 553 | pub local_servers: Vec<String>, |
| 554 | pub network_hosts: Vec<String>, |
| 555 | pub requires_node: bool, |
| 556 | /// Ordinary reviewed Native entry; remains experimental and disabled at install. |
| 557 | pub requires_native: bool, |
| 558 | pub native_rows: Vec<String>, |
| 559 | pub client_closures: Vec<DshClientClosure>, |
| 560 | } |
| 561 | |
| 562 | // ───────────────────────────────────────────────────────────────────────────── |
| 563 | // Bundle loading and patch evaluation |
| 564 | // ───────────────────────────────────────────────────────────────────────────── |
| 565 | |
| 566 | pub struct LoadedBundle { |
| 567 | pub composition: Json, |
| 568 | pub manifest: Value, |
| 569 | pub manifest_sha256: String, |
| 570 | pub entries: Vec<Value>, |
| 571 | pub notes: Vec<String>, |
| 572 | pub layers: Vec<DshLayer>, |
| 573 | pub outcomes: Vec<DshOutcome>, |
| 574 | pub platforms: Option<Vec<String>>, |
| 575 | } |
| 576 | |
| 577 | fn host_node_platform() -> Option<&'static str> { |
| 578 | match std::env::consts::OS { |
| 579 | "macos" => Some("darwin"), |
| 580 | "windows" => Some("win32"), |
| 581 | "linux" => Some("linux"), |
| 582 | _ => None, |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | fn node_platform(name: &str) -> Option<&'static str> { |
| 587 | match name { |
| 588 | "darwin" | "macos" => Some("darwin"), |
| 589 | "win32" | "windows" => Some("win32"), |
| 590 | "linux" => Some("linux"), |
| 591 | "wsl" => Some("wsl"), |
| 592 | _ => None, |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | fn is_wsl_host() -> bool { |
| 597 | if std::env::consts::OS != "linux" { |
| 598 | return false; |
| 599 | } |
| 600 | if std::env::var_os("WSL_DISTRO_NAME").is_some() || std::env::var_os("WSL_INTEROP").is_some() { |
| 601 | return true; |
| 602 | } |
| 603 | ["/proc/sys/kernel/osrelease", "/proc/version"] |
| 604 | .into_iter() |
| 605 | .filter_map(|path| fs::read_to_string(path).ok()) |
| 606 | .any(|text| { |
| 607 | let lower = text.to_ascii_lowercase(); |
| 608 | lower.contains("microsoft") || lower.contains("wsl") |
| 609 | }) |
| 610 | } |
| 611 | |
| 612 | fn platform_admits_host(platforms: &[&str], host: &str, is_wsl: bool) -> bool { |
| 613 | platforms.contains(&host) || (host == "linux" && is_wsl && platforms.contains(&"wsl")) |
| 614 | } |
| 615 | |
| 616 | fn codewhale_os_name(node_platform: &str) -> &'static str { |
| 617 | match node_platform { |
| 618 | "darwin" => "macos", |
| 619 | "win32" => "windows", |
| 620 | _ => "linux", |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | fn target_dsh_version() -> Result<semver::Version> { |
| 625 | let receipt: Json = serde_json::from_slice(crate::activation::DSH_COMPATIBILITY) |
| 626 | .map_err(|_| anyhow::Error::msg("The pinned DSH compatibility receipt is unreadable."))?; |
| 627 | let version = receipt |
| 628 | .get("target_dsh_version") |
| 629 | .and_then(Json::as_str) |
| 630 | .ok_or_else(|| { |
| 631 | anyhow::Error::msg("The pinned DSH compatibility receipt lacks `target_dsh_version`.") |
| 632 | })?; |
| 633 | semver::Version::parse(version).map_err(|_| { |
| 634 | anyhow::Error::msg( |
| 635 | "The pinned DSH compatibility receipt has an invalid `target_dsh_version`.", |
| 636 | ) |
| 637 | }) |
| 638 | } |
| 639 | |
| 640 | pub(crate) fn supported_dsh_versions() -> Result<Vec<semver::Version>> { |
| 641 | let primary = target_dsh_version()?; |
| 642 | let mut versions = vec![primary]; |
| 643 | for extra in [ |
| 644 | "0.2.1-rc.5", |
| 645 | "0.2.2-rc.1", |
| 646 | "0.2.2-rc.2", |
| 647 | "0.2.2-rc.3", |
| 648 | "0.2.2-rc.4", |
| 649 | "0.2.2-rc.5", |
| 650 | ] { |
| 651 | if let Ok(parsed) = semver::Version::parse(extra) |
| 652 | && !versions.contains(&parsed) |
| 653 | { |
| 654 | versions.push(parsed); |
| 655 | } |
| 656 | } |
| 657 | Ok(versions) |
| 658 | } |
| 659 | |
| 660 | #[derive(Clone, Copy)] |
| 661 | enum SemverBoundOp { |
| 662 | Eq, |
| 663 | Lt, |
| 664 | Le, |
| 665 | Gt, |
| 666 | Ge, |
| 667 | } |
| 668 | |
| 669 | #[derive(Clone)] |
| 670 | struct SemverBound { |
| 671 | op: SemverBoundOp, |
| 672 | version: semver::Version, |
| 673 | } |
| 674 | |
| 675 | impl SemverBound { |
| 676 | fn matches(&self, candidate: &semver::Version) -> bool { |
| 677 | let ord = candidate.cmp_precedence(&self.version); |
| 678 | match self.op { |
| 679 | SemverBoundOp::Eq => ord.is_eq(), |
| 680 | SemverBoundOp::Lt => ord.is_lt(), |
| 681 | SemverBoundOp::Le => ord.is_le(), |
| 682 | SemverBoundOp::Gt => ord.is_gt(), |
| 683 | SemverBoundOp::Ge => ord.is_ge(), |
| 684 | } |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | enum ParsedPartialVersion { |
| 689 | Wildcard, |
| 690 | Major(u64), |
| 691 | MajorMinor(u64, u64), |
| 692 | Exact(semver::Version), |
| 693 | } |
| 694 | |
| 695 | fn zero_prerelease(major: u64, minor: u64, patch: u64) -> semver::Version { |
| 696 | semver::Version { |
| 697 | major, |
| 698 | minor, |
| 699 | patch, |
| 700 | pre: semver::Prerelease::new("0").expect("static prerelease"), |
| 701 | build: semver::BuildMetadata::EMPTY, |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | fn parse_partial_version(raw: &str) -> Result<ParsedPartialVersion, String> { |
| 706 | let trimmed = raw.trim(); |
| 707 | let trimmed = trimmed |
| 708 | .strip_prefix('v') |
| 709 | .or_else(|| trimmed.strip_prefix('V')) |
| 710 | .unwrap_or(trimmed); |
| 711 | if trimmed.is_empty() { |
| 712 | return Err("empty version".into()); |
| 713 | } |
| 714 | if matches!(trimmed, "*" | "x" | "X") { |
| 715 | return Ok(ParsedPartialVersion::Wildcard); |
| 716 | } |
| 717 | let core = trimmed.split(['-', '+']).next().unwrap_or(trimmed); |
| 718 | let segments: Vec<&str> = core.split('.').collect(); |
| 719 | let is_wild = |s: &str| matches!(s, "*" | "x" | "X"); |
| 720 | match segments.as_slice() { |
| 721 | [maj] if is_wild(maj) => Ok(ParsedPartialVersion::Wildcard), |
| 722 | [maj] if !trimmed.contains(['-', '+']) => { |
| 723 | let major = maj |
| 724 | .parse::<u64>() |
| 725 | .map_err(|_| "invalid major".to_string())?; |
| 726 | Ok(ParsedPartialVersion::Major(major)) |
| 727 | } |
| 728 | [maj, min] if is_wild(maj) && is_wild(min) && !trimmed.contains(['-', '+']) => { |
| 729 | Ok(ParsedPartialVersion::Wildcard) |
| 730 | } |
| 731 | [maj, min] if is_wild(min) && !trimmed.contains(['-', '+']) => { |
| 732 | let major = maj |
| 733 | .parse::<u64>() |
| 734 | .map_err(|_| "invalid major".to_string())?; |
| 735 | Ok(ParsedPartialVersion::Major(major)) |
| 736 | } |
| 737 | [maj, min] if !trimmed.contains(['-', '+']) => { |
| 738 | let major = maj |
| 739 | .parse::<u64>() |
| 740 | .map_err(|_| "invalid major".to_string())?; |
| 741 | let minor = min |
| 742 | .parse::<u64>() |
| 743 | .map_err(|_| "invalid minor".to_string())?; |
| 744 | Ok(ParsedPartialVersion::MajorMinor(major, minor)) |
| 745 | } |
| 746 | [maj, min, pat] if is_wild(pat) && !trimmed.contains(['-', '+']) => { |
| 747 | if is_wild(maj) && is_wild(min) { |
| 748 | return Ok(ParsedPartialVersion::Wildcard); |
| 749 | } |
| 750 | let major = maj |
| 751 | .parse::<u64>() |
| 752 | .map_err(|_| "invalid major".to_string())?; |
| 753 | if is_wild(min) { |
| 754 | return Ok(ParsedPartialVersion::Major(major)); |
| 755 | } |
| 756 | let minor = min |
| 757 | .parse::<u64>() |
| 758 | .map_err(|_| "invalid minor".to_string())?; |
| 759 | Ok(ParsedPartialVersion::MajorMinor(major, minor)) |
| 760 | } |
| 761 | _ => semver::Version::parse(trimmed) |
| 762 | .map(ParsedPartialVersion::Exact) |
| 763 | .map_err(|e| e.to_string()), |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | fn parse_comparator_token(token: &str, out: &mut Vec<SemverBound>) -> Result<(), String> { |
| 768 | let token = token.trim(); |
| 769 | if token.is_empty() { |
| 770 | return Err("empty comparator".into()); |
| 771 | } |
| 772 | if let Some(rest) = token.strip_prefix('^') { |
| 773 | match parse_partial_version(rest)? { |
| 774 | ParsedPartialVersion::Wildcard => {} |
| 775 | ParsedPartialVersion::Major(major) => { |
| 776 | out.push(SemverBound { |
| 777 | op: SemverBoundOp::Ge, |
| 778 | version: zero_prerelease(major, 0, 0), |
| 779 | }); |
| 780 | out.push(SemverBound { |
| 781 | op: SemverBoundOp::Lt, |
| 782 | version: zero_prerelease(major.saturating_add(1), 0, 0), |
| 783 | }); |
| 784 | } |
| 785 | ParsedPartialVersion::MajorMinor(major, minor) => { |
| 786 | out.push(SemverBound { |
| 787 | op: SemverBoundOp::Ge, |
| 788 | version: zero_prerelease(major, minor, 0), |
| 789 | }); |
| 790 | let upper = if major > 0 { |
| 791 | zero_prerelease(major.saturating_add(1), 0, 0) |
| 792 | } else { |
| 793 | zero_prerelease(0, minor.saturating_add(1), 0) |
| 794 | }; |
| 795 | out.push(SemverBound { |
| 796 | op: SemverBoundOp::Lt, |
| 797 | version: upper, |
| 798 | }); |
| 799 | } |
| 800 | ParsedPartialVersion::Exact(version) => { |
| 801 | let upper = if version.major > 0 { |
| 802 | zero_prerelease(version.major.saturating_add(1), 0, 0) |
| 803 | } else if version.minor > 0 { |
| 804 | zero_prerelease(0, version.minor.saturating_add(1), 0) |
| 805 | } else { |
| 806 | zero_prerelease(0, 0, version.patch.saturating_add(1)) |
| 807 | }; |
| 808 | out.push(SemverBound { |
| 809 | op: SemverBoundOp::Ge, |
| 810 | version, |
| 811 | }); |
| 812 | out.push(SemverBound { |
| 813 | op: SemverBoundOp::Lt, |
| 814 | version: upper, |
| 815 | }); |
| 816 | } |
| 817 | } |
| 818 | return Ok(()); |
| 819 | } |
| 820 | if let Some(rest) = token.strip_prefix('~') { |
| 821 | match parse_partial_version(rest)? { |
| 822 | ParsedPartialVersion::Wildcard => {} |
| 823 | ParsedPartialVersion::Major(major) => { |
| 824 | out.push(SemverBound { |
| 825 | op: SemverBoundOp::Ge, |
| 826 | version: zero_prerelease(major, 0, 0), |
| 827 | }); |
| 828 | out.push(SemverBound { |
| 829 | op: SemverBoundOp::Lt, |
| 830 | version: zero_prerelease(major.saturating_add(1), 0, 0), |
| 831 | }); |
| 832 | } |
| 833 | ParsedPartialVersion::MajorMinor(major, minor) => { |
| 834 | out.push(SemverBound { |
| 835 | op: SemverBoundOp::Ge, |
| 836 | version: zero_prerelease(major, minor, 0), |
| 837 | }); |
| 838 | out.push(SemverBound { |
| 839 | op: SemverBoundOp::Lt, |
| 840 | version: zero_prerelease(major, minor.saturating_add(1), 0), |
| 841 | }); |
| 842 | } |
| 843 | ParsedPartialVersion::Exact(version) => { |
| 844 | let upper = zero_prerelease(version.major, version.minor.saturating_add(1), 0); |
| 845 | out.push(SemverBound { |
| 846 | op: SemverBoundOp::Ge, |
| 847 | version, |
| 848 | }); |
| 849 | out.push(SemverBound { |
| 850 | op: SemverBoundOp::Lt, |
| 851 | version: upper, |
| 852 | }); |
| 853 | } |
| 854 | } |
| 855 | return Ok(()); |
| 856 | } |
| 857 | if let Some(rest) = token.strip_prefix(">=") { |
| 858 | match parse_partial_version(rest)? { |
| 859 | ParsedPartialVersion::Wildcard => {} |
| 860 | ParsedPartialVersion::Major(major) => out.push(SemverBound { |
| 861 | op: SemverBoundOp::Ge, |
| 862 | version: zero_prerelease(major, 0, 0), |
| 863 | }), |
| 864 | ParsedPartialVersion::MajorMinor(major, minor) => out.push(SemverBound { |
| 865 | op: SemverBoundOp::Ge, |
| 866 | version: zero_prerelease(major, minor, 0), |
| 867 | }), |
| 868 | ParsedPartialVersion::Exact(version) => out.push(SemverBound { |
| 869 | op: SemverBoundOp::Ge, |
| 870 | version, |
| 871 | }), |
| 872 | } |
| 873 | return Ok(()); |
| 874 | } |
| 875 | if let Some(rest) = token.strip_prefix("<=") { |
| 876 | match parse_partial_version(rest)? { |
| 877 | ParsedPartialVersion::Wildcard => {} |
| 878 | ParsedPartialVersion::Major(major) => out.push(SemverBound { |
| 879 | op: SemverBoundOp::Lt, |
| 880 | version: zero_prerelease(major.saturating_add(1), 0, 0), |
| 881 | }), |
| 882 | ParsedPartialVersion::MajorMinor(major, minor) => out.push(SemverBound { |
| 883 | op: SemverBoundOp::Lt, |
| 884 | version: zero_prerelease(major, minor.saturating_add(1), 0), |
| 885 | }), |
| 886 | ParsedPartialVersion::Exact(version) => out.push(SemverBound { |
| 887 | op: SemverBoundOp::Le, |
| 888 | version, |
| 889 | }), |
| 890 | } |
| 891 | return Ok(()); |
| 892 | } |
| 893 | if let Some(rest) = token.strip_prefix('>') { |
| 894 | match parse_partial_version(rest)? { |
| 895 | ParsedPartialVersion::Wildcard => { |
| 896 | return Err("impossible >* comparator".into()); |
| 897 | } |
| 898 | ParsedPartialVersion::Major(major) => out.push(SemverBound { |
| 899 | op: SemverBoundOp::Ge, |
| 900 | version: zero_prerelease(major.saturating_add(1), 0, 0), |
| 901 | }), |
| 902 | ParsedPartialVersion::MajorMinor(major, minor) => out.push(SemverBound { |
| 903 | op: SemverBoundOp::Ge, |
| 904 | version: zero_prerelease(major, minor.saturating_add(1), 0), |
| 905 | }), |
| 906 | ParsedPartialVersion::Exact(version) => out.push(SemverBound { |
| 907 | op: SemverBoundOp::Gt, |
| 908 | version, |
| 909 | }), |
| 910 | } |
| 911 | return Ok(()); |
| 912 | } |
| 913 | if let Some(rest) = token.strip_prefix('<') { |
| 914 | match parse_partial_version(rest)? { |
| 915 | ParsedPartialVersion::Wildcard => { |
| 916 | return Err("impossible <* comparator".into()); |
| 917 | } |
| 918 | ParsedPartialVersion::Major(major) => out.push(SemverBound { |
| 919 | op: SemverBoundOp::Lt, |
| 920 | version: zero_prerelease(major, 0, 0), |
| 921 | }), |
| 922 | ParsedPartialVersion::MajorMinor(major, minor) => out.push(SemverBound { |
| 923 | op: SemverBoundOp::Lt, |
| 924 | version: zero_prerelease(major, minor, 0), |
| 925 | }), |
| 926 | ParsedPartialVersion::Exact(version) => out.push(SemverBound { |
| 927 | op: SemverBoundOp::Lt, |
| 928 | version, |
| 929 | }), |
| 930 | } |
| 931 | return Ok(()); |
| 932 | } |
| 933 | let rest = token.strip_prefix('=').unwrap_or(token); |
| 934 | match parse_partial_version(rest)? { |
| 935 | ParsedPartialVersion::Wildcard => {} |
| 936 | ParsedPartialVersion::Major(major) => { |
| 937 | out.push(SemverBound { |
| 938 | op: SemverBoundOp::Ge, |
| 939 | version: zero_prerelease(major, 0, 0), |
| 940 | }); |
| 941 | out.push(SemverBound { |
| 942 | op: SemverBoundOp::Lt, |
| 943 | version: zero_prerelease(major.saturating_add(1), 0, 0), |
| 944 | }); |
| 945 | } |
| 946 | ParsedPartialVersion::MajorMinor(major, minor) => { |
| 947 | out.push(SemverBound { |
| 948 | op: SemverBoundOp::Ge, |
| 949 | version: zero_prerelease(major, minor, 0), |
| 950 | }); |
| 951 | out.push(SemverBound { |
| 952 | op: SemverBoundOp::Lt, |
| 953 | version: zero_prerelease(major, minor.saturating_add(1), 0), |
| 954 | }); |
| 955 | } |
| 956 | ParsedPartialVersion::Exact(version) => out.push(SemverBound { |
| 957 | op: SemverBoundOp::Eq, |
| 958 | version, |
| 959 | }), |
| 960 | } |
| 961 | Ok(()) |
| 962 | } |
| 963 | |
| 964 | fn parse_npm_range(range: &str) -> Result<Vec<Vec<SemverBound>>, String> { |
| 965 | let trimmed = range.trim(); |
| 966 | if trimmed.is_empty() || trimmed.starts_with("workspace:") { |
| 967 | return Err("invalid range".into()); |
| 968 | } |
| 969 | let mut clauses = Vec::new(); |
| 970 | for raw_clause in trimmed.split("||") { |
| 971 | let clause = raw_clause.trim(); |
| 972 | if clause.is_empty() { |
| 973 | clauses.push(Vec::new()); |
| 974 | continue; |
| 975 | } |
| 976 | let raw_tokens: Vec<&str> = clause.split_whitespace().collect(); |
| 977 | let mut merged_tokens = Vec::<String>::new(); |
| 978 | let mut idx = 0; |
| 979 | while idx < raw_tokens.len() { |
| 980 | let tok = raw_tokens[idx]; |
| 981 | if tok == "-" && !merged_tokens.is_empty() && idx + 1 < raw_tokens.len() { |
| 982 | let low = merged_tokens.pop().expect("non-empty"); |
| 983 | let high = raw_tokens[idx + 1]; |
| 984 | merged_tokens.push(format!(">={low}")); |
| 985 | merged_tokens.push(format!("<={high}")); |
| 986 | idx += 2; |
| 987 | continue; |
| 988 | } |
| 989 | if matches!(tok, ">=" | "<=" | ">" | "<" | "=" | "^" | "~") |
| 990 | && idx + 1 < raw_tokens.len() |
| 991 | { |
| 992 | merged_tokens.push(format!("{tok}{}", raw_tokens[idx + 1])); |
| 993 | idx += 2; |
| 994 | continue; |
| 995 | } |
| 996 | merged_tokens.push(tok.to_string()); |
| 997 | idx += 1; |
| 998 | } |
| 999 | let mut bounds = Vec::new(); |
| 1000 | for tok in &merged_tokens { |
| 1001 | parse_comparator_token(tok, &mut bounds)?; |
| 1002 | } |
| 1003 | clauses.push(bounds); |
| 1004 | } |
| 1005 | if clauses.is_empty() { |
| 1006 | return Err("empty range".into()); |
| 1007 | } |
| 1008 | Ok(clauses) |
| 1009 | } |
| 1010 | |
| 1011 | pub(crate) fn match_supported_dsh_range(range: &str) -> Result<Option<semver::Version>, String> { |
| 1012 | let clauses = parse_npm_range(range)?; |
| 1013 | let supported = supported_dsh_versions().map_err(|e| e.to_string())?; |
| 1014 | for candidate in supported { |
| 1015 | if clauses |
| 1016 | .iter() |
| 1017 | .any(|bounds| bounds.iter().all(|bound| bound.matches(&candidate))) |
| 1018 | { |
| 1019 | return Ok(Some(candidate)); |
| 1020 | } |
| 1021 | } |
| 1022 | Ok(None) |
| 1023 | } |
| 1024 | |
| 1025 | struct AdmittedCompatibility { |
| 1026 | dsh_range: Option<String>, |
| 1027 | matched_dsh_version: Option<semver::Version>, |
| 1028 | platforms: Option<Vec<String>>, |
| 1029 | } |
| 1030 | |
| 1031 | fn admit_host_compatibility(manifest: &Value) -> Result<AdmittedCompatibility> { |
| 1032 | let target = target_dsh_version()?; |
| 1033 | let (dsh_range, matched_dsh_version) = match manifest.get("engines") { |
| 1034 | Some(Value::Map(_)) => { |
| 1035 | if let Some(declared) = manifest |
| 1036 | .get("engines") |
| 1037 | .and_then(|engines| engines.get("dsh")) |
| 1038 | { |
| 1039 | let Some(range) = declared.str() else { |
| 1040 | return refuse( |
| 1041 | "incompatible-version: `engines.dsh` must be a string semver range; author the supported DSH range or remove the field.", |
| 1042 | ); |
| 1043 | }; |
| 1044 | match match_supported_dsh_range(range) { |
| 1045 | Ok(Some(matched)) => (Some(range), Some(matched)), |
| 1046 | Ok(None) => { |
| 1047 | return refuse(format!( |
| 1048 | "incompatible-version: this bundle requires DSH `{}`, but this Codewhale host targets DSH {target} (0.2.1-rc.5 / 0.2.2-rc.1..rc.5); import a bundle built for that host or update the host.", |
| 1049 | refusal_text(range) |
| 1050 | )); |
| 1051 | } |
| 1052 | Err(_) => { |
| 1053 | return refuse(format!( |
| 1054 | "incompatible-version: `engines.dsh` value `{}` is not a valid semver range.", |
| 1055 | refusal_text(range) |
| 1056 | )); |
| 1057 | } |
| 1058 | } |
| 1059 | } else { |
| 1060 | (None, None) |
| 1061 | } |
| 1062 | } |
| 1063 | Some(Value::Null) | None => (None, None), |
| 1064 | Some(_) => { |
| 1065 | return refuse( |
| 1066 | "incompatible-version: `engines` in package.json must be an object when present.", |
| 1067 | ); |
| 1068 | } |
| 1069 | }; |
| 1070 | if dsh_range.is_none() { |
| 1071 | match manifest.get("peerDependencies") { |
| 1072 | Some(Value::Map(peers)) => { |
| 1073 | for (pkg, spec_val) in peers { |
| 1074 | if pkg != "@deepseek-ai/dsh" && !pkg.starts_with("@deepseek-ai/dsh-") { |
| 1075 | continue; |
| 1076 | } |
| 1077 | let Some(raw_spec) = spec_val.str().map(str::trim).filter(|s| !s.is_empty()) |
| 1078 | else { |
| 1079 | return refuse(format!( |
| 1080 | "incompatible-version: `peerDependencies.{}` must be a non-empty string semver range.", |
| 1081 | refusal_text(pkg) |
| 1082 | )); |
| 1083 | }; |
| 1084 | let check_range = if let Some(rest) = raw_spec.strip_prefix("workspace:") { |
| 1085 | let rest = rest.trim(); |
| 1086 | if matches!(rest, "*" | "^" | "~") { |
| 1087 | continue; |
| 1088 | } |
| 1089 | rest |
| 1090 | } else { |
| 1091 | raw_spec |
| 1092 | }; |
| 1093 | match match_supported_dsh_range(check_range) { |
| 1094 | Ok(Some(_)) => {} |
| 1095 | Ok(None) => { |
| 1096 | return refuse(format!( |
| 1097 | "incompatible-version: `peerDependencies.{}` requires DSH `{}`, but this Codewhale host targets DSH {target} (0.2.1-rc.5 / 0.2.2-rc.1..rc.5); import a bundle built for that host or update the host.", |
| 1098 | refusal_text(pkg), |
| 1099 | refusal_text(raw_spec) |
| 1100 | )); |
| 1101 | } |
| 1102 | Err(_) => { |
| 1103 | return refuse(format!( |
| 1104 | "incompatible-version: `peerDependencies.{}` value `{}` is not a valid semver range.", |
| 1105 | refusal_text(pkg), |
| 1106 | refusal_text(raw_spec) |
| 1107 | )); |
| 1108 | } |
| 1109 | } |
| 1110 | } |
| 1111 | } |
| 1112 | Some(Value::Null) | None => {} |
| 1113 | Some(_) => { |
| 1114 | return refuse( |
| 1115 | "incompatible-version: `peerDependencies` in package.json must be an object when present.", |
| 1116 | ); |
| 1117 | } |
| 1118 | } |
| 1119 | } |
| 1120 | let platforms = if let Some(declared) = manifest |
| 1121 | .get("dsh") |
| 1122 | .and_then(|dsh| dsh.get("bundle")) |
| 1123 | .and_then(|bundle| bundle.get("platforms")) |
| 1124 | { |
| 1125 | let Value::Seq(items) = declared else { |
| 1126 | return refuse( |
| 1127 | "unsupported-platform: `dsh.bundle.platforms` must be a non-empty list of Node platform names (darwin/macos, win32/windows, linux, wsl).", |
| 1128 | ); |
| 1129 | }; |
| 1130 | require( |
| 1131 | !items.is_empty(), |
| 1132 | "unsupported-platform: `dsh.bundle.platforms` must be a non-empty list of Node platform names (darwin/macos, win32/windows, linux, wsl).", |
| 1133 | )?; |
| 1134 | let mut platforms = Vec::new(); |
| 1135 | for item in items { |
| 1136 | let Some(name) = item.str() else { |
| 1137 | return refuse( |
| 1138 | "unsupported-platform: every `dsh.bundle.platforms` entry must be a Node platform name (darwin/macos, win32/windows, linux, wsl).", |
| 1139 | ); |
| 1140 | }; |
| 1141 | let Some(platform) = node_platform(name) else { |
| 1142 | return refuse(format!( |
| 1143 | "unsupported-platform: `{}` is not a supported Node platform name; use darwin/macos, win32/windows, linux or wsl.", |
| 1144 | refusal_text(name) |
| 1145 | )); |
| 1146 | }; |
| 1147 | platforms.push(platform); |
| 1148 | } |
| 1149 | let host = host_node_platform().ok_or_else(|| { |
| 1150 | anyhow::Error::msg(format!( |
| 1151 | "unsupported-platform: Codewhale cannot verify host platform `{}` against the bundle's declared platforms.", |
| 1152 | std::env::consts::OS |
| 1153 | )) |
| 1154 | })?; |
| 1155 | require( |
| 1156 | platform_admits_host(&platforms, host, is_wsl_host()), |
| 1157 | &format!( |
| 1158 | "unsupported-platform: this bundle declares only {}; this host is {host}.", |
| 1159 | platforms.join(", ") |
| 1160 | ), |
| 1161 | )?; |
| 1162 | let mut mapped: Vec<String> = platforms |
| 1163 | .into_iter() |
| 1164 | .map(|p| codewhale_os_name(p).to_string()) |
| 1165 | .collect(); |
| 1166 | mapped.sort(); |
| 1167 | mapped.dedup(); |
| 1168 | Some(mapped) |
| 1169 | } else { |
| 1170 | None |
| 1171 | }; |
| 1172 | Ok(AdmittedCompatibility { |
| 1173 | dsh_range: dsh_range.map(ToString::to_string), |
| 1174 | matched_dsh_version, |
| 1175 | platforms, |
| 1176 | }) |
| 1177 | } |
| 1178 | |
| 1179 | fn declares_client(manifest: &Value) -> bool { |
| 1180 | manifest |
| 1181 | .get("dsh") |
| 1182 | .and_then(|dsh| dsh.get("client")) |
| 1183 | .is_some_and(|client| !matches!(client, Value::Null)) |
| 1184 | } |
| 1185 | |
| 1186 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 1187 | pub struct DshClientClosure { |
| 1188 | pub package: String, |
| 1189 | pub root: String, |
| 1190 | pub entry: String, |
| 1191 | pub platform: Option<String>, |
| 1192 | pub inject: Vec<String>, |
| 1193 | pub host_provided: Vec<String>, |
| 1194 | pub files: BTreeMap<String, String>, |
| 1195 | pub imports: BTreeMap<String, BTreeMap<String, Option<String>>>, |
| 1196 | pub bytes: usize, |
| 1197 | } |
| 1198 | |
| 1199 | const CLIENT_JS: [&str; 3] = ["js", "mjs", "cjs"]; |
| 1200 | const CLIENT_PROBES: [&str; 8] = [ |
| 1201 | "", |
| 1202 | ".js", |
| 1203 | ".mjs", |
| 1204 | ".cjs", |
| 1205 | ".json", |
| 1206 | "/index.js", |
| 1207 | "/index.mjs", |
| 1208 | "/index.cjs", |
| 1209 | ]; |
| 1210 | const NODE_BUILTINS: [&str; 24] = [ |
| 1211 | "assert", |
| 1212 | "buffer", |
| 1213 | "child_process", |
| 1214 | "cluster", |
| 1215 | "crypto", |
| 1216 | "dgram", |
| 1217 | "dns", |
| 1218 | "events", |
| 1219 | "fs", |
| 1220 | "http", |
| 1221 | "http2", |
| 1222 | "https", |
| 1223 | "module", |
| 1224 | "net", |
| 1225 | "os", |
| 1226 | "path", |
| 1227 | "process", |
| 1228 | "readline", |
| 1229 | "stream", |
| 1230 | "tls", |
| 1231 | "url", |
| 1232 | "util", |
| 1233 | "vm", |
| 1234 | "zlib", |
| 1235 | ]; |
| 1236 | |
| 1237 | fn normalize_slash(path: &str) -> Option<String> { |
| 1238 | if path.contains(['\\', '\0']) { |
| 1239 | return None; |
| 1240 | } |
| 1241 | let mut parts: Vec<&str> = Vec::new(); |
| 1242 | for part in path.split('/') { |
| 1243 | match part { |
| 1244 | "" | "." => {} |
| 1245 | ".." => { |
| 1246 | parts.pop()?; |
| 1247 | } |
| 1248 | other => parts.push(other), |
| 1249 | } |
| 1250 | } |
| 1251 | Some(parts.join("/")) |
| 1252 | } |
| 1253 | |
| 1254 | fn client_entry(manifest: &Value) -> String { |
| 1255 | let target = manifest |
| 1256 | .get("exports") |
| 1257 | .and_then(|exports| exports.get("./client")) |
| 1258 | .and_then(|export| match export { |
| 1259 | Value::Str(target) => Some(target.as_str()), |
| 1260 | Value::Map(_) => ["import", "default", "."] |
| 1261 | .iter() |
| 1262 | .find_map(|key| export.get(key).and_then(Value::str)), |
| 1263 | _ => None, |
| 1264 | }); |
| 1265 | target.unwrap_or("client.js").to_string() |
| 1266 | } |
| 1267 | |
| 1268 | fn package_target(manifest: &Value, subpath: &str) -> Option<String> { |
| 1269 | let key = if subpath.is_empty() { |
| 1270 | ".".to_string() |
| 1271 | } else { |
| 1272 | format!("./{subpath}") |
| 1273 | }; |
| 1274 | let from_exports = manifest.get("exports").and_then(|exports| { |
| 1275 | let slot = if matches!(exports, Value::Map(_)) |
| 1276 | && exports.keys().iter().any(|name| name.starts_with('.')) |
| 1277 | { |
| 1278 | exports.get(&key) |
| 1279 | } else if subpath.is_empty() { |
| 1280 | Some(exports) |
| 1281 | } else { |
| 1282 | None |
| 1283 | }; |
| 1284 | match slot? { |
| 1285 | Value::Str(target) => Some(target.clone()), |
| 1286 | conditions @ Value::Map(_) => ["import", "browser", "require", "default"] |
| 1287 | .iter() |
| 1288 | .find_map(|name| conditions.get(name).and_then(Value::str)) |
| 1289 | .map(str::to_string), |
| 1290 | _ => None, |
| 1291 | } |
| 1292 | }); |
| 1293 | from_exports.or_else(|| { |
| 1294 | if subpath.is_empty() { |
| 1295 | Some( |
| 1296 | manifest |
| 1297 | .get("main") |
| 1298 | .and_then(Value::str) |
| 1299 | .unwrap_or("index.js") |
| 1300 | .to_string(), |
| 1301 | ) |
| 1302 | } else { |
| 1303 | Some(subpath.to_string()) |
| 1304 | } |
| 1305 | }) |
| 1306 | } |
| 1307 | |
| 1308 | struct ClientScan<'a> { |
| 1309 | files: &'a BTreeMap<String, Vec<u8>>, |
| 1310 | closure: BTreeMap<String, String>, |
| 1311 | imports: BTreeMap<String, BTreeMap<String, Option<String>>>, |
| 1312 | host: std::collections::BTreeSet<String>, |
| 1313 | bytes: usize, |
| 1314 | } |
| 1315 | |
| 1316 | impl ClientScan<'_> { |
| 1317 | fn probe(&self, base: &str) -> Option<String> { |
| 1318 | CLIENT_PROBES |
| 1319 | .iter() |
| 1320 | .map(|suffix| format!("{base}{suffix}")) |
| 1321 | .find(|candidate| { |
| 1322 | candidate.starts_with("source/") && self.files.contains_key(candidate.as_str()) |
| 1323 | }) |
| 1324 | } |
| 1325 | |
| 1326 | fn resolve(&mut self, from: &str, specifier: &str) -> Result<Option<String>, String> { |
| 1327 | let directory = from.rsplit_once('/').map_or("", |(dir, _)| dir); |
| 1328 | if specifier.starts_with("./") || specifier.starts_with("../") || specifier == "." { |
| 1329 | let base = normalize_slash(&format!("{directory}/{specifier}")) |
| 1330 | .ok_or_else(|| format!("`{specifier}` is outside the reviewed package files"))?; |
| 1331 | return self |
| 1332 | .probe(&base) |
| 1333 | .map(Some) |
| 1334 | .ok_or_else(|| format!("`{specifier}` is not in the reviewed package files")); |
| 1335 | } |
| 1336 | if specifier.starts_with('/') || specifier.contains(':') || specifier.is_empty() { |
| 1337 | return Err(format!( |
| 1338 | "`{specifier}` is an absolute, URL or built-in specifier" |
| 1339 | )); |
| 1340 | } |
| 1341 | let (name, subpath) = match specifier.split_once('/') { |
| 1342 | Some((scope, rest)) if scope.starts_with('@') => match rest.split_once('/') { |
| 1343 | Some((leaf, sub)) => (format!("{scope}/{leaf}"), sub.to_string()), |
| 1344 | None => (specifier.to_string(), String::new()), |
| 1345 | }, |
| 1346 | Some((head, sub)) => (head.to_string(), sub.to_string()), |
| 1347 | None => (specifier.to_string(), String::new()), |
| 1348 | }; |
| 1349 | if NODE_BUILTINS.contains(&name.as_str()) { |
| 1350 | return Err(format!("`{specifier}` is a Node built-in")); |
| 1351 | } |
| 1352 | let mut current = directory.to_string(); |
| 1353 | loop { |
| 1354 | let package = format!("{current}/node_modules/{name}"); |
| 1355 | if let Some(bytes) = self.files.get(&format!("{package}/package.json")) { |
| 1356 | let manifest = std::str::from_utf8(bytes) |
| 1357 | .ok() |
| 1358 | .and_then(|text| parse_package_json(text).ok()) |
| 1359 | .ok_or_else(|| format!("`{name}` has an unreadable package.json"))?; |
| 1360 | let target = package_target(&manifest, &subpath) |
| 1361 | .and_then(|target| normalize_slash(&format!("{package}/{target}"))) |
| 1362 | .filter(|path| path.starts_with(&format!("{package}/"))) |
| 1363 | .ok_or_else(|| format!("`{specifier}` has no contained entry"))?; |
| 1364 | self.note(format!("{package}/package.json")); |
| 1365 | return self |
| 1366 | .probe(&target) |
| 1367 | .map(Some) |
| 1368 | .ok_or_else(|| format!("`{specifier}` is not in the reviewed package files")); |
| 1369 | } |
| 1370 | match current.rsplit_once('/') { |
| 1371 | Some((parent, _)) => current = parent.to_string(), |
| 1372 | None => break, |
| 1373 | } |
| 1374 | } |
| 1375 | if name == "react" |
| 1376 | || name == "react-dom" |
| 1377 | || name == "cosmokit" |
| 1378 | || name.starts_with("@deepseek-ai/") |
| 1379 | { |
| 1380 | self.host.insert(specifier.to_string()); |
| 1381 | return Ok(None); |
| 1382 | } |
| 1383 | Err(format!( |
| 1384 | "`{specifier}` is an ambient dependency that is not in the reviewed bundle" |
| 1385 | )) |
| 1386 | } |
| 1387 | |
| 1388 | fn note(&mut self, path: String) { |
| 1389 | if let Some(bytes) = self.files.get(&path) |
| 1390 | && !self.closure.contains_key(&path) |
| 1391 | { |
| 1392 | self.bytes += bytes.len(); |
| 1393 | self.closure.insert(path, sha256_hex(bytes)); |
| 1394 | } |
| 1395 | } |
| 1396 | |
| 1397 | fn visit(&mut self, entry: String) -> Result<(), String> { |
| 1398 | let load = pattern( |
| 1399 | r#"(?m)(?:\brequire\s*\(\s*|\bimport\s*\(\s*|(?:^|[;{}])\s*import\s*|\b(?:import|export)\b[^;"'`()]*?\bfrom\b\s*)(?:"([^"\n]*)"|'([^'\n]*)')"#, |
| 1400 | ); |
| 1401 | let dynamic = pattern( |
| 1402 | r#"\b(?:require|import)\s*\(\s*(?:[^\s"'\)]|"[^"\n]*"\s*[^\s,\)]|'[^'\n]*'\s*[^\s,\)])"#, |
| 1403 | ); |
| 1404 | let dynamic_import = pattern(r"\bimport\s*\("); |
| 1405 | let mut pending = vec![entry]; |
| 1406 | while let Some(path) = pending.pop() { |
| 1407 | if self.closure.contains_key(&path) { |
| 1408 | continue; |
| 1409 | } |
| 1410 | require(self.closure.len() < MAX_FILES, "too many client files") |
| 1411 | .map_err(|error| error.to_string())?; |
| 1412 | self.note(path.clone()); |
| 1413 | let extension = path |
| 1414 | .rsplit_once('.') |
| 1415 | .map(|(_, ext)| ext.to_ascii_lowercase()); |
| 1416 | if !extension |
| 1417 | .as_deref() |
| 1418 | .is_some_and(|ext| CLIENT_JS.contains(&ext)) |
| 1419 | { |
| 1420 | continue; |
| 1421 | } |
| 1422 | let text = std::str::from_utf8(&self.files[&path]) |
| 1423 | .map_err(|_| format!("`{path}` is not UTF-8"))? |
| 1424 | .to_string(); |
| 1425 | if dynamic_import.is_match(&text) { |
| 1426 | return Err(format!("`{path}` uses unsupported dynamic import")); |
| 1427 | } |
| 1428 | if dynamic.is_match(&text) { |
| 1429 | return Err(format!("`{path}` loads a module by a computed specifier")); |
| 1430 | } |
| 1431 | for capture in load.captures_iter(&text) { |
| 1432 | let specifier = capture |
| 1433 | .get(1) |
| 1434 | .or_else(|| capture.get(2)) |
| 1435 | .map_or("", |m| m.as_str()); |
| 1436 | let resolved = self.resolve(&path, specifier)?; |
| 1437 | self.imports |
| 1438 | .entry(path.clone()) |
| 1439 | .or_default() |
| 1440 | .insert(specifier.to_string(), resolved.clone()); |
| 1441 | if let Some(resolved) = resolved { |
| 1442 | pending.push(resolved); |
| 1443 | } |
| 1444 | } |
| 1445 | } |
| 1446 | Ok(()) |
| 1447 | } |
| 1448 | } |
| 1449 | |
| 1450 | fn client_closure( |
| 1451 | files: &BTreeMap<String, Vec<u8>>, |
| 1452 | root: &str, |
| 1453 | manifest: &Value, |
| 1454 | ) -> Result<DshClientClosure, String> { |
| 1455 | let prefix = if root.is_empty() { |
| 1456 | "source".to_string() |
| 1457 | } else { |
| 1458 | format!("source/{root}") |
| 1459 | }; |
| 1460 | let raw = client_entry(manifest); |
| 1461 | let entry = normalize_slash(&format!("{prefix}/{raw}")) |
| 1462 | .filter(|path| path.starts_with(&format!("{prefix}/"))) |
| 1463 | .ok_or_else(|| format!("client entry `{raw}` leaves the package"))?; |
| 1464 | if !files.contains_key(&entry) { |
| 1465 | return Err(format!( |
| 1466 | "client entry `{raw}` is not in the reviewed package files" |
| 1467 | )); |
| 1468 | } |
| 1469 | let mut scan = ClientScan { |
| 1470 | files, |
| 1471 | closure: BTreeMap::new(), |
| 1472 | imports: BTreeMap::new(), |
| 1473 | host: Default::default(), |
| 1474 | bytes: 0, |
| 1475 | }; |
| 1476 | scan.note(format!("{prefix}/package.json")); |
| 1477 | scan.visit(entry.clone())?; |
| 1478 | let client = manifest.get("dsh").and_then(|dsh| dsh.get("client")); |
| 1479 | let inject = match client.and_then(|client| client.get("inject")) { |
| 1480 | Some(Value::Seq(items)) => items |
| 1481 | .iter() |
| 1482 | .filter_map(|item| item.str().map(refusal_text)) |
| 1483 | .collect(), |
| 1484 | _ => Vec::new(), |
| 1485 | }; |
| 1486 | Ok(DshClientClosure { |
| 1487 | package: manifest |
| 1488 | .get("name") |
| 1489 | .and_then(Value::str) |
| 1490 | .map(refusal_text) |
| 1491 | .unwrap_or_default(), |
| 1492 | root: root.to_string(), |
| 1493 | entry, |
| 1494 | platform: client |
| 1495 | .and_then(|client| client.get("platform")) |
| 1496 | .and_then(Value::str) |
| 1497 | .map(refusal_text), |
| 1498 | inject, |
| 1499 | host_provided: scan.host.into_iter().collect(), |
| 1500 | files: scan.closure, |
| 1501 | imports: scan.imports, |
| 1502 | bytes: scan.bytes, |
| 1503 | }) |
| 1504 | } |
| 1505 | |
| 1506 | pub fn load_bundle(package: &Package) -> Result<LoadedBundle> { |
| 1507 | let manifest_bytes = read_file(&package.contained(Path::new("package.json"))?, MAX_DOCUMENT) |
| 1508 | .map_err(|_| { |
| 1509 | anyhow::Error::msg("Not a DSH bundle package: package.json is missing or unreadable.") |
| 1510 | })?; |
| 1511 | let manifest_sha256 = sha256_hex(&manifest_bytes); |
| 1512 | let manifest = parse_package_json(&utf8(manifest_bytes)?)?; |
| 1513 | mapping(&manifest, None)?; |
| 1514 | let bundle = manifest.get("dsh").and_then(|dsh| dsh.get("bundle")); |
| 1515 | require( |
| 1516 | matches!(bundle, Some(Value::Map(_))), |
| 1517 | "Not a DSH bundle package: package.json lacks `dsh.bundle.patch`.", |
| 1518 | )?; |
| 1519 | let admitted = admit_host_compatibility(&manifest)?; |
| 1520 | let dsh_range = admitted.dsh_range.as_deref(); |
| 1521 | let mut notes = Vec::new(); |
| 1522 | let declared: Vec<&Value> = match bundle.and_then(|bundle| bundle.get("patch")) { |
| 1523 | Some(single @ Value::Str(_)) => vec![single], |
| 1524 | Some(Value::Seq(items)) if !items.is_empty() => items.iter().collect(), |
| 1525 | _ => { |
| 1526 | return refuse( |
| 1527 | "`dsh.bundle.patch` must name a patch file or a non-empty ordered list of patch files.", |
| 1528 | ); |
| 1529 | } |
| 1530 | }; |
| 1531 | require( |
| 1532 | declared.len() <= MAX_PATCH_FILES, |
| 1533 | "At most 64 `dsh.bundle.patch` files are supported.", |
| 1534 | )?; |
| 1535 | let mut layers = Vec::new(); |
| 1536 | let mut raw_layers = Vec::new(); |
| 1537 | let mut seen = Vec::<PathBuf>::new(); |
| 1538 | let mut total = 0usize; |
| 1539 | for entry in declared { |
| 1540 | let Some(relative) = entry.str().filter(|text| !text.is_empty()) else { |
| 1541 | return refuse("Every `dsh.bundle.patch` entry must be a non-empty relative path."); |
| 1542 | }; |
| 1543 | require( |
| 1544 | plain_relative(relative), |
| 1545 | "Every `dsh.bundle.patch` entry must be a relative path inside the bundle directory.", |
| 1546 | )?; |
| 1547 | let path = package.contained(Path::new(relative))?; |
| 1548 | require( |
| 1549 | path.is_file(), |
| 1550 | "Every `dsh.bundle.patch` entry must resolve to a file inside the bundle directory.", |
| 1551 | )?; |
| 1552 | require( |
| 1553 | !seen.contains(&path), |
| 1554 | "Each `dsh.bundle.patch` file may be listed once; a duplicate would apply its layer twice.", |
| 1555 | )?; |
| 1556 | seen.push(path.clone()); |
| 1557 | require( |
| 1558 | total < MAX_DOCUMENT, |
| 1559 | "Selected patch files exceed the 1 MiB aggregate patch limit.", |
| 1560 | )?; |
| 1561 | let content = read_file(&path, MAX_DOCUMENT - total)?; |
| 1562 | total += content.len(); |
| 1563 | let sha256 = sha256_hex(&content); |
| 1564 | let bytes = content.len(); |
| 1565 | let source = utf8(content)?; |
| 1566 | raw_layers.push(json!({"path": relative_slash(&path, &package.root), "sha256": sha256, "source": source})); |
| 1567 | layers.push(DshLayer { |
| 1568 | path: relative.to_string(), |
| 1569 | sha256, |
| 1570 | bytes, |
| 1571 | }); |
| 1572 | } |
| 1573 | let composition = json!({"version":1,"layers":raw_layers,"modules":[],"files":{}}); |
| 1574 | let mut review_input = composition.clone(); |
| 1575 | let target = if let Some(range) = dsh_range { |
| 1576 | let target = match admitted.matched_dsh_version { |
| 1577 | Some(matched) => matched, |
| 1578 | None => target_dsh_version()?, |
| 1579 | }; |
| 1580 | review_input["compatibility"] = json!({"range":range,"version":target.to_string()}); |
| 1581 | Some(target) |
| 1582 | } else { |
| 1583 | None |
| 1584 | }; |
| 1585 | let reviewed = match crate::composition_review::review(&review_input) { |
| 1586 | Ok(reviewed) => reviewed, |
| 1587 | #[cfg(any(test, feature = "test-support"))] |
| 1588 | Err(ref msg) if msg == "composition reviewer is unavailable" => { |
| 1589 | let mut patches = Vec::new(); |
| 1590 | let mut locations = Vec::new(); |
| 1591 | for (layer_meta, raw) in layers |
| 1592 | .iter() |
| 1593 | .zip(composition["layers"].as_array().into_iter().flatten()) |
| 1594 | { |
| 1595 | let src = raw.get("source").and_then(Json::as_str).unwrap_or_default(); |
| 1596 | let parsed = parse_yaml(src, true)?; |
| 1597 | let Value::Seq(items) = parsed else { |
| 1598 | return refuse("Each DSH patch layer must be a YAML or JSON array."); |
| 1599 | }; |
| 1600 | for (idx, item) in items.into_iter().enumerate() { |
| 1601 | patches.push(item); |
| 1602 | locations.push((layer_meta.path.clone(), idx + 1)); |
| 1603 | } |
| 1604 | } |
| 1605 | let (entries, outcomes) = evaluate_patches(patches, &mut notes, &locations)?; |
| 1606 | return Ok(LoadedBundle { |
| 1607 | composition, |
| 1608 | manifest, |
| 1609 | manifest_sha256, |
| 1610 | entries, |
| 1611 | notes, |
| 1612 | layers, |
| 1613 | outcomes, |
| 1614 | platforms: admitted.platforms, |
| 1615 | }); |
| 1616 | } |
| 1617 | Err(err) => return Err(anyhow::Error::msg(err)), |
| 1618 | }; |
| 1619 | if let (Some(range), Some(target)) = (dsh_range, target) { |
| 1620 | match reviewed.get("compatibility").and_then(Json::as_str) { |
| 1621 | Some("match") => {} |
| 1622 | Some("invalid") => { |
| 1623 | return refuse(format!( |
| 1624 | "incompatible-version: `engines.dsh` value `{}` is not a valid semver range.", |
| 1625 | refusal_text(range) |
| 1626 | )); |
| 1627 | } |
| 1628 | Some("mismatch") => { |
| 1629 | return refuse(format!( |
| 1630 | "incompatible-version: this bundle requires DSH `{}`, but this Codewhale host targets DSH {target}; import a bundle built for that host or update the host.", |
| 1631 | refusal_text(range) |
| 1632 | )); |
| 1633 | } |
| 1634 | _ => { |
| 1635 | return refuse( |
| 1636 | "incompatible-version: compatibility reviewer returned no valid decision.", |
| 1637 | ); |
| 1638 | } |
| 1639 | } |
| 1640 | } |
| 1641 | let entries = reviewed |
| 1642 | .get("entries") |
| 1643 | .and_then(Json::as_array) |
| 1644 | .ok_or_else(|| anyhow::Error::msg("composition reviewer omitted its effective entries"))? |
| 1645 | .iter() |
| 1646 | .map(reviewed_value) |
| 1647 | .collect::<Result<Vec<_>>>()?; |
| 1648 | // Upstream warnings contain row identities only, never configuration values. |
| 1649 | notes.extend( |
| 1650 | reviewed |
| 1651 | .get("warnings") |
| 1652 | .and_then(Json::as_array) |
| 1653 | .into_iter() |
| 1654 | .flatten() |
| 1655 | .filter_map(Json::as_str) |
| 1656 | .map(str::to_string), |
| 1657 | ); |
| 1658 | let outcomes = reviewed |
| 1659 | .get("skipped") |
| 1660 | .and_then(Json::as_array) |
| 1661 | .into_iter() |
| 1662 | .flatten() |
| 1663 | .map(|row| { |
| 1664 | let review_path = row |
| 1665 | .get("layer") |
| 1666 | .and_then(Json::as_str) |
| 1667 | .ok_or_else(|| anyhow::Error::msg("reviewer omitted patch layer"))?; |
| 1668 | let layer = layers |
| 1669 | .iter() |
| 1670 | .find(|layer| layer.path.trim_start_matches("./") == review_path) |
| 1671 | .ok_or_else(|| anyhow::Error::msg("reviewer returned unknown patch layer"))?; |
| 1672 | Ok(DshOutcome { |
| 1673 | row: row.get("row").and_then(Json::as_str).map(str::to_string), |
| 1674 | package: row |
| 1675 | .get("package") |
| 1676 | .and_then(Json::as_str) |
| 1677 | .map(str::to_string), |
| 1678 | kind: "patch".into(), |
| 1679 | outcome: "skipped".into(), |
| 1680 | reason: row |
| 1681 | .get("reason") |
| 1682 | .and_then(Json::as_str) |
| 1683 | .ok_or_else(|| anyhow::Error::msg("reviewer omitted patch reason"))? |
| 1684 | .into(), |
| 1685 | layer: Some(layer.path.clone()), |
| 1686 | patch: Some(usize::try_from( |
| 1687 | row.get("patch") |
| 1688 | .and_then(Json::as_u64) |
| 1689 | .filter(|n| *n > 0) |
| 1690 | .ok_or_else(|| anyhow::Error::msg("reviewer omitted patch number"))?, |
| 1691 | )?), |
| 1692 | }) |
| 1693 | }) |
| 1694 | .collect::<Result<Vec<_>>>()?; |
| 1695 | Ok(LoadedBundle { |
| 1696 | composition, |
| 1697 | manifest, |
| 1698 | manifest_sha256, |
| 1699 | entries, |
| 1700 | notes, |
| 1701 | layers, |
| 1702 | outcomes, |
| 1703 | platforms: admitted.platforms, |
| 1704 | }) |
| 1705 | } |
| 1706 | |
| 1707 | /// Upstream expression markers remain expressions, including nested values. |
| 1708 | fn reviewed_value(value: &Json) -> Result<Value> { |
| 1709 | Ok(match value { |
| 1710 | Json::Null => Value::Null, |
| 1711 | Json::Bool(value) => Value::Bool(*value), |
| 1712 | Json::Number(value) => { |
| 1713 | if let Some(value) = value.as_i64() { |
| 1714 | Value::Int(value) |
| 1715 | } else { |
| 1716 | Value::Float( |
| 1717 | value |
| 1718 | .as_f64() |
| 1719 | .ok_or_else(|| anyhow::Error::msg("nonfinite reviewed value"))?, |
| 1720 | ) |
| 1721 | } |
| 1722 | } |
| 1723 | Json::String(value) => Value::Str(value.clone()), |
| 1724 | Json::Array(values) => { |
| 1725 | Value::Seq(values.iter().map(reviewed_value).collect::<Result<_>>()?) |
| 1726 | } |
| 1727 | Json::Object(values) |
| 1728 | if values.len() == 1 && values.get("__jsExpr").is_some_and(Json::is_string) => |
| 1729 | { |
| 1730 | Value::Js( |
| 1731 | values["__jsExpr"] |
| 1732 | .as_str() |
| 1733 | .expect("checked marker") |
| 1734 | .to_string(), |
| 1735 | ) |
| 1736 | } |
| 1737 | Json::Object(values) => Value::Map( |
| 1738 | values |
| 1739 | .iter() |
| 1740 | .map(|(key, value)| Ok((key.clone(), reviewed_value(value)?))) |
| 1741 | .collect::<Result<_>>()?, |
| 1742 | ), |
| 1743 | }) |
| 1744 | } |
| 1745 | |
| 1746 | /// Rows are addressed by index path: `[i]` is a top-level entry, `[i, j]` the |
| 1747 | /// `j`th child in entry `i`'s group `config`. |
| 1748 | #[cfg(any(test, feature = "test-support"))] |
| 1749 | pub fn row_at<'a>(entries: &'a mut [Value], path: &[usize]) -> &'a mut Value { |
| 1750 | let (first, rest) = path.split_first().expect("non-empty row path"); |
| 1751 | let mut row = &mut entries[*first]; |
| 1752 | for index in rest { |
| 1753 | let Some(Value::Seq(children)) = row.get_mut("config") else { |
| 1754 | unreachable!("row paths only descend through group configs"); |
| 1755 | }; |
| 1756 | row = &mut children[*index]; |
| 1757 | } |
| 1758 | row |
| 1759 | } |
| 1760 | |
| 1761 | /// `applyEntryPatches` parity over an empty entry list: `insert` appends rows |
| 1762 | /// (or appends into a group entry's config); keyed patches replace fields on |
| 1763 | /// an earlier inserted row. Skipped patches are recorded with their layer. |
| 1764 | #[cfg(any(test, feature = "test-support"))] |
| 1765 | pub fn evaluate_patches( |
| 1766 | patches: Vec<Value>, |
| 1767 | notes: &mut Vec<String>, |
| 1768 | locations: &[(String, usize)], |
| 1769 | ) -> Result<(Vec<Value>, Vec<DshOutcome>)> { |
| 1770 | fn index_rows( |
| 1771 | rows: &[Value], |
| 1772 | base: &[usize], |
| 1773 | offset: usize, |
| 1774 | index: &mut BTreeMap<String, Vec<usize>>, |
| 1775 | ) { |
| 1776 | for (position, row) in rows.iter().enumerate() { |
| 1777 | let mut path = base.to_vec(); |
| 1778 | path.push(offset + position); |
| 1779 | if let Some(identifier) = row.get("id").and_then(Value::str) { |
| 1780 | index.insert(identifier.to_string(), path.clone()); |
| 1781 | } |
| 1782 | if is_group_row(row) |
| 1783 | && let Some(Value::Seq(children)) = row.get("config") |
| 1784 | { |
| 1785 | index_rows(children, &path, 0, index); |
| 1786 | } |
| 1787 | } |
| 1788 | } |
| 1789 | |
| 1790 | let mut entries: Vec<Value> = Vec::new(); |
| 1791 | let mut index: BTreeMap<String, Vec<usize>> = BTreeMap::new(); |
| 1792 | let mut outcomes = Vec::new(); |
| 1793 | for (order, patch) in patches.into_iter().enumerate() { |
| 1794 | require( |
| 1795 | matches!(patch, Value::Map(_)), |
| 1796 | "Each DSH patch must be an object.", |
| 1797 | )?; |
| 1798 | let mut skip = |reason: String| { |
| 1799 | notes.push(format!("patch {}: {reason}; skipped", order + 1)); |
| 1800 | let (layer, number) = locations[order].clone(); |
| 1801 | outcomes.push(DshOutcome { |
| 1802 | row: patch.get("id").and_then(Value::str).map(str::to_string), |
| 1803 | package: patch.get("name").and_then(Value::str).map(str::to_string), |
| 1804 | kind: "patch".to_string(), |
| 1805 | outcome: "skipped".to_string(), |
| 1806 | reason, |
| 1807 | layer: Some(layer), |
| 1808 | patch: Some(number), |
| 1809 | }); |
| 1810 | }; |
| 1811 | let identifier = patch.get("id").cloned(); |
| 1812 | if let Some(insert) = patch.get("insert") { |
| 1813 | let Value::Seq(rows) = insert else { |
| 1814 | return refuse("A DSH patch `insert` must be a list of entries."); |
| 1815 | }; |
| 1816 | require( |
| 1817 | rows.iter().all(|row| matches!(row, Value::Map(_))), |
| 1818 | "A DSH patch `insert` must be a list of entries.", |
| 1819 | )?; |
| 1820 | let rows = rows.clone(); |
| 1821 | match identifier { |
| 1822 | None | Some(Value::Null) => { |
| 1823 | let offset = entries.len(); |
| 1824 | entries.extend(rows.iter().cloned()); |
| 1825 | index_rows(&rows, &[], offset, &mut index); |
| 1826 | } |
| 1827 | Some(identifier) => { |
| 1828 | let target = identifier.str().and_then(|id| index.get(id)).cloned(); |
| 1829 | let Some(path) = target.filter(|path| { |
| 1830 | row_at(&mut entries, path) |
| 1831 | .get("group") |
| 1832 | .is_some_and(Value::is_true) |
| 1833 | }) else { |
| 1834 | let shown = identifier.str().unwrap_or("?").to_string(); |
| 1835 | skip(format!("insert target `{shown}` is missing or not a group")); |
| 1836 | continue; |
| 1837 | }; |
| 1838 | let row = row_at(&mut entries, &path); |
| 1839 | if !matches!(row.get("config"), Some(Value::Seq(_))) { |
| 1840 | row.set("config", Value::Seq(Vec::new())); |
| 1841 | } |
| 1842 | let Some(Value::Seq(children)) = row.get_mut("config") else { |
| 1843 | unreachable!("config was just set to a list"); |
| 1844 | }; |
| 1845 | let offset = children.len(); |
| 1846 | children.extend(rows.iter().cloned()); |
| 1847 | index_rows(&rows, &path, offset, &mut index); |
| 1848 | } |
| 1849 | } |
| 1850 | continue; |
| 1851 | } |
| 1852 | let Some(identifier) = identifier.as_ref().and_then(Value::str).map(str::to_string) else { |
| 1853 | skip("non-insert patch without an `id`".to_string()); |
| 1854 | continue; |
| 1855 | }; |
| 1856 | let Some(path) = index.get(&identifier).cloned() else { |
| 1857 | skip(format!( |
| 1858 | "entry `{identifier}` was not inserted by an earlier layer" |
| 1859 | )); |
| 1860 | continue; |
| 1861 | }; |
| 1862 | let target = row_at(&mut entries, &path); |
| 1863 | if let Some(name) = patch.get("name") |
| 1864 | && !matches!(name, Value::Null) |
| 1865 | && Some(name) != target.get("name") |
| 1866 | { |
| 1867 | skip(format!("`name` does not match entry `{identifier}`")); |
| 1868 | continue; |
| 1869 | } |
| 1870 | let Value::Map(fields) = &patch else { |
| 1871 | unreachable!() |
| 1872 | }; |
| 1873 | let replaces_children = fields |
| 1874 | .iter() |
| 1875 | .any(|(key, _)| key == "config" || key == "group"); |
| 1876 | for (key, value) in fields { |
| 1877 | if key != "id" && key != "name" { |
| 1878 | target.set(key, value.clone()); |
| 1879 | } |
| 1880 | } |
| 1881 | if replaces_children { |
| 1882 | // Rows under a replaced config are detached from the profile, as |
| 1883 | // their dict identities are in DSH; later patches cannot reach them. |
| 1884 | index.retain(|_, row_path| { |
| 1885 | !(row_path.len() > path.len() && row_path.starts_with(&path)) |
| 1886 | }); |
| 1887 | } |
| 1888 | } |
| 1889 | Ok((entries, outcomes)) |
| 1890 | } |
| 1891 | |
| 1892 | // ───────────────────────────────────────────────────────────────────────────── |
| 1893 | // MCP conversion |
| 1894 | // ───────────────────────────────────────────────────────────────────────────── |
| 1895 | |
| 1896 | fn js_literal(text: &str, label: &str) -> Result<String> { |
| 1897 | let text = text.trim(); |
| 1898 | let chars: Vec<char> = text.chars().collect(); |
| 1899 | if chars.len() >= 2 |
| 1900 | && (chars[0] == '"' || chars[0] == '\'') |
| 1901 | && chars[chars.len() - 1] == chars[0] |
| 1902 | && !chars[1..chars.len() - 1].contains(&chars[0]) |
| 1903 | { |
| 1904 | let body: String = chars[1..chars.len() - 1].iter().collect(); |
| 1905 | require( |
| 1906 | !body.contains('\\') && !body.contains('\n'), |
| 1907 | &format!("{label} contains JavaScript escapes; author the literal explicitly."), |
| 1908 | )?; |
| 1909 | return Ok(body); |
| 1910 | } |
| 1911 | if chars.len() >= 2 && chars[0] == '`' && chars[chars.len() - 1] == '`' { |
| 1912 | let body: String = chars[1..chars.len() - 1].iter().collect(); |
| 1913 | require( |
| 1914 | !body.contains("${") && !body.contains('\\') && !body.contains('`'), |
| 1915 | &format!( |
| 1916 | "{label} interpolates a value that conversion never evaluates; author the literal explicitly." |
| 1917 | ), |
| 1918 | )?; |
| 1919 | return Ok(body); |
| 1920 | } |
| 1921 | refuse(format!( |
| 1922 | "{label} is not a quoted or template literal; author the value explicitly." |
| 1923 | )) |
| 1924 | } |
| 1925 | |
| 1926 | /// Lower only the `!!js` idioms that need no ambient state. |
| 1927 | pub fn lower_js(text: &str, label: &str) -> Result<String> { |
| 1928 | let text = text.trim(); |
| 1929 | if text == "process.execPath" { |
| 1930 | return Ok("node".to_string()); |
| 1931 | } |
| 1932 | if text.contains("process.env") { |
| 1933 | return refuse(format!( |
| 1934 | "{label} reads an environment value, and conversion never evaluates this machine's environment; author the literal explicitly" |
| 1935 | )); |
| 1936 | } |
| 1937 | if text.starts_with('`') || text.starts_with('"') || text.starts_with('\'') { |
| 1938 | return js_literal(text, label); |
| 1939 | } |
| 1940 | refuse(format!( |
| 1941 | "{label} uses a `!!js` expression with no portable lowering; author the value explicitly." |
| 1942 | )) |
| 1943 | } |
| 1944 | |
| 1945 | fn timeout_seconds(value: &Value) -> Result<i64> { |
| 1946 | match value { |
| 1947 | Value::Int(ms) if (1000..=3_600_000).contains(ms) && ms % 1000 == 0 => Ok(ms / 1000), |
| 1948 | _ => refuse( |
| 1949 | "Timeouts must be whole seconds expressed in milliseconds (1000–3600000); port other values manually.", |
| 1950 | ), |
| 1951 | } |
| 1952 | } |
| 1953 | |
| 1954 | fn server_options(config: &Value) -> Result<serde_json::Map<String, Json>> { |
| 1955 | let mut extension = serde_json::Map::new(); |
| 1956 | match config.get("failOnStartupError") { |
| 1957 | None | Some(Value::Bool(false)) => {} |
| 1958 | Some(Value::Bool(true)) => { |
| 1959 | extension.insert("required".to_string(), json!(true)); |
| 1960 | } |
| 1961 | Some(_) => { |
| 1962 | return refuse("DSH startup-failure policy must be a boolean."); |
| 1963 | } |
| 1964 | } |
| 1965 | if let Some(value) = config.get("toolCallTimeoutMs") { |
| 1966 | extension.insert( |
| 1967 | "execute_timeout".to_string(), |
| 1968 | json!(timeout_seconds(value)?), |
| 1969 | ); |
| 1970 | } |
| 1971 | Ok(extension) |
| 1972 | } |
| 1973 | |
| 1974 | /// Parse a literal HTTP(S) endpoint the way the native reviewer will see it, |
| 1975 | /// returning the host as it enters the capability set. |
| 1976 | pub fn endpoint_host(url: &str) -> Result<String> { |
| 1977 | require( |
| 1978 | !url.chars() |
| 1979 | .any(|c| c.is_whitespace() || c == '\\' || c == '{' || c == '}'), |
| 1980 | "MCP URL must be a literal endpoint without interpolation.", |
| 1981 | )?; |
| 1982 | require( |
| 1983 | url.is_ascii() && url.len() <= 4096, |
| 1984 | "Use an ASCII MCP hostname and URL of at most 4096 characters.", |
| 1985 | )?; |
| 1986 | let (scheme, rest) = url |
| 1987 | .split_once("://") |
| 1988 | .ok_or_else(|| anyhow::Error::msg("Invalid MCP endpoint URL."))?; |
| 1989 | let scheme = scheme.to_ascii_lowercase(); |
| 1990 | require( |
| 1991 | !rest.contains('?') && !rest.contains('#'), |
| 1992 | "MCP URLs must not contain credentials, query strings or fragments.", |
| 1993 | )?; |
| 1994 | let authority = rest.split('/').next().unwrap_or_default(); |
| 1995 | require( |
| 1996 | !authority.contains('@'), |
| 1997 | "MCP URLs must not contain credentials, query strings or fragments.", |
| 1998 | )?; |
| 1999 | let (host, port) = if let Some(bracketed) = authority.strip_prefix('[') { |
| 2000 | let (host, tail) = bracketed |
| 2001 | .split_once(']') |
| 2002 | .ok_or_else(|| anyhow::Error::msg("MCP URL needs a valid host and port."))?; |
| 2003 | (host.to_string(), tail.strip_prefix(':')) |
| 2004 | } else { |
| 2005 | match authority.rsplit_once(':') { |
| 2006 | Some((host, port)) => (host.to_string(), Some(port)), |
| 2007 | None => (authority.to_string(), None), |
| 2008 | } |
| 2009 | }; |
| 2010 | let host = host.to_ascii_lowercase(); |
| 2011 | require(!host.is_empty(), "MCP URL needs a valid host and port.")?; |
| 2012 | if let Some(port) = port { |
| 2013 | require( |
| 2014 | port.parse::<u16>().is_ok_and(|port| port != 0), |
| 2015 | "MCP URL needs a valid host and port.", |
| 2016 | )?; |
| 2017 | } |
| 2018 | let loopback = matches!(host.as_str(), "localhost" | "127.0.0.1" | "::1"); |
| 2019 | require( |
| 2020 | scheme == "https" || (scheme == "http" && loopback), |
| 2021 | "MCP endpoints need HTTPS (or explicit loopback HTTP).", |
| 2022 | )?; |
| 2023 | let last_label = host.rsplit('.').next().unwrap_or_default(); |
| 2024 | let numeric = host.contains(':') || pattern(r"^(?:[0-9]+|0x[0-9a-f]+)$").is_match(last_label); |
| 2025 | if numeric { |
| 2026 | let address: std::net::IpAddr = host |
| 2027 | .parse() |
| 2028 | .map_err(|_| anyhow::Error::msg("Use a canonical numeric MCP address."))?; |
| 2029 | require( |
| 2030 | address.to_string() == host, |
| 2031 | "Use a canonical numeric MCP address.", |
| 2032 | )?; |
| 2033 | if address.is_ipv6() { |
| 2034 | return Ok(format!("[{host}]")); |
| 2035 | } |
| 2036 | } |
| 2037 | Ok(host) |
| 2038 | } |
| 2039 | |
| 2040 | fn remote_server(config: &Value) -> Result<(Json, String)> { |
| 2041 | mapping(config, None)?; |
| 2042 | require( |
| 2043 | config.get("transport").and_then(Value::str) == Some("streamable-http"), |
| 2044 | "Unsupported MCP transport.", |
| 2045 | )?; |
| 2046 | mapping( |
| 2047 | config, |
| 2048 | Some(&[ |
| 2049 | "serverName", |
| 2050 | "transport", |
| 2051 | "url", |
| 2052 | "headers", |
| 2053 | "toolCallTimeoutMs", |
| 2054 | "failOnStartupError", |
| 2055 | ]), |
| 2056 | )?; |
| 2057 | let extension = server_options(config)?; |
| 2058 | let Some(url) = config.get("url").and_then(Value::str) else { |
| 2059 | return refuse("MCP URL must be a literal endpoint without interpolation."); |
| 2060 | }; |
| 2061 | let host = endpoint_host(url)?; |
| 2062 | if let Some(headers) = config.get("headers") { |
| 2063 | require( |
| 2064 | mapping(headers, None)?.is_empty(), |
| 2065 | "Literal headers, DSH expressions and file interpolation cannot be converted; author native env_headers manually.", |
| 2066 | )?; |
| 2067 | } |
| 2068 | Ok(( |
| 2069 | json!({"type": "streamable-http", "url": url, "extensions": {"net.codewhale": extension}}), |
| 2070 | host, |
| 2071 | )) |
| 2072 | } |
| 2073 | |
| 2074 | fn stdio_server(config: &Value, name: &str, root: &Path) -> Result<Json> { |
| 2075 | mapping( |
| 2076 | config, |
| 2077 | Some(&[ |
| 2078 | "serverName", |
| 2079 | "transport", |
| 2080 | "command", |
| 2081 | "args", |
| 2082 | "env", |
| 2083 | "cwd", |
| 2084 | "toolCallTimeoutMs", |
| 2085 | "failOnStartupError", |
| 2086 | ]), |
| 2087 | )?; |
| 2088 | if let Some(env) = config.get("env") { |
| 2089 | require( |
| 2090 | mapping(env, None)?.is_empty(), |
| 2091 | "DSH stdio env values and expressions require a manual native port.", |
| 2092 | )?; |
| 2093 | } |
| 2094 | let entry = match ( |
| 2095 | config.get("command").and_then(Value::str), |
| 2096 | config.get("args"), |
| 2097 | ) { |
| 2098 | (Some("node"), Some(Value::Seq(args))) if args.len() == 1 => args[0].str(), |
| 2099 | _ => None, |
| 2100 | }; |
| 2101 | let Some(entry) = entry else { |
| 2102 | return refuse( |
| 2103 | "Only node with one packaged .mjs, .js or .cjs entry is supported; no launcher flags, package managers or shell commands.", |
| 2104 | ); |
| 2105 | }; |
| 2106 | require( |
| 2107 | pattern(r"^(?:\./)?[A-Za-z0-9_][A-Za-z0-9_./-]*\.(?:mjs|js|cjs)$").is_match(entry) |
| 2108 | && !entry.split('/').any(|part| part == ".."), |
| 2109 | "Node entry must be a contained relative .mjs, .js or .cjs file; compile other entry formats before packaging.", |
| 2110 | )?; |
| 2111 | require( |
| 2112 | config |
| 2113 | .get("cwd") |
| 2114 | .is_none_or(|cwd| matches!(cwd.str(), Some("" | "."))), |
| 2115 | "Other cwd values require a manual port.", |
| 2116 | )?; |
| 2117 | require( |
| 2118 | root.join(entry).is_file(), |
| 2119 | "Packaged Node entry does not exist.", |
| 2120 | )?; |
| 2121 | Ok(json!({ |
| 2122 | "type": "stdio", |
| 2123 | "command": "node", |
| 2124 | "args": [entry], |
| 2125 | "cwd": format!("mcp/{name}"), |
| 2126 | "env": {}, |
| 2127 | "extensions": {"net.codewhale": server_options(config)?}, |
| 2128 | })) |
| 2129 | } |
| 2130 | |
| 2131 | // ───────────────────────────────────────────────────────────────────────────── |
| 2132 | // Row conversion |
| 2133 | // ───────────────────────────────────────────────────────────────────────────── |
| 2134 | |
| 2135 | #[derive(Default)] |
| 2136 | pub struct Components { |
| 2137 | pub servers: Vec<(String, Json)>, |
| 2138 | pub hosts: Vec<String>, |
| 2139 | /// Local server name → packaged source root inside the package. |
| 2140 | pub roots: Vec<(String, PathBuf)>, |
| 2141 | pub skill_dirs: Vec<PathBuf>, |
| 2142 | pub notes: Vec<String>, |
| 2143 | pub outcomes: Vec<DshOutcome>, |
| 2144 | } |
| 2145 | |
| 2146 | impl Components { |
| 2147 | fn record(&mut self, row: &Value, kind: &str, outcome: &str, reason: &str) { |
| 2148 | let identifier = row.get("id").and_then(Value::str).map(str::to_string); |
| 2149 | let label = identifier |
| 2150 | .as_ref() |
| 2151 | .map_or_else(|| "an unlabeled row".to_string(), |id| format!("`{id}`")); |
| 2152 | self.notes.push(format!( |
| 2153 | "{label} [{kind}] {outcome}{}", |
| 2154 | if reason.is_empty() { |
| 2155 | String::new() |
| 2156 | } else { |
| 2157 | format!(": {reason}") |
| 2158 | } |
| 2159 | )); |
| 2160 | self.outcomes.push(DshOutcome { |
| 2161 | row: identifier, |
| 2162 | package: row.get("name").and_then(Value::str).map(str::to_string), |
| 2163 | kind: kind.to_string(), |
| 2164 | outcome: outcome.to_string(), |
| 2165 | reason: reason.to_string(), |
| 2166 | layer: None, |
| 2167 | patch: None, |
| 2168 | }); |
| 2169 | } |
| 2170 | |
| 2171 | fn has_server(&self, name: &str) -> bool { |
| 2172 | self.servers.iter().any(|(existing, _)| existing == name) |
| 2173 | } |
| 2174 | |
| 2175 | fn mcp_row(&mut self, package: &Package, row: &Value, disabled: bool) -> Result<()> { |
| 2176 | let mut config = row.get("config").cloned().unwrap_or(Value::Null); |
| 2177 | mapping(&config, None)?; |
| 2178 | let name = config |
| 2179 | .get("serverName") |
| 2180 | .and_then(Value::str) |
| 2181 | .map(str::to_string); |
| 2182 | let Some(name) = |
| 2183 | name.filter(|name| pattern(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$").is_match(name)) |
| 2184 | else { |
| 2185 | return refuse( |
| 2186 | "dsh-mcp-client config needs a literal `serverName` of 1–32 letters/digits/_/-", |
| 2187 | ); |
| 2188 | }; |
| 2189 | require( |
| 2190 | !self.has_server(&name), |
| 2191 | &format!("Duplicate MCP server name `{name}`; nothing was written for it."), |
| 2192 | )?; |
| 2193 | for field in ["command", "cwd", "url", "serverName"] { |
| 2194 | if let Some(Value::Js(expression)) = config.get(field) { |
| 2195 | let lowered = lower_js(expression, &format!("`{field}` in `{name}`"))?; |
| 2196 | config.set(field, Value::Str(lowered)); |
| 2197 | } |
| 2198 | } |
| 2199 | if let Some(Value::Seq(args)) = config.get("args").cloned() { |
| 2200 | let lowered = args |
| 2201 | .into_iter() |
| 2202 | .map(|arg| match arg { |
| 2203 | Value::Js(expression) => { |
| 2204 | lower_js(&expression, &format!("`args` in `{name}`")).map(Value::Str) |
| 2205 | } |
| 2206 | other => Ok(other), |
| 2207 | }) |
| 2208 | .collect::<Result<Vec<_>>>()?; |
| 2209 | config.set("args", Value::Seq(lowered)); |
| 2210 | } |
| 2211 | let local = config.get("transport").and_then(Value::str) == Some("stdio"); |
| 2212 | let mut root = None; |
| 2213 | if local |
| 2214 | && let Some(Value::Seq(args)) = config.get("args") |
| 2215 | && let [Value::Str(arg)] = args.as_slice() |
| 2216 | { |
| 2217 | let entry = pattern(r"^(?:\./)?[A-Za-z0-9_][A-Za-z0-9_./-]*\.(?:mjs|js|cjs)$"); |
| 2218 | if !entry.is_match(arg) { |
| 2219 | return refuse(format!( |
| 2220 | "`args` in `{name}` names a host path outside the selected package; import never copies an ambient path. Package the server inside the bundle, then import again" |
| 2221 | )); |
| 2222 | } |
| 2223 | if !arg.split('/').any(|part| part == "..") { |
| 2224 | let cwd = config.get("cwd").and_then(Value::str).unwrap_or(""); |
| 2225 | if matches!(cwd, "" | ".") { |
| 2226 | if package.contained(Path::new(arg))?.is_file() { |
| 2227 | root = Some(package.root.clone()); |
| 2228 | } |
| 2229 | } else if plain_relative(cwd) { |
| 2230 | let candidate = package.contained(Path::new(cwd))?; |
| 2231 | if package.contained(&Path::new(cwd).join(arg))?.is_file() { |
| 2232 | root = Some(candidate); |
| 2233 | config.set("cwd", Value::Str(".".to_string())); |
| 2234 | } |
| 2235 | } |
| 2236 | } |
| 2237 | } |
| 2238 | require( |
| 2239 | config.free_of_js(), |
| 2240 | &format!("an unevaluated `!!js` remains in `{name}`; author that field explicitly"), |
| 2241 | )?; |
| 2242 | let mut converted = if local { |
| 2243 | let Some(root) = root else { |
| 2244 | return refuse(format!( |
| 2245 | "`{name}` is a local server whose packaged Node entry is not inside the selected package" |
| 2246 | )); |
| 2247 | }; |
| 2248 | let server = stdio_server(&config, &name, &root)?; |
| 2249 | let shown = package.relative_of(&root).display().to_string(); |
| 2250 | self.notes.push(format!( |
| 2251 | "`{name}`: stdio source root resolved inside the selected package at `{}`", |
| 2252 | if shown.is_empty() { |
| 2253 | ".".to_string() |
| 2254 | } else { |
| 2255 | shown |
| 2256 | } |
| 2257 | )); |
| 2258 | self.roots.push((name.clone(), root)); |
| 2259 | server |
| 2260 | } else { |
| 2261 | let (server, host) = remote_server(&config)?; |
| 2262 | self.hosts.push(host); |
| 2263 | server |
| 2264 | }; |
| 2265 | if disabled { |
| 2266 | converted["extensions"]["net.codewhale"]["disabled"] = json!(true); |
| 2267 | } |
| 2268 | self.servers.push((name, converted)); |
| 2269 | Ok(()) |
| 2270 | } |
| 2271 | |
| 2272 | pub fn walk( |
| 2273 | &mut self, |
| 2274 | package: &Package, |
| 2275 | rows: &[Value], |
| 2276 | disabled_ancestor: Option<&str>, |
| 2277 | ) -> Result<()> { |
| 2278 | for row in rows { |
| 2279 | require( |
| 2280 | matches!(row, Value::Map(_)), |
| 2281 | "Each DSH group child must be an entry object.", |
| 2282 | )?; |
| 2283 | let identifier = row.get("id").and_then(Value::str); |
| 2284 | let label = |
| 2285 | identifier.map_or_else(|| "an unlabeled row".to_string(), |id| format!("`{id}`")); |
| 2286 | let name = row.get("name").and_then(Value::str); |
| 2287 | let group = row.get("group").is_some_and(Value::is_true); |
| 2288 | let convertible = matches!(name, Some(DSH_MCP_CLIENT | DSH_SKILL_FILESYSTEM)); |
| 2289 | if group || convertible { |
| 2290 | require( |
| 2291 | row.keys() |
| 2292 | .iter() |
| 2293 | .all(|key| matches!(*key, "id" | "name" | "config" | "group" | "disabled")), |
| 2294 | &format!( |
| 2295 | "{label} has unsupported entry policy or dependency fields; port its activation and authority semantics manually before conversion." |
| 2296 | ), |
| 2297 | )?; |
| 2298 | require( |
| 2299 | row.get("group") |
| 2300 | .is_none_or(|flag| matches!(flag, Value::Bool(_))), |
| 2301 | &format!("{label} has a non-boolean group flag; resolve it explicitly."), |
| 2302 | )?; |
| 2303 | } |
| 2304 | if group { |
| 2305 | require( |
| 2306 | matches!(row.get("config"), Some(Value::Seq(_))), |
| 2307 | &format!("{label} needs a list of group entries."), |
| 2308 | )?; |
| 2309 | } |
| 2310 | let disabled = match row.get("disabled") { |
| 2311 | None => false, |
| 2312 | Some(Value::Bool(flag)) => *flag, |
| 2313 | Some(_) => { |
| 2314 | if group || convertible { |
| 2315 | return refuse(format!( |
| 2316 | "{label} gates activation with a conditional or non-boolean `disabled` value that cannot be resolved offline; import refuses to assume the row is enabled. Pre-resolve the gate in a reviewed copy of the patch layer, then import that copy." |
| 2317 | )); |
| 2318 | } |
| 2319 | self.record( |
| 2320 | row, |
| 2321 | "foreign", |
| 2322 | "skipped", |
| 2323 | "no portable representation; its conditional `disabled` gate was not evaluated", |
| 2324 | ); |
| 2325 | continue; |
| 2326 | } |
| 2327 | }; |
| 2328 | if group { |
| 2329 | let Some(Value::Seq(children)) = row.get("config") else { |
| 2330 | unreachable!() |
| 2331 | }; |
| 2332 | let inherited = match disabled_ancestor { |
| 2333 | Some(ancestor) => Some(ancestor.to_string()), |
| 2334 | None if disabled => Some(label.clone()), |
| 2335 | None => None, |
| 2336 | }; |
| 2337 | self.walk(package, children, inherited.as_deref())?; |
| 2338 | continue; |
| 2339 | } |
| 2340 | let reason = if disabled { |
| 2341 | "the source row sets `disabled: true`".to_string() |
| 2342 | } else if let Some(ancestor) = disabled_ancestor { |
| 2343 | format!("the row is disabled by ancestor {ancestor}") |
| 2344 | } else { |
| 2345 | String::new() |
| 2346 | }; |
| 2347 | let effective = disabled || disabled_ancestor.is_some(); |
| 2348 | match name { |
| 2349 | Some(DSH_MCP_CLIENT) => { |
| 2350 | if let Some(server) = row |
| 2351 | .get("config") |
| 2352 | .and_then(|c| c.get("serverName")) |
| 2353 | .and_then(Value::str) |
| 2354 | { |
| 2355 | require( |
| 2356 | !self.has_server(server), |
| 2357 | "Duplicate MCP server name; no entries were written.", |
| 2358 | )?; |
| 2359 | } |
| 2360 | match self.mcp_row(package, row, effective) { |
| 2361 | Ok(()) => self.record( |
| 2362 | row, |
| 2363 | "mcp", |
| 2364 | if effective { |
| 2365 | "converted-disabled" |
| 2366 | } else { |
| 2367 | "converted" |
| 2368 | }, |
| 2369 | &reason, |
| 2370 | ), |
| 2371 | Err(error) => self.record(row, "mcp", "skipped", &error.to_string()), |
| 2372 | } |
| 2373 | } |
| 2374 | Some(DSH_SKILL_FILESYSTEM) => { |
| 2375 | if effective { |
| 2376 | self.record( |
| 2377 | row, |
| 2378 | "skill", |
| 2379 | "skipped-disabled", |
| 2380 | &format!( |
| 2381 | "{reason}; native skills have no disabled state, so the intent is preserved by omission" |
| 2382 | ), |
| 2383 | ); |
| 2384 | continue; |
| 2385 | } |
| 2386 | let (resolved_dirs, has_dirs_list) = |
| 2387 | resolve_custom_skill_dirs(package, row, |msg| { |
| 2388 | self.notes.push(format!("{label}: {msg}")); |
| 2389 | })?; |
| 2390 | if !has_dirs_list { |
| 2391 | self.record( |
| 2392 | row, |
| 2393 | "skill", |
| 2394 | "skipped", |
| 2395 | "skill row has no `customSkillDirs` to import", |
| 2396 | ); |
| 2397 | continue; |
| 2398 | } |
| 2399 | let imported = resolved_dirs.len(); |
| 2400 | self.skill_dirs.extend(resolved_dirs); |
| 2401 | if imported > 0 { |
| 2402 | self.record( |
| 2403 | row, |
| 2404 | "skill", |
| 2405 | "converted", |
| 2406 | &format!( |
| 2407 | "imported {imported} `customSkillDirs` entries inside the package" |
| 2408 | ), |
| 2409 | ); |
| 2410 | } else { |
| 2411 | self.record( |
| 2412 | row, |
| 2413 | "skill", |
| 2414 | "skipped", |
| 2415 | "no `customSkillDirs` entry inside the package could be imported", |
| 2416 | ); |
| 2417 | } |
| 2418 | } |
| 2419 | _ => { |
| 2420 | let shown = name.unwrap_or("unlabeled"); |
| 2421 | self.record( |
| 2422 | row, |
| 2423 | "foreign", |
| 2424 | "skipped", |
| 2425 | &format!( |
| 2426 | "only dsh-mcp-client and dsh-skill-filesystem rows convert; `{shown}` has no portable representation" |
| 2427 | ), |
| 2428 | ); |
| 2429 | } |
| 2430 | } |
| 2431 | } |
| 2432 | Ok(()) |
| 2433 | } |
| 2434 | } |
| 2435 | |
| 2436 | // ───────────────────────────────────────────────────────────────────────────── |
| 2437 | // Files |
| 2438 | // ───────────────────────────────────────────────────────────────────────────── |
| 2439 | |
| 2440 | #[derive(Default)] |
| 2441 | struct OutputFiles { |
| 2442 | files: BTreeMap<String, Vec<u8>>, |
| 2443 | bytes: usize, |
| 2444 | } |
| 2445 | |
| 2446 | impl OutputFiles { |
| 2447 | fn add(&mut self, relative: String, content: Vec<u8>) -> Result<()> { |
| 2448 | require( |
| 2449 | !self.files.contains_key(&relative), |
| 2450 | "Two converted files collide; nothing was written.", |
| 2451 | )?; |
| 2452 | require( |
| 2453 | self.files.len() < MAX_FILES, |
| 2454 | "Selected components exceed the file budget.", |
| 2455 | )?; |
| 2456 | self.bytes += content.len(); |
| 2457 | require( |
| 2458 | self.bytes <= MAX_BYTES, |
| 2459 | "Output exceeds the 16384-file / 256 MiB bundle budget.", |
| 2460 | )?; |
| 2461 | self.files.insert(relative, content); |
| 2462 | Ok(()) |
| 2463 | } |
| 2464 | |
| 2465 | fn remaining(&self) -> usize { |
| 2466 | MAX_BYTES.saturating_sub(self.bytes) |
| 2467 | } |
| 2468 | } |
| 2469 | |
| 2470 | /// Walk a contained directory without following links, bounded. |
| 2471 | pub fn walk_files(root: &Path, mut visit: impl FnMut(&Path, bool) -> Result<()>) -> Result<()> { |
| 2472 | let canonical_root = fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); |
| 2473 | require( |
| 2474 | !codewhale_util::path_identity::metadata_is_link_or_reparse(&fs::symlink_metadata(root)?), |
| 2475 | "Source paths must not contain links or reparse points.", |
| 2476 | )?; |
| 2477 | let mut pending = vec![root.to_path_buf()]; |
| 2478 | let mut visited = 0usize; |
| 2479 | while let Some(directory) = pending.pop() { |
| 2480 | let mut children: Vec<_> = fs::read_dir(&directory)?.collect::<std::io::Result<_>>()?; |
| 2481 | children.sort_by_key(fs::DirEntry::file_name); |
| 2482 | for child in children { |
| 2483 | visited += 1; |
| 2484 | require( |
| 2485 | visited <= MAX_FILES, |
| 2486 | "The selected source contains too many filesystem entries.", |
| 2487 | )?; |
| 2488 | let path = child.path(); |
| 2489 | let metadata = fs::symlink_metadata(&path)?; |
| 2490 | if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) { |
| 2491 | let dependency_link = path |
| 2492 | .strip_prefix(root) |
| 2493 | .unwrap_or(path.as_path()) |
| 2494 | .components() |
| 2495 | .any(|part| part.as_os_str().to_str() == Some("node_modules")); |
| 2496 | let contained_target = dependency_link |
| 2497 | .then(|| fs::canonicalize(&path).ok()) |
| 2498 | .flatten() |
| 2499 | .filter(|target| target.starts_with(&canonical_root)); |
| 2500 | match contained_target { |
| 2501 | Some(target) if target.is_dir() => { |
| 2502 | return refuse( |
| 2503 | "This source links `node_modules` dependencies (pnpm-style installs); the converted bundle cannot materialize linked dependency directories. Install dependencies in a real layout, or remove `node_modules` before converting.", |
| 2504 | ); |
| 2505 | } |
| 2506 | Some(target) if target.is_file() => continue, |
| 2507 | _ => { |
| 2508 | return refuse("Source paths must not contain links or reparse points."); |
| 2509 | } |
| 2510 | } |
| 2511 | } |
| 2512 | visit(&path, metadata.is_dir())?; |
| 2513 | if metadata.is_dir() { |
| 2514 | pending.push(path); |
| 2515 | } |
| 2516 | } |
| 2517 | } |
| 2518 | Ok(()) |
| 2519 | } |
| 2520 | |
| 2521 | fn relative_slash(path: &Path, root: &Path) -> String { |
| 2522 | path.strip_prefix(root) |
| 2523 | .unwrap_or(path) |
| 2524 | .components() |
| 2525 | .map(|c| c.as_os_str().to_string_lossy().into_owned()) |
| 2526 | .collect::<Vec<_>>() |
| 2527 | .join("/") |
| 2528 | } |
| 2529 | |
| 2530 | /// Convert one skill directory or Markdown file into native skill files. |
| 2531 | fn skill_files(source: &Path, output: &mut OutputFiles) -> Result<String> { |
| 2532 | let source_metadata = fs::symlink_metadata(source)?; |
| 2533 | require( |
| 2534 | !codewhale_util::path_identity::metadata_is_link_or_reparse(&source_metadata), |
| 2535 | "Source paths must not contain links or reparse points.", |
| 2536 | )?; |
| 2537 | let is_dir = source_metadata.is_dir(); |
| 2538 | let entry = if is_dir { |
| 2539 | source.join("SKILL.md") |
| 2540 | } else { |
| 2541 | source.to_path_buf() |
| 2542 | }; |
| 2543 | require( |
| 2544 | entry.file_name().is_some_and(|name| name == "SKILL.md") |
| 2545 | || entry.extension().is_some_and(|ext| ext == "md"), |
| 2546 | "Select a skill directory or Markdown skill file.", |
| 2547 | )?; |
| 2548 | let text = utf8(read_file(&entry, MAX_DOCUMENT)?)?; |
| 2549 | let delimiter = pattern(r"(?m)^---\s*$"); |
| 2550 | let parts: Vec<&str> = delimiter.splitn(&text, 3).collect(); |
| 2551 | require( |
| 2552 | parts.len() == 3 && parts[0].trim().is_empty(), |
| 2553 | "Skills need YAML frontmatter with name and description.", |
| 2554 | )?; |
| 2555 | let meta = parse_yaml(parts[1], false)?; |
| 2556 | mapping( |
| 2557 | &meta, |
| 2558 | Some(&[ |
| 2559 | "name", |
| 2560 | "description", |
| 2561 | "license", |
| 2562 | "compatibility", |
| 2563 | "metadata", |
| 2564 | "disable-model-invocation", |
| 2565 | "user-invocable", |
| 2566 | ]), |
| 2567 | )?; |
| 2568 | let Some(name) = meta |
| 2569 | .get("name") |
| 2570 | .and_then(Value::str) |
| 2571 | .filter(|name| name.len() <= 64 && pattern(r"^[a-z0-9]+(?:-[a-z0-9]+)*$").is_match(name)) |
| 2572 | else { |
| 2573 | return refuse("Skill name must be a kebab-case identifier of at most 64 characters."); |
| 2574 | }; |
| 2575 | let Some(description) = meta |
| 2576 | .get("description") |
| 2577 | .and_then(Value::str) |
| 2578 | .filter(|d| !d.trim().is_empty()) |
| 2579 | else { |
| 2580 | return refuse("Skills need a non-empty description."); |
| 2581 | }; |
| 2582 | require( |
| 2583 | !description.contains("---"), |
| 2584 | "Skill description contains a delimiter the native reader cannot preserve.", |
| 2585 | )?; |
| 2586 | require( |
| 2587 | meta.get("user-invocable") |
| 2588 | .is_none_or(|v| *v == Value::Bool(true)), |
| 2589 | "user-invocable:false has no equivalent in the native skill adapter; port it manually.", |
| 2590 | )?; |
| 2591 | let explicit = match meta.get("disable-model-invocation") { |
| 2592 | None => false, |
| 2593 | Some(Value::Bool(flag)) => *flag, |
| 2594 | Some(_) => return refuse("disable-model-invocation must be a boolean."), |
| 2595 | }; |
| 2596 | let mut front = format!("---\nname: {name}\ndescription: |-\n"); |
| 2597 | front.push_str( |
| 2598 | &description |
| 2599 | .lines() |
| 2600 | .map(|line| format!(" {line}")) |
| 2601 | .collect::<Vec<_>>() |
| 2602 | .join("\n"), |
| 2603 | ); |
| 2604 | front.push('\n'); |
| 2605 | if explicit { |
| 2606 | front.push_str("invocation: explicit-only\n"); |
| 2607 | } |
| 2608 | output.add( |
| 2609 | format!("skills/{name}/SKILL.md"), |
| 2610 | format!("{front}---{}", parts[2]).into_bytes(), |
| 2611 | )?; |
| 2612 | let extra: serde_json::Map<String, Json> = ["license", "compatibility", "metadata"] |
| 2613 | .into_iter() |
| 2614 | .filter_map(|key| { |
| 2615 | meta.get(key) |
| 2616 | .map(|value| (key.to_string(), value.to_json())) |
| 2617 | }) |
| 2618 | .collect(); |
| 2619 | if !extra.is_empty() { |
| 2620 | output.add( |
| 2621 | format!("skills/{name}/SOURCE_SKILL_METADATA.json"), |
| 2622 | format!("{}\n", serde_json::to_string_pretty(&extra)?).into_bytes(), |
| 2623 | )?; |
| 2624 | } |
| 2625 | if is_dir { |
| 2626 | walk_files(source, |path, is_dir| { |
| 2627 | let file_name = path.file_name().unwrap_or_default().to_string_lossy(); |
| 2628 | require( |
| 2629 | !matches!(file_name.as_ref(), ".git" | ".env" | ".installed-from"), |
| 2630 | "Remove local secrets, repository metadata or install receipts from the selected skill.", |
| 2631 | )?; |
| 2632 | if is_dir || path == entry { |
| 2633 | return Ok(()); |
| 2634 | } |
| 2635 | let content = read_file(path, output.remaining())?; |
| 2636 | output.add( |
| 2637 | format!("skills/{name}/{}", relative_slash(path, source)), |
| 2638 | content, |
| 2639 | ) |
| 2640 | })?; |
| 2641 | } |
| 2642 | Ok(name.to_string()) |
| 2643 | } |
| 2644 | |
| 2645 | /// Copy a packaged MCP source directory as data; never resolve dependencies. |
| 2646 | fn ensure_no_hidden_or_credential_entry( |
| 2647 | path: &Path, |
| 2648 | reject_node_modules: bool, |
| 2649 | message: &str, |
| 2650 | ) -> Result<()> { |
| 2651 | let lower = path |
| 2652 | .file_name() |
| 2653 | .unwrap_or_default() |
| 2654 | .to_string_lossy() |
| 2655 | .to_ascii_lowercase(); |
| 2656 | let suffix = path |
| 2657 | .extension() |
| 2658 | .map(|ext| ext.to_string_lossy().to_ascii_lowercase()); |
| 2659 | require( |
| 2660 | !lower.starts_with('.') |
| 2661 | && (!reject_node_modules || lower != "node_modules") |
| 2662 | && !matches!( |
| 2663 | lower.as_str(), |
| 2664 | "credentials" | "credentials.json" | "secrets.json" | "id_rsa" | "id_ed25519" |
| 2665 | ) |
| 2666 | && !matches!(suffix.as_deref(), Some("pem" | "key" | "p12" | "pfx")), |
| 2667 | message, |
| 2668 | ) |
| 2669 | } |
| 2670 | |
| 2671 | fn stdio_files(root: &Path, name: &str, output: &mut OutputFiles) -> Result<()> { |
| 2672 | walk_files(root, |path, is_dir| { |
| 2673 | ensure_no_hidden_or_credential_entry( |
| 2674 | path, |
| 2675 | false, |
| 2676 | "Package MCP source without hidden files, repository metadata or credential files; nothing was copied.", |
| 2677 | )?; |
| 2678 | if is_dir { |
| 2679 | return Ok(()); |
| 2680 | } |
| 2681 | let content = read_file(path, output.remaining())?; |
| 2682 | output.add( |
| 2683 | format!("mcp/{name}/{}", relative_slash(path, root)), |
| 2684 | content, |
| 2685 | ) |
| 2686 | }) |
| 2687 | } |
| 2688 | |
| 2689 | /// A native plugin name from the package name: its last path segment, |
| 2690 | /// lowercased, with other characters replaced by single hyphens. |
| 2691 | const OTHER_MANIFEST_SPELLINGS: [&str; 5] = [ |
| 2692 | crate::agent_plugin::KIMI_PLUGIN_JSON_NAME, |
| 2693 | crate::agent_plugin::PLUGIN_TOML_NAME, |
| 2694 | ".claude-plugin/plugin.json", |
| 2695 | ".plugin/plugin.json", |
| 2696 | ".github/plugin/plugin.json", |
| 2697 | ]; |
| 2698 | |
| 2699 | #[derive(Default)] |
| 2700 | struct MergedPluginJson { |
| 2701 | present: bool, |
| 2702 | commands_spec: Option<crate::manifest::PluginPathSpec>, |
| 2703 | agents_spec: Option<crate::manifest::PluginPathSpec>, |
| 2704 | hooks_spec: Option<crate::manifest::PluginPathSpec>, |
| 2705 | commands: Vec<String>, |
| 2706 | agents: Vec<String>, |
| 2707 | hooks: Vec<String>, |
| 2708 | } |
| 2709 | |
| 2710 | fn package_entry_exists(package: &Package, relative: &str) -> Result<Option<PathBuf>> { |
| 2711 | let resolved = package.contained(Path::new(relative))?; |
| 2712 | match fs::symlink_metadata(&resolved) { |
| 2713 | Ok(_) => Ok(Some(resolved)), |
| 2714 | Err(error) |
| 2715 | if matches!( |
| 2716 | error.kind(), |
| 2717 | std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory |
| 2718 | ) => |
| 2719 | { |
| 2720 | Ok(None) |
| 2721 | } |
| 2722 | Err(error) => Err(error.into()), |
| 2723 | } |
| 2724 | } |
| 2725 | |
| 2726 | fn same_package_path(left: &Path, right: &Path) -> bool { |
| 2727 | if left == right { |
| 2728 | return true; |
| 2729 | } |
| 2730 | match (fs::canonicalize(left), fs::canonicalize(right)) { |
| 2731 | (Ok(left), Ok(right)) => left == right, |
| 2732 | _ => false, |
| 2733 | } |
| 2734 | } |
| 2735 | |
| 2736 | fn dsh_row_bridge_kind(name: &str) -> Option<&'static str> { |
| 2737 | static TABLE: std::sync::OnceLock<Option<Json>> = std::sync::OnceLock::new(); |
| 2738 | let raw = TABLE |
| 2739 | .get_or_init(|| serde_json::from_slice(crate::activation::DSH_COMPATIBILITY).ok()) |
| 2740 | .as_ref()? |
| 2741 | .get("row_bridges")? |
| 2742 | .get(name)? |
| 2743 | .as_str()?; |
| 2744 | if raw == "hooks" || raw.starts_with("hooks-") { |
| 2745 | Some("hooks") |
| 2746 | } else if raw == "commands" { |
| 2747 | Some("commands") |
| 2748 | } else if raw == "agents" { |
| 2749 | Some("agents") |
| 2750 | } else if raw == "skills" { |
| 2751 | Some("skills") |
| 2752 | } else if raw == "mcp" { |
| 2753 | Some("mcp") |
| 2754 | } else { |
| 2755 | None |
| 2756 | } |
| 2757 | } |
| 2758 | |
| 2759 | fn is_group_row(row: &Value) -> bool { |
| 2760 | row.get("group").is_some_and(Value::is_true) |
| 2761 | || row |
| 2762 | .get("name") |
| 2763 | .and_then(Value::str) |
| 2764 | .is_some_and(|name| matches!(name, "cordis:group" | "@deepseek-ai/cordis-plugin-group")) |
| 2765 | } |
| 2766 | |
| 2767 | fn resolve_custom_skill_dirs( |
| 2768 | package: &Package, |
| 2769 | row: &Value, |
| 2770 | mut note: impl FnMut(String), |
| 2771 | ) -> Result<(Vec<PathBuf>, bool)> { |
| 2772 | let dirs = match row.get("config").and_then(|c| c.get("customSkillDirs")) { |
| 2773 | Some(Value::Seq(dirs)) if !dirs.is_empty() => dirs, |
| 2774 | _ => return Ok((Vec::new(), false)), |
| 2775 | }; |
| 2776 | let mut resolved_dirs = Vec::new(); |
| 2777 | for entry in dirs { |
| 2778 | let Value::Str(entry) = entry else { |
| 2779 | note("a `customSkillDirs` entry is not a literal path; skipped".to_string()); |
| 2780 | continue; |
| 2781 | }; |
| 2782 | if !plain_relative(entry) { |
| 2783 | note(format!( |
| 2784 | "`customSkillDirs` entry `{entry}` is outside the bundle; skipped" |
| 2785 | )); |
| 2786 | continue; |
| 2787 | } |
| 2788 | let resolved = package.contained(Path::new(entry))?; |
| 2789 | if !resolved.is_dir() { |
| 2790 | note(format!( |
| 2791 | "`customSkillDirs` entry `{entry}` does not exist in the bundle; skipped" |
| 2792 | )); |
| 2793 | continue; |
| 2794 | } |
| 2795 | resolved_dirs.push(resolved); |
| 2796 | } |
| 2797 | Ok((resolved_dirs, true)) |
| 2798 | } |
| 2799 | |
| 2800 | fn collect_active_skill_dirs( |
| 2801 | package: &Package, |
| 2802 | rows: &[Value], |
| 2803 | disabled_ancestor: bool, |
| 2804 | out: &mut Vec<PathBuf>, |
| 2805 | ) -> Result<()> { |
| 2806 | for row in rows { |
| 2807 | let row_disabled = match row.get("disabled") { |
| 2808 | None => false, |
| 2809 | Some(Value::Bool(flag)) => *flag, |
| 2810 | Some(_) => true, |
| 2811 | }; |
| 2812 | let effective = disabled_ancestor || row_disabled; |
| 2813 | if is_group_row(row) { |
| 2814 | if let Some(Value::Seq(children)) = row.get("config") { |
| 2815 | collect_active_skill_dirs(package, children, effective, out)?; |
| 2816 | } |
| 2817 | continue; |
| 2818 | } |
| 2819 | if effective { |
| 2820 | continue; |
| 2821 | } |
| 2822 | if row.get("name").and_then(Value::str) == Some(DSH_SKILL_FILESYSTEM) { |
| 2823 | let (dirs, _) = resolve_custom_skill_dirs(package, row, |_| {})?; |
| 2824 | out.extend(dirs); |
| 2825 | } |
| 2826 | } |
| 2827 | Ok(()) |
| 2828 | } |
| 2829 | |
| 2830 | fn walk_entry_modules(rows: &[Value], require_names: bool, names: &mut Vec<String>) -> Result<()> { |
| 2831 | for row in rows { |
| 2832 | if is_group_row(row) { |
| 2833 | if let Some(name) = row.get("name").and_then(Value::str) |
| 2834 | && !matches!(name, "cordis:group" | "@deepseek-ai/cordis-plugin-group") |
| 2835 | && !names.iter().any(|old| old == name) |
| 2836 | { |
| 2837 | names.push(name.into()); |
| 2838 | } |
| 2839 | if let Some(Value::Seq(children)) = row.get("config") { |
| 2840 | walk_entry_modules(children, require_names, names)?; |
| 2841 | } |
| 2842 | continue; |
| 2843 | } |
| 2844 | let name = match row.get("name").and_then(Value::str) { |
| 2845 | Some(name) => name, |
| 2846 | None if require_names => { |
| 2847 | return Err(anyhow::Error::msg("reviewed row has no module name")); |
| 2848 | } |
| 2849 | None => continue, |
| 2850 | }; |
| 2851 | if !names.iter().any(|old| old == name) { |
| 2852 | names.push(name.into()); |
| 2853 | } |
| 2854 | } |
| 2855 | Ok(()) |
| 2856 | } |
| 2857 | |
| 2858 | fn enforce_no_other_manifests(package: &Package) -> Result<()> { |
| 2859 | for spelling in OTHER_MANIFEST_SPELLINGS { |
| 2860 | if package_entry_exists(package, spelling)?.is_some() { |
| 2861 | return refuse(format!( |
| 2862 | "Cannot import `{}` alongside `package.json`: declare Codewhale `commands`, `agents`, and `hooks` only in a sibling `plugin.json`.", |
| 2863 | refusal_text(spelling), |
| 2864 | )); |
| 2865 | } |
| 2866 | } |
| 2867 | Ok(()) |
| 2868 | } |
| 2869 | |
| 2870 | fn verify_matches_source_closure( |
| 2871 | package: &Package, |
| 2872 | path: &Path, |
| 2873 | bytes: &[u8], |
| 2874 | output: &OutputFiles, |
| 2875 | ) -> Result<()> { |
| 2876 | let rel = relative_slash(path, &package.root); |
| 2877 | if let Some(existing) = output.files.get(&format!("source/{rel}")) { |
| 2878 | require( |
| 2879 | bytes == existing.as_slice(), |
| 2880 | "Component file changed during conversion; nothing was installed.", |
| 2881 | )?; |
| 2882 | return Ok(()); |
| 2883 | } |
| 2884 | if let Ok(canonical) = fs::canonicalize(path) |
| 2885 | && canonical.starts_with(&package.root) |
| 2886 | { |
| 2887 | let canonical_rel = relative_slash(&canonical, &package.root); |
| 2888 | if let Some(existing) = output.files.get(&format!("source/{canonical_rel}")) { |
| 2889 | require( |
| 2890 | bytes == existing.as_slice(), |
| 2891 | "Component file changed during conversion; nothing was installed.", |
| 2892 | )?; |
| 2893 | } |
| 2894 | } |
| 2895 | Ok(()) |
| 2896 | } |
| 2897 | |
| 2898 | fn normalize_component_destination(kind: &str, raw: &str) -> Result<String> { |
| 2899 | require( |
| 2900 | raw.len() <= 1_024 && !raw.chars().any(char::is_control) && plain_relative(raw), |
| 2901 | &format!( |
| 2902 | "`plugin.json` {kind} path `{}` must stay inside the package.", |
| 2903 | refusal_text(raw) |
| 2904 | ), |
| 2905 | )?; |
| 2906 | let mut parts = Vec::new(); |
| 2907 | for component in Path::new(raw).components() { |
| 2908 | match component { |
| 2909 | Component::CurDir => continue, |
| 2910 | Component::Normal(part) => { |
| 2911 | let text = part.to_string_lossy().into_owned(); |
| 2912 | ensure_no_hidden_or_credential_entry( |
| 2913 | Path::new(&text), |
| 2914 | true, |
| 2915 | "Plugin component paths in `plugin.json` must not include hidden, dependency or credential files.", |
| 2916 | )?; |
| 2917 | parts.push(text); |
| 2918 | } |
| 2919 | _ => { |
| 2920 | return refuse(format!( |
| 2921 | "`plugin.json` {kind} path `{}` must stay inside the package.", |
| 2922 | refusal_text(raw) |
| 2923 | )); |
| 2924 | } |
| 2925 | } |
| 2926 | } |
| 2927 | require( |
| 2928 | !parts.is_empty(), |
| 2929 | "`plugin.json` component paths must name a file or subdirectory inside the package.", |
| 2930 | )?; |
| 2931 | if parts[0].eq_ignore_ascii_case(kind) { |
| 2932 | if parts.len() == 1 { |
| 2933 | Ok(kind.to_string()) |
| 2934 | } else { |
| 2935 | Ok(format!("{kind}/{}", parts[1..].join("/"))) |
| 2936 | } |
| 2937 | } else { |
| 2938 | Ok(format!("{kind}/{}", parts.join("/"))) |
| 2939 | } |
| 2940 | } |
| 2941 | |
| 2942 | fn copy_declared_component( |
| 2943 | package: &Package, |
| 2944 | kind: &str, |
| 2945 | spec: &crate::manifest::PluginPathSpec, |
| 2946 | output: &mut OutputFiles, |
| 2947 | ) -> Result<(Option<crate::manifest::PluginPathSpec>, Vec<String>)> { |
| 2948 | let declared = spec.declared_paths(None).map_err(|error| { |
| 2949 | anyhow::Error::msg(format!( |
| 2950 | "Invalid `{kind}` declaration in sibling `plugin.json` beside `package.json`: {}", |
| 2951 | refusal_text(&error) |
| 2952 | )) |
| 2953 | })?; |
| 2954 | let mut seen_targets = BTreeSet::new(); |
| 2955 | let mut emitted_specs = Vec::with_capacity(declared.len()); |
| 2956 | let mut copied_files = BTreeSet::new(); |
| 2957 | for raw in declared { |
| 2958 | let dest_rel = normalize_component_destination(kind, &raw)?; |
| 2959 | require( |
| 2960 | seen_targets.insert(dest_rel.clone()), |
| 2961 | "Duplicate component target path in sibling `plugin.json`; nothing was written.", |
| 2962 | )?; |
| 2963 | let resolved = package.contained(Path::new(&raw))?; |
| 2964 | let metadata = fs::symlink_metadata(&resolved).map_err(|_| { |
| 2965 | anyhow::Error::msg(format!( |
| 2966 | "`plugin.json` {kind} path `{}` does not exist inside `package.json` bundle.", |
| 2967 | refusal_text(&raw) |
| 2968 | )) |
| 2969 | })?; |
| 2970 | require( |
| 2971 | !codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata), |
| 2972 | "Source paths must not contain links or reparse points.", |
| 2973 | )?; |
| 2974 | let before = copied_files.len(); |
| 2975 | if metadata.is_file() { |
| 2976 | let bytes = read_file(&resolved, output.remaining())?; |
| 2977 | verify_matches_source_closure(package, &resolved, &bytes, output)?; |
| 2978 | output.add(dest_rel.clone(), bytes)?; |
| 2979 | copied_files.insert(dest_rel.clone()); |
| 2980 | } else if metadata.is_dir() { |
| 2981 | walk_files(&resolved, |path, is_dir| { |
| 2982 | ensure_no_hidden_or_credential_entry( |
| 2983 | path, |
| 2984 | true, |
| 2985 | "Plugin component paths in `plugin.json` must not include hidden, dependency or credential files.", |
| 2986 | )?; |
| 2987 | let rel_in_dir = relative_slash(path, &resolved); |
| 2988 | if rel_in_dir.is_empty() || is_dir { |
| 2989 | return Ok(()); |
| 2990 | } |
| 2991 | let target = format!("{dest_rel}/{rel_in_dir}"); |
| 2992 | let bytes = read_file(path, output.remaining())?; |
| 2993 | verify_matches_source_closure(package, path, &bytes, output)?; |
| 2994 | output.add(target.clone(), bytes)?; |
| 2995 | copied_files.insert(target); |
| 2996 | Ok(()) |
| 2997 | })?; |
| 2998 | } else { |
| 2999 | return refuse(format!( |
| 3000 | "`plugin.json` {kind} path `{}` must be a regular file or directory.", |
| 3001 | refusal_text(&raw) |
| 3002 | )); |
| 3003 | } |
| 3004 | if copied_files.len() > before { |
| 3005 | emitted_specs.push(dest_rel); |
| 3006 | } |
| 3007 | } |
| 3008 | let emitted = if emitted_specs.is_empty() { |
| 3009 | None |
| 3010 | } else if emitted_specs.len() == 1 { |
| 3011 | Some(crate::manifest::PluginPathSpec { |
| 3012 | path: Some(emitted_specs.remove(0)), |
| 3013 | paths: Vec::new(), |
| 3014 | }) |
| 3015 | } else { |
| 3016 | Some(crate::manifest::PluginPathSpec { |
| 3017 | path: None, |
| 3018 | paths: emitted_specs, |
| 3019 | }) |
| 3020 | }; |
| 3021 | Ok((emitted, copied_files.into_iter().collect())) |
| 3022 | } |
| 3023 | |
| 3024 | fn merge_sibling_plugin_json( |
| 3025 | package: &Package, |
| 3026 | plugin_name: &str, |
| 3027 | package_version: Option<&str>, |
| 3028 | entries: &[Value], |
| 3029 | skill_dirs: &[PathBuf], |
| 3030 | output: &mut OutputFiles, |
| 3031 | notes: &mut Vec<String>, |
| 3032 | ) -> Result<MergedPluginJson> { |
| 3033 | enforce_no_other_manifests(package)?; |
| 3034 | let Some(plugin_json_path) = |
| 3035 | package_entry_exists(package, crate::agent_plugin::PLUGIN_JSON_NAME)? |
| 3036 | else { |
| 3037 | return Ok(MergedPluginJson::default()); |
| 3038 | }; |
| 3039 | if package_entry_exists(package, crate::agent_plugin::MCP_JSON_NAME)?.is_some() { |
| 3040 | return refuse( |
| 3041 | "`plugin.json` beside `package.json` may not include a sibling `mcp.json`; declare MCP servers in the DSH patch instead.", |
| 3042 | ); |
| 3043 | } |
| 3044 | if let Some(skills_path) = package_entry_exists(package, "skills")? { |
| 3045 | require( |
| 3046 | skill_dirs |
| 3047 | .iter() |
| 3048 | .any(|dir| same_package_path(dir, &skills_path)), |
| 3049 | "`plugin.json` beside `package.json` cannot auto-pick up a root `skills/` folder; declare skills in a `dsh-skill-filesystem` patch row or remove `skills/`.", |
| 3050 | )?; |
| 3051 | } |
| 3052 | |
| 3053 | let raw_bytes = read_file(&plugin_json_path, MAX_DOCUMENT)?; |
| 3054 | verify_matches_source_closure(package, &plugin_json_path, &raw_bytes, output)?; |
| 3055 | let text = utf8(raw_bytes)?; |
| 3056 | let standard = crate::agent_plugin::parse_plugin_json(&text).map_err(|error| { |
| 3057 | anyhow::Error::msg(format!( |
| 3058 | "Invalid sibling `plugin.json` beside `package.json`: {}", |
| 3059 | refusal_text(&error) |
| 3060 | )) |
| 3061 | })?; |
| 3062 | |
| 3063 | require( |
| 3064 | standard.name == plugin_name, |
| 3065 | &format!( |
| 3066 | "`plugin.json` name `{}` does not match `package.json` derived plugin name `{}`.", |
| 3067 | refusal_text(&standard.name), |
| 3068 | refusal_text(plugin_name), |
| 3069 | ), |
| 3070 | )?; |
| 3071 | let json_version = standard.version.as_deref().map(str::trim); |
| 3072 | if json_version == Some("") { |
| 3073 | return refuse("`plugin.json` beside `package.json` may not declare an empty `version`."); |
| 3074 | } |
| 3075 | if let (Some(pkg_v), Some(json_v)) = (package_version, json_version) { |
| 3076 | require( |
| 3077 | pkg_v == json_v, |
| 3078 | &format!( |
| 3079 | "`plugin.json` version `{}` does not match `package.json` version `{}`.", |
| 3080 | refusal_text(json_v), |
| 3081 | refusal_text(pkg_v), |
| 3082 | ), |
| 3083 | )?; |
| 3084 | } |
| 3085 | |
| 3086 | let mut ignored_fields = Vec::new(); |
| 3087 | if package_version.is_none() && json_version.is_some() { |
| 3088 | ignored_fields.push("version"); |
| 3089 | } |
| 3090 | if standard.description.is_some() { |
| 3091 | ignored_fields.push("description"); |
| 3092 | } |
| 3093 | if standard.author.is_some() { |
| 3094 | ignored_fields.push("author"); |
| 3095 | } |
| 3096 | if standard.homepage.is_some() { |
| 3097 | ignored_fields.push("homepage"); |
| 3098 | } |
| 3099 | if standard.repository.is_some() { |
| 3100 | ignored_fields.push("repository"); |
| 3101 | } |
| 3102 | if standard.license.is_some() { |
| 3103 | ignored_fields.push("license"); |
| 3104 | } |
| 3105 | if !standard.keywords.is_empty() { |
| 3106 | ignored_fields.push("keywords"); |
| 3107 | } |
| 3108 | if !ignored_fields.is_empty() { |
| 3109 | notes.push(format!( |
| 3110 | "sibling plugin.json metadata fields ignored (package.json controls bundle metadata): {}", |
| 3111 | ignored_fields.join(", ") |
| 3112 | )); |
| 3113 | } |
| 3114 | |
| 3115 | let extension = match standard |
| 3116 | .extensions |
| 3117 | .get(crate::agent_plugin::CODEWHALE_NAMESPACE) |
| 3118 | { |
| 3119 | Some(value) => { |
| 3120 | let Some(object) = value.as_object() else { |
| 3121 | return refuse( |
| 3122 | "`plugin.json` beside `package.json` must use an object for `extensions[\"net.codewhale\"]`.", |
| 3123 | ); |
| 3124 | }; |
| 3125 | for key in object.keys() { |
| 3126 | if !matches!(key.as_str(), "commands" | "agents" | "hooks") { |
| 3127 | return refuse(format!( |
| 3128 | "`plugin.json` beside `package.json` may only declare `commands`, `agents`, and `hooks` under `extensions[\"{}\"]`; forbidden key `{}`.", |
| 3129 | crate::agent_plugin::CODEWHALE_NAMESPACE, |
| 3130 | refusal_text(key), |
| 3131 | )); |
| 3132 | } |
| 3133 | } |
| 3134 | serde_json::from_value::<crate::agent_plugin::CodewhalePluginExtension>(value.clone()) |
| 3135 | .map_err(|error| { |
| 3136 | anyhow::Error::msg(format!( |
| 3137 | "Invalid `extensions[\"{}\"]` in sibling `plugin.json` beside `package.json`: {}", |
| 3138 | crate::agent_plugin::CODEWHALE_NAMESPACE, |
| 3139 | refusal_text(&error.to_string()), |
| 3140 | )) |
| 3141 | })? |
| 3142 | } |
| 3143 | None => crate::agent_plugin::CodewhalePluginExtension::default(), |
| 3144 | }; |
| 3145 | |
| 3146 | let mut row_names = Vec::new(); |
| 3147 | walk_entry_modules(entries, false, &mut row_names)?; |
| 3148 | for (kind, declared) in [ |
| 3149 | ("commands", extension.commands.is_some()), |
| 3150 | ("agents", extension.agents.is_some()), |
| 3151 | ("hooks", extension.hooks.is_some()), |
| 3152 | ] { |
| 3153 | if declared |
| 3154 | && let Some(row_name) = row_names |
| 3155 | .iter() |
| 3156 | .find(|name| dsh_row_bridge_kind(name) == Some(kind)) |
| 3157 | { |
| 3158 | return refuse(format!( |
| 3159 | "Duplicate `{kind}` declaration in `package.json` patch row `{}` and sibling `plugin.json`: declare `{kind}` in only one place.", |
| 3160 | refusal_text(row_name), |
| 3161 | )); |
| 3162 | } |
| 3163 | } |
| 3164 | |
| 3165 | let mut merged = MergedPluginJson { |
| 3166 | present: true, |
| 3167 | ..MergedPluginJson::default() |
| 3168 | }; |
| 3169 | if let Some(spec) = extension.commands.as_ref() { |
| 3170 | let (emitted, files) = copy_declared_component(package, "commands", spec, output)?; |
| 3171 | merged.commands_spec = emitted; |
| 3172 | merged.commands = files; |
| 3173 | } |
| 3174 | if let Some(spec) = extension.agents.as_ref() { |
| 3175 | let (emitted, files) = copy_declared_component(package, "agents", spec, output)?; |
| 3176 | merged.agents_spec = emitted; |
| 3177 | merged.agents = files; |
| 3178 | } |
| 3179 | if let Some(spec) = extension.hooks.as_ref() { |
| 3180 | let (emitted, files) = copy_declared_component(package, "hooks", spec, output)?; |
| 3181 | merged.hooks_spec = emitted; |
| 3182 | merged.hooks = files; |
| 3183 | } |
| 3184 | Ok(merged) |
| 3185 | } |
| 3186 | |
| 3187 | fn host_hook_bridge(name: &str) -> bool { |
| 3188 | crate::activation::dsh_row_bridge(name) |
| 3189 | } |
| 3190 | |
| 3191 | pub(crate) fn asked_host_services( |
| 3192 | files: &BTreeMap<String, Vec<u8>>, |
| 3193 | rows: &[String], |
| 3194 | client_closures: &[DshClientClosure], |
| 3195 | table: &[(&str, crate::host_services::HostService)], |
| 3196 | ) -> Vec<crate::host_services::HostService> { |
| 3197 | if table.is_empty() { |
| 3198 | return Vec::new(); |
| 3199 | } |
| 3200 | let mut injects = std::collections::BTreeSet::new(); |
| 3201 | for (path, bytes) in files { |
| 3202 | let Some(relative) = path.strip_prefix("source/") else { |
| 3203 | continue; |
| 3204 | }; |
| 3205 | let module = relative |
| 3206 | .rsplit_once('.') |
| 3207 | .is_some_and(|(_, extension)| CLIENT_JS.contains(&extension)); |
| 3208 | let own = match relative.split_once("node_modules/") { |
| 3209 | None => true, |
| 3210 | Some(("", dependency)) => rows.iter().any(|row| { |
| 3211 | dependency |
| 3212 | .strip_prefix(row.as_str()) |
| 3213 | .and_then(|rest| rest.strip_prefix('/')) |
| 3214 | .is_some_and(|rest| !rest.split('/').any(|part| part == "node_modules")) |
| 3215 | }), |
| 3216 | Some(_) => false, |
| 3217 | }; |
| 3218 | if !module |
| 3219 | || !own |
| 3220 | || client_closures |
| 3221 | .iter() |
| 3222 | .any(|closure| closure.files.contains_key(path)) |
| 3223 | { |
| 3224 | continue; |
| 3225 | } |
| 3226 | if let Ok(text) = std::str::from_utf8(bytes) { |
| 3227 | injects.extend(crate::host_services::declared_injects(text)); |
| 3228 | } |
| 3229 | } |
| 3230 | crate::host_services::services_for_injects(injects.iter().map(String::as_str), table) |
| 3231 | } |
| 3232 | |
| 3233 | /// Closed relative modules and exact contained ESM package exports. Missing |
| 3234 | /// foreign rows remain manual ports for a portable-only import; a live Native |
| 3235 | /// graph refuses unresolved rows and never uses an ambient Node parent-walk. |
| 3236 | fn native_composition_files( |
| 3237 | package: &Package, |
| 3238 | entries: &[Value], |
| 3239 | mut document: Json, |
| 3240 | output: &mut OutputFiles, |
| 3241 | client_outcomes: &mut Vec<DshOutcome>, |
| 3242 | client_closures: &mut Vec<DshClientClosure>, |
| 3243 | ui: bool, |
| 3244 | ) -> Result<Vec<String>> { |
| 3245 | let mut names = Vec::new(); |
| 3246 | walk_entry_modules(entries, true, &mut names)?; |
| 3247 | if names.is_empty() && !ui { |
| 3248 | return Ok(names); |
| 3249 | } |
| 3250 | // Portable-only import keeps absent foreign rows visible as manual ports. |
| 3251 | // Once one real Native closure is present, every row must be admitted: |
| 3252 | // refusing a mixed partial graph is stronger than silently pruning it. |
| 3253 | let mut paths = BTreeMap::new(); |
| 3254 | let mut unresolved = Vec::new(); |
| 3255 | for name in &names { |
| 3256 | if name == presets::AGENT_PRESETS || host_hook_bridge(name) { |
| 3257 | continue; |
| 3258 | } |
| 3259 | match presets::contained_module(package, name) { |
| 3260 | Ok(path) if crate::runtime::native_entry_problem(&path, path.is_file()).is_none() => { |
| 3261 | paths.insert(name.clone(), path); |
| 3262 | } |
| 3263 | _ => unresolved.push(name), |
| 3264 | } |
| 3265 | } |
| 3266 | let native_graph = !paths.is_empty() |
| 3267 | || names.iter().any(|name| { |
| 3268 | name == presets::AGENT_PRESETS |
| 3269 | || (host_hook_bridge(name) |
| 3270 | && !matches!(name.as_str(), DSH_MCP_CLIENT | DSH_SKILL_FILESYSTEM)) |
| 3271 | }); |
| 3272 | if !native_graph && !ui { |
| 3273 | return Ok(Vec::new()); |
| 3274 | } |
| 3275 | if native_graph && !unresolved.is_empty() { |
| 3276 | return refuse(format!( |
| 3277 | "Native composition contains an unsupported or missing row with no exact admitted module ({}); no partial graph was installed.", |
| 3278 | refusal_list(unresolved.iter().map(|name| refusal_text(name))) |
| 3279 | )); |
| 3280 | } |
| 3281 | let mut files = serde_json::Map::new(); |
| 3282 | walk_files(&package.root, |path, is_dir| { |
| 3283 | let relative = relative_slash(path, &package.root); |
| 3284 | let dependency = relative.split('/').any(|part| part == "node_modules"); |
| 3285 | let lower = path |
| 3286 | .file_name() |
| 3287 | .unwrap_or_default() |
| 3288 | .to_string_lossy() |
| 3289 | .to_ascii_lowercase(); |
| 3290 | let suffix = path |
| 3291 | .extension() |
| 3292 | .map(|ext| ext.to_string_lossy().to_ascii_lowercase()); |
| 3293 | require( |
| 3294 | !matches!(suffix.as_deref(), Some("node")), |
| 3295 | "Native Node addons (`.node`) are not supported in DSH bundles.", |
| 3296 | )?; |
| 3297 | require( |
| 3298 | (dependency |
| 3299 | || !lower.starts_with('.') |
| 3300 | || lower == ".agent-presets" |
| 3301 | || (lower == ".dsh-tui-managed.json" |
| 3302 | && (relative.starts_with("presets/") |
| 3303 | || relative.starts_with(".agent-presets/"))) |
| 3304 | || relative == ".gitignore") |
| 3305 | && !lower.starts_with(".env.") |
| 3306 | && !matches!( |
| 3307 | lower.as_str(), |
| 3308 | "credentials" |
| 3309 | | "credentials.json" |
| 3310 | | "secrets.json" |
| 3311 | | "id_rsa" |
| 3312 | | "id_ed25519" |
| 3313 | | ".env" |
| 3314 | | ".npmrc" |
| 3315 | | ".netrc" |
| 3316 | | ".git" |
| 3317 | ) |
| 3318 | && !matches!(suffix.as_deref(), Some("pem" | "key" | "p12" | "pfx")), |
| 3319 | "Package a closed Native source without credential files or repository metadata; hidden dependency files are admitted only under node_modules.", |
| 3320 | )?; |
| 3321 | if is_dir { |
| 3322 | return Ok(()); |
| 3323 | } |
| 3324 | let bytes = read_file( |
| 3325 | &package.contained(Path::new(&relative))?, |
| 3326 | output.remaining(), |
| 3327 | )?; |
| 3328 | files.insert(relative.clone(), json!(sha256_hex(&bytes))); |
| 3329 | output.add(format!("source/{relative}"), bytes) |
| 3330 | })?; |
| 3331 | let mut selected_manifests = std::collections::BTreeSet::new(); |
| 3332 | let mut client_paths: Vec<_> = vec![(String::new(), package.root.join("index.js"))]; |
| 3333 | client_paths.extend( |
| 3334 | paths |
| 3335 | .iter() |
| 3336 | .map(|(name, path)| (name.clone(), path.clone())), |
| 3337 | ); |
| 3338 | for name in &names { |
| 3339 | if name == presets::AGENT_PRESETS || host_hook_bridge(name) { |
| 3340 | let manifest = format!("source/node_modules/{name}/package.json"); |
| 3341 | if output.files.contains_key(&manifest) { |
| 3342 | client_paths.push(( |
| 3343 | name.clone(), |
| 3344 | package.root.join(format!("node_modules/{name}/index.js")), |
| 3345 | )); |
| 3346 | } |
| 3347 | } |
| 3348 | } |
| 3349 | for (name, path) in client_paths { |
| 3350 | let mut directory = path.parent(); |
| 3351 | while let Some(parent) = directory.filter(|parent| parent.starts_with(&package.root)) { |
| 3352 | let manifest_path = relative_slash(&parent.join("package.json"), &package.root); |
| 3353 | let key = format!("source/{manifest_path}"); |
| 3354 | if let Some(bytes) = output.files.get(&key) { |
| 3355 | if selected_manifests.insert(manifest_path.clone()) { |
| 3356 | require( |
| 3357 | bytes.len() <= MAX_DOCUMENT, |
| 3358 | "Package manifest exceeds the conversion size limit.", |
| 3359 | )?; |
| 3360 | let text = std::str::from_utf8(bytes).map_err(|_| { |
| 3361 | anyhow::Error::msg("Configuration and skill entrypoints must be UTF-8.") |
| 3362 | })?; |
| 3363 | let manifest = parse_package_json(text)?; |
| 3364 | if declares_client(&manifest) { |
| 3365 | let root = manifest_path |
| 3366 | .rsplit_once('/') |
| 3367 | .map_or("", |(parent, _)| parent); |
| 3368 | let row = (!name.is_empty()).then(|| refusal_text(&name)); |
| 3369 | let package_name = refusal_text( |
| 3370 | manifest.get("name").and_then(Value::str).unwrap_or(&name), |
| 3371 | ); |
| 3372 | match client_closure(&output.files, root, &manifest) { |
| 3373 | Ok(closure) => { |
| 3374 | client_outcomes.push(DshOutcome { |
| 3375 | row, |
| 3376 | package: Some(package_name), |
| 3377 | kind: "client".into(), |
| 3378 | outcome: "retained".into(), |
| 3379 | reason: format!( |
| 3380 | "client closure reviewed and retained: entry {}, {} files, {} bytes{}; it is not served until the Engine client bootstrap admits it", |
| 3381 | refusal_text(&closure.entry), |
| 3382 | closure.files.len(), |
| 3383 | closure.bytes, |
| 3384 | if closure.host_provided.is_empty() { |
| 3385 | String::new() |
| 3386 | } else { |
| 3387 | format!( |
| 3388 | ", host-provided modules {}", |
| 3389 | refusal_list(closure.host_provided.iter().cloned()) |
| 3390 | ) |
| 3391 | } |
| 3392 | ), |
| 3393 | layer: None, |
| 3394 | patch: None, |
| 3395 | }); |
| 3396 | client_closures.push(closure); |
| 3397 | } |
| 3398 | Err(reason) => client_outcomes.push(DshOutcome { |
| 3399 | row, |
| 3400 | package: Some(package_name), |
| 3401 | kind: "client".into(), |
| 3402 | outcome: "skipped".into(), |
| 3403 | reason: format!( |
| 3404 | "Client UI stays disabled: {}", |
| 3405 | refusal_text(&reason) |
| 3406 | ), |
| 3407 | layer: None, |
| 3408 | patch: None, |
| 3409 | }), |
| 3410 | } |
| 3411 | } |
| 3412 | } |
| 3413 | break; |
| 3414 | } |
| 3415 | directory = parent.parent(); |
| 3416 | } |
| 3417 | } |
| 3418 | if !native_graph { |
| 3419 | return Ok(Vec::new()); |
| 3420 | } |
| 3421 | let mut selected = Vec::new(); |
| 3422 | for name in &names { |
| 3423 | if name == presets::AGENT_PRESETS || host_hook_bridge(name) { |
| 3424 | continue; |
| 3425 | } |
| 3426 | let path = paths |
| 3427 | .get(name) |
| 3428 | .ok_or_else(|| anyhow::Error::msg("Native module lost its admitted path"))?; |
| 3429 | let relative = relative_slash(path, &package.root); |
| 3430 | let digest = files |
| 3431 | .get(&relative) |
| 3432 | .ok_or_else(|| anyhow::Error::msg("Native module was absent from source closure"))?; |
| 3433 | selected.push(json!({"name":name,"path":relative,"sha256":digest})); |
| 3434 | } |
| 3435 | document["modules"] = json!(selected); |
| 3436 | document["files"] = json!(files); |
| 3437 | if selected.is_empty() && presets::has_roster(entries) { |
| 3438 | presets::prepare(package, &document, output)?; |
| 3439 | return Ok(names); |
| 3440 | } |
| 3441 | output.add( |
| 3442 | "native/composition.json".into(), |
| 3443 | format!("{}\n", serde_json::to_string_pretty(&document)?).into_bytes(), |
| 3444 | )?; |
| 3445 | output.add("native/index.mjs".into(),b"import { mountReviewedComposition } from '@codewhale/dsh-composition';\nimport spec from './composition.json' with { type: 'json' };\nexport async function apply(ctx) { await mountReviewedComposition(ctx, new URL('../source/', import.meta.url).href, spec); }\n".to_vec())?; |
| 3446 | Ok(names) |
| 3447 | } |
| 3448 | |
| 3449 | pub fn derived_plugin_name(package_name: &str) -> Option<String> { |
| 3450 | let segment = package_name |
| 3451 | .rsplit('/') |
| 3452 | .next() |
| 3453 | .unwrap_or(package_name) |
| 3454 | .to_ascii_lowercase(); |
| 3455 | let mut name = String::new(); |
| 3456 | for c in segment.chars() { |
| 3457 | let c = if c.is_ascii_lowercase() || c.is_ascii_digit() || c == '.' { |
| 3458 | c |
| 3459 | } else { |
| 3460 | '-' |
| 3461 | }; |
| 3462 | if c == '-' && name.ends_with('-') { |
| 3463 | continue; |
| 3464 | } |
| 3465 | name.push(c); |
| 3466 | } |
| 3467 | let name = name.trim_matches(|c| c == '-' || c == '.').to_string(); |
| 3468 | valid_plugin_name(&name).then_some(name) |
| 3469 | } |
| 3470 | |
| 3471 | fn valid_plugin_name(name: &str) -> bool { |
| 3472 | pattern(r"^[a-z0-9](?:[a-z0-9.-]{0,62}[a-z0-9])?$").is_match(name) |
| 3473 | && !name.contains("..") |
| 3474 | && !name.contains("--") |
| 3475 | } |
| 3476 | |
| 3477 | const NPM_REGISTRY: &str = "https://registry.npmjs.org"; |
| 3478 | |
| 3479 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 3480 | pub struct NpmInstallPlan { |
| 3481 | pub spec: String, |
| 3482 | pub plugin_name: String, |
| 3483 | } |
| 3484 | |
| 3485 | pub fn plan_npm_install( |
| 3486 | package: &str, |
| 3487 | version: &str, |
| 3488 | registry: Option<&str>, |
| 3489 | ) -> Result<NpmInstallPlan, String> { |
| 3490 | let file = package.rsplit('/').next().unwrap_or(package); |
| 3491 | let tarball = |base: &str| format!("{base}/{package}/-/{file}-{version}.tgz"); |
| 3492 | let remote = |url: String| { |
| 3493 | super::PluginInstallSource::Remote( |
| 3494 | codewhale_skill_install::install::InstallSource::DirectUrl(url), |
| 3495 | ) |
| 3496 | }; |
| 3497 | let exact = format!("npm:{package}@{version}"); |
| 3498 | if super::PluginInstallSource::parse(&exact).ok() != Some(remote(tarball(NPM_REGISTRY))) { |
| 3499 | return Err(format!( |
| 3500 | "`{}@{}` is not an exact npm package version Codewhale can fetch: the name must be a lowercase npm name with an optional @scope, and the version exact, canonical SemVer", |
| 3501 | refusal_text(package), |
| 3502 | refusal_text(version) |
| 3503 | )); |
| 3504 | } |
| 3505 | let plugin_name = derived_plugin_name(package).ok_or_else(|| { |
| 3506 | format!( |
| 3507 | "npm package `{}` cannot form a native plugin name (1–64 lowercase letters/digits with single dots or hyphens), so its bundle could not be imported", |
| 3508 | refusal_text(package) |
| 3509 | ) |
| 3510 | })?; |
| 3511 | let Some(registry) = registry else { |
| 3512 | return Ok(NpmInstallPlan { |
| 3513 | spec: exact, |
| 3514 | plugin_name, |
| 3515 | }); |
| 3516 | }; |
| 3517 | let url = reqwest::Url::parse(registry) |
| 3518 | .map_err(|_| "the declared npm registry is not an absolute URL".to_string())?; |
| 3519 | let host = refusal_text(url.host_str().unwrap_or_default()); |
| 3520 | if url.scheme() != "https" |
| 3521 | || url.host_str().is_none() |
| 3522 | || !url.username().is_empty() |
| 3523 | || url.password().is_some() |
| 3524 | || url.query().is_some() |
| 3525 | || url.fragment().is_some() |
| 3526 | { |
| 3527 | return Err(format!( |
| 3528 | "npm registry `{host}` must be an https URL without credentials, query or fragment; Codewhale fetches a registry tarball only over https" |
| 3529 | )); |
| 3530 | } |
| 3531 | let base = url.as_str().trim_end_matches('/'); |
| 3532 | if base == NPM_REGISTRY { |
| 3533 | return Ok(NpmInstallPlan { |
| 3534 | spec: exact, |
| 3535 | plugin_name, |
| 3536 | }); |
| 3537 | } |
| 3538 | let spec = tarball(base); |
| 3539 | if super::PluginInstallSource::parse(&spec).ok() != Some(remote(spec.clone())) { |
| 3540 | return Err(format!( |
| 3541 | "npm registry `{host}` does not give a tarball address the reviewed installer accepts" |
| 3542 | )); |
| 3543 | } |
| 3544 | Ok(NpmInstallPlan { spec, plugin_name }) |
| 3545 | } |
| 3546 | |
| 3547 | // ───────────────────────────────────────────────────────────────────────────── |
| 3548 | // Entry point |
| 3549 | // ───────────────────────────────────────────────────────────────────────────── |
| 3550 | |
| 3551 | /// Return whether a DSH package imports declared external npm dependencies not bundled in `node_modules`. |
| 3552 | pub fn has_unresolved_npm_dependencies(package: &Path) -> Result<bool> { |
| 3553 | let package = Package::open(package)?; |
| 3554 | let loaded = load_bundle(&package)?; |
| 3555 | let (_, seeds) = super::npm_deps::collect_unresolved_seeds( |
| 3556 | &package.root, |
| 3557 | &loaded.manifest, |
| 3558 | &loaded.entries, |
| 3559 | )?; |
| 3560 | Ok(!seeds.is_empty()) |
| 3561 | } |
| 3562 | |
| 3563 | /// Convert the DSH bundle package at `package` into a fresh native bundle at |
| 3564 | /// `output`. `output` must not exist; nothing is written unless every |
| 3565 | /// component validated, and a failed write removes what it created. |
| 3566 | pub fn convert_package(package: &Path, output: &Path) -> Result<DshConversion> { |
| 3567 | convert_package_with_network(package, output, None) |
| 3568 | } |
| 3569 | |
| 3570 | pub fn convert_package_with_network( |
| 3571 | package: &Path, |
| 3572 | output: &Path, |
| 3573 | network: Option<&codewhale_net::network_policy::NetworkPolicy>, |
| 3574 | ) -> Result<DshConversion> { |
| 3575 | static CONVERSION: std::sync::Mutex<()> = std::sync::Mutex::new(()); |
| 3576 | let _conversion = CONVERSION |
| 3577 | .lock() |
| 3578 | .map_err(|_| anyhow::Error::msg("DSH preparation is unavailable"))?; |
| 3579 | let mut package = Package::open(package)?; |
| 3580 | require( |
| 3581 | !output.exists(), |
| 3582 | "Output already exists; choose a fresh directory. Nothing was overwritten.", |
| 3583 | )?; |
| 3584 | if let Some(parent) = output.parent().and_then(|p| p.canonicalize().ok()) { |
| 3585 | require( |
| 3586 | !parent.starts_with(&package.root), |
| 3587 | "Output must be outside the selected bundle.", |
| 3588 | )?; |
| 3589 | } |
| 3590 | let loaded = load_bundle(&package)?; |
| 3591 | let staged_npm = if let Some(policy) = network { |
| 3592 | if let Some(stage) = super::npm_deps::maybe_stage_with_dependencies( |
| 3593 | &package.root, |
| 3594 | &loaded.manifest, |
| 3595 | &loaded.entries, |
| 3596 | policy, |
| 3597 | )? { |
| 3598 | package = Package::open(stage.path())?; |
| 3599 | Some(stage) |
| 3600 | } else { |
| 3601 | None |
| 3602 | } |
| 3603 | } else { |
| 3604 | None |
| 3605 | }; |
| 3606 | let fetched_npm = staged_npm |
| 3607 | .as_ref() |
| 3608 | .map(|stage| stage.fetched.clone()) |
| 3609 | .unwrap_or_default(); |
| 3610 | let mut output_files = OutputFiles::default(); |
| 3611 | let mut client_outcomes = Vec::new(); |
| 3612 | let mut client_closures = Vec::new(); |
| 3613 | let ui = declares_client(&loaded.manifest); |
| 3614 | let native_rows = native_composition_files( |
| 3615 | &package, |
| 3616 | &loaded.entries, |
| 3617 | loaded.composition, |
| 3618 | &mut output_files, |
| 3619 | &mut client_outcomes, |
| 3620 | &mut client_closures, |
| 3621 | ui, |
| 3622 | )?; |
| 3623 | let requires_native = !native_rows.is_empty(); |
| 3624 | let mut notes = loaded.notes; |
| 3625 | if let Some(note) = fetched_npm_note(&fetched_npm) { |
| 3626 | notes.push(note); |
| 3627 | } |
| 3628 | let mut components = Components::default(); |
| 3629 | if !requires_native { |
| 3630 | components.walk(&package, &loaded.entries, None)?; |
| 3631 | } |
| 3632 | require( |
| 3633 | components.servers.len() <= MAX_SERVERS, |
| 3634 | "At most 64 MCP servers can be converted at once.", |
| 3635 | )?; |
| 3636 | let mut outcomes = loaded.outcomes; |
| 3637 | outcomes.append(&mut components.outcomes); |
| 3638 | outcomes.append(&mut client_outcomes); |
| 3639 | notes.append(&mut components.notes); |
| 3640 | |
| 3641 | let package_name = loaded |
| 3642 | .manifest |
| 3643 | .get("name") |
| 3644 | .and_then(Value::str) |
| 3645 | .map(str::to_string); |
| 3646 | let package_version = loaded |
| 3647 | .manifest |
| 3648 | .get("version") |
| 3649 | .and_then(Value::str) |
| 3650 | .map(str::trim) |
| 3651 | .filter(|v| !v.is_empty()) |
| 3652 | .map(str::to_string); |
| 3653 | let Some(plugin_name) = package_name.as_deref().and_then(derived_plugin_name) else { |
| 3654 | return refuse( |
| 3655 | "The package name cannot form a native plugin name (1–64 lowercase letters/digits with single dots or hyphens).", |
| 3656 | ); |
| 3657 | }; |
| 3658 | |
| 3659 | let mut skill_sources = Vec::new(); |
| 3660 | for directory in &components.skill_dirs { |
| 3661 | let mut children: Vec<_> = fs::read_dir(directory)?.collect::<std::io::Result<_>>()?; |
| 3662 | children.sort_by_key(fs::DirEntry::file_name); |
| 3663 | for child in children { |
| 3664 | let path = child.path(); |
| 3665 | if child.file_name().to_string_lossy().starts_with('.') { |
| 3666 | continue; |
| 3667 | } |
| 3668 | require( |
| 3669 | !codewhale_util::path_identity::metadata_is_link_or_reparse(&fs::symlink_metadata( |
| 3670 | &path, |
| 3671 | )?), |
| 3672 | "Source paths must not contain links or reparse points.", |
| 3673 | )?; |
| 3674 | if path.join("SKILL.md").is_file() || path.extension().is_some_and(|ext| ext == "md") { |
| 3675 | skill_sources.push(path); |
| 3676 | } |
| 3677 | } |
| 3678 | } |
| 3679 | let mut skills = Vec::new(); |
| 3680 | for source in skill_sources.iter().filter(|_| !requires_native) { |
| 3681 | let name = skill_files(source, &mut output_files)?; |
| 3682 | require( |
| 3683 | !skills.contains(&name), |
| 3684 | "Duplicate skill name; no files were written.", |
| 3685 | )?; |
| 3686 | skills.push(name); |
| 3687 | } |
| 3688 | if !requires_native { |
| 3689 | for (name, root) in &components.roots { |
| 3690 | stdio_files(root, name, &mut output_files)?; |
| 3691 | } |
| 3692 | } else { |
| 3693 | // Live rows register only under their selected Native entry. The |
| 3694 | // declarative copy would otherwise leak across all caller presets. |
| 3695 | components.servers.clear(); |
| 3696 | } |
| 3697 | |
| 3698 | if let Some(bytes) = output_files.files.get("native/presets.json") { |
| 3699 | let catalog: Json = serde_json::from_slice(bytes)?; |
| 3700 | for row in catalog |
| 3701 | .get("presets") |
| 3702 | .and_then(Json::as_array) |
| 3703 | .into_iter() |
| 3704 | .flatten() |
| 3705 | { |
| 3706 | if let Some(reason) = row.get("broken").and_then(Json::as_str) { |
| 3707 | outcomes.push(DshOutcome { |
| 3708 | row: row.get("id").and_then(Json::as_str).map(str::to_string), |
| 3709 | package: Some(presets::AGENT_PRESETS.into()), |
| 3710 | kind: "native-preset".into(), |
| 3711 | outcome: "skipped".into(), |
| 3712 | reason: reason.into(), |
| 3713 | layer: None, |
| 3714 | patch: None, |
| 3715 | }); |
| 3716 | } |
| 3717 | } |
| 3718 | } |
| 3719 | |
| 3720 | for outcome in &mut outcomes { |
| 3721 | if outcome.kind == "foreign" |
| 3722 | && outcome |
| 3723 | .package |
| 3724 | .as_ref() |
| 3725 | .is_some_and(|name| native_rows.contains(name)) |
| 3726 | { |
| 3727 | outcome.kind = "native".to_string(); |
| 3728 | outcome.outcome = "converted".to_string(); |
| 3729 | outcome.reason = |
| 3730 | "reviewed Native composition; core authority and experimental host required" |
| 3731 | .to_string(); |
| 3732 | } |
| 3733 | } |
| 3734 | let mut native_skill_dirs = Vec::new(); |
| 3735 | let skill_dirs_for_merge = if requires_native { |
| 3736 | collect_active_skill_dirs(&package, &loaded.entries, false, &mut native_skill_dirs)?; |
| 3737 | &native_skill_dirs |
| 3738 | } else { |
| 3739 | &components.skill_dirs |
| 3740 | }; |
| 3741 | let merged = merge_sibling_plugin_json( |
| 3742 | &package, |
| 3743 | &plugin_name, |
| 3744 | package_version.as_deref(), |
| 3745 | &loaded.entries, |
| 3746 | skill_dirs_for_merge, |
| 3747 | &mut output_files, |
| 3748 | &mut notes, |
| 3749 | )?; |
| 3750 | |
| 3751 | if !ui && output_files.files.is_empty() && components.servers.is_empty() { |
| 3752 | let skipped = refusal_list( |
| 3753 | outcomes |
| 3754 | .iter() |
| 3755 | .filter(|outcome| outcome.needs_manual_port()) |
| 3756 | .map(|outcome| { |
| 3757 | format!( |
| 3758 | "{} ({}): {}", |
| 3759 | refusal_text(outcome.row.as_deref().unwrap_or("unlabeled")), |
| 3760 | refusal_text(outcome.package.as_deref().unwrap_or("unlabeled")), |
| 3761 | refusal_text(&outcome.reason) |
| 3762 | ) |
| 3763 | }), |
| 3764 | ); |
| 3765 | return refuse(if skipped.is_empty() { |
| 3766 | "No portable components in this package: nothing to import.".to_string() |
| 3767 | } else { |
| 3768 | format!( |
| 3769 | "No portable components in this package: nothing to import. Skipped rows, each needing a manual port: {skipped}" |
| 3770 | ) |
| 3771 | }); |
| 3772 | } |
| 3773 | |
| 3774 | let mut hosts = components.hosts.clone(); |
| 3775 | hosts.sort(); |
| 3776 | hosts.dedup(); |
| 3777 | // Only portable stdio roots copied for a Node command require Node. Native |
| 3778 | // composition runs on the selected host runtime and must remain usable on |
| 3779 | // a reviewed Bun-only installation; individual MCP launches keep their own |
| 3780 | // exact command/dependency admission. |
| 3781 | let requires_node = !components.roots.is_empty(); |
| 3782 | let mut manifest = json!({ |
| 3783 | "$schema": "https://agent-plugins.org/schemas/plugin.json", |
| 3784 | "name": plugin_name, |
| 3785 | }); |
| 3786 | if let Some(version) = &package_version { |
| 3787 | manifest["version"] = json!(version); |
| 3788 | } |
| 3789 | if let Some(raw_description) = loaded.manifest.get("description").and_then(Value::str) { |
| 3790 | let cleaned: String = raw_description |
| 3791 | .chars() |
| 3792 | .filter(|c| !codewhale_sanitize::sanitize::is_bidi_control(*c)) |
| 3793 | .map(|c| if c.is_control() { ' ' } else { c }) |
| 3794 | .collect(); |
| 3795 | let trimmed = cleaned.trim(); |
| 3796 | if !trimmed.is_empty() { |
| 3797 | let truncated = if trimmed.chars().count() > 1024 { |
| 3798 | let prefix: String = trimmed.chars().take(1023).collect(); |
| 3799 | format!("{}…", prefix.trim_end()) |
| 3800 | } else { |
| 3801 | trimmed.to_string() |
| 3802 | }; |
| 3803 | manifest["description"] = json!(truncated); |
| 3804 | } |
| 3805 | } |
| 3806 | let mut extension = serde_json::Map::new(); |
| 3807 | if requires_native { |
| 3808 | let paths: Vec<_> = output_files |
| 3809 | .files |
| 3810 | .keys() |
| 3811 | .filter(|p| p.starts_with("native/presets/") && p.ends_with(".mjs")) |
| 3812 | .cloned() |
| 3813 | .collect(); |
| 3814 | extension.insert( |
| 3815 | "native".into(), |
| 3816 | if paths.is_empty() { |
| 3817 | json!({"path":"native/index.mjs"}) |
| 3818 | } else { |
| 3819 | json!({"paths":paths}) |
| 3820 | }, |
| 3821 | ); |
| 3822 | } |
| 3823 | let mut capabilities = serde_json::Map::new(); |
| 3824 | if !hosts.is_empty() { |
| 3825 | capabilities.insert("network_hosts".into(), json!(hosts)); |
| 3826 | } |
| 3827 | let host_services = if requires_native { |
| 3828 | asked_host_services( |
| 3829 | &output_files.files, |
| 3830 | &native_rows, |
| 3831 | &client_closures, |
| 3832 | crate::host_services::HOST_SERVICE_INJECTS, |
| 3833 | ) |
| 3834 | } else { |
| 3835 | Vec::new() |
| 3836 | }; |
| 3837 | if !host_services.is_empty() { |
| 3838 | capabilities.insert("host_services".into(), json!(host_services)); |
| 3839 | notes.push(format!( |
| 3840 | "asks for host services: {}; each is granted only by a review that shows it", |
| 3841 | host_services |
| 3842 | .iter() |
| 3843 | .map(|service| service.name()) |
| 3844 | .collect::<Vec<_>>() |
| 3845 | .join(", ") |
| 3846 | )); |
| 3847 | } |
| 3848 | if !capabilities.is_empty() { |
| 3849 | extension.insert("capabilities".into(), Json::Object(capabilities)); |
| 3850 | } |
| 3851 | if requires_node || loaded.platforms.is_some() { |
| 3852 | let mut when = serde_json::Map::new(); |
| 3853 | if requires_node { |
| 3854 | when.insert("binaries".into(), json!(["node"])); |
| 3855 | } |
| 3856 | if let Some(platforms) = &loaded.platforms { |
| 3857 | when.insert("os".into(), json!(platforms)); |
| 3858 | } |
| 3859 | extension.insert("when".into(), Json::Object(when)); |
| 3860 | } |
| 3861 | if let Some(spec) = merged.commands_spec { |
| 3862 | extension.insert("commands".into(), serde_json::to_value(spec)?); |
| 3863 | } |
| 3864 | if let Some(spec) = merged.agents_spec { |
| 3865 | extension.insert("agents".into(), serde_json::to_value(spec)?); |
| 3866 | } |
| 3867 | if let Some(spec) = merged.hooks_spec { |
| 3868 | extension.insert("hooks".into(), serde_json::to_value(spec)?); |
| 3869 | } |
| 3870 | if !extension.is_empty() { |
| 3871 | manifest["extensions"] = json!({"net.codewhale": extension}); |
| 3872 | } |
| 3873 | if merged.present { |
| 3874 | crate::agent_plugin::validate_plugin_json(&manifest).map_err(|error| { |
| 3875 | anyhow::Error::msg(format!( |
| 3876 | "Converted `plugin.json` is invalid: {}", |
| 3877 | refusal_text(&error) |
| 3878 | )) |
| 3879 | })?; |
| 3880 | } |
| 3881 | notes.insert( |
| 3882 | 0, |
| 3883 | format!( |
| 3884 | "source package: {}{}", |
| 3885 | package_name.as_deref().unwrap_or("unnamed"), |
| 3886 | package_version |
| 3887 | .as_deref() |
| 3888 | .map(|v| format!("@{v}")) |
| 3889 | .unwrap_or_default() |
| 3890 | ), |
| 3891 | ); |
| 3892 | output_files.add( |
| 3893 | "plugin.json".into(), |
| 3894 | format!("{}\n", serde_json::to_string_pretty(&manifest)?).into_bytes(), |
| 3895 | )?; |
| 3896 | let (local, remote): (Vec<_>, Vec<_>) = components |
| 3897 | .servers |
| 3898 | .iter() |
| 3899 | .partition(|(_, server)| server["type"] == "stdio"); |
| 3900 | if !components.servers.is_empty() { |
| 3901 | let servers: serde_json::Map<String, Json> = components.servers.iter().cloned().collect(); |
| 3902 | output_files.add( |
| 3903 | "mcp.json".into(), |
| 3904 | format!( |
| 3905 | "{}\n", |
| 3906 | serde_json::to_string_pretty(&json!({"mcpServers": servers}))? |
| 3907 | ) |
| 3908 | .into_bytes(), |
| 3909 | )?; |
| 3910 | } |
| 3911 | |
| 3912 | let conversion = DshConversion { |
| 3913 | plugin_name, |
| 3914 | source_package: package_name, |
| 3915 | source_version: package_version, |
| 3916 | manifest_sha256: loaded.manifest_sha256, |
| 3917 | layers: loaded.layers, |
| 3918 | outcomes, |
| 3919 | diagnostics: notes, |
| 3920 | skills, |
| 3921 | commands: merged.commands, |
| 3922 | agents: merged.agents, |
| 3923 | hooks: merged.hooks, |
| 3924 | remote_servers: remote.iter().map(|(name, _)| name.clone()).collect(), |
| 3925 | local_servers: local.iter().map(|(name, _)| name.clone()).collect(), |
| 3926 | network_hosts: hosts, |
| 3927 | requires_node, |
| 3928 | requires_native, |
| 3929 | native_rows, |
| 3930 | client_closures, |
| 3931 | }; |
| 3932 | output_files.add( |
| 3933 | "CONVERSION.md".into(), |
| 3934 | conversion_markdown(&conversion, !fetched_npm.is_empty()).into_bytes(), |
| 3935 | )?; |
| 3936 | let mut counts = json!({ |
| 3937 | "skills": conversion.skills.len(), |
| 3938 | "mcp_servers": components.servers.len(), |
| 3939 | "native_rows": conversion.native_rows.len(), |
| 3940 | }); |
| 3941 | let has_merged_components = !conversion.commands.is_empty() |
| 3942 | || !conversion.agents.is_empty() |
| 3943 | || !conversion.hooks.is_empty(); |
| 3944 | if has_merged_components { |
| 3945 | counts["commands"] = json!(conversion.commands.len()); |
| 3946 | counts["agents"] = json!(conversion.agents.len()); |
| 3947 | counts["hooks"] = json!(conversion.hooks.len()); |
| 3948 | } |
| 3949 | let mut receipt = json!({ |
| 3950 | "schema": "codewhale.plugin-conversion.v1", |
| 3951 | "converter_version": CONVERTER_VERSION, |
| 3952 | "converter": "codewhale-native", |
| 3953 | "source": { |
| 3954 | "dialect": "dsh", |
| 3955 | "package": conversion.source_package, |
| 3956 | "version": conversion.source_version, |
| 3957 | "manifest_sha256": conversion.manifest_sha256, |
| 3958 | "patch_layers": conversion.layers, |
| 3959 | }, |
| 3960 | "counts": counts, |
| 3961 | "requires_native": conversion.requires_native, |
| 3962 | "outcomes": conversion.outcomes, |
| 3963 | "client_closures": conversion.client_closures, |
| 3964 | "diagnostics": conversion.diagnostics, |
| 3965 | "required_manual_ports": conversion.outcomes.iter().filter(|o| o.needs_manual_port()).collect::<Vec<_>>(), |
| 3966 | }); |
| 3967 | if has_merged_components { |
| 3968 | receipt["commands"] = json!(conversion.commands); |
| 3969 | receipt["agents"] = json!(conversion.agents); |
| 3970 | receipt["hooks"] = json!(conversion.hooks); |
| 3971 | } |
| 3972 | output_files.add( |
| 3973 | "CONVERSION.json".into(), |
| 3974 | format!("{}\n", serde_json::to_string_pretty(&receipt)?).into_bytes(), |
| 3975 | )?; |
| 3976 | |
| 3977 | write_output(output, &output_files)?; |
| 3978 | if merged.present |
| 3979 | && let Err(error) = crate::manifest::PluginManifest::validate_from_path( |
| 3980 | &output.join(crate::agent_plugin::PLUGIN_JSON_NAME), |
| 3981 | ) |
| 3982 | { |
| 3983 | let _ = fs::remove_dir_all(output); |
| 3984 | return refuse(format!( |
| 3985 | "Converted bundle failed manifest validation: {}", |
| 3986 | refusal_text(&error) |
| 3987 | )); |
| 3988 | } |
| 3989 | Ok(conversion) |
| 3990 | } |
| 3991 | |
| 3992 | const MAX_FETCHED_NPM_NAMES: usize = 40; |
| 3993 | |
| 3994 | pub(super) fn fetched_npm_note(fetched: &[String]) -> Option<String> { |
| 3995 | if fetched.is_empty() { |
| 3996 | return None; |
| 3997 | } |
| 3998 | let shown = fetched |
| 3999 | .iter() |
| 4000 | .take(MAX_FETCHED_NPM_NAMES) |
| 4001 | .map(String::as_str) |
| 4002 | .collect::<Vec<_>>() |
| 4003 | .join(", "); |
| 4004 | let more = fetched.len().saturating_sub(MAX_FETCHED_NPM_NAMES); |
| 4005 | Some(format!( |
| 4006 | "Fetched from registry.npmjs.org (sha512-verified; install scripts not run): {shown}{}", |
| 4007 | if more > 0 { |
| 4008 | format!(", +{more} more") |
| 4009 | } else { |
| 4010 | String::new() |
| 4011 | } |
| 4012 | )) |
| 4013 | } |
| 4014 | |
| 4015 | pub(super) fn conversion_markdown(conversion: &DshConversion, fetched_npm: bool) -> String { |
| 4016 | let mut lines = vec![ |
| 4017 | "# Conversion receipt".to_string(), |
| 4018 | String::new(), |
| 4019 | format!( |
| 4020 | "Converter version {CONVERTER_VERSION} (native Codewhale import). Source dialect: dsh." |
| 4021 | ), |
| 4022 | format!( |
| 4023 | "Source package: {}{}", |
| 4024 | conversion.source_package.as_deref().unwrap_or("unnamed"), |
| 4025 | conversion |
| 4026 | .source_version |
| 4027 | .as_deref() |
| 4028 | .map(|v| format!("@{v}")) |
| 4029 | .unwrap_or_default() |
| 4030 | ), |
| 4031 | format!("Source manifest sha256: {}", conversion.manifest_sha256), |
| 4032 | "Selected patch layers, applied in declaration order:".to_string(), |
| 4033 | ]; |
| 4034 | lines.extend(conversion.layers.iter().map(|layer| { |
| 4035 | format!( |
| 4036 | "- {} (sha256 {}, {} bytes)", |
| 4037 | layer.path, layer.sha256, layer.bytes |
| 4038 | ) |
| 4039 | })); |
| 4040 | lines.push(String::new()); |
| 4041 | lines.push(format!( |
| 4042 | "Converted {} Skills, {} remote and {} local MCP declarations; {} reviewed Native composition rows.", |
| 4043 | conversion.skills.len(), |
| 4044 | conversion.remote_servers.len(), |
| 4045 | conversion.local_servers.len(),conversion.native_rows.len() |
| 4046 | )); |
| 4047 | if !conversion.commands.is_empty() |
| 4048 | || !conversion.agents.is_empty() |
| 4049 | || !conversion.hooks.is_empty() |
| 4050 | { |
| 4051 | let shown = |items: &[String]| { |
| 4052 | if items.is_empty() { |
| 4053 | "none".to_string() |
| 4054 | } else { |
| 4055 | items.join(", ") |
| 4056 | } |
| 4057 | }; |
| 4058 | lines.push(format!( |
| 4059 | "Merged from sibling plugin.json: {} Commands ({}), {} Agents ({}), {} Hooks ({}).", |
| 4060 | conversion.commands.len(), |
| 4061 | shown(&conversion.commands), |
| 4062 | conversion.agents.len(), |
| 4063 | shown(&conversion.agents), |
| 4064 | conversion.hooks.len(), |
| 4065 | shown(&conversion.hooks), |
| 4066 | )); |
| 4067 | } |
| 4068 | lines.push(String::new()); |
| 4069 | if !conversion.outcomes.is_empty() { |
| 4070 | lines.push("## Component outcomes".to_string()); |
| 4071 | lines.push(String::new()); |
| 4072 | lines.push( |
| 4073 | "Unsupported rows need a manual port; disabled rows remain intentionally inactive." |
| 4074 | .to_string(), |
| 4075 | ); |
| 4076 | lines.push(String::new()); |
| 4077 | for outcome in &conversion.outcomes { |
| 4078 | lines.push(format!( |
| 4079 | "- {} ({}) {}: {}{}", |
| 4080 | outcome.row.as_deref().unwrap_or("unlabeled"), |
| 4081 | outcome.package.as_deref().unwrap_or("unlabeled"), |
| 4082 | outcome.kind, |
| 4083 | outcome.outcome, |
| 4084 | if outcome.reason.is_empty() { |
| 4085 | String::new() |
| 4086 | } else { |
| 4087 | format!(" — {}", outcome.reason) |
| 4088 | } |
| 4089 | )); |
| 4090 | } |
| 4091 | lines.push(String::new()); |
| 4092 | } |
| 4093 | if !conversion.diagnostics.is_empty() { |
| 4094 | lines.push("Bundle diagnostics:".to_string()); |
| 4095 | lines.extend( |
| 4096 | conversion |
| 4097 | .diagnostics |
| 4098 | .iter() |
| 4099 | .map(|note| format!("- {note}")), |
| 4100 | ); |
| 4101 | lines.push(String::new()); |
| 4102 | } |
| 4103 | lines.push(if fetched_npm { |
| 4104 | "No selected-package code, package manager, install hook or credential lookup ran; the pinned pure review evaluator parsed configuration." |
| 4105 | } else { |
| 4106 | "No selected-package code, package manager, install hook, network request or credential lookup ran; the pinned pure review evaluator parsed configuration." |
| 4107 | }.to_string()); |
| 4108 | lines.push(if fetched_npm { |
| 4109 | "No environment variable values were resolved. Files inside the selected package and the npm packages listed under Bundle diagnostics were read;" |
| 4110 | } else { |
| 4111 | "No environment variable values were resolved. Only files inside the selected package were read;" |
| 4112 | }.to_string()); |
| 4113 | lines.extend( |
| 4114 | [ |
| 4115 | "host paths are never inferred from expressions or copied.", |
| 4116 | "Companion skill files and packaged Node source were copied as data.", |
| 4117 | "Local MCP runs with host-user process authority, not an OS sandbox; stdio does not confine its network or files.", |
| 4118 | "The bundle is installed disabled and untrusted: review it with /plugin validate <name> and the exact trust token before enabling.", |
| 4119 | "Remote MCP output uses Streamable HTTP only. Conversion does not prove server connectivity or foreign runtime compatibility.", |
| 4120 | ] |
| 4121 | .map(str::to_string), |
| 4122 | ); |
| 4123 | format!("{}\n", lines.join("\n")) |
| 4124 | } |
| 4125 | |
| 4126 | fn write_output(output: &Path, files: &OutputFiles) -> Result<()> { |
| 4127 | #[cfg(unix)] |
| 4128 | { |
| 4129 | use std::os::unix::fs::DirBuilderExt as _; |
| 4130 | fs::DirBuilder::new().mode(0o700).create(output)?; |
| 4131 | } |
| 4132 | #[cfg(not(unix))] |
| 4133 | fs::create_dir(output)?; |
| 4134 | let result = (|| -> Result<()> { |
| 4135 | for (relative, content) in &files.files { |
| 4136 | let destination = output.join(relative); |
| 4137 | if let Some(parent) = destination.parent() { |
| 4138 | fs::create_dir_all(parent)?; |
| 4139 | } |
| 4140 | let mut file = fs::OpenOptions::new() |
| 4141 | .write(true) |
| 4142 | .create_new(true) |
| 4143 | .open(&destination)?; |
| 4144 | std::io::Write::write_all(&mut file, content)?; |
| 4145 | } |
| 4146 | Ok(()) |
| 4147 | })(); |
| 4148 | if result.is_err() { |
| 4149 | // The directory was created by this call, so removing it removes |
| 4150 | // only what this conversion wrote. |
| 4151 | let _ = fs::remove_dir_all(output); |
| 4152 | } |
| 4153 | result.map_err(|_| { |
| 4154 | anyhow::Error::msg("Writing the converted bundle failed; nothing was installed.") |
| 4155 | }) |
| 4156 | } |
| 4157 | |
| 4158 | /// Convert into a private scratch directory and return it with the receipt. |
| 4159 | /// The directory is removed when the returned guard drops. |
| 4160 | pub fn convert_to_scratch(package: &Path) -> Result<(tempfile::TempDir, PathBuf, DshConversion)> { |
| 4161 | convert_to_scratch_with_network(package, None) |
| 4162 | } |
| 4163 | |
| 4164 | pub fn convert_to_scratch_with_network( |
| 4165 | package: &Path, |
| 4166 | network: Option<&codewhale_net::network_policy::NetworkPolicy>, |
| 4167 | ) -> Result<(tempfile::TempDir, PathBuf, DshConversion)> { |
| 4168 | let scratch = tempfile::Builder::new() |
| 4169 | .prefix("codewhale-dsh-import-") |
| 4170 | .tempdir()?; |
| 4171 | let bundle = scratch.path().join("bundle"); |
| 4172 | let conversion = convert_package_with_network(package, &bundle, network)?; |
| 4173 | Ok((scratch, bundle, conversion)) |
| 4174 | } |
| 4175 | |
| 4176 | /// Whether `path` looks like a DSH bundle package (for routing a plain local |
| 4177 | /// install to the importer instead of the native bundle reader). |
| 4178 | pub fn is_dsh_package(path: &Path) -> bool { |
| 4179 | matches!(try_is_dsh_package(path), Ok(true)) |
| 4180 | } |
| 4181 | |
| 4182 | pub fn try_is_dsh_package(path: &Path) -> Result<bool> { |
| 4183 | match fs::metadata(path) { |
| 4184 | Ok(meta) if !meta.is_dir() => return Ok(false), |
| 4185 | Ok(_) => {} |
| 4186 | Err(error) |
| 4187 | if matches!( |
| 4188 | error.kind(), |
| 4189 | std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory |
| 4190 | ) => |
| 4191 | { |
| 4192 | return Ok(false); |
| 4193 | } |
| 4194 | Err(error) => return Err(error.into()), |
| 4195 | } |
| 4196 | let package = Package::open(path)?; |
| 4197 | let Some(manifest_path) = package_entry_exists(&package, "package.json")? else { |
| 4198 | return Ok(false); |
| 4199 | }; |
| 4200 | let text = utf8(read_file(&manifest_path, MAX_DOCUMENT)?)?; |
| 4201 | let manifest = parse_package_json(&text)?; |
| 4202 | Ok(manifest |
| 4203 | .get("dsh") |
| 4204 | .and_then(|dsh| dsh.get("bundle")) |
| 4205 | .is_some()) |
| 4206 | } |
| 4207 | |
| 4208 | #[cfg(test)] |
| 4209 | mod tests { |
| 4210 | use super::*; |
| 4211 | |
| 4212 | #[test] |
| 4213 | fn supported_dsh_versions_accepts_022_rc2_through_rc5() { |
| 4214 | for range in [ |
| 4215 | "0.2.2-rc.2", |
| 4216 | "0.2.2-rc.3", |
| 4217 | "0.2.2-rc.4", |
| 4218 | "0.2.2-rc.5", |
| 4219 | ">=0.2.2-rc.2 <0.2.3", |
| 4220 | "^0.2.2-rc.5", |
| 4221 | ] { |
| 4222 | let matched = match_supported_dsh_range(range).expect("valid semver range"); |
| 4223 | assert!(matched.is_some(), "expected {range} to match"); |
| 4224 | } |
| 4225 | assert!( |
| 4226 | match_supported_dsh_range("^0.2.3-alpha.1") |
| 4227 | .expect("valid semver range") |
| 4228 | .is_none() |
| 4229 | ); |
| 4230 | } |
| 4231 | |
| 4232 | #[test] |
| 4233 | fn wsl_platform_is_recognized_and_admitted_only_on_wsl_hosts() { |
| 4234 | assert_eq!(node_platform("wsl"), Some("wsl")); |
| 4235 | assert!(platform_admits_host(&["win32", "wsl"], "linux", true)); |
| 4236 | assert!(!platform_admits_host(&["win32", "wsl"], "linux", false)); |
| 4237 | assert!(!platform_admits_host(&["wsl"], "darwin", true)); |
| 4238 | assert!(platform_admits_host( |
| 4239 | &["darwin", "win32", "linux", "wsl"], |
| 4240 | "darwin", |
| 4241 | false |
| 4242 | )); |
| 4243 | } |
| 4244 | } |
| 4245 |