lib.rs 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361
  1. mod hooks;
  2. use std::collections::{BTreeMap, BTreeSet};
  3. use std::fmt::{Display, Formatter};
  4. use std::fs;
  5. use std::path::{Path, PathBuf};
  6. use std::process::{Command, Stdio};
  7. use std::time::{SystemTime, UNIX_EPOCH};
  8. use serde::{Deserialize, Serialize};
  9. use serde_json::{Map, Value};
  10. pub use hooks::{HookEvent, HookRunResult, HookRunner};
  11. const EXTERNAL_MARKETPLACE: &str = "external";
  12. const BUILTIN_MARKETPLACE: &str = "builtin";
  13. const BUNDLED_MARKETPLACE: &str = "bundled";
  14. const SETTINGS_FILE_NAME: &str = "settings.json";
  15. const REGISTRY_FILE_NAME: &str = "installed.json";
  16. const MANIFEST_FILE_NAME: &str = "plugin.json";
  17. const MANIFEST_RELATIVE_PATH: &str = ".claude-plugin/plugin.json";
  18. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
  19. #[serde(rename_all = "lowercase")]
  20. pub enum PluginKind {
  21. Builtin,
  22. Bundled,
  23. External,
  24. }
  25. impl Display for PluginKind {
  26. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  27. match self {
  28. Self::Builtin => write!(f, "builtin"),
  29. Self::Bundled => write!(f, "bundled"),
  30. Self::External => write!(f, "external"),
  31. }
  32. }
  33. }
  34. impl PluginKind {
  35. #[must_use]
  36. fn marketplace(self) -> &'static str {
  37. match self {
  38. Self::Builtin => BUILTIN_MARKETPLACE,
  39. Self::Bundled => BUNDLED_MARKETPLACE,
  40. Self::External => EXTERNAL_MARKETPLACE,
  41. }
  42. }
  43. }
  44. #[derive(Debug, Clone, PartialEq, Eq)]
  45. pub struct PluginMetadata {
  46. pub id: String,
  47. pub name: String,
  48. pub version: String,
  49. pub description: String,
  50. pub kind: PluginKind,
  51. pub source: String,
  52. pub default_enabled: bool,
  53. pub root: Option<PathBuf>,
  54. }
  55. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
  56. pub struct PluginHooks {
  57. #[serde(rename = "PreToolUse", default)]
  58. pub pre_tool_use: Vec<String>,
  59. #[serde(rename = "PostToolUse", default)]
  60. pub post_tool_use: Vec<String>,
  61. #[serde(rename = "PostToolUseFailure", default)]
  62. pub post_tool_use_failure: Vec<String>,
  63. }
  64. impl PluginHooks {
  65. #[must_use]
  66. pub fn is_empty(&self) -> bool {
  67. self.pre_tool_use.is_empty()
  68. && self.post_tool_use.is_empty()
  69. && self.post_tool_use_failure.is_empty()
  70. }
  71. #[must_use]
  72. pub fn merged_with(&self, other: &Self) -> Self {
  73. let mut merged = self.clone();
  74. merged
  75. .pre_tool_use
  76. .extend(other.pre_tool_use.iter().cloned());
  77. merged
  78. .post_tool_use
  79. .extend(other.post_tool_use.iter().cloned());
  80. merged
  81. .post_tool_use_failure
  82. .extend(other.post_tool_use_failure.iter().cloned());
  83. merged
  84. }
  85. }
  86. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
  87. pub struct PluginLifecycle {
  88. #[serde(rename = "Init", default)]
  89. pub init: Vec<String>,
  90. #[serde(rename = "Shutdown", default)]
  91. pub shutdown: Vec<String>,
  92. }
  93. impl PluginLifecycle {
  94. #[must_use]
  95. pub fn is_empty(&self) -> bool {
  96. self.init.is_empty() && self.shutdown.is_empty()
  97. }
  98. }
  99. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
  100. pub struct PluginManifest {
  101. pub name: String,
  102. pub version: String,
  103. pub description: String,
  104. pub permissions: Vec<PluginPermission>,
  105. #[serde(rename = "defaultEnabled", default)]
  106. pub default_enabled: bool,
  107. #[serde(default)]
  108. pub hooks: PluginHooks,
  109. #[serde(default)]
  110. pub lifecycle: PluginLifecycle,
  111. #[serde(default)]
  112. pub tools: Vec<PluginToolManifest>,
  113. #[serde(default)]
  114. pub commands: Vec<PluginCommandManifest>,
  115. }
  116. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
  117. #[serde(rename_all = "lowercase")]
  118. pub enum PluginPermission {
  119. Read,
  120. Write,
  121. Execute,
  122. }
  123. impl PluginPermission {
  124. #[must_use]
  125. pub fn as_str(self) -> &'static str {
  126. match self {
  127. Self::Read => "read",
  128. Self::Write => "write",
  129. Self::Execute => "execute",
  130. }
  131. }
  132. fn parse(value: &str) -> Option<Self> {
  133. match value {
  134. "read" => Some(Self::Read),
  135. "write" => Some(Self::Write),
  136. "execute" => Some(Self::Execute),
  137. _ => None,
  138. }
  139. }
  140. }
  141. impl AsRef<str> for PluginPermission {
  142. fn as_ref(&self) -> &str {
  143. self.as_str()
  144. }
  145. }
  146. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
  147. pub struct PluginToolManifest {
  148. pub name: String,
  149. pub description: String,
  150. #[serde(rename = "inputSchema")]
  151. pub input_schema: Value,
  152. pub command: String,
  153. #[serde(default)]
  154. pub args: Vec<String>,
  155. pub required_permission: PluginToolPermission,
  156. }
  157. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
  158. #[serde(rename_all = "kebab-case")]
  159. pub enum PluginToolPermission {
  160. ReadOnly,
  161. WorkspaceWrite,
  162. DangerFullAccess,
  163. }
  164. impl PluginToolPermission {
  165. #[must_use]
  166. pub fn as_str(self) -> &'static str {
  167. match self {
  168. Self::ReadOnly => "read-only",
  169. Self::WorkspaceWrite => "workspace-write",
  170. Self::DangerFullAccess => "danger-full-access",
  171. }
  172. }
  173. fn parse(value: &str) -> Option<Self> {
  174. match value {
  175. "read-only" => Some(Self::ReadOnly),
  176. "workspace-write" => Some(Self::WorkspaceWrite),
  177. "danger-full-access" => Some(Self::DangerFullAccess),
  178. _ => None,
  179. }
  180. }
  181. }
  182. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
  183. pub struct PluginToolDefinition {
  184. pub name: String,
  185. #[serde(default)]
  186. pub description: Option<String>,
  187. #[serde(rename = "inputSchema")]
  188. pub input_schema: Value,
  189. }
  190. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  191. pub struct PluginCommandManifest {
  192. pub name: String,
  193. pub description: String,
  194. pub command: String,
  195. }
  196. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  197. struct RawPluginManifest {
  198. pub name: String,
  199. pub version: String,
  200. pub description: String,
  201. #[serde(default)]
  202. pub permissions: Vec<String>,
  203. #[serde(rename = "defaultEnabled", default)]
  204. pub default_enabled: bool,
  205. #[serde(default)]
  206. pub hooks: PluginHooks,
  207. #[serde(default)]
  208. pub lifecycle: PluginLifecycle,
  209. #[serde(default)]
  210. pub tools: Vec<RawPluginToolManifest>,
  211. #[serde(default)]
  212. pub commands: Vec<PluginCommandManifest>,
  213. }
  214. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  215. struct RawPluginToolManifest {
  216. pub name: String,
  217. pub description: String,
  218. #[serde(rename = "inputSchema")]
  219. pub input_schema: Value,
  220. pub command: String,
  221. #[serde(default)]
  222. pub args: Vec<String>,
  223. #[serde(
  224. rename = "requiredPermission",
  225. default = "default_tool_permission_label"
  226. )]
  227. pub required_permission: String,
  228. }
  229. #[derive(Debug, Clone, PartialEq)]
  230. pub struct PluginTool {
  231. plugin_id: String,
  232. plugin_name: String,
  233. definition: PluginToolDefinition,
  234. command: String,
  235. args: Vec<String>,
  236. required_permission: PluginToolPermission,
  237. root: Option<PathBuf>,
  238. }
  239. impl PluginTool {
  240. #[must_use]
  241. pub fn new(
  242. plugin_id: impl Into<String>,
  243. plugin_name: impl Into<String>,
  244. definition: PluginToolDefinition,
  245. command: impl Into<String>,
  246. args: Vec<String>,
  247. required_permission: PluginToolPermission,
  248. root: Option<PathBuf>,
  249. ) -> Self {
  250. Self {
  251. plugin_id: plugin_id.into(),
  252. plugin_name: plugin_name.into(),
  253. definition,
  254. command: command.into(),
  255. args,
  256. required_permission,
  257. root,
  258. }
  259. }
  260. #[must_use]
  261. pub fn plugin_id(&self) -> &str {
  262. &self.plugin_id
  263. }
  264. #[must_use]
  265. pub fn definition(&self) -> &PluginToolDefinition {
  266. &self.definition
  267. }
  268. #[must_use]
  269. pub fn required_permission(&self) -> &str {
  270. self.required_permission.as_str()
  271. }
  272. pub fn execute(&self, input: &Value) -> Result<String, PluginError> {
  273. let input_json = input.to_string();
  274. let mut process = Command::new(&self.command);
  275. process
  276. .args(&self.args)
  277. .stdin(Stdio::piped())
  278. .stdout(Stdio::piped())
  279. .stderr(Stdio::piped())
  280. .env("CLAWD_PLUGIN_ID", &self.plugin_id)
  281. .env("CLAWD_PLUGIN_NAME", &self.plugin_name)
  282. .env("CLAWD_TOOL_NAME", &self.definition.name)
  283. .env("CLAWD_TOOL_INPUT", &input_json);
  284. if let Some(root) = &self.root {
  285. process
  286. .current_dir(root)
  287. .env("CLAWD_PLUGIN_ROOT", root.display().to_string());
  288. }
  289. let mut child = process.spawn()?;
  290. if let Some(stdin) = child.stdin.as_mut() {
  291. use std::io::Write as _;
  292. stdin.write_all(input_json.as_bytes())?;
  293. }
  294. let output = child.wait_with_output()?;
  295. if output.status.success() {
  296. Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
  297. } else {
  298. let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
  299. Err(PluginError::CommandFailed(format!(
  300. "plugin tool `{}` from `{}` failed for `{}`: {}",
  301. self.definition.name,
  302. self.plugin_id,
  303. self.command,
  304. if stderr.is_empty() {
  305. format!("exit status {}", output.status)
  306. } else {
  307. stderr
  308. }
  309. )))
  310. }
  311. }
  312. }
  313. fn default_tool_permission_label() -> String {
  314. "danger-full-access".to_string()
  315. }
  316. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  317. #[serde(tag = "type", rename_all = "snake_case")]
  318. pub enum PluginInstallSource {
  319. LocalPath { path: PathBuf },
  320. GitUrl { url: String },
  321. }
  322. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  323. pub struct InstalledPluginRecord {
  324. #[serde(default = "default_plugin_kind")]
  325. pub kind: PluginKind,
  326. pub id: String,
  327. pub name: String,
  328. pub version: String,
  329. pub description: String,
  330. pub install_path: PathBuf,
  331. pub source: PluginInstallSource,
  332. pub installed_at_unix_ms: u128,
  333. pub updated_at_unix_ms: u128,
  334. }
  335. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
  336. pub struct InstalledPluginRegistry {
  337. #[serde(default)]
  338. pub plugins: BTreeMap<String, InstalledPluginRecord>,
  339. }
  340. fn default_plugin_kind() -> PluginKind {
  341. PluginKind::External
  342. }
  343. #[derive(Debug, Clone, PartialEq)]
  344. pub struct BuiltinPlugin {
  345. metadata: PluginMetadata,
  346. hooks: PluginHooks,
  347. lifecycle: PluginLifecycle,
  348. tools: Vec<PluginTool>,
  349. }
  350. #[derive(Debug, Clone, PartialEq)]
  351. pub struct BundledPlugin {
  352. metadata: PluginMetadata,
  353. hooks: PluginHooks,
  354. lifecycle: PluginLifecycle,
  355. tools: Vec<PluginTool>,
  356. }
  357. #[derive(Debug, Clone, PartialEq)]
  358. pub struct ExternalPlugin {
  359. metadata: PluginMetadata,
  360. hooks: PluginHooks,
  361. lifecycle: PluginLifecycle,
  362. tools: Vec<PluginTool>,
  363. }
  364. pub trait Plugin {
  365. fn metadata(&self) -> &PluginMetadata;
  366. fn hooks(&self) -> &PluginHooks;
  367. fn lifecycle(&self) -> &PluginLifecycle;
  368. fn tools(&self) -> &[PluginTool];
  369. fn validate(&self) -> Result<(), PluginError>;
  370. fn initialize(&self) -> Result<(), PluginError>;
  371. fn shutdown(&self) -> Result<(), PluginError>;
  372. }
  373. #[derive(Debug, Clone, PartialEq)]
  374. pub enum PluginDefinition {
  375. Builtin(BuiltinPlugin),
  376. Bundled(BundledPlugin),
  377. External(ExternalPlugin),
  378. }
  379. impl Plugin for BuiltinPlugin {
  380. fn metadata(&self) -> &PluginMetadata {
  381. &self.metadata
  382. }
  383. fn hooks(&self) -> &PluginHooks {
  384. &self.hooks
  385. }
  386. fn lifecycle(&self) -> &PluginLifecycle {
  387. &self.lifecycle
  388. }
  389. fn tools(&self) -> &[PluginTool] {
  390. &self.tools
  391. }
  392. fn validate(&self) -> Result<(), PluginError> {
  393. Ok(())
  394. }
  395. fn initialize(&self) -> Result<(), PluginError> {
  396. Ok(())
  397. }
  398. fn shutdown(&self) -> Result<(), PluginError> {
  399. Ok(())
  400. }
  401. }
  402. impl Plugin for BundledPlugin {
  403. fn metadata(&self) -> &PluginMetadata {
  404. &self.metadata
  405. }
  406. fn hooks(&self) -> &PluginHooks {
  407. &self.hooks
  408. }
  409. fn lifecycle(&self) -> &PluginLifecycle {
  410. &self.lifecycle
  411. }
  412. fn tools(&self) -> &[PluginTool] {
  413. &self.tools
  414. }
  415. fn validate(&self) -> Result<(), PluginError> {
  416. validate_hook_paths(self.metadata.root.as_deref(), &self.hooks)?;
  417. validate_lifecycle_paths(self.metadata.root.as_deref(), &self.lifecycle)?;
  418. validate_tool_paths(self.metadata.root.as_deref(), &self.tools)
  419. }
  420. fn initialize(&self) -> Result<(), PluginError> {
  421. run_lifecycle_commands(
  422. self.metadata(),
  423. self.lifecycle(),
  424. "init",
  425. &self.lifecycle.init,
  426. )
  427. }
  428. fn shutdown(&self) -> Result<(), PluginError> {
  429. run_lifecycle_commands(
  430. self.metadata(),
  431. self.lifecycle(),
  432. "shutdown",
  433. &self.lifecycle.shutdown,
  434. )
  435. }
  436. }
  437. impl Plugin for ExternalPlugin {
  438. fn metadata(&self) -> &PluginMetadata {
  439. &self.metadata
  440. }
  441. fn hooks(&self) -> &PluginHooks {
  442. &self.hooks
  443. }
  444. fn lifecycle(&self) -> &PluginLifecycle {
  445. &self.lifecycle
  446. }
  447. fn tools(&self) -> &[PluginTool] {
  448. &self.tools
  449. }
  450. fn validate(&self) -> Result<(), PluginError> {
  451. validate_hook_paths(self.metadata.root.as_deref(), &self.hooks)?;
  452. validate_lifecycle_paths(self.metadata.root.as_deref(), &self.lifecycle)?;
  453. validate_tool_paths(self.metadata.root.as_deref(), &self.tools)
  454. }
  455. fn initialize(&self) -> Result<(), PluginError> {
  456. run_lifecycle_commands(
  457. self.metadata(),
  458. self.lifecycle(),
  459. "init",
  460. &self.lifecycle.init,
  461. )
  462. }
  463. fn shutdown(&self) -> Result<(), PluginError> {
  464. run_lifecycle_commands(
  465. self.metadata(),
  466. self.lifecycle(),
  467. "shutdown",
  468. &self.lifecycle.shutdown,
  469. )
  470. }
  471. }
  472. impl Plugin for PluginDefinition {
  473. fn metadata(&self) -> &PluginMetadata {
  474. match self {
  475. Self::Builtin(plugin) => plugin.metadata(),
  476. Self::Bundled(plugin) => plugin.metadata(),
  477. Self::External(plugin) => plugin.metadata(),
  478. }
  479. }
  480. fn hooks(&self) -> &PluginHooks {
  481. match self {
  482. Self::Builtin(plugin) => plugin.hooks(),
  483. Self::Bundled(plugin) => plugin.hooks(),
  484. Self::External(plugin) => plugin.hooks(),
  485. }
  486. }
  487. fn lifecycle(&self) -> &PluginLifecycle {
  488. match self {
  489. Self::Builtin(plugin) => plugin.lifecycle(),
  490. Self::Bundled(plugin) => plugin.lifecycle(),
  491. Self::External(plugin) => plugin.lifecycle(),
  492. }
  493. }
  494. fn tools(&self) -> &[PluginTool] {
  495. match self {
  496. Self::Builtin(plugin) => plugin.tools(),
  497. Self::Bundled(plugin) => plugin.tools(),
  498. Self::External(plugin) => plugin.tools(),
  499. }
  500. }
  501. fn validate(&self) -> Result<(), PluginError> {
  502. match self {
  503. Self::Builtin(plugin) => plugin.validate(),
  504. Self::Bundled(plugin) => plugin.validate(),
  505. Self::External(plugin) => plugin.validate(),
  506. }
  507. }
  508. fn initialize(&self) -> Result<(), PluginError> {
  509. match self {
  510. Self::Builtin(plugin) => plugin.initialize(),
  511. Self::Bundled(plugin) => plugin.initialize(),
  512. Self::External(plugin) => plugin.initialize(),
  513. }
  514. }
  515. fn shutdown(&self) -> Result<(), PluginError> {
  516. match self {
  517. Self::Builtin(plugin) => plugin.shutdown(),
  518. Self::Bundled(plugin) => plugin.shutdown(),
  519. Self::External(plugin) => plugin.shutdown(),
  520. }
  521. }
  522. }
  523. #[derive(Debug, Clone, PartialEq)]
  524. pub struct RegisteredPlugin {
  525. definition: PluginDefinition,
  526. enabled: bool,
  527. }
  528. impl RegisteredPlugin {
  529. #[must_use]
  530. pub fn new(definition: PluginDefinition, enabled: bool) -> Self {
  531. Self {
  532. definition,
  533. enabled,
  534. }
  535. }
  536. #[must_use]
  537. pub fn metadata(&self) -> &PluginMetadata {
  538. self.definition.metadata()
  539. }
  540. #[must_use]
  541. pub fn hooks(&self) -> &PluginHooks {
  542. self.definition.hooks()
  543. }
  544. #[must_use]
  545. pub fn tools(&self) -> &[PluginTool] {
  546. self.definition.tools()
  547. }
  548. #[must_use]
  549. pub fn is_enabled(&self) -> bool {
  550. self.enabled
  551. }
  552. pub fn validate(&self) -> Result<(), PluginError> {
  553. self.definition.validate()
  554. }
  555. pub fn initialize(&self) -> Result<(), PluginError> {
  556. self.definition.initialize()
  557. }
  558. pub fn shutdown(&self) -> Result<(), PluginError> {
  559. self.definition.shutdown()
  560. }
  561. #[must_use]
  562. pub fn summary(&self) -> PluginSummary {
  563. PluginSummary {
  564. metadata: self.metadata().clone(),
  565. enabled: self.enabled,
  566. }
  567. }
  568. }
  569. #[derive(Debug, Clone, PartialEq, Eq)]
  570. pub struct PluginSummary {
  571. pub metadata: PluginMetadata,
  572. pub enabled: bool,
  573. }
  574. #[derive(Debug)]
  575. pub struct PluginLoadFailure {
  576. pub plugin_root: PathBuf,
  577. pub kind: PluginKind,
  578. pub source: String,
  579. error: Box<PluginError>,
  580. }
  581. impl PluginLoadFailure {
  582. #[must_use]
  583. pub fn new(plugin_root: PathBuf, kind: PluginKind, source: String, error: PluginError) -> Self {
  584. Self {
  585. plugin_root,
  586. kind,
  587. source,
  588. error: Box::new(error),
  589. }
  590. }
  591. #[must_use]
  592. pub fn error(&self) -> &PluginError {
  593. self.error.as_ref()
  594. }
  595. }
  596. impl Display for PluginLoadFailure {
  597. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  598. write!(
  599. f,
  600. "failed to load {} plugin from `{}` (source: {}): {}",
  601. self.kind,
  602. self.plugin_root.display(),
  603. self.source,
  604. self.error()
  605. )
  606. }
  607. }
  608. #[derive(Debug)]
  609. pub struct PluginRegistryReport {
  610. registry: PluginRegistry,
  611. failures: Vec<PluginLoadFailure>,
  612. }
  613. impl PluginRegistryReport {
  614. #[must_use]
  615. pub fn new(registry: PluginRegistry, failures: Vec<PluginLoadFailure>) -> Self {
  616. Self { registry, failures }
  617. }
  618. #[must_use]
  619. pub fn registry(&self) -> &PluginRegistry {
  620. &self.registry
  621. }
  622. #[must_use]
  623. pub fn failures(&self) -> &[PluginLoadFailure] {
  624. &self.failures
  625. }
  626. #[must_use]
  627. pub fn has_failures(&self) -> bool {
  628. !self.failures.is_empty()
  629. }
  630. #[must_use]
  631. pub fn summaries(&self) -> Vec<PluginSummary> {
  632. self.registry.summaries()
  633. }
  634. pub fn into_registry(self) -> Result<PluginRegistry, PluginError> {
  635. if self.failures.is_empty() {
  636. Ok(self.registry)
  637. } else {
  638. Err(PluginError::LoadFailures(self.failures))
  639. }
  640. }
  641. }
  642. #[derive(Debug, Default)]
  643. struct PluginDiscovery {
  644. plugins: Vec<PluginDefinition>,
  645. failures: Vec<PluginLoadFailure>,
  646. }
  647. impl PluginDiscovery {
  648. fn push_plugin(&mut self, plugin: PluginDefinition) {
  649. self.plugins.push(plugin);
  650. }
  651. fn push_failure(&mut self, failure: PluginLoadFailure) {
  652. self.failures.push(failure);
  653. }
  654. fn extend(&mut self, other: Self) {
  655. self.plugins.extend(other.plugins);
  656. self.failures.extend(other.failures);
  657. }
  658. }
  659. #[derive(Debug, Clone, Default, PartialEq)]
  660. pub struct PluginRegistry {
  661. plugins: Vec<RegisteredPlugin>,
  662. }
  663. impl PluginRegistry {
  664. #[must_use]
  665. pub fn new(mut plugins: Vec<RegisteredPlugin>) -> Self {
  666. plugins.sort_by(|left, right| left.metadata().id.cmp(&right.metadata().id));
  667. Self { plugins }
  668. }
  669. #[must_use]
  670. pub fn plugins(&self) -> &[RegisteredPlugin] {
  671. &self.plugins
  672. }
  673. #[must_use]
  674. pub fn get(&self, plugin_id: &str) -> Option<&RegisteredPlugin> {
  675. self.plugins
  676. .iter()
  677. .find(|plugin| plugin.metadata().id == plugin_id)
  678. }
  679. #[must_use]
  680. pub fn contains(&self, plugin_id: &str) -> bool {
  681. self.get(plugin_id).is_some()
  682. }
  683. #[must_use]
  684. pub fn summaries(&self) -> Vec<PluginSummary> {
  685. self.plugins.iter().map(RegisteredPlugin::summary).collect()
  686. }
  687. pub fn aggregated_hooks(&self) -> Result<PluginHooks, PluginError> {
  688. self.plugins
  689. .iter()
  690. .filter(|plugin| plugin.is_enabled())
  691. .try_fold(PluginHooks::default(), |acc, plugin| {
  692. plugin.validate()?;
  693. Ok(acc.merged_with(plugin.hooks()))
  694. })
  695. }
  696. pub fn aggregated_tools(&self) -> Result<Vec<PluginTool>, PluginError> {
  697. let mut tools = Vec::new();
  698. let mut seen_names = BTreeMap::new();
  699. for plugin in self.plugins.iter().filter(|plugin| plugin.is_enabled()) {
  700. plugin.validate()?;
  701. for tool in plugin.tools() {
  702. if let Some(existing_plugin) =
  703. seen_names.insert(tool.definition().name.clone(), tool.plugin_id().to_string())
  704. {
  705. return Err(PluginError::InvalidManifest(format!(
  706. "plugin tool `{}` is defined by both `{existing_plugin}` and `{}`",
  707. tool.definition().name,
  708. tool.plugin_id()
  709. )));
  710. }
  711. tools.push(tool.clone());
  712. }
  713. }
  714. Ok(tools)
  715. }
  716. pub fn initialize(&self) -> Result<(), PluginError> {
  717. for plugin in self.plugins.iter().filter(|plugin| plugin.is_enabled()) {
  718. plugin.validate()?;
  719. plugin.initialize()?;
  720. }
  721. Ok(())
  722. }
  723. pub fn shutdown(&self) -> Result<(), PluginError> {
  724. for plugin in self
  725. .plugins
  726. .iter()
  727. .rev()
  728. .filter(|plugin| plugin.is_enabled())
  729. {
  730. plugin.shutdown()?;
  731. }
  732. Ok(())
  733. }
  734. }
  735. #[derive(Debug, Clone, PartialEq, Eq)]
  736. pub struct PluginManagerConfig {
  737. pub config_home: PathBuf,
  738. pub enabled_plugins: BTreeMap<String, bool>,
  739. pub external_dirs: Vec<PathBuf>,
  740. pub install_root: Option<PathBuf>,
  741. pub registry_path: Option<PathBuf>,
  742. pub bundled_root: Option<PathBuf>,
  743. }
  744. impl PluginManagerConfig {
  745. #[must_use]
  746. pub fn new(config_home: impl Into<PathBuf>) -> Self {
  747. Self {
  748. config_home: config_home.into(),
  749. enabled_plugins: BTreeMap::new(),
  750. external_dirs: Vec::new(),
  751. install_root: None,
  752. registry_path: None,
  753. bundled_root: None,
  754. }
  755. }
  756. }
  757. #[derive(Debug, Clone, PartialEq, Eq)]
  758. pub struct PluginManager {
  759. config: PluginManagerConfig,
  760. }
  761. #[derive(Debug, Clone, PartialEq, Eq)]
  762. pub struct InstallOutcome {
  763. pub plugin_id: String,
  764. pub version: String,
  765. pub install_path: PathBuf,
  766. }
  767. #[derive(Debug, Clone, PartialEq, Eq)]
  768. pub struct UpdateOutcome {
  769. pub plugin_id: String,
  770. pub old_version: String,
  771. pub new_version: String,
  772. pub install_path: PathBuf,
  773. }
  774. #[derive(Debug, Clone, PartialEq, Eq)]
  775. pub enum PluginManifestValidationError {
  776. EmptyField {
  777. field: &'static str,
  778. },
  779. EmptyEntryField {
  780. kind: &'static str,
  781. field: &'static str,
  782. name: Option<String>,
  783. },
  784. InvalidPermission {
  785. permission: String,
  786. },
  787. DuplicatePermission {
  788. permission: String,
  789. },
  790. DuplicateEntry {
  791. kind: &'static str,
  792. name: String,
  793. },
  794. MissingPath {
  795. kind: &'static str,
  796. path: PathBuf,
  797. },
  798. PathIsDirectory {
  799. kind: &'static str,
  800. path: PathBuf,
  801. },
  802. InvalidToolInputSchema {
  803. tool_name: String,
  804. },
  805. InvalidToolRequiredPermission {
  806. tool_name: String,
  807. permission: String,
  808. },
  809. }
  810. impl Display for PluginManifestValidationError {
  811. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  812. match self {
  813. Self::EmptyField { field } => {
  814. write!(f, "plugin manifest {field} cannot be empty")
  815. }
  816. Self::EmptyEntryField { kind, field, name } => match name {
  817. Some(name) if !name.is_empty() => {
  818. write!(f, "plugin {kind} `{name}` {field} cannot be empty")
  819. }
  820. _ => write!(f, "plugin {kind} {field} cannot be empty"),
  821. },
  822. Self::InvalidPermission { permission } => {
  823. write!(
  824. f,
  825. "plugin manifest permission `{permission}` must be one of read, write, or execute"
  826. )
  827. }
  828. Self::DuplicatePermission { permission } => {
  829. write!(f, "plugin manifest permission `{permission}` is duplicated")
  830. }
  831. Self::DuplicateEntry { kind, name } => {
  832. write!(f, "plugin {kind} `{name}` is duplicated")
  833. }
  834. Self::MissingPath { kind, path } => {
  835. write!(f, "{kind} path `{}` does not exist", path.display())
  836. }
  837. Self::PathIsDirectory { kind, path } => {
  838. write!(f, "{kind} path `{}` must point to a file", path.display())
  839. }
  840. Self::InvalidToolInputSchema { tool_name } => {
  841. write!(
  842. f,
  843. "plugin tool `{tool_name}` inputSchema must be a JSON object"
  844. )
  845. }
  846. Self::InvalidToolRequiredPermission {
  847. tool_name,
  848. permission,
  849. } => write!(
  850. f,
  851. "plugin tool `{tool_name}` requiredPermission `{permission}` must be read-only, workspace-write, or danger-full-access"
  852. ),
  853. }
  854. }
  855. }
  856. #[derive(Debug)]
  857. pub enum PluginError {
  858. Io(std::io::Error),
  859. Json(serde_json::Error),
  860. ManifestValidation(Vec<PluginManifestValidationError>),
  861. LoadFailures(Vec<PluginLoadFailure>),
  862. InvalidManifest(String),
  863. NotFound(String),
  864. CommandFailed(String),
  865. }
  866. impl Display for PluginError {
  867. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  868. match self {
  869. Self::Io(error) => write!(f, "{error}"),
  870. Self::Json(error) => write!(f, "{error}"),
  871. Self::ManifestValidation(errors) => {
  872. for (index, error) in errors.iter().enumerate() {
  873. if index > 0 {
  874. write!(f, "; ")?;
  875. }
  876. write!(f, "{error}")?;
  877. }
  878. Ok(())
  879. }
  880. Self::LoadFailures(failures) => {
  881. for (index, failure) in failures.iter().enumerate() {
  882. if index > 0 {
  883. write!(f, "; ")?;
  884. }
  885. write!(f, "{failure}")?;
  886. }
  887. Ok(())
  888. }
  889. Self::InvalidManifest(message)
  890. | Self::NotFound(message)
  891. | Self::CommandFailed(message) => write!(f, "{message}"),
  892. }
  893. }
  894. }
  895. impl std::error::Error for PluginError {}
  896. impl From<std::io::Error> for PluginError {
  897. fn from(value: std::io::Error) -> Self {
  898. Self::Io(value)
  899. }
  900. }
  901. impl From<serde_json::Error> for PluginError {
  902. fn from(value: serde_json::Error) -> Self {
  903. Self::Json(value)
  904. }
  905. }
  906. impl PluginManager {
  907. #[must_use]
  908. pub fn new(config: PluginManagerConfig) -> Self {
  909. Self { config }
  910. }
  911. #[must_use]
  912. pub fn bundled_root() -> PathBuf {
  913. PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("bundled")
  914. }
  915. #[must_use]
  916. pub fn install_root(&self) -> PathBuf {
  917. self.config
  918. .install_root
  919. .clone()
  920. .unwrap_or_else(|| self.config.config_home.join("plugins").join("installed"))
  921. }
  922. #[must_use]
  923. pub fn registry_path(&self) -> PathBuf {
  924. self.config.registry_path.clone().unwrap_or_else(|| {
  925. self.config
  926. .config_home
  927. .join("plugins")
  928. .join(REGISTRY_FILE_NAME)
  929. })
  930. }
  931. #[must_use]
  932. pub fn settings_path(&self) -> PathBuf {
  933. self.config.config_home.join(SETTINGS_FILE_NAME)
  934. }
  935. pub fn plugin_registry(&self) -> Result<PluginRegistry, PluginError> {
  936. self.plugin_registry_report()?.into_registry()
  937. }
  938. pub fn plugin_registry_report(&self) -> Result<PluginRegistryReport, PluginError> {
  939. self.sync_bundled_plugins()?;
  940. let mut discovery = PluginDiscovery::default();
  941. discovery.plugins.extend(builtin_plugins());
  942. let installed = self.discover_installed_plugins_with_failures()?;
  943. discovery.extend(installed);
  944. let external =
  945. self.discover_external_directory_plugins_with_failures(&discovery.plugins)?;
  946. discovery.extend(external);
  947. Ok(self.build_registry_report(discovery))
  948. }
  949. pub fn list_plugins(&self) -> Result<Vec<PluginSummary>, PluginError> {
  950. Ok(self.plugin_registry()?.summaries())
  951. }
  952. pub fn list_installed_plugins(&self) -> Result<Vec<PluginSummary>, PluginError> {
  953. Ok(self.installed_plugin_registry()?.summaries())
  954. }
  955. pub fn discover_plugins(&self) -> Result<Vec<PluginDefinition>, PluginError> {
  956. Ok(self
  957. .plugin_registry()?
  958. .plugins
  959. .into_iter()
  960. .map(|plugin| plugin.definition)
  961. .collect())
  962. }
  963. pub fn aggregated_hooks(&self) -> Result<PluginHooks, PluginError> {
  964. self.plugin_registry()?.aggregated_hooks()
  965. }
  966. pub fn aggregated_tools(&self) -> Result<Vec<PluginTool>, PluginError> {
  967. self.plugin_registry()?.aggregated_tools()
  968. }
  969. pub fn validate_plugin_source(&self, source: &str) -> Result<PluginManifest, PluginError> {
  970. let path = resolve_local_source(source)?;
  971. load_plugin_from_directory(&path)
  972. }
  973. pub fn install(&mut self, source: &str) -> Result<InstallOutcome, PluginError> {
  974. let install_source = parse_install_source(source)?;
  975. let temp_root = self.install_root().join(".tmp");
  976. let staged_source = materialize_source(&install_source, &temp_root)?;
  977. let cleanup_source = matches!(install_source, PluginInstallSource::GitUrl { .. });
  978. let manifest = load_plugin_from_directory(&staged_source)?;
  979. let plugin_id = plugin_id(&manifest.name, EXTERNAL_MARKETPLACE);
  980. let install_path = self.install_root().join(sanitize_plugin_id(&plugin_id));
  981. if install_path.exists() {
  982. fs::remove_dir_all(&install_path)?;
  983. }
  984. copy_dir_all(&staged_source, &install_path)?;
  985. if cleanup_source {
  986. let _ = fs::remove_dir_all(&staged_source);
  987. }
  988. let now = unix_time_ms();
  989. let record = InstalledPluginRecord {
  990. kind: PluginKind::External,
  991. id: plugin_id.clone(),
  992. name: manifest.name,
  993. version: manifest.version.clone(),
  994. description: manifest.description,
  995. install_path: install_path.clone(),
  996. source: install_source,
  997. installed_at_unix_ms: now,
  998. updated_at_unix_ms: now,
  999. };
  1000. let mut registry = self.load_registry()?;
  1001. registry.plugins.insert(plugin_id.clone(), record);
  1002. self.store_registry(&registry)?;
  1003. self.write_enabled_state(&plugin_id, Some(true))?;
  1004. self.config.enabled_plugins.insert(plugin_id.clone(), true);
  1005. Ok(InstallOutcome {
  1006. plugin_id,
  1007. version: manifest.version,
  1008. install_path,
  1009. })
  1010. }
  1011. pub fn enable(&mut self, plugin_id: &str) -> Result<(), PluginError> {
  1012. self.ensure_known_plugin(plugin_id)?;
  1013. self.write_enabled_state(plugin_id, Some(true))?;
  1014. self.config
  1015. .enabled_plugins
  1016. .insert(plugin_id.to_string(), true);
  1017. Ok(())
  1018. }
  1019. pub fn disable(&mut self, plugin_id: &str) -> Result<(), PluginError> {
  1020. self.ensure_known_plugin(plugin_id)?;
  1021. self.write_enabled_state(plugin_id, Some(false))?;
  1022. self.config
  1023. .enabled_plugins
  1024. .insert(plugin_id.to_string(), false);
  1025. Ok(())
  1026. }
  1027. pub fn uninstall(&mut self, plugin_id: &str) -> Result<(), PluginError> {
  1028. let mut registry = self.load_registry()?;
  1029. let record = registry.plugins.remove(plugin_id).ok_or_else(|| {
  1030. PluginError::NotFound(format!("plugin `{plugin_id}` is not installed"))
  1031. })?;
  1032. if record.kind == PluginKind::Bundled {
  1033. registry.plugins.insert(plugin_id.to_string(), record);
  1034. return Err(PluginError::CommandFailed(format!(
  1035. "plugin `{plugin_id}` is bundled and managed automatically; disable it instead"
  1036. )));
  1037. }
  1038. if record.install_path.exists() {
  1039. fs::remove_dir_all(&record.install_path)?;
  1040. }
  1041. self.store_registry(&registry)?;
  1042. self.write_enabled_state(plugin_id, None)?;
  1043. self.config.enabled_plugins.remove(plugin_id);
  1044. Ok(())
  1045. }
  1046. pub fn update(&mut self, plugin_id: &str) -> Result<UpdateOutcome, PluginError> {
  1047. let mut registry = self.load_registry()?;
  1048. let record = registry.plugins.get(plugin_id).cloned().ok_or_else(|| {
  1049. PluginError::NotFound(format!("plugin `{plugin_id}` is not installed"))
  1050. })?;
  1051. let temp_root = self.install_root().join(".tmp");
  1052. let staged_source = materialize_source(&record.source, &temp_root)?;
  1053. let cleanup_source = matches!(record.source, PluginInstallSource::GitUrl { .. });
  1054. let manifest = load_plugin_from_directory(&staged_source)?;
  1055. if record.install_path.exists() {
  1056. fs::remove_dir_all(&record.install_path)?;
  1057. }
  1058. copy_dir_all(&staged_source, &record.install_path)?;
  1059. if cleanup_source {
  1060. let _ = fs::remove_dir_all(&staged_source);
  1061. }
  1062. let updated_record = InstalledPluginRecord {
  1063. version: manifest.version.clone(),
  1064. description: manifest.description,
  1065. updated_at_unix_ms: unix_time_ms(),
  1066. ..record.clone()
  1067. };
  1068. registry
  1069. .plugins
  1070. .insert(plugin_id.to_string(), updated_record);
  1071. self.store_registry(&registry)?;
  1072. Ok(UpdateOutcome {
  1073. plugin_id: plugin_id.to_string(),
  1074. old_version: record.version,
  1075. new_version: manifest.version,
  1076. install_path: record.install_path,
  1077. })
  1078. }
  1079. fn discover_installed_plugins_with_failures(&self) -> Result<PluginDiscovery, PluginError> {
  1080. let mut registry = self.load_registry()?;
  1081. let mut discovery = PluginDiscovery::default();
  1082. let mut seen_ids = BTreeSet::<String>::new();
  1083. let mut seen_paths = BTreeSet::<PathBuf>::new();
  1084. let mut stale_registry_ids = Vec::new();
  1085. for install_path in discover_plugin_dirs(&self.install_root())? {
  1086. let matched_record = registry
  1087. .plugins
  1088. .values()
  1089. .find(|record| record.install_path == install_path);
  1090. let kind = matched_record.map_or(PluginKind::External, |record| record.kind);
  1091. let source = matched_record.map_or_else(
  1092. || install_path.display().to_string(),
  1093. |record| describe_install_source(&record.source),
  1094. );
  1095. match load_plugin_definition(&install_path, kind, source.clone(), kind.marketplace()) {
  1096. Ok(plugin) => {
  1097. if seen_ids.insert(plugin.metadata().id.clone()) {
  1098. seen_paths.insert(install_path);
  1099. discovery.push_plugin(plugin);
  1100. }
  1101. }
  1102. Err(error) => {
  1103. discovery.push_failure(PluginLoadFailure::new(
  1104. install_path,
  1105. kind,
  1106. source,
  1107. error,
  1108. ));
  1109. }
  1110. }
  1111. }
  1112. for record in registry.plugins.values() {
  1113. if seen_paths.contains(&record.install_path) {
  1114. continue;
  1115. }
  1116. if !record.install_path.exists() || plugin_manifest_path(&record.install_path).is_err()
  1117. {
  1118. stale_registry_ids.push(record.id.clone());
  1119. continue;
  1120. }
  1121. let source = describe_install_source(&record.source);
  1122. match load_plugin_definition(
  1123. &record.install_path,
  1124. record.kind,
  1125. source.clone(),
  1126. record.kind.marketplace(),
  1127. ) {
  1128. Ok(plugin) => {
  1129. if seen_ids.insert(plugin.metadata().id.clone()) {
  1130. seen_paths.insert(record.install_path.clone());
  1131. discovery.push_plugin(plugin);
  1132. }
  1133. }
  1134. Err(error) => {
  1135. discovery.push_failure(PluginLoadFailure::new(
  1136. record.install_path.clone(),
  1137. record.kind,
  1138. source,
  1139. error,
  1140. ));
  1141. }
  1142. }
  1143. }
  1144. if !stale_registry_ids.is_empty() {
  1145. for plugin_id in stale_registry_ids {
  1146. registry.plugins.remove(&plugin_id);
  1147. }
  1148. self.store_registry(&registry)?;
  1149. }
  1150. Ok(discovery)
  1151. }
  1152. fn discover_external_directory_plugins_with_failures(
  1153. &self,
  1154. existing_plugins: &[PluginDefinition],
  1155. ) -> Result<PluginDiscovery, PluginError> {
  1156. let mut discovery = PluginDiscovery::default();
  1157. for directory in &self.config.external_dirs {
  1158. for root in discover_plugin_dirs(directory)? {
  1159. let source = root.display().to_string();
  1160. match load_plugin_definition(
  1161. &root,
  1162. PluginKind::External,
  1163. source.clone(),
  1164. EXTERNAL_MARKETPLACE,
  1165. ) {
  1166. Ok(plugin) => {
  1167. if existing_plugins
  1168. .iter()
  1169. .chain(discovery.plugins.iter())
  1170. .all(|existing| existing.metadata().id != plugin.metadata().id)
  1171. {
  1172. discovery.push_plugin(plugin);
  1173. }
  1174. }
  1175. Err(error) => {
  1176. discovery.push_failure(PluginLoadFailure::new(
  1177. root,
  1178. PluginKind::External,
  1179. source,
  1180. error,
  1181. ));
  1182. }
  1183. }
  1184. }
  1185. }
  1186. Ok(discovery)
  1187. }
  1188. pub fn installed_plugin_registry_report(&self) -> Result<PluginRegistryReport, PluginError> {
  1189. self.sync_bundled_plugins()?;
  1190. Ok(self.build_registry_report(self.discover_installed_plugins_with_failures()?))
  1191. }
  1192. fn sync_bundled_plugins(&self) -> Result<(), PluginError> {
  1193. let bundled_root = self
  1194. .config
  1195. .bundled_root
  1196. .clone()
  1197. .unwrap_or_else(Self::bundled_root);
  1198. let bundled_plugins = discover_plugin_dirs(&bundled_root)?;
  1199. let mut registry = self.load_registry()?;
  1200. let mut changed = false;
  1201. let install_root = self.install_root();
  1202. let mut active_bundled_ids = BTreeSet::new();
  1203. for source_root in bundled_plugins {
  1204. let manifest = load_plugin_from_directory(&source_root)?;
  1205. let plugin_id = plugin_id(&manifest.name, BUNDLED_MARKETPLACE);
  1206. active_bundled_ids.insert(plugin_id.clone());
  1207. let install_path = install_root.join(sanitize_plugin_id(&plugin_id));
  1208. let now = unix_time_ms();
  1209. let existing_record = registry.plugins.get(&plugin_id);
  1210. let installed_copy_is_valid =
  1211. install_path.exists() && load_plugin_from_directory(&install_path).is_ok();
  1212. let needs_sync = existing_record.is_none_or(|record| {
  1213. record.kind != PluginKind::Bundled
  1214. || record.version != manifest.version
  1215. || record.name != manifest.name
  1216. || record.description != manifest.description
  1217. || record.install_path != install_path
  1218. || !record.install_path.exists()
  1219. || !installed_copy_is_valid
  1220. });
  1221. if !needs_sync {
  1222. continue;
  1223. }
  1224. if install_path.exists() {
  1225. fs::remove_dir_all(&install_path)?;
  1226. }
  1227. copy_dir_all(&source_root, &install_path)?;
  1228. let installed_at_unix_ms =
  1229. existing_record.map_or(now, |record| record.installed_at_unix_ms);
  1230. registry.plugins.insert(
  1231. plugin_id.clone(),
  1232. InstalledPluginRecord {
  1233. kind: PluginKind::Bundled,
  1234. id: plugin_id,
  1235. name: manifest.name,
  1236. version: manifest.version,
  1237. description: manifest.description,
  1238. install_path,
  1239. source: PluginInstallSource::LocalPath { path: source_root },
  1240. installed_at_unix_ms,
  1241. updated_at_unix_ms: now,
  1242. },
  1243. );
  1244. changed = true;
  1245. }
  1246. let stale_bundled_ids = registry
  1247. .plugins
  1248. .iter()
  1249. .filter_map(|(plugin_id, record)| {
  1250. (record.kind == PluginKind::Bundled && !active_bundled_ids.contains(plugin_id))
  1251. .then_some(plugin_id.clone())
  1252. })
  1253. .collect::<Vec<_>>();
  1254. for plugin_id in stale_bundled_ids {
  1255. if let Some(record) = registry.plugins.remove(&plugin_id) {
  1256. if record.install_path.exists() {
  1257. fs::remove_dir_all(&record.install_path)?;
  1258. }
  1259. changed = true;
  1260. }
  1261. }
  1262. if changed {
  1263. self.store_registry(&registry)?;
  1264. }
  1265. Ok(())
  1266. }
  1267. fn is_enabled(&self, metadata: &PluginMetadata) -> bool {
  1268. self.config
  1269. .enabled_plugins
  1270. .get(&metadata.id)
  1271. .copied()
  1272. .unwrap_or(match metadata.kind {
  1273. PluginKind::External => false,
  1274. PluginKind::Builtin | PluginKind::Bundled => metadata.default_enabled,
  1275. })
  1276. }
  1277. fn ensure_known_plugin(&self, plugin_id: &str) -> Result<(), PluginError> {
  1278. if self.plugin_registry()?.contains(plugin_id) {
  1279. Ok(())
  1280. } else {
  1281. Err(PluginError::NotFound(format!(
  1282. "plugin `{plugin_id}` is not installed or discoverable"
  1283. )))
  1284. }
  1285. }
  1286. fn load_registry(&self) -> Result<InstalledPluginRegistry, PluginError> {
  1287. let path = self.registry_path();
  1288. match fs::read_to_string(&path) {
  1289. Ok(contents) if contents.trim().is_empty() => Ok(InstalledPluginRegistry::default()),
  1290. Ok(contents) => Ok(serde_json::from_str(&contents)?),
  1291. Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
  1292. Ok(InstalledPluginRegistry::default())
  1293. }
  1294. Err(error) => Err(PluginError::Io(error)),
  1295. }
  1296. }
  1297. fn store_registry(&self, registry: &InstalledPluginRegistry) -> Result<(), PluginError> {
  1298. let path = self.registry_path();
  1299. if let Some(parent) = path.parent() {
  1300. fs::create_dir_all(parent)?;
  1301. }
  1302. fs::write(path, serde_json::to_string_pretty(registry)?)?;
  1303. Ok(())
  1304. }
  1305. fn write_enabled_state(
  1306. &self,
  1307. plugin_id: &str,
  1308. enabled: Option<bool>,
  1309. ) -> Result<(), PluginError> {
  1310. update_settings_json(&self.settings_path(), |root| {
  1311. let enabled_plugins = ensure_object(root, "enabledPlugins");
  1312. match enabled {
  1313. Some(value) => {
  1314. enabled_plugins.insert(plugin_id.to_string(), Value::Bool(value));
  1315. }
  1316. None => {
  1317. enabled_plugins.remove(plugin_id);
  1318. }
  1319. }
  1320. })
  1321. }
  1322. fn installed_plugin_registry(&self) -> Result<PluginRegistry, PluginError> {
  1323. self.installed_plugin_registry_report()?.into_registry()
  1324. }
  1325. fn build_registry_report(&self, discovery: PluginDiscovery) -> PluginRegistryReport {
  1326. PluginRegistryReport::new(
  1327. PluginRegistry::new(
  1328. discovery
  1329. .plugins
  1330. .into_iter()
  1331. .map(|plugin| {
  1332. let enabled = self.is_enabled(plugin.metadata());
  1333. RegisteredPlugin::new(plugin, enabled)
  1334. })
  1335. .collect(),
  1336. ),
  1337. discovery.failures,
  1338. )
  1339. }
  1340. }
  1341. #[must_use]
  1342. pub fn builtin_plugins() -> Vec<PluginDefinition> {
  1343. vec![PluginDefinition::Builtin(BuiltinPlugin {
  1344. metadata: PluginMetadata {
  1345. id: plugin_id("example-builtin", BUILTIN_MARKETPLACE),
  1346. name: "example-builtin".to_string(),
  1347. version: "0.1.0".to_string(),
  1348. description: "Example built-in plugin scaffold for the Rust plugin system".to_string(),
  1349. kind: PluginKind::Builtin,
  1350. source: BUILTIN_MARKETPLACE.to_string(),
  1351. default_enabled: false,
  1352. root: None,
  1353. },
  1354. hooks: PluginHooks::default(),
  1355. lifecycle: PluginLifecycle::default(),
  1356. tools: Vec::new(),
  1357. })]
  1358. }
  1359. fn load_plugin_definition(
  1360. root: &Path,
  1361. kind: PluginKind,
  1362. source: String,
  1363. marketplace: &str,
  1364. ) -> Result<PluginDefinition, PluginError> {
  1365. let manifest = load_plugin_from_directory(root)?;
  1366. let metadata = PluginMetadata {
  1367. id: plugin_id(&manifest.name, marketplace),
  1368. name: manifest.name,
  1369. version: manifest.version,
  1370. description: manifest.description,
  1371. kind,
  1372. source,
  1373. default_enabled: manifest.default_enabled,
  1374. root: Some(root.to_path_buf()),
  1375. };
  1376. let hooks = resolve_hooks(root, &manifest.hooks);
  1377. let lifecycle = resolve_lifecycle(root, &manifest.lifecycle);
  1378. let tools = resolve_tools(root, &metadata.id, &metadata.name, &manifest.tools);
  1379. Ok(match kind {
  1380. PluginKind::Builtin => PluginDefinition::Builtin(BuiltinPlugin {
  1381. metadata,
  1382. hooks,
  1383. lifecycle,
  1384. tools,
  1385. }),
  1386. PluginKind::Bundled => PluginDefinition::Bundled(BundledPlugin {
  1387. metadata,
  1388. hooks,
  1389. lifecycle,
  1390. tools,
  1391. }),
  1392. PluginKind::External => PluginDefinition::External(ExternalPlugin {
  1393. metadata,
  1394. hooks,
  1395. lifecycle,
  1396. tools,
  1397. }),
  1398. })
  1399. }
  1400. pub fn load_plugin_from_directory(root: &Path) -> Result<PluginManifest, PluginError> {
  1401. load_manifest_from_directory(root)
  1402. }
  1403. fn load_manifest_from_directory(root: &Path) -> Result<PluginManifest, PluginError> {
  1404. let manifest_path = plugin_manifest_path(root)?;
  1405. load_manifest_from_path(root, &manifest_path)
  1406. }
  1407. fn load_manifest_from_path(
  1408. root: &Path,
  1409. manifest_path: &Path,
  1410. ) -> Result<PluginManifest, PluginError> {
  1411. let contents = fs::read_to_string(manifest_path).map_err(|error| {
  1412. PluginError::NotFound(format!(
  1413. "plugin manifest not found at {}: {error}",
  1414. manifest_path.display()
  1415. ))
  1416. })?;
  1417. let raw_manifest: RawPluginManifest = serde_json::from_str(&contents)?;
  1418. build_plugin_manifest(root, raw_manifest)
  1419. }
  1420. fn plugin_manifest_path(root: &Path) -> Result<PathBuf, PluginError> {
  1421. let direct_path = root.join(MANIFEST_FILE_NAME);
  1422. if direct_path.exists() {
  1423. return Ok(direct_path);
  1424. }
  1425. let packaged_path = root.join(MANIFEST_RELATIVE_PATH);
  1426. if packaged_path.exists() {
  1427. return Ok(packaged_path);
  1428. }
  1429. Err(PluginError::NotFound(format!(
  1430. "plugin manifest not found at {} or {}",
  1431. direct_path.display(),
  1432. packaged_path.display()
  1433. )))
  1434. }
  1435. fn build_plugin_manifest(
  1436. root: &Path,
  1437. raw: RawPluginManifest,
  1438. ) -> Result<PluginManifest, PluginError> {
  1439. let mut errors = Vec::new();
  1440. validate_required_manifest_field("name", &raw.name, &mut errors);
  1441. validate_required_manifest_field("version", &raw.version, &mut errors);
  1442. validate_required_manifest_field("description", &raw.description, &mut errors);
  1443. let permissions = build_manifest_permissions(&raw.permissions, &mut errors);
  1444. validate_command_entries(root, raw.hooks.pre_tool_use.iter(), "hook", &mut errors);
  1445. validate_command_entries(root, raw.hooks.post_tool_use.iter(), "hook", &mut errors);
  1446. validate_command_entries(
  1447. root,
  1448. raw.hooks.post_tool_use_failure.iter(),
  1449. "hook",
  1450. &mut errors,
  1451. );
  1452. validate_command_entries(
  1453. root,
  1454. raw.lifecycle.init.iter(),
  1455. "lifecycle command",
  1456. &mut errors,
  1457. );
  1458. validate_command_entries(
  1459. root,
  1460. raw.lifecycle.shutdown.iter(),
  1461. "lifecycle command",
  1462. &mut errors,
  1463. );
  1464. let tools = build_manifest_tools(root, raw.tools, &mut errors);
  1465. let commands = build_manifest_commands(root, raw.commands, &mut errors);
  1466. if !errors.is_empty() {
  1467. return Err(PluginError::ManifestValidation(errors));
  1468. }
  1469. Ok(PluginManifest {
  1470. name: raw.name,
  1471. version: raw.version,
  1472. description: raw.description,
  1473. permissions,
  1474. default_enabled: raw.default_enabled,
  1475. hooks: raw.hooks,
  1476. lifecycle: raw.lifecycle,
  1477. tools,
  1478. commands,
  1479. })
  1480. }
  1481. fn validate_required_manifest_field(
  1482. field: &'static str,
  1483. value: &str,
  1484. errors: &mut Vec<PluginManifestValidationError>,
  1485. ) {
  1486. if value.trim().is_empty() {
  1487. errors.push(PluginManifestValidationError::EmptyField { field });
  1488. }
  1489. }
  1490. fn build_manifest_permissions(
  1491. permissions: &[String],
  1492. errors: &mut Vec<PluginManifestValidationError>,
  1493. ) -> Vec<PluginPermission> {
  1494. let mut seen = BTreeSet::new();
  1495. let mut validated = Vec::new();
  1496. for permission in permissions {
  1497. let permission = permission.trim();
  1498. if permission.is_empty() {
  1499. errors.push(PluginManifestValidationError::EmptyEntryField {
  1500. kind: "permission",
  1501. field: "value",
  1502. name: None,
  1503. });
  1504. continue;
  1505. }
  1506. if !seen.insert(permission.to_string()) {
  1507. errors.push(PluginManifestValidationError::DuplicatePermission {
  1508. permission: permission.to_string(),
  1509. });
  1510. continue;
  1511. }
  1512. match PluginPermission::parse(permission) {
  1513. Some(permission) => validated.push(permission),
  1514. None => errors.push(PluginManifestValidationError::InvalidPermission {
  1515. permission: permission.to_string(),
  1516. }),
  1517. }
  1518. }
  1519. validated
  1520. }
  1521. fn build_manifest_tools(
  1522. root: &Path,
  1523. tools: Vec<RawPluginToolManifest>,
  1524. errors: &mut Vec<PluginManifestValidationError>,
  1525. ) -> Vec<PluginToolManifest> {
  1526. let mut seen = BTreeSet::new();
  1527. let mut validated = Vec::new();
  1528. for tool in tools {
  1529. let name = tool.name.trim().to_string();
  1530. if name.is_empty() {
  1531. errors.push(PluginManifestValidationError::EmptyEntryField {
  1532. kind: "tool",
  1533. field: "name",
  1534. name: None,
  1535. });
  1536. continue;
  1537. }
  1538. if !seen.insert(name.clone()) {
  1539. errors.push(PluginManifestValidationError::DuplicateEntry { kind: "tool", name });
  1540. continue;
  1541. }
  1542. if tool.description.trim().is_empty() {
  1543. errors.push(PluginManifestValidationError::EmptyEntryField {
  1544. kind: "tool",
  1545. field: "description",
  1546. name: Some(name.clone()),
  1547. });
  1548. }
  1549. if tool.command.trim().is_empty() {
  1550. errors.push(PluginManifestValidationError::EmptyEntryField {
  1551. kind: "tool",
  1552. field: "command",
  1553. name: Some(name.clone()),
  1554. });
  1555. } else {
  1556. validate_command_entry(root, &tool.command, "tool", errors);
  1557. }
  1558. if !tool.input_schema.is_object() {
  1559. errors.push(PluginManifestValidationError::InvalidToolInputSchema {
  1560. tool_name: name.clone(),
  1561. });
  1562. }
  1563. let Some(required_permission) =
  1564. PluginToolPermission::parse(tool.required_permission.trim())
  1565. else {
  1566. errors.push(
  1567. PluginManifestValidationError::InvalidToolRequiredPermission {
  1568. tool_name: name.clone(),
  1569. permission: tool.required_permission.trim().to_string(),
  1570. },
  1571. );
  1572. continue;
  1573. };
  1574. validated.push(PluginToolManifest {
  1575. name,
  1576. description: tool.description,
  1577. input_schema: tool.input_schema,
  1578. command: tool.command,
  1579. args: tool.args,
  1580. required_permission,
  1581. });
  1582. }
  1583. validated
  1584. }
  1585. fn build_manifest_commands(
  1586. root: &Path,
  1587. commands: Vec<PluginCommandManifest>,
  1588. errors: &mut Vec<PluginManifestValidationError>,
  1589. ) -> Vec<PluginCommandManifest> {
  1590. let mut seen = BTreeSet::new();
  1591. let mut validated = Vec::new();
  1592. for command in commands {
  1593. let name = command.name.trim().to_string();
  1594. if name.is_empty() {
  1595. errors.push(PluginManifestValidationError::EmptyEntryField {
  1596. kind: "command",
  1597. field: "name",
  1598. name: None,
  1599. });
  1600. continue;
  1601. }
  1602. if !seen.insert(name.clone()) {
  1603. errors.push(PluginManifestValidationError::DuplicateEntry {
  1604. kind: "command",
  1605. name,
  1606. });
  1607. continue;
  1608. }
  1609. if command.description.trim().is_empty() {
  1610. errors.push(PluginManifestValidationError::EmptyEntryField {
  1611. kind: "command",
  1612. field: "description",
  1613. name: Some(name.clone()),
  1614. });
  1615. }
  1616. if command.command.trim().is_empty() {
  1617. errors.push(PluginManifestValidationError::EmptyEntryField {
  1618. kind: "command",
  1619. field: "command",
  1620. name: Some(name.clone()),
  1621. });
  1622. } else {
  1623. validate_command_entry(root, &command.command, "command", errors);
  1624. }
  1625. validated.push(command);
  1626. }
  1627. validated
  1628. }
  1629. fn validate_command_entries<'a>(
  1630. root: &Path,
  1631. entries: impl Iterator<Item = &'a String>,
  1632. kind: &'static str,
  1633. errors: &mut Vec<PluginManifestValidationError>,
  1634. ) {
  1635. for entry in entries {
  1636. validate_command_entry(root, entry, kind, errors);
  1637. }
  1638. }
  1639. fn validate_command_entry(
  1640. root: &Path,
  1641. entry: &str,
  1642. kind: &'static str,
  1643. errors: &mut Vec<PluginManifestValidationError>,
  1644. ) {
  1645. if entry.trim().is_empty() {
  1646. errors.push(PluginManifestValidationError::EmptyEntryField {
  1647. kind,
  1648. field: "command",
  1649. name: None,
  1650. });
  1651. return;
  1652. }
  1653. if is_literal_command(entry) {
  1654. return;
  1655. }
  1656. let path = if Path::new(entry).is_absolute() {
  1657. PathBuf::from(entry)
  1658. } else {
  1659. root.join(entry)
  1660. };
  1661. if !path.exists() {
  1662. errors.push(PluginManifestValidationError::MissingPath { kind, path });
  1663. } else if !path.is_file() {
  1664. errors.push(PluginManifestValidationError::PathIsDirectory { kind, path });
  1665. }
  1666. }
  1667. fn resolve_hooks(root: &Path, hooks: &PluginHooks) -> PluginHooks {
  1668. PluginHooks {
  1669. pre_tool_use: hooks
  1670. .pre_tool_use
  1671. .iter()
  1672. .map(|entry| resolve_hook_entry(root, entry))
  1673. .collect(),
  1674. post_tool_use: hooks
  1675. .post_tool_use
  1676. .iter()
  1677. .map(|entry| resolve_hook_entry(root, entry))
  1678. .collect(),
  1679. post_tool_use_failure: hooks
  1680. .post_tool_use_failure
  1681. .iter()
  1682. .map(|entry| resolve_hook_entry(root, entry))
  1683. .collect(),
  1684. }
  1685. }
  1686. fn resolve_lifecycle(root: &Path, lifecycle: &PluginLifecycle) -> PluginLifecycle {
  1687. PluginLifecycle {
  1688. init: lifecycle
  1689. .init
  1690. .iter()
  1691. .map(|entry| resolve_hook_entry(root, entry))
  1692. .collect(),
  1693. shutdown: lifecycle
  1694. .shutdown
  1695. .iter()
  1696. .map(|entry| resolve_hook_entry(root, entry))
  1697. .collect(),
  1698. }
  1699. }
  1700. fn resolve_tools(
  1701. root: &Path,
  1702. plugin_id: &str,
  1703. plugin_name: &str,
  1704. tools: &[PluginToolManifest],
  1705. ) -> Vec<PluginTool> {
  1706. tools
  1707. .iter()
  1708. .map(|tool| {
  1709. PluginTool::new(
  1710. plugin_id,
  1711. plugin_name,
  1712. PluginToolDefinition {
  1713. name: tool.name.clone(),
  1714. description: Some(tool.description.clone()),
  1715. input_schema: tool.input_schema.clone(),
  1716. },
  1717. resolve_hook_entry(root, &tool.command),
  1718. tool.args.clone(),
  1719. tool.required_permission,
  1720. Some(root.to_path_buf()),
  1721. )
  1722. })
  1723. .collect()
  1724. }
  1725. fn validate_hook_paths(root: Option<&Path>, hooks: &PluginHooks) -> Result<(), PluginError> {
  1726. let Some(root) = root else {
  1727. return Ok(());
  1728. };
  1729. for entry in hooks
  1730. .pre_tool_use
  1731. .iter()
  1732. .chain(hooks.post_tool_use.iter())
  1733. .chain(hooks.post_tool_use_failure.iter())
  1734. {
  1735. validate_command_path(root, entry, "hook")?;
  1736. }
  1737. Ok(())
  1738. }
  1739. fn validate_lifecycle_paths(
  1740. root: Option<&Path>,
  1741. lifecycle: &PluginLifecycle,
  1742. ) -> Result<(), PluginError> {
  1743. let Some(root) = root else {
  1744. return Ok(());
  1745. };
  1746. for entry in lifecycle.init.iter().chain(lifecycle.shutdown.iter()) {
  1747. validate_command_path(root, entry, "lifecycle command")?;
  1748. }
  1749. Ok(())
  1750. }
  1751. fn validate_tool_paths(root: Option<&Path>, tools: &[PluginTool]) -> Result<(), PluginError> {
  1752. let Some(root) = root else {
  1753. return Ok(());
  1754. };
  1755. for tool in tools {
  1756. validate_command_path(root, &tool.command, "tool")?;
  1757. }
  1758. Ok(())
  1759. }
  1760. fn validate_command_path(root: &Path, entry: &str, kind: &str) -> Result<(), PluginError> {
  1761. if is_literal_command(entry) {
  1762. return Ok(());
  1763. }
  1764. let path = if Path::new(entry).is_absolute() {
  1765. PathBuf::from(entry)
  1766. } else {
  1767. root.join(entry)
  1768. };
  1769. if !path.exists() {
  1770. return Err(PluginError::InvalidManifest(format!(
  1771. "{kind} path `{}` does not exist",
  1772. path.display()
  1773. )));
  1774. }
  1775. if !path.is_file() {
  1776. return Err(PluginError::InvalidManifest(format!(
  1777. "{kind} path `{}` must point to a file",
  1778. path.display()
  1779. )));
  1780. }
  1781. Ok(())
  1782. }
  1783. fn resolve_hook_entry(root: &Path, entry: &str) -> String {
  1784. if is_literal_command(entry) {
  1785. entry.to_string()
  1786. } else {
  1787. root.join(entry).display().to_string()
  1788. }
  1789. }
  1790. fn is_literal_command(entry: &str) -> bool {
  1791. !entry.starts_with("./") && !entry.starts_with("../") && !Path::new(entry).is_absolute()
  1792. }
  1793. fn run_lifecycle_commands(
  1794. metadata: &PluginMetadata,
  1795. lifecycle: &PluginLifecycle,
  1796. phase: &str,
  1797. commands: &[String],
  1798. ) -> Result<(), PluginError> {
  1799. if lifecycle.is_empty() || commands.is_empty() {
  1800. return Ok(());
  1801. }
  1802. for command in commands {
  1803. let mut process = if Path::new(command).exists() {
  1804. if cfg!(windows) {
  1805. let mut process = Command::new("cmd");
  1806. process.arg("/C").arg(command);
  1807. process
  1808. } else {
  1809. let mut process = Command::new("sh");
  1810. process.arg(command);
  1811. process
  1812. }
  1813. } else if cfg!(windows) {
  1814. let mut process = Command::new("cmd");
  1815. process.arg("/C").arg(command);
  1816. process
  1817. } else {
  1818. let mut process = Command::new("sh");
  1819. process.arg("-lc").arg(command);
  1820. process
  1821. };
  1822. if let Some(root) = &metadata.root {
  1823. process.current_dir(root);
  1824. }
  1825. let output = process.output()?;
  1826. if !output.status.success() {
  1827. let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
  1828. return Err(PluginError::CommandFailed(format!(
  1829. "plugin `{}` {} failed for `{}`: {}",
  1830. metadata.id,
  1831. phase,
  1832. command,
  1833. if stderr.is_empty() {
  1834. format!("exit status {}", output.status)
  1835. } else {
  1836. stderr
  1837. }
  1838. )));
  1839. }
  1840. }
  1841. Ok(())
  1842. }
  1843. fn resolve_local_source(source: &str) -> Result<PathBuf, PluginError> {
  1844. let path = PathBuf::from(source);
  1845. if path.exists() {
  1846. Ok(path)
  1847. } else {
  1848. Err(PluginError::NotFound(format!(
  1849. "plugin source `{source}` was not found"
  1850. )))
  1851. }
  1852. }
  1853. fn parse_install_source(source: &str) -> Result<PluginInstallSource, PluginError> {
  1854. if source.starts_with("http://")
  1855. || source.starts_with("https://")
  1856. || source.starts_with("git@")
  1857. || Path::new(source)
  1858. .extension()
  1859. .is_some_and(|extension| extension.eq_ignore_ascii_case("git"))
  1860. {
  1861. Ok(PluginInstallSource::GitUrl {
  1862. url: source.to_string(),
  1863. })
  1864. } else {
  1865. Ok(PluginInstallSource::LocalPath {
  1866. path: resolve_local_source(source)?,
  1867. })
  1868. }
  1869. }
  1870. fn materialize_source(
  1871. source: &PluginInstallSource,
  1872. temp_root: &Path,
  1873. ) -> Result<PathBuf, PluginError> {
  1874. fs::create_dir_all(temp_root)?;
  1875. match source {
  1876. PluginInstallSource::LocalPath { path } => Ok(path.clone()),
  1877. PluginInstallSource::GitUrl { url } => {
  1878. let destination = temp_root.join(format!("plugin-{}", unix_time_ms()));
  1879. let output = Command::new("git")
  1880. .arg("clone")
  1881. .arg("--depth")
  1882. .arg("1")
  1883. .arg(url)
  1884. .arg(&destination)
  1885. .output()?;
  1886. if !output.status.success() {
  1887. return Err(PluginError::CommandFailed(format!(
  1888. "git clone failed for `{url}`: {}",
  1889. String::from_utf8_lossy(&output.stderr).trim()
  1890. )));
  1891. }
  1892. Ok(destination)
  1893. }
  1894. }
  1895. }
  1896. fn discover_plugin_dirs(root: &Path) -> Result<Vec<PathBuf>, PluginError> {
  1897. match fs::read_dir(root) {
  1898. Ok(entries) => {
  1899. let mut paths = Vec::new();
  1900. for entry in entries {
  1901. let path = entry?.path();
  1902. if path.is_dir() && plugin_manifest_path(&path).is_ok() {
  1903. paths.push(path);
  1904. }
  1905. }
  1906. paths.sort();
  1907. Ok(paths)
  1908. }
  1909. Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
  1910. Err(error) => Err(PluginError::Io(error)),
  1911. }
  1912. }
  1913. fn plugin_id(name: &str, marketplace: &str) -> String {
  1914. format!("{name}@{marketplace}")
  1915. }
  1916. fn sanitize_plugin_id(plugin_id: &str) -> String {
  1917. plugin_id
  1918. .chars()
  1919. .map(|ch| match ch {
  1920. '/' | '\\' | '@' | ':' => '-',
  1921. other => other,
  1922. })
  1923. .collect()
  1924. }
  1925. fn describe_install_source(source: &PluginInstallSource) -> String {
  1926. match source {
  1927. PluginInstallSource::LocalPath { path } => path.display().to_string(),
  1928. PluginInstallSource::GitUrl { url } => url.clone(),
  1929. }
  1930. }
  1931. fn unix_time_ms() -> u128 {
  1932. SystemTime::now()
  1933. .duration_since(UNIX_EPOCH)
  1934. .expect("time should be after epoch")
  1935. .as_millis()
  1936. }
  1937. fn copy_dir_all(source: &Path, destination: &Path) -> Result<(), PluginError> {
  1938. fs::create_dir_all(destination)?;
  1939. for entry in fs::read_dir(source)? {
  1940. let entry = entry?;
  1941. let target = destination.join(entry.file_name());
  1942. if entry.file_type()?.is_dir() {
  1943. copy_dir_all(&entry.path(), &target)?;
  1944. } else {
  1945. fs::copy(entry.path(), target)?;
  1946. }
  1947. }
  1948. Ok(())
  1949. }
  1950. fn update_settings_json(
  1951. path: &Path,
  1952. mut update: impl FnMut(&mut Map<String, Value>),
  1953. ) -> Result<(), PluginError> {
  1954. if let Some(parent) = path.parent() {
  1955. fs::create_dir_all(parent)?;
  1956. }
  1957. let mut root = match fs::read_to_string(path) {
  1958. Ok(contents) if !contents.trim().is_empty() => serde_json::from_str::<Value>(&contents)?,
  1959. Ok(_) => Value::Object(Map::new()),
  1960. Err(error) if error.kind() == std::io::ErrorKind::NotFound => Value::Object(Map::new()),
  1961. Err(error) => return Err(PluginError::Io(error)),
  1962. };
  1963. let object = root.as_object_mut().ok_or_else(|| {
  1964. PluginError::InvalidManifest(format!(
  1965. "settings file {} must contain a JSON object",
  1966. path.display()
  1967. ))
  1968. })?;
  1969. update(object);
  1970. fs::write(path, serde_json::to_string_pretty(&root)?)?;
  1971. Ok(())
  1972. }
  1973. fn ensure_object<'a>(root: &'a mut Map<String, Value>, key: &str) -> &'a mut Map<String, Value> {
  1974. if !root.get(key).is_some_and(Value::is_object) {
  1975. root.insert(key.to_string(), Value::Object(Map::new()));
  1976. }
  1977. root.get_mut(key)
  1978. .and_then(Value::as_object_mut)
  1979. .expect("object should exist")
  1980. }
  1981. #[cfg(test)]
  1982. mod tests {
  1983. use super::*;
  1984. fn temp_dir(label: &str) -> PathBuf {
  1985. let nanos = std::time::SystemTime::now()
  1986. .duration_since(std::time::UNIX_EPOCH)
  1987. .expect("time should be after epoch")
  1988. .as_nanos();
  1989. std::env::temp_dir().join(format!("plugins-{label}-{nanos}"))
  1990. }
  1991. fn write_file(path: &Path, contents: &str) {
  1992. if let Some(parent) = path.parent() {
  1993. fs::create_dir_all(parent).expect("parent dir");
  1994. }
  1995. fs::write(path, contents).expect("write file");
  1996. }
  1997. fn write_loader_plugin(root: &Path) {
  1998. write_file(
  1999. root.join("hooks").join("pre.sh").as_path(),
  2000. "#!/bin/sh\nprintf 'pre'\n",
  2001. );
  2002. write_file(
  2003. root.join("tools").join("echo-tool.sh").as_path(),
  2004. "#!/bin/sh\ncat\n",
  2005. );
  2006. write_file(
  2007. root.join("commands").join("sync.sh").as_path(),
  2008. "#!/bin/sh\nprintf 'sync'\n",
  2009. );
  2010. write_file(
  2011. root.join(MANIFEST_FILE_NAME).as_path(),
  2012. r#"{
  2013. "name": "loader-demo",
  2014. "version": "1.2.3",
  2015. "description": "Manifest loader test plugin",
  2016. "permissions": ["read", "write"],
  2017. "hooks": {
  2018. "PreToolUse": ["./hooks/pre.sh"]
  2019. },
  2020. "tools": [
  2021. {
  2022. "name": "echo_tool",
  2023. "description": "Echoes JSON input",
  2024. "inputSchema": {
  2025. "type": "object"
  2026. },
  2027. "command": "./tools/echo-tool.sh",
  2028. "requiredPermission": "workspace-write"
  2029. }
  2030. ],
  2031. "commands": [
  2032. {
  2033. "name": "sync",
  2034. "description": "Sync command",
  2035. "command": "./commands/sync.sh"
  2036. }
  2037. ]
  2038. }"#,
  2039. );
  2040. }
  2041. fn write_external_plugin(root: &Path, name: &str, version: &str) {
  2042. write_file(
  2043. root.join("hooks").join("pre.sh").as_path(),
  2044. "#!/bin/sh\nprintf 'pre'\n",
  2045. );
  2046. write_file(
  2047. root.join("hooks").join("post.sh").as_path(),
  2048. "#!/bin/sh\nprintf 'post'\n",
  2049. );
  2050. write_file(
  2051. root.join(MANIFEST_RELATIVE_PATH).as_path(),
  2052. format!(
  2053. "{{\n \"name\": \"{name}\",\n \"version\": \"{version}\",\n \"description\": \"test plugin\",\n \"hooks\": {{\n \"PreToolUse\": [\"./hooks/pre.sh\"],\n \"PostToolUse\": [\"./hooks/post.sh\"]\n }}\n}}"
  2054. )
  2055. .as_str(),
  2056. );
  2057. }
  2058. fn write_broken_plugin(root: &Path, name: &str) {
  2059. write_file(
  2060. root.join(MANIFEST_RELATIVE_PATH).as_path(),
  2061. format!(
  2062. "{{\n \"name\": \"{name}\",\n \"version\": \"1.0.0\",\n \"description\": \"broken plugin\",\n \"hooks\": {{\n \"PreToolUse\": [\"./hooks/missing.sh\"]\n }}\n}}"
  2063. )
  2064. .as_str(),
  2065. );
  2066. }
  2067. fn write_directory_path_plugin(root: &Path, name: &str) {
  2068. fs::create_dir_all(root.join("hooks").join("pre-dir")).expect("hook dir");
  2069. fs::create_dir_all(root.join("tools").join("tool-dir")).expect("tool dir");
  2070. fs::create_dir_all(root.join("commands").join("sync-dir")).expect("command dir");
  2071. fs::create_dir_all(root.join("lifecycle").join("init-dir")).expect("lifecycle dir");
  2072. write_file(
  2073. root.join(MANIFEST_FILE_NAME).as_path(),
  2074. format!(
  2075. "{{\n \"name\": \"{name}\",\n \"version\": \"1.0.0\",\n \"description\": \"directory path plugin\",\n \"hooks\": {{\n \"PreToolUse\": [\"./hooks/pre-dir\"]\n }},\n \"lifecycle\": {{\n \"Init\": [\"./lifecycle/init-dir\"]\n }},\n \"tools\": [\n {{\n \"name\": \"dir_tool\",\n \"description\": \"Directory tool\",\n \"inputSchema\": {{\"type\": \"object\"}},\n \"command\": \"./tools/tool-dir\"\n }}\n ],\n \"commands\": [\n {{\n \"name\": \"sync\",\n \"description\": \"Directory command\",\n \"command\": \"./commands/sync-dir\"\n }}\n ]\n}}"
  2076. )
  2077. .as_str(),
  2078. );
  2079. }
  2080. fn write_broken_failure_hook_plugin(root: &Path, name: &str) {
  2081. write_file(
  2082. root.join(MANIFEST_RELATIVE_PATH).as_path(),
  2083. format!(
  2084. "{{\n \"name\": \"{name}\",\n \"version\": \"1.0.0\",\n \"description\": \"broken plugin\",\n \"hooks\": {{\n \"PostToolUseFailure\": [\"./hooks/missing-failure.sh\"]\n }}\n}}"
  2085. )
  2086. .as_str(),
  2087. );
  2088. }
  2089. fn write_lifecycle_plugin(root: &Path, name: &str, version: &str) -> PathBuf {
  2090. let log_path = root.join("lifecycle.log");
  2091. write_file(
  2092. root.join("lifecycle").join("init.sh").as_path(),
  2093. "#!/bin/sh\nprintf 'init\\n' >> lifecycle.log\n",
  2094. );
  2095. write_file(
  2096. root.join("lifecycle").join("shutdown.sh").as_path(),
  2097. "#!/bin/sh\nprintf 'shutdown\\n' >> lifecycle.log\n",
  2098. );
  2099. write_file(
  2100. root.join(MANIFEST_RELATIVE_PATH).as_path(),
  2101. format!(
  2102. "{{\n \"name\": \"{name}\",\n \"version\": \"{version}\",\n \"description\": \"lifecycle plugin\",\n \"lifecycle\": {{\n \"Init\": [\"./lifecycle/init.sh\"],\n \"Shutdown\": [\"./lifecycle/shutdown.sh\"]\n }}\n}}"
  2103. )
  2104. .as_str(),
  2105. );
  2106. log_path
  2107. }
  2108. fn write_tool_plugin(root: &Path, name: &str, version: &str) {
  2109. write_tool_plugin_with_name(root, name, version, "plugin_echo");
  2110. }
  2111. fn write_tool_plugin_with_name(root: &Path, name: &str, version: &str, tool_name: &str) {
  2112. let script_path = root.join("tools").join("echo-json.sh");
  2113. write_file(
  2114. &script_path,
  2115. "#!/bin/sh\nINPUT=$(cat)\nprintf '{\"plugin\":\"%s\",\"tool\":\"%s\",\"input\":%s}\\n' \"$CLAWD_PLUGIN_ID\" \"$CLAWD_TOOL_NAME\" \"$INPUT\"\n",
  2116. );
  2117. #[cfg(unix)]
  2118. {
  2119. use std::os::unix::fs::PermissionsExt;
  2120. let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
  2121. permissions.set_mode(0o755);
  2122. fs::set_permissions(&script_path, permissions).expect("chmod");
  2123. }
  2124. write_file(
  2125. root.join(MANIFEST_RELATIVE_PATH).as_path(),
  2126. format!(
  2127. "{{\n \"name\": \"{name}\",\n \"version\": \"{version}\",\n \"description\": \"tool plugin\",\n \"tools\": [\n {{\n \"name\": \"{tool_name}\",\n \"description\": \"Echo JSON input\",\n \"inputSchema\": {{\"type\": \"object\", \"properties\": {{\"message\": {{\"type\": \"string\"}}}}, \"required\": [\"message\"], \"additionalProperties\": false}},\n \"command\": \"./tools/echo-json.sh\",\n \"requiredPermission\": \"workspace-write\"\n }}\n ]\n}}"
  2128. )
  2129. .as_str(),
  2130. );
  2131. }
  2132. fn write_bundled_plugin(root: &Path, name: &str, version: &str, default_enabled: bool) {
  2133. write_file(
  2134. root.join(MANIFEST_RELATIVE_PATH).as_path(),
  2135. format!(
  2136. "{{\n \"name\": \"{name}\",\n \"version\": \"{version}\",\n \"description\": \"bundled plugin\",\n \"defaultEnabled\": {}\n}}",
  2137. if default_enabled { "true" } else { "false" }
  2138. )
  2139. .as_str(),
  2140. );
  2141. }
  2142. fn load_enabled_plugins(path: &Path) -> BTreeMap<String, bool> {
  2143. let contents = fs::read_to_string(path).expect("settings should exist");
  2144. let root: Value = serde_json::from_str(&contents).expect("settings json");
  2145. root.get("enabledPlugins")
  2146. .and_then(Value::as_object)
  2147. .map(|enabled_plugins| {
  2148. enabled_plugins
  2149. .iter()
  2150. .map(|(plugin_id, value)| {
  2151. (
  2152. plugin_id.clone(),
  2153. value.as_bool().expect("plugin state should be a bool"),
  2154. )
  2155. })
  2156. .collect()
  2157. })
  2158. .unwrap_or_default()
  2159. }
  2160. #[test]
  2161. fn load_plugin_from_directory_validates_required_fields() {
  2162. let root = temp_dir("manifest-required");
  2163. write_file(
  2164. root.join(MANIFEST_FILE_NAME).as_path(),
  2165. r#"{"name":"","version":"1.0.0","description":"desc"}"#,
  2166. );
  2167. let error = load_plugin_from_directory(&root).expect_err("empty name should fail");
  2168. assert!(error.to_string().contains("name cannot be empty"));
  2169. let _ = fs::remove_dir_all(root);
  2170. }
  2171. #[test]
  2172. fn load_plugin_from_directory_reads_root_manifest_and_validates_entries() {
  2173. let root = temp_dir("manifest-root");
  2174. write_loader_plugin(&root);
  2175. let manifest = load_plugin_from_directory(&root).expect("manifest should load");
  2176. assert_eq!(manifest.name, "loader-demo");
  2177. assert_eq!(manifest.version, "1.2.3");
  2178. assert_eq!(
  2179. manifest
  2180. .permissions
  2181. .iter()
  2182. .map(|permission| permission.as_str())
  2183. .collect::<Vec<_>>(),
  2184. vec!["read", "write"]
  2185. );
  2186. assert_eq!(manifest.hooks.pre_tool_use, vec!["./hooks/pre.sh"]);
  2187. assert_eq!(manifest.tools.len(), 1);
  2188. assert_eq!(manifest.tools[0].name, "echo_tool");
  2189. assert_eq!(
  2190. manifest.tools[0].required_permission,
  2191. PluginToolPermission::WorkspaceWrite
  2192. );
  2193. assert_eq!(manifest.commands.len(), 1);
  2194. assert_eq!(manifest.commands[0].name, "sync");
  2195. let _ = fs::remove_dir_all(root);
  2196. }
  2197. #[test]
  2198. fn load_plugin_from_directory_supports_packaged_manifest_path() {
  2199. let root = temp_dir("manifest-packaged");
  2200. write_external_plugin(&root, "packaged-demo", "1.0.0");
  2201. let manifest = load_plugin_from_directory(&root).expect("packaged manifest should load");
  2202. assert_eq!(manifest.name, "packaged-demo");
  2203. assert!(manifest.tools.is_empty());
  2204. assert!(manifest.commands.is_empty());
  2205. let _ = fs::remove_dir_all(root);
  2206. }
  2207. #[test]
  2208. fn load_plugin_from_directory_defaults_optional_fields() {
  2209. let root = temp_dir("manifest-defaults");
  2210. write_file(
  2211. root.join(MANIFEST_FILE_NAME).as_path(),
  2212. r#"{
  2213. "name": "minimal",
  2214. "version": "0.1.0",
  2215. "description": "Minimal manifest"
  2216. }"#,
  2217. );
  2218. let manifest = load_plugin_from_directory(&root).expect("minimal manifest should load");
  2219. assert!(manifest.permissions.is_empty());
  2220. assert!(manifest.hooks.is_empty());
  2221. assert!(manifest.tools.is_empty());
  2222. assert!(manifest.commands.is_empty());
  2223. let _ = fs::remove_dir_all(root);
  2224. }
  2225. #[test]
  2226. fn load_plugin_from_directory_rejects_duplicate_permissions_and_commands() {
  2227. let root = temp_dir("manifest-duplicates");
  2228. write_file(
  2229. root.join("commands").join("sync.sh").as_path(),
  2230. "#!/bin/sh\nprintf 'sync'\n",
  2231. );
  2232. write_file(
  2233. root.join(MANIFEST_FILE_NAME).as_path(),
  2234. r#"{
  2235. "name": "duplicate-manifest",
  2236. "version": "1.0.0",
  2237. "description": "Duplicate validation",
  2238. "permissions": ["read", "read"],
  2239. "commands": [
  2240. {"name": "sync", "description": "Sync one", "command": "./commands/sync.sh"},
  2241. {"name": "sync", "description": "Sync two", "command": "./commands/sync.sh"}
  2242. ]
  2243. }"#,
  2244. );
  2245. let error = load_plugin_from_directory(&root).expect_err("duplicates should fail");
  2246. match error {
  2247. PluginError::ManifestValidation(errors) => {
  2248. assert!(errors.iter().any(|error| matches!(
  2249. error,
  2250. PluginManifestValidationError::DuplicatePermission { permission }
  2251. if permission == "read"
  2252. )));
  2253. assert!(errors.iter().any(|error| matches!(
  2254. error,
  2255. PluginManifestValidationError::DuplicateEntry { kind, name }
  2256. if *kind == "command" && name == "sync"
  2257. )));
  2258. }
  2259. other => panic!("expected manifest validation errors, got {other}"),
  2260. }
  2261. let _ = fs::remove_dir_all(root);
  2262. }
  2263. #[test]
  2264. fn load_plugin_from_directory_rejects_missing_tool_or_command_paths() {
  2265. let root = temp_dir("manifest-paths");
  2266. write_file(
  2267. root.join(MANIFEST_FILE_NAME).as_path(),
  2268. r#"{
  2269. "name": "missing-paths",
  2270. "version": "1.0.0",
  2271. "description": "Missing path validation",
  2272. "tools": [
  2273. {
  2274. "name": "tool_one",
  2275. "description": "Missing tool script",
  2276. "inputSchema": {"type": "object"},
  2277. "command": "./tools/missing.sh"
  2278. }
  2279. ]
  2280. }"#,
  2281. );
  2282. let error = load_plugin_from_directory(&root).expect_err("missing paths should fail");
  2283. assert!(error.to_string().contains("does not exist"));
  2284. let _ = fs::remove_dir_all(root);
  2285. }
  2286. #[test]
  2287. fn load_plugin_from_directory_rejects_missing_lifecycle_paths() {
  2288. // given
  2289. let root = temp_dir("manifest-lifecycle-paths");
  2290. write_file(
  2291. root.join(MANIFEST_FILE_NAME).as_path(),
  2292. r#"{
  2293. "name": "missing-lifecycle-paths",
  2294. "version": "1.0.0",
  2295. "description": "Missing lifecycle path validation",
  2296. "lifecycle": {
  2297. "Init": ["./lifecycle/init.sh"],
  2298. "Shutdown": ["./lifecycle/shutdown.sh"]
  2299. }
  2300. }"#,
  2301. );
  2302. // when
  2303. let error =
  2304. load_plugin_from_directory(&root).expect_err("missing lifecycle paths should fail");
  2305. // then
  2306. match error {
  2307. PluginError::ManifestValidation(errors) => {
  2308. assert!(errors.iter().any(|error| matches!(
  2309. error,
  2310. PluginManifestValidationError::MissingPath { kind, path }
  2311. if *kind == "lifecycle command"
  2312. && path.ends_with(Path::new("lifecycle/init.sh"))
  2313. )));
  2314. assert!(errors.iter().any(|error| matches!(
  2315. error,
  2316. PluginManifestValidationError::MissingPath { kind, path }
  2317. if *kind == "lifecycle command"
  2318. && path.ends_with(Path::new("lifecycle/shutdown.sh"))
  2319. )));
  2320. }
  2321. other => panic!("expected manifest validation errors, got {other}"),
  2322. }
  2323. let _ = fs::remove_dir_all(root);
  2324. }
  2325. #[test]
  2326. fn load_plugin_from_directory_rejects_directory_command_paths() {
  2327. // given
  2328. let root = temp_dir("manifest-directory-paths");
  2329. write_directory_path_plugin(&root, "directory-paths");
  2330. // when
  2331. let error =
  2332. load_plugin_from_directory(&root).expect_err("directory command paths should fail");
  2333. // then
  2334. match error {
  2335. PluginError::ManifestValidation(errors) => {
  2336. assert!(errors.iter().any(|error| matches!(
  2337. error,
  2338. PluginManifestValidationError::PathIsDirectory { kind, path }
  2339. if *kind == "hook" && path.ends_with(Path::new("hooks/pre-dir"))
  2340. )));
  2341. assert!(errors.iter().any(|error| matches!(
  2342. error,
  2343. PluginManifestValidationError::PathIsDirectory { kind, path }
  2344. if *kind == "lifecycle command"
  2345. && path.ends_with(Path::new("lifecycle/init-dir"))
  2346. )));
  2347. assert!(errors.iter().any(|error| matches!(
  2348. error,
  2349. PluginManifestValidationError::PathIsDirectory { kind, path }
  2350. if *kind == "tool" && path.ends_with(Path::new("tools/tool-dir"))
  2351. )));
  2352. assert!(errors.iter().any(|error| matches!(
  2353. error,
  2354. PluginManifestValidationError::PathIsDirectory { kind, path }
  2355. if *kind == "command" && path.ends_with(Path::new("commands/sync-dir"))
  2356. )));
  2357. }
  2358. other => panic!("expected manifest validation errors, got {other}"),
  2359. }
  2360. let _ = fs::remove_dir_all(root);
  2361. }
  2362. #[test]
  2363. fn load_plugin_from_directory_rejects_invalid_permissions() {
  2364. let root = temp_dir("manifest-invalid-permissions");
  2365. write_file(
  2366. root.join(MANIFEST_FILE_NAME).as_path(),
  2367. r#"{
  2368. "name": "invalid-permissions",
  2369. "version": "1.0.0",
  2370. "description": "Invalid permission validation",
  2371. "permissions": ["admin"]
  2372. }"#,
  2373. );
  2374. let error = load_plugin_from_directory(&root).expect_err("invalid permissions should fail");
  2375. match error {
  2376. PluginError::ManifestValidation(errors) => {
  2377. assert!(errors.iter().any(|error| matches!(
  2378. error,
  2379. PluginManifestValidationError::InvalidPermission { permission }
  2380. if permission == "admin"
  2381. )));
  2382. }
  2383. other => panic!("expected manifest validation errors, got {other}"),
  2384. }
  2385. let _ = fs::remove_dir_all(root);
  2386. }
  2387. #[test]
  2388. fn load_plugin_from_directory_rejects_invalid_tool_required_permission() {
  2389. let root = temp_dir("manifest-invalid-tool-permission");
  2390. write_file(
  2391. root.join("tools").join("echo.sh").as_path(),
  2392. "#!/bin/sh\ncat\n",
  2393. );
  2394. write_file(
  2395. root.join(MANIFEST_FILE_NAME).as_path(),
  2396. r#"{
  2397. "name": "invalid-tool-permission",
  2398. "version": "1.0.0",
  2399. "description": "Invalid tool permission validation",
  2400. "tools": [
  2401. {
  2402. "name": "echo_tool",
  2403. "description": "Echo tool",
  2404. "inputSchema": {"type": "object"},
  2405. "command": "./tools/echo.sh",
  2406. "requiredPermission": "admin"
  2407. }
  2408. ]
  2409. }"#,
  2410. );
  2411. let error =
  2412. load_plugin_from_directory(&root).expect_err("invalid tool permission should fail");
  2413. match error {
  2414. PluginError::ManifestValidation(errors) => {
  2415. assert!(errors.iter().any(|error| matches!(
  2416. error,
  2417. PluginManifestValidationError::InvalidToolRequiredPermission {
  2418. tool_name,
  2419. permission
  2420. } if tool_name == "echo_tool" && permission == "admin"
  2421. )));
  2422. }
  2423. other => panic!("expected manifest validation errors, got {other}"),
  2424. }
  2425. let _ = fs::remove_dir_all(root);
  2426. }
  2427. #[test]
  2428. fn load_plugin_from_directory_accumulates_multiple_validation_errors() {
  2429. let root = temp_dir("manifest-multi-error");
  2430. write_file(
  2431. root.join(MANIFEST_FILE_NAME).as_path(),
  2432. r#"{
  2433. "name": "",
  2434. "version": "1.0.0",
  2435. "description": "",
  2436. "permissions": ["admin"],
  2437. "commands": [
  2438. {"name": "", "description": "", "command": "./commands/missing.sh"}
  2439. ]
  2440. }"#,
  2441. );
  2442. let error =
  2443. load_plugin_from_directory(&root).expect_err("multiple manifest errors should fail");
  2444. match error {
  2445. PluginError::ManifestValidation(errors) => {
  2446. assert!(errors.len() >= 4);
  2447. assert!(errors.iter().any(|error| matches!(
  2448. error,
  2449. PluginManifestValidationError::EmptyField { field } if *field == "name"
  2450. )));
  2451. assert!(errors.iter().any(|error| matches!(
  2452. error,
  2453. PluginManifestValidationError::EmptyField { field }
  2454. if *field == "description"
  2455. )));
  2456. assert!(errors.iter().any(|error| matches!(
  2457. error,
  2458. PluginManifestValidationError::InvalidPermission { permission }
  2459. if permission == "admin"
  2460. )));
  2461. }
  2462. other => panic!("expected manifest validation errors, got {other}"),
  2463. }
  2464. let _ = fs::remove_dir_all(root);
  2465. }
  2466. #[test]
  2467. fn discovers_builtin_and_bundled_plugins() {
  2468. let manager = PluginManager::new(PluginManagerConfig::new(temp_dir("discover")));
  2469. let plugins = manager.list_plugins().expect("plugins should list");
  2470. assert!(plugins
  2471. .iter()
  2472. .any(|plugin| plugin.metadata.kind == PluginKind::Builtin));
  2473. assert!(plugins
  2474. .iter()
  2475. .any(|plugin| plugin.metadata.kind == PluginKind::Bundled));
  2476. }
  2477. #[test]
  2478. fn installs_enables_updates_and_uninstalls_external_plugins() {
  2479. let config_home = temp_dir("home");
  2480. let source_root = temp_dir("source");
  2481. write_external_plugin(&source_root, "demo", "1.0.0");
  2482. let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2483. let install = manager
  2484. .install(source_root.to_str().expect("utf8 path"))
  2485. .expect("install should succeed");
  2486. assert_eq!(install.plugin_id, "demo@external");
  2487. assert!(manager
  2488. .list_plugins()
  2489. .expect("list plugins")
  2490. .iter()
  2491. .any(|plugin| plugin.metadata.id == "demo@external" && plugin.enabled));
  2492. let hooks = manager.aggregated_hooks().expect("hooks should aggregate");
  2493. assert_eq!(hooks.pre_tool_use.len(), 1);
  2494. assert!(hooks.pre_tool_use[0].contains("pre.sh"));
  2495. manager
  2496. .disable("demo@external")
  2497. .expect("disable should work");
  2498. assert!(manager
  2499. .aggregated_hooks()
  2500. .expect("hooks after disable")
  2501. .is_empty());
  2502. manager.enable("demo@external").expect("enable should work");
  2503. write_external_plugin(&source_root, "demo", "2.0.0");
  2504. let update = manager.update("demo@external").expect("update should work");
  2505. assert_eq!(update.old_version, "1.0.0");
  2506. assert_eq!(update.new_version, "2.0.0");
  2507. manager
  2508. .uninstall("demo@external")
  2509. .expect("uninstall should work");
  2510. assert!(!manager
  2511. .list_plugins()
  2512. .expect("list plugins")
  2513. .iter()
  2514. .any(|plugin| plugin.metadata.id == "demo@external"));
  2515. let _ = fs::remove_dir_all(config_home);
  2516. let _ = fs::remove_dir_all(source_root);
  2517. }
  2518. #[test]
  2519. fn auto_installs_bundled_plugins_into_the_registry() {
  2520. let config_home = temp_dir("bundled-home");
  2521. let bundled_root = temp_dir("bundled-root");
  2522. write_bundled_plugin(&bundled_root.join("starter"), "starter", "0.1.0", false);
  2523. let mut config = PluginManagerConfig::new(&config_home);
  2524. config.bundled_root = Some(bundled_root.clone());
  2525. let manager = PluginManager::new(config);
  2526. let installed = manager
  2527. .list_installed_plugins()
  2528. .expect("bundled plugins should auto-install");
  2529. assert!(installed.iter().any(|plugin| {
  2530. plugin.metadata.id == "starter@bundled"
  2531. && plugin.metadata.kind == PluginKind::Bundled
  2532. && !plugin.enabled
  2533. }));
  2534. let registry = manager.load_registry().expect("registry should exist");
  2535. let record = registry
  2536. .plugins
  2537. .get("starter@bundled")
  2538. .expect("bundled plugin should be recorded");
  2539. assert_eq!(record.kind, PluginKind::Bundled);
  2540. assert!(record.install_path.exists());
  2541. let _ = fs::remove_dir_all(config_home);
  2542. let _ = fs::remove_dir_all(bundled_root);
  2543. }
  2544. #[test]
  2545. fn default_bundled_root_loads_repo_bundles_as_installed_plugins() {
  2546. let config_home = temp_dir("default-bundled-home");
  2547. let manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2548. let installed = manager
  2549. .list_installed_plugins()
  2550. .expect("default bundled plugins should auto-install");
  2551. assert!(installed
  2552. .iter()
  2553. .any(|plugin| plugin.metadata.id == "example-bundled@bundled"));
  2554. assert!(installed
  2555. .iter()
  2556. .any(|plugin| plugin.metadata.id == "sample-hooks@bundled"));
  2557. let _ = fs::remove_dir_all(config_home);
  2558. }
  2559. #[test]
  2560. fn bundled_sync_prunes_removed_bundled_registry_entries() {
  2561. let config_home = temp_dir("bundled-prune-home");
  2562. let bundled_root = temp_dir("bundled-prune-root");
  2563. let stale_install_path = config_home
  2564. .join("plugins")
  2565. .join("installed")
  2566. .join("stale-bundled-external");
  2567. write_bundled_plugin(&bundled_root.join("active"), "active", "0.1.0", false);
  2568. write_file(
  2569. stale_install_path.join(MANIFEST_RELATIVE_PATH).as_path(),
  2570. r#"{
  2571. "name": "stale",
  2572. "version": "0.1.0",
  2573. "description": "stale bundled plugin"
  2574. }"#,
  2575. );
  2576. let mut config = PluginManagerConfig::new(&config_home);
  2577. config.bundled_root = Some(bundled_root.clone());
  2578. config.install_root = Some(config_home.join("plugins").join("installed"));
  2579. let manager = PluginManager::new(config);
  2580. let mut registry = InstalledPluginRegistry::default();
  2581. registry.plugins.insert(
  2582. "stale@bundled".to_string(),
  2583. InstalledPluginRecord {
  2584. kind: PluginKind::Bundled,
  2585. id: "stale@bundled".to_string(),
  2586. name: "stale".to_string(),
  2587. version: "0.1.0".to_string(),
  2588. description: "stale bundled plugin".to_string(),
  2589. install_path: stale_install_path.clone(),
  2590. source: PluginInstallSource::LocalPath {
  2591. path: bundled_root.join("stale"),
  2592. },
  2593. installed_at_unix_ms: 1,
  2594. updated_at_unix_ms: 1,
  2595. },
  2596. );
  2597. manager.store_registry(&registry).expect("store registry");
  2598. manager
  2599. .write_enabled_state("stale@bundled", Some(true))
  2600. .expect("seed bundled enabled state");
  2601. let installed = manager
  2602. .list_installed_plugins()
  2603. .expect("bundled sync should succeed");
  2604. assert!(installed
  2605. .iter()
  2606. .any(|plugin| plugin.metadata.id == "active@bundled"));
  2607. assert!(!installed
  2608. .iter()
  2609. .any(|plugin| plugin.metadata.id == "stale@bundled"));
  2610. let registry = manager.load_registry().expect("load registry");
  2611. assert!(!registry.plugins.contains_key("stale@bundled"));
  2612. assert!(!stale_install_path.exists());
  2613. let _ = fs::remove_dir_all(config_home);
  2614. let _ = fs::remove_dir_all(bundled_root);
  2615. }
  2616. #[test]
  2617. fn installed_plugin_discovery_keeps_registry_entries_outside_install_root() {
  2618. let config_home = temp_dir("registry-fallback-home");
  2619. let bundled_root = temp_dir("registry-fallback-bundled");
  2620. let install_root = config_home.join("plugins").join("installed");
  2621. let external_install_path = temp_dir("registry-fallback-external");
  2622. write_file(
  2623. external_install_path.join(MANIFEST_FILE_NAME).as_path(),
  2624. r#"{
  2625. "name": "registry-fallback",
  2626. "version": "1.0.0",
  2627. "description": "Registry fallback plugin"
  2628. }"#,
  2629. );
  2630. let mut config = PluginManagerConfig::new(&config_home);
  2631. config.bundled_root = Some(bundled_root.clone());
  2632. config.install_root = Some(install_root.clone());
  2633. let manager = PluginManager::new(config);
  2634. let mut registry = InstalledPluginRegistry::default();
  2635. registry.plugins.insert(
  2636. "registry-fallback@external".to_string(),
  2637. InstalledPluginRecord {
  2638. kind: PluginKind::External,
  2639. id: "registry-fallback@external".to_string(),
  2640. name: "registry-fallback".to_string(),
  2641. version: "1.0.0".to_string(),
  2642. description: "Registry fallback plugin".to_string(),
  2643. install_path: external_install_path.clone(),
  2644. source: PluginInstallSource::LocalPath {
  2645. path: external_install_path.clone(),
  2646. },
  2647. installed_at_unix_ms: 1,
  2648. updated_at_unix_ms: 1,
  2649. },
  2650. );
  2651. manager.store_registry(&registry).expect("store registry");
  2652. manager
  2653. .write_enabled_state("stale-external@external", Some(true))
  2654. .expect("seed stale external enabled state");
  2655. let installed = manager
  2656. .list_installed_plugins()
  2657. .expect("registry fallback plugin should load");
  2658. assert!(installed
  2659. .iter()
  2660. .any(|plugin| plugin.metadata.id == "registry-fallback@external"));
  2661. let _ = fs::remove_dir_all(config_home);
  2662. let _ = fs::remove_dir_all(bundled_root);
  2663. let _ = fs::remove_dir_all(external_install_path);
  2664. }
  2665. #[test]
  2666. fn installed_plugin_discovery_prunes_stale_registry_entries() {
  2667. let config_home = temp_dir("registry-prune-home");
  2668. let bundled_root = temp_dir("registry-prune-bundled");
  2669. let install_root = config_home.join("plugins").join("installed");
  2670. let missing_install_path = temp_dir("registry-prune-missing");
  2671. let mut config = PluginManagerConfig::new(&config_home);
  2672. config.bundled_root = Some(bundled_root.clone());
  2673. config.install_root = Some(install_root);
  2674. let manager = PluginManager::new(config);
  2675. let mut registry = InstalledPluginRegistry::default();
  2676. registry.plugins.insert(
  2677. "stale-external@external".to_string(),
  2678. InstalledPluginRecord {
  2679. kind: PluginKind::External,
  2680. id: "stale-external@external".to_string(),
  2681. name: "stale-external".to_string(),
  2682. version: "1.0.0".to_string(),
  2683. description: "stale external plugin".to_string(),
  2684. install_path: missing_install_path.clone(),
  2685. source: PluginInstallSource::LocalPath {
  2686. path: missing_install_path.clone(),
  2687. },
  2688. installed_at_unix_ms: 1,
  2689. updated_at_unix_ms: 1,
  2690. },
  2691. );
  2692. manager.store_registry(&registry).expect("store registry");
  2693. let installed = manager
  2694. .list_installed_plugins()
  2695. .expect("stale registry entries should be pruned");
  2696. assert!(!installed
  2697. .iter()
  2698. .any(|plugin| plugin.metadata.id == "stale-external@external"));
  2699. let registry = manager.load_registry().expect("load registry");
  2700. assert!(!registry.plugins.contains_key("stale-external@external"));
  2701. let _ = fs::remove_dir_all(config_home);
  2702. let _ = fs::remove_dir_all(bundled_root);
  2703. }
  2704. #[test]
  2705. fn persists_bundled_plugin_enable_state_across_reloads() {
  2706. let config_home = temp_dir("bundled-state-home");
  2707. let bundled_root = temp_dir("bundled-state-root");
  2708. write_bundled_plugin(&bundled_root.join("starter"), "starter", "0.1.0", false);
  2709. let mut config = PluginManagerConfig::new(&config_home);
  2710. config.bundled_root = Some(bundled_root.clone());
  2711. let mut manager = PluginManager::new(config.clone());
  2712. manager
  2713. .enable("starter@bundled")
  2714. .expect("enable bundled plugin should succeed");
  2715. assert_eq!(
  2716. load_enabled_plugins(&manager.settings_path()).get("starter@bundled"),
  2717. Some(&true)
  2718. );
  2719. let mut reloaded_config = PluginManagerConfig::new(&config_home);
  2720. reloaded_config.bundled_root = Some(bundled_root.clone());
  2721. reloaded_config.enabled_plugins = load_enabled_plugins(&manager.settings_path());
  2722. let reloaded_manager = PluginManager::new(reloaded_config);
  2723. let reloaded = reloaded_manager
  2724. .list_installed_plugins()
  2725. .expect("bundled plugins should still be listed");
  2726. assert!(reloaded
  2727. .iter()
  2728. .any(|plugin| { plugin.metadata.id == "starter@bundled" && plugin.enabled }));
  2729. let _ = fs::remove_dir_all(config_home);
  2730. let _ = fs::remove_dir_all(bundled_root);
  2731. }
  2732. #[test]
  2733. fn persists_bundled_plugin_disable_state_across_reloads() {
  2734. let config_home = temp_dir("bundled-disabled-home");
  2735. let bundled_root = temp_dir("bundled-disabled-root");
  2736. write_bundled_plugin(&bundled_root.join("starter"), "starter", "0.1.0", true);
  2737. let mut config = PluginManagerConfig::new(&config_home);
  2738. config.bundled_root = Some(bundled_root.clone());
  2739. let mut manager = PluginManager::new(config);
  2740. manager
  2741. .disable("starter@bundled")
  2742. .expect("disable bundled plugin should succeed");
  2743. assert_eq!(
  2744. load_enabled_plugins(&manager.settings_path()).get("starter@bundled"),
  2745. Some(&false)
  2746. );
  2747. let mut reloaded_config = PluginManagerConfig::new(&config_home);
  2748. reloaded_config.bundled_root = Some(bundled_root.clone());
  2749. reloaded_config.enabled_plugins = load_enabled_plugins(&manager.settings_path());
  2750. let reloaded_manager = PluginManager::new(reloaded_config);
  2751. let reloaded = reloaded_manager
  2752. .list_installed_plugins()
  2753. .expect("bundled plugins should still be listed");
  2754. assert!(reloaded
  2755. .iter()
  2756. .any(|plugin| { plugin.metadata.id == "starter@bundled" && !plugin.enabled }));
  2757. let _ = fs::remove_dir_all(config_home);
  2758. let _ = fs::remove_dir_all(bundled_root);
  2759. }
  2760. #[test]
  2761. fn validates_plugin_source_before_install() {
  2762. let config_home = temp_dir("validate-home");
  2763. let source_root = temp_dir("validate-source");
  2764. write_external_plugin(&source_root, "validator", "1.0.0");
  2765. let manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2766. let manifest = manager
  2767. .validate_plugin_source(source_root.to_str().expect("utf8 path"))
  2768. .expect("manifest should validate");
  2769. assert_eq!(manifest.name, "validator");
  2770. let _ = fs::remove_dir_all(config_home);
  2771. let _ = fs::remove_dir_all(source_root);
  2772. }
  2773. #[test]
  2774. fn plugin_registry_tracks_enabled_state_and_lookup() {
  2775. let config_home = temp_dir("registry-home");
  2776. let source_root = temp_dir("registry-source");
  2777. write_external_plugin(&source_root, "registry-demo", "1.0.0");
  2778. let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2779. manager
  2780. .install(source_root.to_str().expect("utf8 path"))
  2781. .expect("install should succeed");
  2782. manager
  2783. .disable("registry-demo@external")
  2784. .expect("disable should succeed");
  2785. let registry = manager.plugin_registry().expect("registry should build");
  2786. let plugin = registry
  2787. .get("registry-demo@external")
  2788. .expect("installed plugin should be discoverable");
  2789. assert_eq!(plugin.metadata().name, "registry-demo");
  2790. assert!(!plugin.is_enabled());
  2791. assert!(registry.contains("registry-demo@external"));
  2792. assert!(!registry.contains("missing@external"));
  2793. let _ = fs::remove_dir_all(config_home);
  2794. let _ = fs::remove_dir_all(source_root);
  2795. }
  2796. #[test]
  2797. fn plugin_registry_report_collects_load_failures_without_dropping_valid_plugins() {
  2798. // given
  2799. let config_home = temp_dir("report-home");
  2800. let external_root = temp_dir("report-external");
  2801. write_external_plugin(&external_root.join("valid"), "valid-report", "1.0.0");
  2802. write_broken_plugin(&external_root.join("broken"), "broken-report");
  2803. let mut config = PluginManagerConfig::new(&config_home);
  2804. config.external_dirs = vec![external_root.clone()];
  2805. let manager = PluginManager::new(config);
  2806. // when
  2807. let report = manager
  2808. .plugin_registry_report()
  2809. .expect("report should tolerate invalid external plugins");
  2810. // then
  2811. assert!(report.registry().contains("valid-report@external"));
  2812. assert_eq!(report.failures().len(), 1);
  2813. assert_eq!(report.failures()[0].kind, PluginKind::External);
  2814. assert!(report.failures()[0]
  2815. .plugin_root
  2816. .ends_with(Path::new("broken")));
  2817. assert!(report.failures()[0]
  2818. .error()
  2819. .to_string()
  2820. .contains("does not exist"));
  2821. let error = manager
  2822. .plugin_registry()
  2823. .expect_err("strict registry should surface load failures");
  2824. match error {
  2825. PluginError::LoadFailures(failures) => {
  2826. assert_eq!(failures.len(), 1);
  2827. assert!(failures[0].plugin_root.ends_with(Path::new("broken")));
  2828. }
  2829. other => panic!("expected load failures, got {other}"),
  2830. }
  2831. let _ = fs::remove_dir_all(config_home);
  2832. let _ = fs::remove_dir_all(external_root);
  2833. }
  2834. #[test]
  2835. fn installed_plugin_registry_report_collects_load_failures_from_install_root() {
  2836. // given
  2837. let config_home = temp_dir("installed-report-home");
  2838. let bundled_root = temp_dir("installed-report-bundled");
  2839. let install_root = config_home.join("plugins").join("installed");
  2840. write_external_plugin(&install_root.join("valid"), "installed-valid", "1.0.0");
  2841. write_broken_plugin(&install_root.join("broken"), "installed-broken");
  2842. let mut config = PluginManagerConfig::new(&config_home);
  2843. config.bundled_root = Some(bundled_root.clone());
  2844. config.install_root = Some(install_root);
  2845. let manager = PluginManager::new(config);
  2846. // when
  2847. let report = manager
  2848. .installed_plugin_registry_report()
  2849. .expect("installed report should tolerate invalid installed plugins");
  2850. // then
  2851. assert!(report.registry().contains("installed-valid@external"));
  2852. assert_eq!(report.failures().len(), 1);
  2853. assert!(report.failures()[0]
  2854. .plugin_root
  2855. .ends_with(Path::new("broken")));
  2856. let _ = fs::remove_dir_all(config_home);
  2857. let _ = fs::remove_dir_all(bundled_root);
  2858. }
  2859. #[test]
  2860. fn rejects_plugin_sources_with_missing_hook_paths() {
  2861. // given
  2862. let config_home = temp_dir("broken-home");
  2863. let source_root = temp_dir("broken-source");
  2864. write_broken_plugin(&source_root, "broken");
  2865. let manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2866. // when
  2867. let error = manager
  2868. .validate_plugin_source(source_root.to_str().expect("utf8 path"))
  2869. .expect_err("missing hook file should fail validation");
  2870. // then
  2871. assert!(error.to_string().contains("does not exist"));
  2872. let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2873. let install_error = manager
  2874. .install(source_root.to_str().expect("utf8 path"))
  2875. .expect_err("install should reject invalid hook paths");
  2876. assert!(install_error.to_string().contains("does not exist"));
  2877. let _ = fs::remove_dir_all(config_home);
  2878. let _ = fs::remove_dir_all(source_root);
  2879. }
  2880. #[test]
  2881. fn rejects_plugin_sources_with_missing_failure_hook_paths() {
  2882. // given
  2883. let config_home = temp_dir("broken-failure-home");
  2884. let source_root = temp_dir("broken-failure-source");
  2885. write_broken_failure_hook_plugin(&source_root, "broken-failure");
  2886. let manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2887. // when
  2888. let error = manager
  2889. .validate_plugin_source(source_root.to_str().expect("utf8 path"))
  2890. .expect_err("missing failure hook file should fail validation");
  2891. // then
  2892. assert!(error.to_string().contains("does not exist"));
  2893. let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2894. let install_error = manager
  2895. .install(source_root.to_str().expect("utf8 path"))
  2896. .expect_err("install should reject invalid failure hook paths");
  2897. assert!(install_error.to_string().contains("does not exist"));
  2898. let _ = fs::remove_dir_all(config_home);
  2899. let _ = fs::remove_dir_all(source_root);
  2900. }
  2901. #[test]
  2902. fn plugin_registry_runs_initialize_and_shutdown_for_enabled_plugins() {
  2903. let config_home = temp_dir("lifecycle-home");
  2904. let source_root = temp_dir("lifecycle-source");
  2905. let _ = write_lifecycle_plugin(&source_root, "lifecycle-demo", "1.0.0");
  2906. let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2907. let install = manager
  2908. .install(source_root.to_str().expect("utf8 path"))
  2909. .expect("install should succeed");
  2910. let log_path = install.install_path.join("lifecycle.log");
  2911. let registry = manager.plugin_registry().expect("registry should build");
  2912. registry.initialize().expect("init should succeed");
  2913. registry.shutdown().expect("shutdown should succeed");
  2914. let log = fs::read_to_string(&log_path).expect("lifecycle log should exist");
  2915. assert_eq!(log, "init\nshutdown\n");
  2916. let _ = fs::remove_dir_all(config_home);
  2917. let _ = fs::remove_dir_all(source_root);
  2918. }
  2919. #[test]
  2920. fn aggregates_and_executes_plugin_tools() {
  2921. let config_home = temp_dir("tool-home");
  2922. let source_root = temp_dir("tool-source");
  2923. write_tool_plugin(&source_root, "tool-demo", "1.0.0");
  2924. let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2925. manager
  2926. .install(source_root.to_str().expect("utf8 path"))
  2927. .expect("install should succeed");
  2928. let tools = manager.aggregated_tools().expect("tools should aggregate");
  2929. assert_eq!(tools.len(), 1);
  2930. assert_eq!(tools[0].definition().name, "plugin_echo");
  2931. assert_eq!(tools[0].required_permission(), "workspace-write");
  2932. let output = tools[0]
  2933. .execute(&serde_json::json!({ "message": "hello" }))
  2934. .expect("plugin tool should execute");
  2935. let payload: Value = serde_json::from_str(&output).expect("valid json");
  2936. assert_eq!(payload["plugin"], "tool-demo@external");
  2937. assert_eq!(payload["tool"], "plugin_echo");
  2938. assert_eq!(payload["input"]["message"], "hello");
  2939. let _ = fs::remove_dir_all(config_home);
  2940. let _ = fs::remove_dir_all(source_root);
  2941. }
  2942. #[test]
  2943. fn list_installed_plugins_scans_install_root_without_registry_entries() {
  2944. let config_home = temp_dir("installed-scan-home");
  2945. let bundled_root = temp_dir("installed-scan-bundled");
  2946. let install_root = config_home.join("plugins").join("installed");
  2947. let installed_plugin_root = install_root.join("scan-demo");
  2948. write_file(
  2949. installed_plugin_root.join(MANIFEST_FILE_NAME).as_path(),
  2950. r#"{
  2951. "name": "scan-demo",
  2952. "version": "1.0.0",
  2953. "description": "Scanned from install root"
  2954. }"#,
  2955. );
  2956. let mut config = PluginManagerConfig::new(&config_home);
  2957. config.bundled_root = Some(bundled_root.clone());
  2958. config.install_root = Some(install_root);
  2959. let manager = PluginManager::new(config);
  2960. let installed = manager
  2961. .list_installed_plugins()
  2962. .expect("installed plugins should scan directories");
  2963. assert!(installed
  2964. .iter()
  2965. .any(|plugin| plugin.metadata.id == "scan-demo@external"));
  2966. let _ = fs::remove_dir_all(config_home);
  2967. let _ = fs::remove_dir_all(bundled_root);
  2968. }
  2969. #[test]
  2970. fn list_installed_plugins_scans_packaged_manifests_in_install_root() {
  2971. let config_home = temp_dir("installed-packaged-scan-home");
  2972. let bundled_root = temp_dir("installed-packaged-scan-bundled");
  2973. let install_root = config_home.join("plugins").join("installed");
  2974. let installed_plugin_root = install_root.join("scan-packaged");
  2975. write_file(
  2976. installed_plugin_root.join(MANIFEST_RELATIVE_PATH).as_path(),
  2977. r#"{
  2978. "name": "scan-packaged",
  2979. "version": "1.0.0",
  2980. "description": "Packaged manifest in install root"
  2981. }"#,
  2982. );
  2983. let mut config = PluginManagerConfig::new(&config_home);
  2984. config.bundled_root = Some(bundled_root.clone());
  2985. config.install_root = Some(install_root);
  2986. let manager = PluginManager::new(config);
  2987. let installed = manager
  2988. .list_installed_plugins()
  2989. .expect("installed plugins should scan packaged manifests");
  2990. assert!(installed
  2991. .iter()
  2992. .any(|plugin| plugin.metadata.id == "scan-packaged@external"));
  2993. let _ = fs::remove_dir_all(config_home);
  2994. let _ = fs::remove_dir_all(bundled_root);
  2995. }
  2996. }